In AVR, following set of registers are used to communicate over USART

  • UCSRA
  • UCSRB
  • UCSRC
  • UBRRH
  • UBRRL

UCSRA: in this register there are flags for various errors that might occur during data transmission, e.g. parity error, frame error etc.

UCSRB: in this register we have a lot of enable bits. For example different interrupt enable bits but also the receiving and transmitting enable bits.

UCSRC: in this register we set the parity mode, stop bits and so on.

UBRRH & UBRRL: in UBRRH register, the higher byte and in UBRRL, lower byte is stored for generating a required Baud rate.

More information on the above registers can be found in the datasheet of the AVR you are using.

.include \"m8515def.inc\"
.def reg1 = r16
.def reg2 = r17
Serial_Init:
	;Load UBRRH with 0 and UBRRL with 25
	;to set a baud rate of 9600 at 4MHz
	ldi reg1,00
	out UBRRH,reg1
	ldi reg2,25
	out UBRRL,reg1
	;Clear all error flags
	ldi reg1,00
	out UCSRA,reg1
	;Enable Transmission and Reception
	ldi reg1,(1<<RXEN)+(1<<TXEN)
	out UCSRB,reg1
	;Set Frame format
	;8,N,1
	ldi reg1,(1<<URSEL)|(3<<UCSZ0)
	out UCSRC,reg1
	ret

Intialization in C is bit straight forward as we say...

#include <avr/io.h>.
void serial_init(){
	UCSRA=0x00;
	UCSRB=0x18;
	UCSRC=0x86;
	UBRRH=0x00;
	UBRRL=0x19;
}

To transmit data serial we need to put the data to send in 8-bit UDR (UART Data Register) and poll the empty transmit buffer to set. While receiving data we wait for the receive flag, when its set the data recieved can be read from the UDR register. Here is an example to implement this in assembly:

Serial_Send:
	;wait for empty transmit buffer flag
	sbis UCSRA, UDRE
	rjmp Serial_Send
	;If the flag is set
	;Then move the data to send in UDR
	out UDR,reg2
	ret
	
Serial_Read:
	;Wait for Receive flag
	sbis UCSRA,RXC
	rjmp Serial_Read
	;If falg is set
	;Then read data from UDR
	in reg2,UDR
	ret

Similarly in C:

void serial_send(unsigned char dat){
	while(!(UCSRA & (1<<UDRE)));
	UDR = dat;
}
unsigned char serial_read(){
	while(!(UCSRA & (1<<RXC)));
	return UDR;
}

See Also

Help & Queries

If you have any queries, doubts or feedback on this tutorial please share in our discussion forum.

Powered by MediaWiki
This page was last modified on 6 March 2015, at 18:57.
ArrayContent is available under Creative Commons Attribution Non-Commercial Share Alike unless otherwise noted.