Embedded Freaks..

September 20, 2008

AVR UART Loopback Sample Code

Filed under: avr — Tags: — kunilkuda @ 2:32 pm

No matter how long have you been with AVR, UART loopback is always pop up every time you need to debug the UART problem.

Here is my favorite UART loopback code example:

/**
 * UART loopback code example
 * by : daniel 'kunilkuda' widyanto
 * - Tested using ATMega128L, 7.3728Mhz xtal
 */
#include <avr/io.h>

#define UART_BAUD_SELECT(baudRate, xtalCpu)   ((xtalCpu)/((baudRate)*16l)-1)
#define B57600 UART_BAUD_SELECT(57600, 7372800)

int main(void)
{
  // Set baud rate to 57600bps
  UBRR0H = (unsigned char) (B57600>>8);
  UBRR0L = (unsigned char) B57600;

  // Enable UART TX and RX
  UCSR0B = ( 1 << RXEN0 ) | ( 1 << TXEN0 );
  // 8-bit, No parity, 1-stop bit
  UCSR0C = ( 1 << USBS0 ) | ( 1 << UCSZ01 ) | ( 1 << UCSZ00 );

  while(1) {
    // Wait until we got some data
    while ((UCSR0A & (1 << RXC0)) == 0);

    // Read UART data
    uint8_t data = UDR0;

    // Send it back
    UDR0 = data;
  }
}

Enjoy your debugging !!

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: