Calculate Baud Rate for UART in Embedded C: Simple Guide
To calculate the UART baud rate in Embedded C, use the formula
UBRR = (F_CPU / (16 * baud)) - 1, where F_CPU is the CPU clock frequency and baud is the desired baud rate. Set the UART baud rate register with this value to configure communication speed.Syntax
The baud rate register value is calculated using the formula:
- UBRR: UART Baud Rate Register value to set
- F_CPU: CPU clock frequency in Hertz
- baud: Desired baud rate (bits per second)
Formula: UBRR = (F_CPU / (16 * baud)) - 1
This formula assumes UART is in asynchronous normal mode with 16x oversampling.
c
unsigned int calculate_ubrr(unsigned long F_CPU, unsigned long baud) { return (F_CPU / (16UL * baud)) - 1; }
Example
This example shows how to calculate and set the baud rate register for 9600 baud with a 16 MHz CPU clock on an AVR microcontroller.
c
#include <avr/io.h> #define F_CPU 16000000UL #define BAUD 9600 unsigned int calculate_ubrr(unsigned long F_CPU, unsigned long baud) { return (F_CPU / (16UL * baud)) - 1; } int main(void) { unsigned int ubrr_value = calculate_ubrr(F_CPU, BAUD); UBRR0H = (unsigned char)(ubrr_value >> 8); // Set high byte UBRR0L = (unsigned char)ubrr_value; // Set low byte UCSR0B = (1 << RXEN0) | (1 << TXEN0); // Enable receiver and transmitter UCSR0C = (1 << UCSZ01) | (1 << UCSZ00); // Set frame format: 8 data bits, 1 stop bit while (1) { // Main loop } return 0; }
Common Pitfalls
- Wrong clock frequency: Using incorrect
F_CPUvalue leads to wrong baud rate. - Integer division: Make sure to use unsigned long for calculations to avoid truncation errors.
- Wrong UART mode: The formula applies to asynchronous normal mode; other modes need different formulas.
- Off-by-one errors: Forgetting the
-1in the formula causes incorrect baud rate.
c
/* Wrong way: missing -1 and integer division issues */ unsigned int wrong_ubrr = F_CPU / (16UL * BAUD); /* Correct way: use unsigned long and subtract 1 */ unsigned int correct_ubrr = (F_CPU / (16UL * BAUD)) - 1;
Quick Reference
Remember these key points when calculating UART baud rate:
- Use
UBRR = (F_CPU / (16 * baud)) - 1for asynchronous normal mode. - Ensure
F_CPUmatches your microcontroller clock. - Use unsigned long for intermediate calculations.
- Set UART registers correctly after calculation.
Key Takeaways
Calculate UART baud rate register using UBRR = (F_CPU / (16 * baud)) - 1 formula.
Always use the correct CPU clock frequency (F_CPU) for accurate baud rate.
Use unsigned long type to avoid integer division errors in calculations.
The formula applies to asynchronous normal UART mode with 16x oversampling.
Set UART registers properly after calculating UBRR to enable communication.