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.
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 If anyone can explain why thats happening, please let me know.
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...