Search code examples
c++arraysserial-communication

Question about C++


This is perhaps quite a simple one for some of you.

I was looking at the following serial read function and I can't quite comprehend what &prefix[2] does here. Does it mean only two bytes can be filled or something else ?

I should also mention this is part of the player/stage platform.

while (1)
{
  cnt = 0;
  while (cnt != 1)
  {
    if ((cnt += read(fd, &prefix[2], 1)) < 0)
    {
      perror("Error reading packet header from robot connection: P2OSPacket():Receive():read():");
      return (1);
    }
  }

  if (prefix[0] == 0xFA && prefix[1] == 0xFB)
  {
    break;
  }

  GlobalTime->GetTimeDouble(&timestamp);

  prefix[0] = prefix[1];
  prefix[1] = prefix[2];

}

Solution

  • This fragment implements a shift register of the size 3.

    The oldest value is in prefix[0] and the latest in prefix[2]. That's why the address of prefix[2] is passed to the function read().

    The loop is left, when the previous two bytes have been FA FB, the current (last received) byte is in prefix[2]. The function is left before that point, if nothing could be read (the return value of read differs from 1).

    This shift register is used when you can't predict if other bytes are received in front of the sync characters FA FB. Reading three bytes with each read operation would not allow to synchronize somewhere in a data stream.