Friday, April 27, 2007

Radio, radio

I feel like I've made great strides in my code. Everything seems to be working with the units talking and listening to each other.

Setting up the radios was a little bit challenging but thanks to the help of Jeff LeBlanc, I got things going. He convinced me to simplify the type of data I was sending, and to forgo sending characters and strings and stick with straight bytes. This made it a lot easier, especially when combined with the packet structure provided by Rob Faludi (a big thanks to him as well.)

My protocol contains 4 bytes, the first being a header, the second being the unit ID number, the third the unit's state, and the fourth an end byte. Given that I'm using the broadcast mode, this protocol makes it easy for each radio to look only for messages intended for it.

When a unit receives a message, it:
1) looks to see if it has the header, if it does it knows it's at the start of a message, and continues reading
2) looks for the unit ID number, if it's from a unit it wants to hear from, it
3) looks for a change in state, causing a reaction in its own state.

Here is the send code: super simple.

void sendData() { // listen to the potentiometer:

// if there's something to send, send it:
//light the tx LED to say you're sending:
digitalWrite(txLed, HIGH); //green LED

Serial.print(255, BYTE); // header byte
Serial.print(1,BYTE); // unit ID number
Serial.print(myState,BYTE); // sends a 1, as this function only runs when
// myState == 1
Serial.print(254,BYTE); // end byte

// turn off the tx LED:
digitalWrite(txLed, LOW); //greenLED


Receive code:

void ReadIncoming(){
// listen for incoming serial data:
if (Serial.available() > 3)
incomingByte =;
if(incomingByte == 255)
digitalWrite(rxLed, HIGH); // Yellow LED turn on the RX LED whenever
// you're reading data:
id =;
state =;
end =;
if (id == 2){
digitalWrite(idLED, HIGH); // do we have the right ID?, if so IDLED pin 9
// RED on

if (state == 1){ // is that unit active ?
myState = 2;
else {
myState = 0;
else {
// turn off the receive LED when there's no incoming data:
digitalWrite(rxLed, LOW); // yellow LED off
digitalWrite(idLED, LOW); // we don't have the right ID, so IDLED pin 9
// RED off

No comments: