0
0
Embedded Cprogramming~5 mins

Baud rate configuration in Embedded C

Choose your learning style9 modes available
Introduction
Baud rate configuration sets how fast data is sent or received over serial communication. It helps devices talk to each other at the same speed.
When setting up communication between a microcontroller and a computer.
When connecting two devices using UART (Universal Asynchronous Receiver/Transmitter).
When you want to change the speed of data transfer in a serial port.
When debugging serial communication to match the device's speed.
When initializing serial communication in embedded projects.
Syntax
Embedded C
void UART_Init(unsigned int baudrate) {
    unsigned int ubrr_value = (F_CPU / (16UL * baudrate)) - 1;
    UBRR0H = (unsigned char)(ubrr_value >> 8);
    UBRR0L = (unsigned char)ubrr_value;
    UCSR0B = (1 << RXEN0) | (1 << TXEN0);  // Enable receiver and transmitter
    UCSR0C = (1 << UCSZ01) | (1 << UCSZ00); // Set frame format: 8 data bits, 1 stop bit
}
F_CPU is the clock frequency of the microcontroller (e.g., 16 MHz).
UBRR0H and UBRR0L set the baud rate registers for UART.
UCSR0B and UCSR0C are control registers to enable UART and set data format.
Examples
Initialize UART communication at 9600 baud rate.
Embedded C
UART_Init(9600);
Initialize UART communication at 115200 baud rate for faster data transfer.
Embedded C
UART_Init(115200);
Sample Program
This program sets up UART communication at 9600 baud rate on an AVR microcontroller running at 16 MHz clock.
Embedded C
#include <avr/io.h>
#define F_CPU 16000000UL

void UART_Init(unsigned int baudrate) {
    unsigned int ubrr_value = (F_CPU / (16UL * baudrate)) - 1;
    UBRR0H = (unsigned char)(ubrr_value >> 8);
    UBRR0L = (unsigned char)ubrr_value;
    UCSR0B = (1 << RXEN0) | (1 << TXEN0);  // Enable receiver and transmitter
    UCSR0C = (1 << UCSZ01) | (1 << UCSZ00); // 8 data bits, 1 stop bit
}

int main(void) {
    UART_Init(9600);
    while (1) {
        // Main loop
    }
    return 0;
}
OutputSuccess
Important Notes
Make sure the baud rate matches on both communicating devices to avoid errors.
The formula for UBRR value depends on the microcontroller clock and desired baud rate.
Always enable the UART transmitter and receiver after setting baud rate.
Summary
Baud rate controls the speed of serial communication.
Set baud rate by calculating and loading the correct register values.
Enable UART transmitter and receiver to start communication.