Friday, March 9, 2012

Transmit String Through UART

In this tutorial i am going to show you how to transmit a string through UART. For that you first have to initialize the UART circuitry in your micro-controller. For initializing we have to update UART registers in AVR. There are basically 5 registers for UART in AVR....

1. UBRR register for setting up the baud rate for the transmission. Its a 16 bit value and the AVR is an 8 bit micro-controller, so this 16 bit value is stored in two 8 bit registers (UBRRnL and UBRRnH)
2 And 3 control registers (UCSRnA, UCSRnB and UCSRnC).
3. ATmega 128 is having 2 UART ciruitry (UART0 and UART1) and for each circuitry we are having different registers, for ex: UBRR1L for UART1 and UBRR0L for UART0.

(these codes have been written for ATmega128 micro-controller which has two UART circuitry, UART0 & UART1, the same code can be used with other AVR micro-controllers with some minor changes)

#include <avr/io.h>

void UART1_Init()

{
//set baud rate = 9600 bps
UBRR1H = 0x00;
UBRR1L = 103;        //0x67

//set 1 stop bit, no parity bit and 8 bit charachter size
UCSR1C = 0x06;         //(1<<UCSZ1)|(1<<UCSZ0)

//enable transmission and reception
UCSR1B = 0x18;         //(1<<RXEN)|(1<<TXEN)
}

void main()
{
int i=0;

//define the string to be transmitted
char string[] = "MoMos lOveRs";

while(string[i] != '\0')

{
//transmit the string by putting characters into UDR one by one
UDR1 = string[i++];

//wait until UDR is empty to take new byte
while(!(UCSR1A & (1<<UDRE)));
}

//send the NULL character
UDR1 = '\0';

//wait until UDR is empty to take new byte
while(!(UCSR1A & (1<<UDRE)));
}

3 comments:

Filip said...

Dear friend, this doesn't work for me!
I'm using uart<>uart atmega8 communication.. :(

Ashish Gaur said...

Dear fbonacic, this program is written for ATmega 64/128. If you want to use UART with ATmega 8 then you will have make some changes.....like UDR1 must be UDR only.....check out the datasheet for ATmega 8 under UART topic, you will get to know

Filip said...

I found mistake, this code is not sending the NULL character at the end! ;)

Post a Comment

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews