Example1: Calculate the UBR value for 9600 Baud with a 4MHz crystal.
Solution:
UBR = ( 4E6 / (9600 * 16) ) - 1
UBR = ( 4,000,000 / 153,600) - 1
UBR = 26.041 - 1
UBR = 25.041
Now What?
Truncate the answer down to 25 and use this value for UBR.
UBRR = 25; // sets baud rate to 9600 with a 4MHz clock
*Since the answer to the equation is less than 255, the value of UBRRHI is zero.
UBRRHI = 0;
Example2: Have the compiler calculate the UBR value for 9600 Baud with a 4MHz crystal.
Solution:
#define XTAL 4000000L
#define BAUD 9600
unsigned int UBR;
UBR = XTAL / 16 / BAUD - 1;
UBRR = UBR & 0xFF;
UBRRHI = UBR >> 8;