Hi,
I'm having trouble printing out numerical data from a packet sent over a couple of xbee radios. I have a coordinator which is sending out regular heartbeat broadcast packets, and a receiver which receives these packets and sends back a log packet to show what it's doing. I'm trying to work out why I can't get the log packets to print out correctly over software serial. I've reduced the problem to sending a character string "1234567890ABCDEF" from the receiver, and printing it out either as characters, or as decimal character codes, from the coordinator.
The relevant code on the transmitter looks like this:
char readLogPacket() {
// wait for a log packet and print out the contents.
//delay(10);
//usb.print(".");
xbee.readPacket();
//usb.print("-");
if (xbee.getResponse().isAvailable()) {
// something arrived.
//usb.println("ia");
if (xbee.getResponse().getApiId() == ZB_RX_RESPONSE) {
// it's a log packet.
//usb.println("rx");
xbee.getResponse().getZBRxResponse(rx);
//usb.println("done");
return 1;
} else {
// not an RX packet.
return 0;
}
} else {
return 0; // no packet.
}
}
...
void loop() {
...
unsigned char* rxPayload;
unsigned char test;
...
while (!readLogPacket() && tickNo < oldTicks + 2);
if (tickNo < oldTicks + 2) {
usb.print("unpack: ");
rxPayload = (unsigned char*) rx.getData();
for (unsigned char i = 0; i < 16; i++) {
test = rxPayload[i];
usb.print(test);
usb.print(" ");
}
usb.println();
}
...
}
In other words, it's waiting to receive the log packet, and if it doesn't time out waiting, it puts a copy of the pointer to the received packet payload into rxPayload, then goes through storing successive characters in 'test' and printing them out.
If I use the exact code above, the result is like this:
Tick: 4
Tick: 8
Tick: 12
Tick: 16
unpack: 49 0 22 0 6 115 0 0 0 1 8 202 1 4 4 8
Tick: 20
unpack: 49 0 22 0 6 115 0 0 0 1 8 202 1 4 73 8
Tick: 24
Whereas if I print the characters cast into 'char' instead of 'unsigned char', it prints as it should. I.e. if I change the code to:
...
for (unsigned char i = 0; i < 16; i++) {
test = rxPayload[i];
usb.print((char)test);
usb.print(" ");
}
...
it prints this:
Tick: 4
Tick: 8
Tick: 12
Tick: 16
unpack: 1 2 3 4 5 6 7 8 9 0 A B C D E F
Tick: 20
unpack: 1 2 3 4 5 6 7 8 9 0 A B C D E F
Tick: 24
unpack: 1 2 3 4 5 6 7 8 9 0 A B C D E F
Tick: 28
unpack: 1 2 3 4 5 6 7 8 9 0 A B C D E F
Another thing to add to my perplexity is that when I define the character string in the coordinator's code, and print it directly, it works fine both ways...
If anyone has any idea what is going on here, I'd really appreciate it, as I've been stuck on what looked at first sight like a simple problem (sending log packets) for several days now. The only thing I can guess is that it might be due to some compiler optimisation that I don't know about, but I may be wrong.
Thanks.