Serial port communication using AVR

11 Oct 2013

Serial port communication is pretty much useful and also simple to carry out. There are certain thing you need to get first.1. A microcontroller (Here Atmega328p).2. A USB2serial converter.3. A terminal software.Modern computers won’t have this rs232 serial ports. So there is no use to go for an rs232 module and get started. Only option left is to communicate through USB ports. Many microcontrollers lack USB support. So there is an easy way. Buy a USB2serial converter or use an old Nokia 1200 or 1680 USB data cable. It has a serial to USB converter. It costs only around 60Rs(India). These are old handsets.


If you ain’t find this one, go to eBay and buy this USB To RS232 TTL Converter Adapter Module PL2303HX( Link here). You have to pay around 200 RS for this one.Let’s get started.Find the TX pin from datasheet. For Atmega328 it’s pin no: 3. Connect it to RX pin of the USB2serial converter. Then use the given code for sending the word “HELLO” to PC.Use a terminal to view the output. You can use putty (link here) or HyperTerminal. Putty is free and open source. It’s available for Linux and Windows. HyperTerminal is preinstalled with windows. You can download it for WIN7 or WIN8.

 * Serial_port.c   
 * Created: 06-10-2013 11:51:41   

#define F_CPU 1000000UL   
#define FOSC 1000000   
#define BAUD 4800  
#define MYUBRR FOSC/16/BAUD-1  

 #include <avr/io.h>  
 #include <util/delay.h>  

void USART_Init( unsigned int ubrr);  
void USART_Transmit( unsigned char data );  

int main(void)  
     USART_Init(MYUBRR);                                               //Initializing USART  
 void USART_Init( unsigned int ubrr)  
/*Set baud rate */  
 	UBRR0H = (unsigned char)(ubrr>>8);  
 	UBRR0L = (unsigned char)ubrr;  
//Enable receiver and transmitter */  
 	UCSR0B = (1<<TXEN0) | (1<<RXEN0);  
/* Set frame format: 8data, 2stop bit */  
     UCSR0C = (1<<USBS0)|(3<<UCSZ00)|(1<<UPM01);//Asynchronous 8bit data Even parity 1 stop bit  
 void USART_Transmit( unsigned char data )   
// Wait for empty transmit buffer */  
 	while ((UCSR0A & (1 << UDRE0)) == 0) {};  
// Put data into buffer, sends the data */  
 	UDR0 = data;  

The code is self explanatory. If you have any doubts do comment. Don’t forget to add same boad rate and parity in the terminal.Here is a snapshot of putty displaying the output.