Hardware Reference
In-Depth Information
When you run this sketch, you'll
get a result like what's shown to
the right.
8
201 1 201 1 200 1 197 91
126 0 18 131 0 1 43 0 5 2 0 1 197 1 196 1 198 1 198 1 197 106
126 0 18 131 0 1 43 0 5 2 0 1 197 1 193 1 193 1 192 1 192 125
126 0 18 131 0 1 44 0 5 2 0 1 194 1 194 1 193 1 190 1 190 130
126 0 18 131 0 1 43 0 5 2 0 1 189 1 189 1 191 1 190 1 190 143
126 0 18 131 0 1 43 0 5 2 0 1 190 1 186 1 186 1 186 1 188 156
126 0 18 131 0 1 43 0 5 2 0 1 187 1 187 1 186 1 183 1 183 166
126 0 18 131 0 1 43 0 5 2 0 1 182 1 182 1 184 1 183 1 183 178
126 0 18 131 0 1 43 0 5 2 0 1 181 1 180 1 179 1 179 1 182 191
126 0 18 131 0 1 43 0 5 2 0 1 181 1 181 1 180 1 178 1 177 195
126
Each line that starts with 126 (0x7E
in hexadecimal) is a single XBee
message. Most of the lines have 22
bytes, corresponding to the packet
format described earlier. You may
wonder why the first line of the output
shown here didn't have a full comple-
ment of bytes. It's simply because
there's no way to know what byte the
XBee is sending when the Arduino first
starts listening. That's OK, because the
code below will filter out the incom-
plete packets.
It would be handy
to have each
packet in its own array. That's how
you'll use the global variables you set
up before.
Refine It
void listenToSerial() {
// read incoming byte:
int inByte = Serial.read();
// beginning of a new packet is 0x7E:
if (inByte == 0x7E ) {
// parse the last packet and get a reading:
int thisReading = parseData();
// print the reading:
Serial.println(thisReading);
// empty the data array:
for (int thisByte = 0; thisByte < packetLength; thisByte++) {
dataPacket[thisByte] = 0;
}
// reset the incoming byte counter:
byteCounter = 0;
}
// if the byte counter is less than the data packet length,
// add this byte to the data array:
if (byteCounter < packetLength) {
dataPacket[byteCounter] = inByte;
// increment the byte counter:
byteCounter++;
}
}
Next, change the listenToSerial()
method, adding code to parse the dat-
aPacket array; then, empty the array to
prepare to receive new data. Replace
everything in the if statement with the
code shown in blue, and remove the
two lines that printed the byte and the
space.
This function calls another function,
parseData() , that extracts and
averages the sensor readings in bytes
12 to 21 of the packet.
 
Search WWH ::




Custom Search