BufferedSerial/UnbufferedSerial read not receiving the whole array of bytes

Hi guys, I am hoping to get some pointers here…

I am receiving a request packet that is 8 bytes long, and I am using BufferedSerial.read, but I am only getting one byte of data and seems like the other bytes are getting discarded. My code is as below

if (serial_rs485.readable())

{

    int read = 0;

    {

    read = serial_rs485.read(requestBuffer, REQUEST_LENGTH);

    }

    crc_received = (requestBuffer[6] << 8) | requestBuffer[7];

REQUEST_LENGTH = 8;
Where am I going wrong?

Hello Raymond,

Try something like this:

    ...
    int i = 0;

    while (serial_rs485.readable() && (i < 8)) {
        i += serial_rs485.read(&requestBuffer[i], REQUEST_LENGTH - i);
    }
    
    if (i == 8) {
        crc_received = (requestBuffer[6] << 8) | requestBuffer[7];        
    }
    ...

Thanks for the rapid respond this worked very well but it need me to put that 1ms delay, without it i still was facing that challenge.

while (serial_rs485.readable() && (i < 8)) {
i += serial_rs485.read(&requestBuffer[i], REQUEST_LENGTH - i);
ThisThread::sleep_for(1);
}

Thank you so much for the quick response, I can move forward now…