xBee to Arduino small code problem

Hi,

I'm adapting the basic xBee doorbell project from 'Building wireless sensor networks' by Robert Faludi which involves two xbees and two arduino boards. I'm having some arduino code problems.

What I want the system to do is turn on a light based on the value from the LDR sensor OR print out a message when a button is pressed. At the moment the best I can do is have both sensors triggering the same action (flashing LED). I have tried to make them trigger seperate actions by using the code below, but it doesn't work.

Code on arduino1:

if(photocellReading<lightsetting) {
Serial.print('D');
delay(100); //prevents port being overwhelmed
}
if (digitalRead(BUTTON) == LOW) {
Serial.print('H');
delay(100); // prevents overwhelming the serial port i increased the delay
}

Code on receiving arduino2:

if (Serial.available() > 0) {
if (Serial.read() == 'D'){
digitalWrite(BELL, HIGH);
delay(10);
digitalWrite(BELL, LOW);
}

else if (Serial.read() == 'H'){
Serial.print("hey");
}
}

I've just started using xbees, and have looked around online but i cant understand why the code 'if (Serial.read() == 'H' || 'D')' responds to both the LDR and push button but when i try to seperate them it only listens to one of them.

I would really appreciate any help on this!

Thanks!

Maraesa

Hey everyone!

Seems I managed to fix the problem myself by looking at this post and incorporating the responses http://arduino.cc/forum/index.php/topic,91707.0.html

I declared a variable at the top: 'char val';

And then rather than putting 'Serial.read()' into my if loop, i instead placed the serial value into the 'val' variable, and inserted 'val' into the if loop.

My new code looks like this

char val;

if (Serial.available() > 0) {
val=Serial.read();
if (val == 'D'){
//ring the bell briefly
digitalWrite(BELL, HIGH);
delay(10);
digitalWrite(BELL, LOW);
// uncomment the next line if you don't have an oscillating buzzer
//tone(BELL, 440, 100);
}

if (val == 'H'){
Serial.print(Serial.read());
}
}

It's still coming up with '-1's in the serial window rather than actual words but it's a start :slight_smile: If anyone can explain why thats happening, please let me know.

Thanks,

Maraesa

It's still coming up with '-1's in the serial window rather than actual words but it's a start smiley If anyone can explain why thats happening, please let me know.

Well, of course it is.

if (val == 'H'){
     Serial.print(Serial.read());
    }

Why are you trying to print what you are reading from the serial port to the serial port? I thought you said you wanted to print a specific message...

Hiya yes i'd figured that out lol

Thanks for your help. Will now close this topic :slight_smile: