AVR Serial Port Programming
AVR Serial Port Programming
Systems
Lecture 0801
1
UART Registers in AVR
Data Send/Receive register
UDR
Baud Rate Control register
UBRR
Control and Status register
UCSRA, UCSRB, and UCSRC
2
Data Transfer Rate
The rate of data transfer in serial data communication is
stated in bps (bits per second), which is also called baud
rate.
3
UBRR Register and Baud Rate in AVR
The Baud rate of AVR microcontroller is
programmable that can be set with the
help of register UBRR
4
UBRR Register and Baud Rate in AVR
System
clock
UART
baud rate
5
UBRR Register (16-Bit Register)
6
Data Register (UDR)
In AVR, There are 2 shift registers that have directly connected buffers TXB and
RXB. When we write data to UDR, it is transferred to TXB buffer register and
when read data from UDR, it will return the contents of RXB buffer register
7
UCSR (USART Control and Status) Registers
UCSRA Register
8
UCSR (USART Control and Status) Registers
UCSRB Register
one.
TXEN (Bit 3): Transmit Enable
To enable the USART transmitter you should set this bit
to one.
UCSZ2 (Bit 2): Character Size
This bit combined with the UCSZ1:0 bits in UCSRC sets the
9
UCSR (USART Control and Status) Registers
UCSRC Register
10
Programming AVR to Transfer Data Serially
1. Load UCSRB register with value 08H.
(Enabling the USART Transmitter, TXEN)
2. Load UCSRC register with value 06H.
(Indicating 8-bit data frame, no parity and 1 stop bit)
3. Load UBRR register with value of baud rate.
11
Write a C program for AVR to transfer character ‘G’ continuously at
9600 baud rate. Use 8-bit data and 1 stop bit. XTAL = 8MHz
#include <avr/io.h>
#include <avr/io.h> void usart_init (void)
int main (void) {
UCSRB = 0x08;
{ UCSRC = 0x06;
UCSRB = 0x08; UBRRL = 0x33;
}
UCSRC = 0x06;
UBRRL = 0x33; void usart_send (unsigned char ch)
{
UDR = ch;
while(1) while ((UCSRA & (0x40)) == 0);
{ }
UDR = 'G’; int main (void)
while ((UCSRA & (0x40)) == 0); {
} usart_init();
return 0; while(1)
} usart_send ('G’);
return 0;
}
12 12
Problem
Write a program for AVR to transfer message ‘Hello
World’ to serial port continuously at 9600 baud
rate. Use 8-bit data and 1 stop bit. XTAL = 8MHz
13 13
Programming AVR to Receive Data Serially
1. Load UCSRB register with value 10H.
(Enabling the USART Receiver, RXEN)
2. Load UCSRC register with value 06H.
(Indicating 8-bit data frame, no parity and 1 stop bit)
3. Load UBRR register with value of baud rate.
14
Write program to receive bytes of data serially and puts them
on Port B. Set 9600 baud rate, 8-bit data and 1 stop bit
#include <avr/io.h>
int main (void)
{
DDRB = 0xFF; //Port B is output
UCSRB = 0x10; //initialize USART0
UCSRC = 0x06;
UBRRL = 103;
while(1)
{
while ((UCSRA & (0x80)) == 0); //wait until new data
PORTB = UDR;
}
return 0;
}
15 15