Reading data based on value of a byte

I’m trying to figure out the best method of filling an array of data based on a size of data packet byte.


Device sends a header of 0x24 then the next byte tells us how much data is expected to follow, lets say it’s 0x05

So, say we get 0x24 0x05 0x01 0x02 0x03 0x04 0x05

Can someone help me with what method I would use to look to the data where 0x05 is and then place that amount of data into an array? If anything follows it it can be ignored and trashed.

I have tried numerous different methods but I’m not keying on the right thing.

I was playing around with this as a basis:

void loop()
   while(Serial.available() > 0) 
	 if(index < 39) 
	     inChar =; 
             inData[index] = inChar;        
	     inData[index] = '\0'; 

I was thinking of maybe a second after inChar to get to the length byte then somehow use that information with index+ to constrain it but when I try different combinations of things it doesn’t work.

You may want to look at this thread for some ideas... The concept is similar to what you are attempting,6348.0.html

PaulS was helping me with something similar. He gave me a bit of code to work with. You will likely want to change the code to read the first 2 bytes and set the variable “count” to the value of the second byte.

if(Serial.available() >= 4)
   // read the 1st 4 bytes

static int count = readString[3]; // the 4th byte is the number of additional bytes to get

while(Serial.available() < count) {} // Do nothing until they data arrives

// Now, read the rest of the data
for(int i=0; i<count; i++)
   readString[i+4] =;

// Now do whatever with it

I will play around with it.