NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » How to know data has finished received from UART?

April 02, 2013
by oshjdf
oshjdf's Avatar

I'm trying to code a simple program that display string I enter at pc terminal on LCD.

e.g. Mom, I love you.

But, how to know data has finished received from UART so it can be displayed at LCD?

April 02, 2013
by Ralphxyz
Ralphxyz's Avatar

Hi oshjdf, one method is to put a EOL character at the end of the line:

So you might have Mom, I love you.~

You could actually use the period instead of the tilde.

Or you could do a character count every sixteen characters send to LCD.


April 02, 2013
by pcbolt
pcbolt's Avatar

oshjdf -

One of the more reliable ways of doing UART reads is with interrupts. Whenever a character is ready on the receive line (RX) an interrupt can be set up to simply read the character and copy it to a data array or buffer. Then the main part of the program can just sit around and wait for a change in the buffer and output the character to the LCD one at a time. When the data from the PC stops, the main program just sits and waits again after outputting to the LCD. Here is a simple interrupt code segment:

ISR(USART_RX_vect){ // this is the symbol from AVR compiler docs (interrupt.h)

//  UDR0 is data register for uart - must read it during interrupt
//  See page 185 of datasheet for chip
//  Simply read uart rx reg and copy to buffer, update pointer

    rx_buf[rx_in_idx] = UDR0;
    if (rx_in_idx >= MAX_RX) rx_in_idx = 0; //wrap around to 0 if needed

In the main part of the code I have another buffer pointer or index variable "rx_out_idx" that I test against "rx_in_idx".

while (rx_out_idx != rx_in_idx){    // chase the input pointer
    ch = rx_buf[rx_out_idx];
    if (rx_out_idx >= MAX_RX) rx_out_idx = 0;  //wrap around to 0 if needed

You have to do some setup for the interrupt and the global variables, but that's not hard.

Post a Reply

Please log in to post a reply.

Did you know that Pulse Width Modulation (PWM) can be used to control the speed of a motor digitally? Learn more...