Go Down

Topic: Reading data based on value of a byte (Read 339 times) previous topic - next topic

mancow

Jun 03, 2012, 12:16 am Last Edit: Jun 03, 2012, 12:21 am by mancow Reason: 1
I'm trying to figure out the best method of filling an array of data based on a size of data packet byte.

Example:

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:
Code: [Select]
void loop()
{
  while(Serial.available() > 0)
  {
if(index < 39)
{
    inChar = Serial.read();
            inData[index] = inChar;        
    index++;
    inData[index] = '\0';
    }
  }    
}


I was thinking of maybe a second Serial.read 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.

wanderson

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

http://arduino.cc/forum/index.php/topic,6348.0.html
New true random number library available at: http://code.google.com/p/avr-hardware-random-number-generation/

Current version 1.0.1

cyclegadget


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.

Code: [Select]
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] = Serial.read();
}

// Now do whatever with it

mancow


Go Up