Electronic – How to determine the end of data received by USART

avruart

I am receiving some strings from UART in AVR. Strings are chaotic, not deterministic. It also includes new line \n and carriage return \r characters that's why I couldn't find a solution including checking bytes if they are \n or \r.

So is there a way to determine the end of the data?

EDIT: For more details about the data I receive.
I am acquiring some strings from my web server and they are commands to be used such as "weather+check\r\n". Another one is, for example, "time\r\nNew York+Check\r\n\r\". I simply want to get these strings and assign to a char array. But to do this I need to know when data ends so that I can go out of the While loop that I use to fill the array.

Best Answer

Without some sort of defined protocol, there is no sure way to determinate the end of a string, except for it being terminated by a carriage return ('\r') and/or linefeed ('\n') character.

You want to try something like this:

#define BUF_LEN 100
char buf [BUF_LEN];
unsigned short i;


i = 0;
while (1)
{
    char ch;
    ch = getChar();
    if (ch != '\n')     // ignore lf's
    {
        if (ch != '\r')
        {
                if (i < BUF_LEN-2)
                {
                    buf[i++] = ch;
                    buf[i] = '\0';
                }
        }
        else
        {
            break;      // string now in buf, terminated w/ '\0'
        }
    }   
}

Some strings don't have line feeds ('\n') so I just generally ignore them and treat carriage returns ('\r') as an end of string.

This code allocates a buffer buf which is 100 characters long. If that is not enough, then increase the number in the #define. Of course the buffer could have been allocated on the heap, but a lot of small microcontrollers don't have enough RAM for a useful heap.

I'm using a routine called getChar to get the character, one by one. Change that to whatever you have available.

The routine is very simple, it just gets characters and stores them in a buffer until a carriage return is found. Then it breaks out of the loop with the string in the buffer, terminated by a 0 ('\0') without any '\r' or '\n' in it.