Understanding the USART Baud Rate Macro

Last modified by Microchip on 2023/11/10 11:09

In this video:

  • Baud rate equations to set the USART Baud Rate Register (UBRRn), based on a required baud rate and CPU frequency.
  • Tables of UBRRn settings for different CPU frequencies.
  • How to debug in order to check that the macro used to set UBRRn matches the recommendation in the tables.

In the previous lesson, we set up a simple USART loopback where the ATmega328PB could communicate with a Terminal program.  One of the things that helped us set this up efficiently is the baud rate macro.  Here, we will take a little closer look at what this macro was doing for us.

Here is the macro...

#define F_CPU 16000000UL // Clock Speed
#define BAUD 9600
#define UBRR_VALUE ((F_CPU / (BAUD * 16UL)) - 1)

Referring back to the datasheet we see the equation for calculating the UBRRn value.

UBRRn Equation

If you enter the following values...

  • BAUD = 9600
  • Fosc = 16000000

UBRRn will evaluate to 103.

Follow the procedure below for another method

Procedure

Select Baud Rate and CPU Speed

We have selected 9600 baud and are running our CPU at Fosc = 16MHz


UBRRn settings

We look these values up in the UBRRn settings table to find the value that should be written to the UBBRn= register.

UBRR Settings Table
 


Write Values to UBBR0H and UBBR0L

Write these values to the UBBR0H and UBBR0L with the following code...

UBRR0H = (unsigned char)(103 >> 8);
UBRR0L = (unsigned char) 103;

Previous Lesson:

Using the USART to Loopback from a Serial Terminal

Next Video:

Using an App Note to Implement IRQ Based USART Communications