Lecture 3’s sequence
3.1 Serial communica on ─ The basics
3.2 Serial communication in ATmega16
Review of C Programming
3.3 Example application & Debugging tool
Serial communica on─ The basics
Computers transfer data in two ways: parallel and serial:
Parallel: Several data bits are transferred simultaneously, e.g., to printers and hard disks
Serial: A single data bit is transferred at one time
Advantages of serial communication: longer distances, easier to synchronize, fewer IO
pins, and lower cost.
Serial communication often requires:
Shift registers: convert a byte to serial bits and vice versa
Modems: modulate/demodulate serial bits to/from audio tones
Synchronous versus asynchronous
Synchronous serial communication:
The clocks of the sender and receiver are synchronized
A block of characters, enclosed by synchronizing bytes, is sent at a time
Faster transfer and less overhead
Examples: serial peripheral interface (SPI) by Motorola, binary synchronous communication
(BISYNC) by IBM.
Asynchronous serial communication:
The clocks of the sender and receiver are not synchronized
One character (usually 8 bits) is sent at a time, enclosed between a start bit and one or two
stop bits. A parity bit may be included
Examples: RS-232 by Electronic Industries Alliance, USART of ATmega16
Data framing examples
BISYNC Control Characters
Data Framing in Synchronous BISYNC
SYN (16h): synchronization
SYN SYN STX DATA FIELD ETX BCC PAD STX (02h): start of text
ETX (03h): end of text
BCC: block checksum char
PAD (FFh): end of frame block
Data Framing in Asynchronous Transmission parity bit
1 0 0 0 0 0 1 0 0
Receiver
start bit (0) LSB MSB stop bits (1)
Sending character “A” (41h = 0100 0001)
8-bit data, 1 start bit, 2 stop bits, even-parity
Serial communication terminology
Baud rate: The number of bits sent per second (bps). Strictly speaking, it is the
number of signal changes per second.
Parity bit: A single bit for error checking, sent with data bits to make the total
number of 1’s.
even (for even parity), or
odd (for odd parity)
Start bit: to indicate the start of a character. Its typical value is 0
Stop bit: to indicate the end of a character. Its typical value is 1
RS-232 standard
The RS-232 (latest revision RS-232E) is a widely used standard for serial
interfacing.
It covers four main aspects:
Electrical: voltage level, rise and fall time, data rate, distance
Functional: function of each signal
Mechanical: number of pins, shape & dimension of connectors
Procedural: sequence of events for transmitting data
RS-232 standard
It defines 25-pin D connectors, but 9-pin connectors are often used.
RS-232 specifies the baud rate up to 20Kbps, and the cable length up to 15m.
In practice, it supports up to 56Kbps & 30m of shielded cables.
Male DB9 connector Female DB9 connector
RS-232 standard
Pin Name Description Data Terminal Equipment (DTE)
essentially refers to the computer.
1 CD Carrier Detect DCE has detected a carrier tone
2 RXD Received Data Incoming data from DCE
Data Communication Equipment
(DCE) essentially refers to a remote
3 TXD Transmit Data Outgoing data to DCE device or modem.
4 DTR Data Terminal Ready DTE is connected and turned on
These terms are needed to explain
5 GND Ground the pin functions.
6 DSR Data Set Ready DCE is connected and turned on
7 RTS Request To Send DTE has data to send
8 CTS Clear To Send DCE can receive data
9 RI Ring Indicator Synchronized with the phone’s ringing tone
Modem connection
Computer A Modem A Modem B Computer A
DTE DCE DCE DTE
RS-2322 was originally used with modems to connect two PCs over the public phone lines
When Computer A has data to send, it assert its RTS pin
Modem A will assert its CTS when it is ready to receive
Computer A transmits data through its TXD
Null-modem connection
Full handshaking cable Simple cable
RS-232 is now mainly used to connect a microcontroller with PC or peripheral devices (e.g.,
GPS receiver, infrared range finder, camera).
This configuration is known as null-modem:
Connect pin TXD of a DTE with pin RXD of the other DTE
Wire other pins to support flow control
RS-232 interface and MAX232 chip
Compared to TTL in computer
Logic RS-232 levels TTL levels
electronics, RS-232 interface uses
1 [-12V, -3V] [+2V, +5V]
different voltage levels
0 [+3V, +12V] [0V, +0.8V]
A level converter is required
between RS-232 interface and
TXD/RXD pins of microcontroller
MAX232 chip is often used for
this purpose
Lecture 3’s sequence
3.1 Serial communica on ─ The basics
3.2 Serial communication in ATmega16
Review of C Programming
3.3 Example application & Debugging tool
Serial communication in ATmega16
ATmega16 has 3 subsystems for serial communication:
Universal Synchronous & Asynchronous Receiver & Transmitter (USART)
Serial Peripheral Interface (SPI)
Two-wire Serial Interface (TWI)
USART:
We focus on this subsystem in this lecture
Supports full-duplex mode between two devices
Typically used in asynchronous communication
Start bit and stop bit are used for each byte of data
Serial communication in ATmega16
Serial Peripheral Interface (SPI):
The receiver and transmitter share a common clock line
The transmitter is treated as the master, the receiver as the slave
SPI supports higher data rates
Examples: liquid crystal display, high-speed ADC
Two-wire Serial Interface (TWI):
For connecting several devices, e.g., microcontrollers and display boards, using a two-wire bus
Each device has a unique address and can exchange data with other devices in a small network
Up to 128 devices are supported
Serial USART ─ An overview
USART of the ATmega16 supports:
baud rates from 960bps to 57.6kbps
character size: 5 to 9 bits
1 start bit
1 or 2 stop bits
optional parity bit (even or odd parity)
Common baud rates are 19200, 9600,
4800, 2400, and 1200 bps
Serial USART ─ An overview
c) Register UBRR
to set baud rate
d) Register UDR to store a) TxD and RxD pins
the sent/received byte to another device
b) Registers to configure/
monitor USART
Serial USART ─ Hardware elements
USART Clock Generator:
to provide clock source
to set baud rate using UBRR register
USART Transmitter:
to send a character through TxD pin
to handle start/stop bit framing, parity bit, shift register
USART Receiver:
to receive a character through RxD pin
to perform the reverse operation of the transmitter
USART Registers:
to configure, control and monitor the serial USART
Serial USART ─ Three groups of registers
USART Baud Rate Registers:
UBRRH and UBRRL
USART Control and Status Registers:
UCSRA
UCSRB
UCSRC
USART Data Registers:
UDR
Understanding these registers is essential in using the serial port. Therefore, we’ll
study these registers in depth.
USART Baud Rate Registers : UBRR
Two 8-bit registers together define the baud rate:
( )
=
( + )
( )
⇒ = −
Example: Find UBRR registers for baud rate of 1200 bps assuming system clock is 1MHz:
UBRR = 1000000/(16 × 1200) ─ 1 = 51d = 0033H
Therefore, UBRRH = 00H and UBRRL = 33H
C code: UBRRH = 0x00; UBRRL = 0x33;
USART Control and Status Register A: UCSRA
7 6 5 4 3 2 1 0
RXC TXC UDRE FE DOR PE U2X MPCM
1 to enable multi-processor com mode
1 to double the transmission speed
1 when there is Parity Error
1 when there is Data Over Run
1 when there is Frame Error
1 when USART Data Register is Empty
1 when no new data in transmit buffer (TX Complete)
1 when receive buffer has unread data (RX Complete)
USART Control and Status Register B: UCSRB
7 6 5 4 3 2 1 0
RXCIE TXCIE UDRIE RXEN TXEN UCSZ2 RXB8 TXB8
Tx extra data bit for 9-bit character size
Rx extra data bit for 9-bit character size
bit UCSZ2 to decide character size
1 to enable USART transmitter: Pin D.1 = TXD pin
1 to enable USART receiver: Pin D 0 = RXD pin
1 to enable USART Data Register Empty Interrupt
1 to enable TX Complete Interrupt, valid only if Global Interrupt Flag = 1 and TXC = 1
1 to enable RX Complete Interrupt, valid only if Global Interrupt Flag = 1 and RXC = 1
USART Control and Status Register C: UCSRC
7 6 5 4 3 2 1 0
URSEL UMSEL UPM1 UPM0 USBS UCSZ1 UCSZ0 UCPOL
Clock polarity, used with synchronous
Used with UCSZ2 to select character size
To select stop bit modes: 0 -> 1 stop bit, 1 -> 2 stop bits
To select parity mode: 00 no parity, 10 - even party, 11 - odd parity
To select USART modes: 0 - asynchronous, 1 - synchronous
Must be set to 1 to write to UCSRC. (Note: UCSRC and UBRRH share same location)
Setting character size
Character size (5 to 9) is determined by three bits: UCSZ2, UCSZ1, UCSZ0
RXCIE TXCIE UDRIE RXEN TXEN UCSZ2 RXB8 TXB8 UCSRB
URSEL UMSEL UPM1 UPM0 USBS UCSZ1 UCSZ0 UCPOL UCSRC
UCSZ2 UCSZ1 UCSZ0 Character Size
0 0 0 5-bit
0 0 1 6-bit
0 1 0 7-bit
0 1 1 8-bit
1 0 0 Reserved
1 0 1 Reserved
1 1 0 Reserved
1 1 1 9-bit
USART Data Register : UDR
Register UDR is the buffer for characters sent or received through the serial port.
To start sending a character, we write it to UDR:
UDR = 'a'; // start sending character ‘a’
To process a received character, we read it from UDR:
unsigned char data;
data = UDR; // this read will clear UDR
Serial USART ─ Main tasks
There are 4 main tasks in using the serial port:
Initializing the serial port
Sending a character
Receiving a character
Sending/receiving a formatted string
Initializing serial port
begin
Set USART for asynchronous mode
Set USART communication parameters
(data bits, stop bit, parity bit)
Set baud rate
Enable transmitter and receiver
end
Ini alizing serial port ─ Example
Initialize serial port of ATmega16 to baud rate 1200 bps, no parity, 1 stop bit 8
data bits. Assume a clock speed of 1MHz.
void USART_init(void) {
// Asynchronous mode, no parity, 1 stop bit, 8 data bits
UCSRC = 0b10000110;
// Normal speed, disable multi-proc
UCSRA = 0b00000000;
// Baud rate 1200bps, assuming 1MHz clock
UBRRL = 0x33;
UBRRH = 0x00;
// Enable Tx and Rx, disable interrupts
UCSRB = 0b00011000;
}
Sending a character
begin
No Has UDRE flag been set to 1?
(register UCSRA)
Yes
Write the character to register
UDR for transmission
end
Sending a character ─ Example
Write a C function to send a character through ATmega16 serial port.
void USART_send(unsigned char data) {
// Wait until UDRE flag = 1
while ((UCSRA & (1<<UDRE)) == 0x00){;}
// Write char to UDR for transmission
UDR = data;
}
UCSRA RXC TXC UDRE PE DOR PE U2X MPCM
Constant UDRE is defined in avr/io.h
1<<UDRE 0 0 1 0 0 0 0 0
#define UDRE 5
Bit-wise AND returns zero if bit
bit-wise AND 0 0 UDRE 0 0 0 0 0 at position UDRE is 0
Receiving a character
begin
No Has RXC flag been set to 1?
(register UCSRA)
Yes
Read the received character
from register UDR
end
Receiving a character ─ Example
Write a C function to receive a character via ATmega16 serial port.
unsigned char USART_receive(void) {
// Wait until RXC flag = 1
while ((UCSRA & (1<<RXC)) == 0x00) {;}
// Read the received char from UDR
return (UDR);
}
UCSRA RXC TXC UDRE PE DOR PE U2X MPCM
Constant RXC is defined in avr/io.h
1<<RXC 1 0 0 0 0 0 0 0
#define RXC 7
Bit-wise AND returns zero if bit at
bit-wise AND RXC 0 0 0 0 0 0 0
position RXC is 0
Sending/receiving a formatted string
In ANSI C, the header file <stdio.h> has two functions for formatted strings:
printf and scanf.
Function printf sends a formatted string to the standard output device, which is
usually the video display.
first = 2, second = 3, sum = 5
unsigned char a, b;
a = 2; b = 3;
printf("first = %d, second = %d, sum = %d", a, b, a + b);
Function scanf reads a formatted string from the standard input device, which is
usually the keyboard.
unsigned char a, b;
scanf("%d %d", &a, &b); // get integers a, b from input string
Sending/receiving a formatted strings
Being able to send/receive formatted strings through a serial port is useful in
microcontroller applications.
To this end, we configure the serial port as the standard input and output
devices.
General steps:
1) Write two functions to send and receive a character via serial port.
2) In main(), call fdevopen() to set the two functions as the handlers for standard output
and input devices.
3) Use printf/scanf as usual. Formatted strings will be sent/received via serial port.
Sending/receiving a forma ed strings ─ Example
#include <avr/io.h>
#include <stdio.h>
int serial_send(char c, FILE *stream) {
// wait until UDRE flag is set to logic 1
while ((UCSRA & (1<<UDRE)) == 0x00){;}
UDR = c; // Write character to UDR for transmission
}
int serial_receive(FILE *stream) {
// wait until RXC flag is set to logic 1
while ((UCSRA & (1<<RXC)) == 0x00) {;}
return (UDR); // Read the received character from UDR
}
int main(void) {
unsigned char a;
// ... Code to initialize baud rate, TXD, RXD, and so on is not shown here
// Initialize the standard IO handlers
stdout = fdevopen(serial_send, NULL);
stdin = fdevopen(NULL, serial_receive);
// Start using printf, scanf as usual
while (1) {
printf("\n\rEnter a = ");
scanf("%d", &a); printf("%d", a);
}
}
Sending/receiving a forma ed strings ─ Example
Lecture 3’s sequence
3.1 Serial communica on ─ The basics
3.2 Serial communication in ATmega16
Review of C Programming
3.3 Example application & Debugging tool
Lecture 3’s references
M. Mazidi, J. Mazidi, R. McKinlay, “The 8051 microcontroller and embedded systems
using assembly and C,” 2nd ed., Pearson Prentice Hall, 2006, [Chapters 10]
M. Mazidi and J. Mazidi, “The 8086 IBM PC and compatible computers,” 4th ed.,
Pearson Prentice Hall, 2003, [Chapters 17]
P. Spasov, “Microcontroller technology the 68HC11,” 3rd ed., Prentice Hall 1999,
[Chapters 10]
H Huang . Huang, “MC68HC12 an introduction: software and hardware interfacing,”
Thomson Delmar Learning, 2003, [Chapter 9]