Pages: [1]   Go Down
Author Topic: Reading data based on value of a byte  (Read 285 times)
0 Members and 1 Guest are viewing this topic.
Kansas
Offline Offline
Newbie
*
Karma: 0
Posts: 42
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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.
« Last Edit: June 02, 2012, 05:21:02 pm by mancow » Logged

Dallas, Texas
Offline Offline
God Member
*****
Karma: 3
Posts: 718
Old, decrepit curmugeon
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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
Logged

New true random number library available at: http://code.google.com/p/avr-hardware-random-number-generation/

Current version 0.7.2

Greenville, IL
Offline Offline
Edison Member
*
Karma: 11
Posts: 1310
Warning Novice on board! 0 to 1 chance of errors!
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset


 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:
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
Logged


Kansas
Offline Offline
Newbie
*
Karma: 0
Posts: 42
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I will play around with it.

Thanks
Logged

Pages: [1]   Go Up
Jump to: