Electronic – get dynamic length packet from UART

atmegauart

I Write a program for receive data from Uart ISI, my Data Packet is something like :

Data Packet Structure

2 first byte contain Device ID and type of command. Data is contain some bytes that could be have different length, minimum 1 byte to max 15 bytes, and the last byte represent the packet is finish.

Uart ISI code is:

volatile char UartFlag=Fulse;
volatile unsigned char count=0;
unsigned char coder[13];

ISR     (USART_RX_vect)
{
    coder[count]=UDR0;
    if (coder[count] == 20)
        UartFlag=True;
    else
        count++;
}

That receive each byte and save in coder. As you see when receive number 20, stop receiving process by UartFlag=True; and in main call a function DoSomthing(); to do something with coder as below:

while (1)
    {
        if (UartFlag)
        {
            DoSomthing();
            count=0;
            UartFlag=Fulse;
        }
    }

But I have problem that sometime the Data section have 20 in their bytes and its lead to i dont get Correct packet. I try to put \0 (the last byte=0 instead of 20) but maybe have same error.

I am looking for best way to find dynamic length of packet. What is the best way to find the dynamic length of packet?

A way that maybe work is put the data length in first byte of Data section, but it add extra process in sender device.

Best Answer

In my opinion, to be 100% that it will work in all cases, you have to do what you thought of yourself:

Include the length of the data (the number of bytes you are sending) as an additional header field, for example after the Type field.

This is actually what the Ethernet protocols do.

About extra process on sender I don't know how the sender is implemented. But it doesn't seem to require much processing effort. I mean the sender already knows how many packets will be sent, no? So, as you fill in the other two fields (Device ID and Type), you can fill in this additional field as well.