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  It worked for me with the Arduino serial console.


#define USART_BAUDRATE 9600

int main(void){
 char recieved_byte;
 UCSR0B |= (1<<RXEN0)  | (1<<TXEN0);
 UCSR0C |= (1<<UCSZ00) | (1<<UCSZ01);
  // 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


nopantstuesday 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!

elvi esclamado 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.

Cindy Dy said...

Hey there! Someone in my Myspace group shared this website with us so I came to check it out.I’m definitely loving the information. I’m book-marking and will be tweeting this to my followers!Terrific blog and fantastic design and style.


Silvia Jacinto said...

As a person you should know what are your priorities and goals so that it is easier for you to determine and decide when is the time to give up or go on.
Thanks for sharing such a wonderful article, I hope you could inspire more people. Visit my site for an offer you wouldn't want to refuse.

Carlos Andres Galvez said...

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