Question

I have found this part of code on the Internet, on how to initialise USART on atmega32. It works fine for my application but I want to understand it better.

void USART_initial (void){
#define BAUD 9600 // We set the desired baud rate( here we set it at 9600bps)
#include <util/setbaud.h>  // 
UBRRH = UBRRH_VALUE;
UBRRL = UBRRL_VALUE;
#if USE_2X
UCSRA |= (1 << U2X);
#else
UCSRA &= ~(1 << U2X);
#endif

UCSRB = (1<<RXEN)|(1<<TXEN); // Enable transmitter/receiver.
UCSRC = (1<<URSEL)|(1<<UCSZ0)|(1<<UCSZ1); // Character size : 8 bit

My question is what is the exact use of UBRRH and UBRRL registers, and why do I need to use them?

Thank you very much in advance

Was it helpful?

Solution

The UART needs a clock signal that determines the baud rate. It is generated in the chip by dividing the CPU clock frequency by the UBRR register value. It must be 16x higher than the desired baud rate. The x16 factor is used by the UART to sub-sample the received serial data, it improves noise immunity by calculating the received bit value from the average of 16 samples.

So if the desired baudrate is 9600 baud and the CPU clock is 16 MHz then UBBR is (16000000 / (16 x 9600)) - 1 = 103.167. Round that to the closest integer = 103. Which makes UBRRL = 0x67, UBRRH = 0x00. You should see this calculation being made in the util/setbaud.h source file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top