Xbee packets giving Incorrect values

serialxbee

I am trying to extract analog sample data from an xbee packet that are present in the 20th and th 21st bytes. However after extracting them into the serial monitor the garbage value that is received turns out to be wrong.

Here is the output I receive in the serial monitor :

enter image description here

First column- lsb
Second column – msb
The code for extracting data looks like this:

if(Serial.available()>21){

if(Serial.read==0x7e){

for(int i=1;i<19;i++){

byte discard=Serial.read();
}

int analogMSB=Serial.read();

int analogLSB=Serial.read();

int analogReading=analogLSB+(analogMSB*256);

When I calculate lsb + msb*256 for the above , I receive negative values as well which is undesirable. Please tell me how I can rectify this issue .

Best Answer

If you complain about negative numbers, then you are not correctly accounting for signed versus unsigned arithmetic. Make sure you convert all values to unsigned int, and print them out as unsigned int, to cover the entire 16-bit range.

unsigned int x = (unsigned int)lsb + (unsigned int)msb * 256;
printf("%u\n", x);

There's a few other troubleshooting tips here, too, like "are you sure these are the right offsets," and "are you sure you have the byte order correct," but let's start with the first thing that's wrong in your post, first!