Hi, Scott here from Salem. I recently bought 3 Xbee series 2 radios from Sparkfun, and also I bought the book "Building wireless sensors by Robert Faludi. Great book! I am struggling to understand serial communications. Here is the code from page 102 of the book. I spent a few hours trying to answer these questions via the internet. Can you please help? That would be great! I also tried to find a good serial communications tutorial with no luck. Can you reccommend a good resource to help me with xbee and serial communications? I would like to try controlling servo motors, sensors… but back to my question.
if (Serial.available() >=21)
{
if (Serial.read() == 0x7E)
{
digitalWrite(debugLED, HIGH);
delay(10);
digitalWrite(debugLED, LOW);
for (int i = 0; i < 18; i++)
{
byte discard = Serial.read();
}
int analogHigh = Serial.read();
int analogLow = Serial.read();
analogValue = analogLow + (analogHigh * 256);
Question #1: Serial.available() >=21. Does this mean the arduino is looking for 21 bytes of information or more in a buffer? Does this come from the Xbee? Why 21 bytes? How big is the buffer to hold the incoming info? 64 bytes (from arduino reference) , or 128 bytes?
Question #2: if (Serial.read() == 0x7E): I don’t understand. Why look for the number 126 bytes?
Question #3: why discard bytes in "byte discard =Serial.read()? and only then the first 18 bytes?
I don’t have the book, but suggest that you read it carefully enough to know what the program is supposed to be doing. Doesn’t the author tell you that?
My guess from the code is that it looks for a message longer than 20 bytes, then for a start character 0x7E, which signifies a data block of a certain type. It then interprets that block as 18 bytes to be read but ignored, followed by two bytes that are interpreted and stored as a 16 bit number (analogValue).
“Serial communications” just means that the message bits come one at a time, serially. How you interpret the bits is up to you.
Thank you jremington. The book is a great book, but doesn’t go into explaining much about serial communications. Thanks for responding. I understand now, that 0x7e is a character from the ascii table, not a decimal number 126? I’ll keep at it.
Scott
0x7E and 126 are just two different representations of the same eight-bit quantity. “0x” means hex digits follow, 7E is the hexadecimal representation and 126 is the decimal representation. The “0x” is important, because for example, 0x13 and 13 (decimal) are not equivalent.
When certain values have special significance, such as 0x7E in the program above, hexadecimal representations are often easier for a human to recognize and interpret than are the equivalent decimal representations. For that reason “hex” values are often used when programming.
if (Serial.read() == 126)
would work just as well.
Also, 0x7E is used in Digi’s binary API (if you config the XBee for that mode). The 0x7E signals the beginning of an API frame flowing to/from the XBee serial port.