Code UART for Arduino Serial Communication with Atmel Studio 7

It just a bit of sample code for serial communications with the Arduino UNO R3 (Atmega328p). It took a bit of hours to find code that worked properly on our Arduino. Original code is taken from https://sites.google.com/site/qeewiki/books/avr-guide/usart. And this code working for me😀

/*
 * serialUart328p.c
 *
 * Created: 01/08/2016 13.39.51
 * Author : SDP
 */ 

#include<avr/io.h>
#define USART_BAUDRATE 9600
#define F_CPU 16000000UL 
#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 */
}

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s