Issue Receiving Full Data from PLC in Arduino Project with 7-Segment Display

Serial communication is slow; it might very well be that a byte is still being transferred so not yet available and the while loop will terminate.

You can improve your code using the following approach

  while (receivedIndex < sizeof(receivedData)) {
    if (rs485.available()) {
      receivedData[receivedIndex++] = rs485.read();
      lastByteTime = millis(); // Update the time of the last received byte
    }
  }

Note that this is blocking code.

To properly implement a timeout, you can improve the above

  while (receivedIndex < sizeof(receivedData)) {
    if (receiveIndex != 0 && millis() - lastByteTime >= timeout)
    {
      // timeout occured
      break;
    }
    if (rs485.available()) {
      receivedData[receivedIndex++] = rs485.read();
      lastByteTime = millis(); // Update the time of the last received byte
    }
  }

Not tested, probably needs some polishing.

You can study Robin's updated Serial Input Basics to get some ideas for an approach without while-loops. Although it was written with text communication in mind, ideas might still apply.

1 Like