syntax-highlighter

Sunday, July 15, 2012

Sample Code for atmega328p Serial Communication

Nothing special, just a bit of sample code for serial communications with the Atmega328p.  It took a bit of hunting to find code that worked properly on the 328.  The code is taken from https://sites.google.com/site/qeewiki/books/avr-guide/usart.  It worked for me with the Arduino serial console.



#include<avr/io.h>

#define USART_BAUDRATE 9600
#define BAUD_PRESCALE (((F_CPU/(USART_BAUDRATE*16UL)))-1)

int main(void){
 char recieved_byte;
 
 UCSR0B |= (1<<RXEN0)  | (1<<TXEN0);
 UCSR0C |= (1<<UCSZ00) | (1<<UCSZ01);
 UBRR0H  = (BAUD_PRESCALE >> 8);
 UBRR0L  = BAUD_PRESCALE;
 
    for(;;){
  // wait until a byte is ready to read
  while( ( UCSR0A & ( 1 << RXC0 ) ) == 0 ){}

  // grab the byte from the serial port
  recieved_byte = UDR0;
  
  // wait until the port is ready to be written to
  while( ( UCSR0A & ( 1 << UDRE0 ) ) == 0 ){}

  // write the byte to the serial port
  UDR0 = recieved_byte;
    }
    return 0;   /* never reached */
}

Makefile settings for this code were the following, uses a 16MHz external crystal:

DEVICE     = atmega328p
CLOCK      = 16000000
PROGRAMMER = -c dragon_isp -P usb
OBJECTS    = main.o
FUSES      = -U hfuse:w:0xd2:m -U lfuse:w:0xff:m

4 comments:

Anonymous said...

Thanks for posting this! The site you referenced was very helpful for understanding the concepts behind some of my homework! And the code does just what I was hoping it would!

James Gregson said...

My pleasure, I'm glad it was helpful!

Unknown said...

Create a program that increments the value of r16 rvry 300ms. use a clock frequency of 1Mhz .

do you have any coding or program regarding this problem? were using AVR studio v4.
thank you so much.

Anonymous said...

Hey this is just what i was searching for. thanks! regards from Colombia :D