Microchip® Advanced Software Framework

 All Files Functions Typedefs Enumerations Enumerator Macros Groups
AVR libc setbaud utility example for the ATmega2560 Documentation

STK600 development board

Introduction

This example demonstrates how to use the avr libc utility setbaud to find the correct settings for the UART baudrate registers.

Files:

Brief description of the example application

This application will set up the UART according to the settings in the conf_uart.h file, baudrate is calculated using the avr libc setbaud utility. When initialization of the UART is done the application sends the letter 'A' on the UART and expect to receive the same letter, hence the hardware must be set up so that the TX and RX pin is shorted to create a loop back.

The util/setbaud tool is a tool offered by the avr libc library, and is a function for compile time calculation of the baudrate register of values. In application where run-time baudrate change is not needed this is a tool which easily calculates the best baudrate register settings while keeping the flash footprint at a minimum.

A common way of using the setbaud tool is:

// Define the CPU clock frequency, e.g. 1MHz
#define F_CPU 1000000UL
// Define the target baudrate, e.g. 9600bps
#define BAUD 9600
// Set the accepted tolerance, e.g. 2%
#define BAUD_TOL 2
// Load the calculated values into the correct registers
UBRR0H = UBRRH_VALUE;
UBRR0L = UBRRL_VALUE;
//Then we need to take into account that we may need to set the 2X bit in
//the UART control register to achieve the correct baudrate.
#ifdef USE_2X
UCSR0A |= (1 << U2X0);
#endif
// The last thing that needs to be done is to enable output on the TX pin,
// input on the RX pin and enable the RX and TX in the UART itself. In
// addition to setting the correct mode and bit length, parity and stop-bits.

Compilation Info

This software was written for the GNU GCC for AVR.
Other compilers may or may not work.

Contact Information

For further information, visit Microchip.