TKT-3500 Microcontroller systems - TUT · 2011-09-14 · TKT-3500 Microcontroller systems ... with...
Transcript of TKT-3500 Microcontroller systems - TUT · 2011-09-14 · TKT-3500 Microcontroller systems ... with...
TKT-3500
Microcontroller
systems
Lec 3a – Serial Input/output
Teemu Laukkarinen
Department of Computer Systems
Tampere University of Technology
Fall 2011
#2/43
Sources
Original slides by Erno Salminen
Robert Reese, Microprocessors: From Assembly
to C with the PIC18Fxx2, Charles River Media,
2005
Tim Wilmshurst, Designing Embedded Systems
with PIC Microcontrollers – Principles and
applications, Elsevier, 2007.
Wikipedia
#3/43
Topics
Basics of communication channels
USART – Universal Sync/Async Rx/Tx
RS-232 – Recommended standard 232 (for
serial communication)
#4/43
Simplex, half-duplex, (full) duplex
3 basic types of communication channels
#5/43
Channel control
Only two communicating blocks in simplest
case
During transfer
master initiates transfers
slave accepts transfers and responds to them
In some cases, a certain block can act both
as master and slave
Many buses are shared multimaster buses
Arbitration mechanism decides which one is the
master
#6/43
Bidirectional IO port
Three-state buffer allows output ports to have a value of logical
0, 1, or Hi-Z (high-impedance)
aka. tri-state, or 3-state logic
In high-impedance state, the buffer‟s input is not connected to its output
Output ”floats”
Other blocks can drive it
Pull-up/down resistors are often used
Buffer is ”stronger” than pull-up
Read: MCU IO port is input
Signal output_enable selects between conducting and Hi-Z states
output_enable
data_in
data_out
oe = 0
Hi-Z
oe = 1
conduct
Vdd
R
#7/43
Bidirectional IO port (2)
Only 1 output can be driven at any time to avoid short-circuit!
Bus protocol defines arbitration policy How to select current master (driver) block
Note that here the tri-state enable TRISn is active low.
#8/43
Open-collector is another choice
BJT instead of FET
Output transistors cannot drive
output high (as they‟re ‟open‟)
”no connection to anything” or
”connection to the ground”
Again pull-up resistor guarantees
correct operation
Outputs are wired together
aka. wired-AND – ‟1‟ only iff all
blocks drive ‟1‟
Uses bipolar npn transistors
c= collector – current flows in
e = emitter – current flows out
b = base - controls
data_in
Vdd
R
GND
Open-collector as bidir IO port
data_inGND
data_inGND
c
b
e
I
#9/43
Parallel channel vs. serial channel
a) Parallel
A group of data signals - High bandwidth
b) Serial
Data transferred one bit at a time - low
bandwidth
In both cases, new data is valid on every rising edge of clock
Note! Error in book‟s fig.
#10/43
Parallel channel vs. serial channel (2)
Compared to serial, parallel communication
requires much wiring – complicates PCB design, skew
problems, not very practical for cables, crosstalk
requires many pins – increase the package price,
increase chips footprint, complicate PCB design
may use lower frequency to achieve the same bandwidth
In both cases, data transfers are controlled with a
clock or strobe signal
Examples:
a) Parallel: memory bus, PCI, AGP, ATA, IDE, SCSI...
b) Serial: RS-232, U(S)ART, I2C, SPI, USB, Ethernet,
SATA...
#11/43
Par vs. ser (3)
Assuming 10 MHz clock
A 16-bit parallel channel, achieves bandwidth= 10 MHz *
16 bits = 160 Mbit/s
Whereas serial, achieves only 10MHz * 1bit=10 Mbit/s
It would require 160 MHz for the same performance
Serial applicable only for low data rate
communication
High data rates (few Gb/s) are possible at short distances
(few meters), e.g. USB 2.0
Parallel usually not applicable (practical) at long
distances
No practical communication scheme can achieve the
theoretical channel limit, though
#12/43
Clocking: synchronous vs. asynchronous
a) Synchronous a common timing signal is established that
dictates when individual bits can be transmittedi. Separate clock signal
ii. Clocking is encoded into data
iii. Receiver‟s clock is synchronized to the data stream
All new high speed serial standards are synchronous, e.g. IEEE 1394 aka Firewire
b) Asynchronous uses none of the above methods i-iii)
sender and receiver agree on a common data rate
Simple HW, but lower bandwidth
#13/43
Synchronous serial IO – i)
Fig. 9.5 Wire delays
complicate the
sending of clk with
data
A B A B
clkclk
i) Separate clock wire is intuitive but its propagation delay must be matched that of
the data (complicated)
data data
#14/43
Synchronous serial IO – ii)
ii) Data strobe encoding Data line always contains the serial data, nothing
special here
Strobe encodes the clock, it has a pulse if data doesnot change -> Either Data or Strobe changes its logical value in one clock cycle, but never both
Fig. 9.5 Data strobe encoding
#15/43
Synchronous serial IO – iii)
iii) Synchronization Even clocks have the same f, they might be out of phase
as they are generated independently
PLL modifies receiver‟s clock to macth the sender‟s
a b the data line must have enough changes within a particular time interval (transition density)
Otherwise, PLL does not work
#16/43
Asynchronous serial IO
Does not transmit the clock on a separate wire
Does not guarantee a particular transition density
the data line could remain in the same state, either „1‟ or „0‟
for the duration of the transmission after the initial state
change indicating start of transmission
Separate start and stop bits are sent
They ”waste” bandwidth
Data is sent least significant bit (LSb) first
#17/43
Asynchronous serial IO (2)
Bit time denotes how long it takes to transfer one bit
Before transmission, the line is in the idle or mark
condition (logical ‟1‟)
Start is signalled by moving into space condition
(logical ‟0‟)
Transmission ends with at least one stop bit
Three common
formats:
#18/43
Parity bit
Parity bit is an extra bit added to a data frame to
detect a single bit error
One bit of the frame was received incorrectly (read as „0‟
when should have been „1‟, or vice-versa)
Not guaranteed to detect multi-bit errors
a) Odd parity – parity bit value makes the total number
of „1‟ bits in the frame odd
For 7-bit data value 0x56 (1010110), odd parity bit = „1‟
b) Even parity – parity bit value makes the total
number of „1‟ bits in the frame even
For 7-bit data value 0x56 (1010110), even parity bit = „0‟
Very simple to implement
#19/43
Parity bit (2)
Example of correct transfers (4 ‟1‟-bits)
Example of detection of single bit error
1 0
Aaargh! Mein Gott!
#20/43
Baud Rate vs Bits Per Second
Baud rate is the rate at which signaling events are sent
Bits per second (bps) is the number of bits transferred per second (any type of bits, data or overhead bits)
If only a „1‟ or „0‟ is sent for each signaling event, then baud rate = bps (typical case) However, could use a signaling protocol that transfers
multiple bits per signaling event–
e.g. 4 different voltage levels sends two bits per signaling event (”00” = -15v, ”01”= -5v, ”10”=+5v, “11” = +15v).
In this case, bit rate will be double the baud rate
The effective data rate is the rate at which data is transferred, minus the overhead bits (ie. start, stop,and parity bits) Could be also called payload data rate
#21/43
Receiver sampling
Used when receiver‟s frequency is high
Example shows receiver freq = 16x the baud rate
Usually integer multiple, 32x, 64x etc.
At start bit, internal 4-bit counter set to 0 (ratio is
16=24)
Sample always at mid-point of bit time for glitch
rejection
Some receivers sample at cycles 7,8 and 9 and only
accept bit if all values are the same
Serial data input
Receiver‟s clk
#22/43
Receiver sampling (2)
Receiver and transmitter sychronize at start bit
Receiver/Transmitter clocks not perfectly matched E.g. tx clk is few % faster
After long series of bits (frame), receiver may read wrong bit value Miss one or read one bit twice
In prev. example, tolerance is ½ bit time (50%, 8 cycles) spread over entire frame Assuming a 10 bit frame, maximum allowed
mismatch between Rx/Tx clocks is 50%/10 = 5%
#23/43
Example: SW-based asynch. serial data link
void putch (unsigned char c)
{
unsigned char i=0;
RB2 = 0; /* start bit*/
delay_1bit();
for(i=0,i<8;i++){
if (bittst(c,0)) {RB2=1;}
else { RB2=0;}
delay_1bit(),
c = c >> 1;
}
RB2=1; /* stop bit*/
delay_1bit();
}
unsigned char getch (void)
{
unsigned char i=0;
unsigned char c=0;
while(RB3){} /*wait start*/
delay_onehalf_bit();
for(i=0,i<8;i++){
delay_1bit();
if (RB3) {c = c | 0x80}
if (i !=7) {c = c >> 1}
}
delay_1bit(); /* discard stop bit */
return(c);
}
#24/43
Example: SW-based asynch. serial... (2)
Sender‟s putch() assumes that output RB2 is
already in idle state, i.e. ‟1‟
Then it sends, start bit, 8 data bits, and stop bit
Receiver‟s getch() waits for start bit, i.e. until RB3
goes low
Then it waits for the middle point bit time
After 1 bit time, it starts sampling
After 8 bits, wait that stop bit has gone but do not check
anything
Finally, 8-bit char is returned
Max. performance is limited by the accuracy of delay
functions
CPU is either transmitting or receiving - half-duplex
#25/43
Double buffering
Allows concurrent computation and communication
Allocate two buffers and simultaneously fill one with new data
process the data that already exists in the other buffer
Switch buffers when both operations completed
Buffer filling with DMA (direct-memory access) and ISR or ISR only
Use interrupt service routine to notice that a buffer has been filled
CPU Memory
data sourcenew data
buf0
buf1processed data
Universal
Synchronous/Asynchrono
us Receiver/Transmitter
(USART)
#27/43
Universal Synch/Asynch Rx/Tx (USART)
HW sub-system that implements serial data
communication
Handles start and stop bits and data serial-
parallel conversion for data
CPU can do processing at the same time
HW allows higher data rates than SW
Not available in all PICs
Controlled and monitored with special
function registers
UART module can handle async-only
communication
#28/43
USART registers
Data registers
Tx
rx
Control
tx
rx
baud rate
io pins
#29/43
USART transmitter
Control signals are bits from SFR TXSTAx
Sent data is placed into TXREG if it is empty (TXIF=‟1‟) Some processors have a FIFO instead of single data
register
Serial Port
sent data interrupt flag bit tx
completed interrupt enable
bit
transmit enable
9th data bit or
parity
TSR emptyserial port
enable (in RCSTATx)
enable 9th bit
sending
multipurpose
pin
#30/43
UASRT receiver
Control signals are bits of SFR RXSTATx
multipurpose
pin
serial port
enable
received data
(2-word FIFO)
framing error –
wrong stop bit
overrun error - FIFO and RSR
are full when new bits come
interrupt flag rx completed
continuous
reception enable
Select 8 or 9 bits
interrupt
enable
rx shift reg
#31/43
putch() + getch() with USART
putch() clears watchdog timer while waiting that tx
buffer becomes free
getch() checks rx interrupt flag to see if data is
available
clear watchdog similarly to putch()
Error checks are omitted...
Both functions actively poll the interrupt flags
#32/43
Baud rate generator
The BRG is a dedicated 8-bit or 16-bit clock generator
(counter)
supports both the Asynchronous and Synchronous modes
controlled with 8-bit SFR SPBRG
The SPBRGHx:SPBRGx register pair controls the
period of a free running timer
Then baud rate Rbaud = (9.2)
where f is the oscillator clk frequency
S is either 16 or 64 (high-speed, low-speed)
speed S is defined with bit BRGH, i.e. TXSTA[2]
SPBRG is counter‟s period (num of cycles)
f
(S * (SPBRG+1))
#33/43
Controlling baud rate
Given the desired baud rate and f, the nearest integer value for the period SPBRG can be calculated
Writing a new value to SPBRG causes the BRG timer to be
reset (or cleared)
This ensures the BRG does not wait for a timer overflow
before outputting the new baud rate.
From 9.2, period SPBRG= (9.3)
where denote rounding to nearest integer
Rounding causes error in actual baud rate!
Depends on the utilized frequency f
f
S * Rbaud
-1
#34/43
Controlling baud rate (2)
Frequency 29.4912 MHz is integer-multiple of
common baud rates
No rounding errors! (as if magic...)
RS-232
#36/43
RS-232
Recommended Standard 232 is a an EIA standard for serial binary data signals connecting between
1. DTE (Data Terminal Equipment) e.g. terminal software on PC
usually a male connector and
2. DCE (Data Circuit-terminating Equipment) e.g. modem or PIC
usually a female connector
PC‟s serial port
Full-duplex
#37/43
RS-232 (2)
Defines Electrical signal characteristics such as voltage levels,
signaling rate, timing, and maximum load capacitance.
Mechanical connectors and pin identification
Functions of each circuit in the interface connector
Standard subsets for selected telecom applications.
The standard does not define such elements as character encoding (ASCII, Baudot code or EBCDIC)
the framing of characters in the data stream (bits per character, start/stop bits, parity)
data compression or error detection protocols
bit rates for transmission
power supply to external devices
These are defined by the utilized UART device
#38/43
RS-232 (3)
Connector is either
a) 9-pin (DB9) as in personal
computers
b) 25-pin (DB25)
Connection is possible with only 2
or 3 pins also (TX/RX and GND)
Voltage levels
logical ‟0‟ is [3,15] Volts and
logical ‟1‟ is [-15, -3] Volts counter-
intuitively
Voltages near zero are not valid
devices must withstand short
circuit to ground or to voltages up
to +/-25 volts
Oscilloscope trace of voltage levels
for an uppercase ASCII "K"
character (0x4b) with 1 start bit, 8
data bits, 1 stop bit
#39/43
RS-232 – Voltage translation
Voltages levels are too high for most ICs
Convert to so called TTL (transistor-transistor logic)
levels
With a standard 5-volt power supply "low" means [0, 0.8]
Volts and "high" [2.2, 5] Volts
Separate IC
can do voltage
conversion
Note the
minimal 3-wire
connection in
fig
#40/43
RS-232 DB9 signals
Name Symbol DB-9
pin
Src
Common ground G 5 -
Transmitted Data TxD 3 DTE
Received Data RxD 2 DCE
Request To Send RTS 7 DTE
Clear To Send CTS 8 DCE
Data Terminal
Ready
DTR 4 DTE
Data Set Ready DSR 6 DCE
Carrier Detect DCD 1 DCE
Ring Indicator RI 9 DCE
DTE, i.e. PC DCE, i.e. modem
1
9
2
3
4
5
6
7
8
1
9
2
3
4
5
6
7
8
DCD
RxD
TxD
DTR
GND
DSR
RTS
CTS
RI
ha
nd-s
hake
PC (DTE) another PC (DTE)
1
9
2
3
4
5
6
7
8
1
9
2
3
4
5
6
7
8
”Null modem”
co
nn
ectio
n s
etu
pm
an
da
tory
Copyright Tampere University of Technology Department of Computer Systems
#41/43
RS-232 Flow Control (RTS/CTS)
RS-232 devices may have different capabilities to handle
the data
A flow control is needed: devices use two separate lines to
tell they ability to receive data
Request To Send (RTS) is risen when a device has something to
send (notify the slave)
Clear to send (CTS) is risen when the slave is ready to receive
Change in line during transimmission == stop the transmission
This example is for cases where the master implicates
transmission (other way round is also possible)
DTR/DSR are similar for the session of the PC-to-modem
communication (”keep alive the dial-up connection”),
CTS/RTS are used for data blocks
Copyright Tampere University of Technology Department of Computer Systems
#42/43
PC’s serial interface
Terminal program, such as HyperTerminal
Exercise platform is programmed via USB but printf() should be forwarded to PC‟s terminal via serial interface
Being superseded in personal computers by USB USB-to-serial adapters
are available for the newer PCs that omit serial port
Fig. HyperTerminal configuration and terminal window.
Copyright Tampere University of Technology Department of Computer Systems
#43/43
Serial port debugging
Most common mistakes is
swapping TX and RX pins or incorrectly identifying
them on DB9 conncetor
wrong baud rate
wrong settings for 7/8 bits, or stop and parity bits
signal levels: PIC [0,5] V vs. PC [-10, +10] V
no common ground potential
Book provides step-by-step debug
instructions
Copyright Tampere University of Technology Department of Computer Systems
#44/43
Conclusions
Basic properties of communication channels Simplex, half-duplex, duplex
Serial, parallel
Synchronous, asynchronous
Serial and parallel communication channels have different usage scenarios Both are commonly utilized in the same system
Parity bit provides simple single-bit error detection capability
USART HW can handle serial communication instead of CPU
Copyright Tampere University of Technology Department of Computer Systems