Baby-O serial example question

Hi,

Probably a very basic question, regarding the Pololu Library serial communication example. Been using it pretty much as is for years, just copying/pasting it and adjusting slightly.

Now I’m wondering a couple of things - again very basic stuff, but helpful for my understanding. About this example functions:

void check_for_new_bytes_received()
{
    while(serial_get_received_bytes() != receive_buffer_position)
    {
        // Process the new byte that has just been received.
        process_received_byte(receive_buffer[receive_buffer_position]);
 
        // Increment receive_buffer_position, but wrap around when it gets to
        // the end of the buffer. 
        if (receive_buffer_position == sizeof(receive_buffer)-1)
        {
            receive_buffer_position = 0;
        }
        else
        {
            receive_buffer_position++;
        }
    }
}
  1. Is there a reason why the while loop couldn’t be an if statement here?
  2. Couldn’t receive_buffer_position simply be set to serial_get_receivedIbytes() here, instead of the if statement?

Basically, any reason why this wouldn’t work:

void check_for_new_bytes_received()
{
    unsigned char current_buffer_byte = serial_get_received_bytes();
    if(current_buffer_byte != receive_buffer_position)
    {
        process_received_byte(receive_buffer[receive_buffer_position]);
        receive_buffer_position = current_buffer_byte;
    }
}

Thanks,

-A

Hello.

Your version of check_for_new_bytes_received() does not process every byte if more than one byte is received between checks. If serial_get_received_bytes() returns a value greater than 1, let’s say 6, and receive_buffer_position is 1 (meaning there are five bytes received but not processed), only one of the five bytes is passed to process_received_byte() before updating receive_buffer_position to 6 and returning back to main(). The last four bytes are skipped. So, for example, “hello” is received, ‘h’ is sent back and the rest is passed over. This is why we use a while loop instead of an if statement to ensure that every new byte received is handled in the receive_buffer.

- Amanda

Thanks Amanda,

It escaped me that several bytes could have been received between checks, makes perfect sense.

1 Like