Skip to content

Latest commit

 

History

History
38 lines (33 loc) · 2.09 KB

File metadata and controls

38 lines (33 loc) · 2.09 KB

USART (serial) communication with ATMega328

TX only

This example shows how to send data one way (AVR -> PC)

void serial_send(unsigned char data){
	// send a single character via USART
	while(!(UCSR0A&(1<<UDRE0))){}; //wait while previous byte is completed
	UDR0 = data; // Transmit data
}

TX + RX (polling method)

This example shows how bidirectionally exchange data (AVR <-> PC) using a polling method. This is typically less favorable than the interrupt method because the processing of the chip gets to a point where it waits (perhaps forever) until the PC sends data.

char serial_read()
{
   // wait until single character is read via USART
   while(!(UCSR0A & (1<<RXC0))){} // wait until data comes
   return UDR0; // return the character
}

TX + RX (polling interrupt method)

This example shows how bidirectionally exchange data (AVR <-> PC) using an interrupt method. This is typically the best method because the MCU can run continuously doing its own thing, and the PC interrupts the microcontroller when USART data begins to come in.

volatile char lastLetter; // make a variable that can be accessed
ISR(USART_RX_vect){
    lastLetter=UDR0;  // quickly do something with this before it changes
}

Hardware

description picture
I typically use an FT232 breakboard board to capture serial data from my microcontroller on my computer. These breakoutboards can be purchased from SparkFun (which are always high quality and genuine) or from eBay (cheaper, but variable quality, and questionable chips).
On the software side, I typically use RealTerm. It's simple, easy, and allows file logging. If you configure your microcontroller to output CSV format, you can save directly as CSV so files can be opened in Excel. Nice!