Wireless Alarm

I am trying to create a a wireless alarm system using two arduinos and two xbees. I want the arlam to be on when the button is not pressed and off when it is.

My router code is:

const int buttonPin = 2;

int buttonState = 0;

void setup() { Serial.begin(9600); pinMode(buttonPin, OUTPUT); }

void loop(){ buttonState = digitalRead(buttonPin); Serial.println(buttonState); delay(500); }

AND THE COORDINATOR CODE IS:

int ledPin = 2; int buttonState;

void setup() { Serial.begin(9600); pinMode(ledPin, OUTPUT); }

void loop(){ if (Serial.available() > 0) { while(Serial.available()>0) {buttonState=Serial.write(Serial.read());} if (buttonState == LOW) {digitalWrite(ledPin, LOW);} else {digitalWrite(ledPin, HIGH);} } }

.... the coordinator receives the signals from the router but the alarm doesn't turn off when the button is pushed.

Oh where to start...

First, when posting code, use CODE tags; it makes it much easier to read. Speaking of easier to read, there should only be be statement per line, none of this crap:

while(Serial.available()>0) {buttonState=Serial.write(Serial.read());}
    if (buttonState == LOW) {digitalWrite(ledPin, LOW);}

It should look more like this:

while(Serial.available()>0) 
{
  buttonState=Serial.write(Serial.read());
}

if (buttonState == LOW)
{
  digitalWrite(ledPin, LOW);
}

That makes it much more readable. It may not suit your "style" of coding if you prefer the other way, but you're asking others for help, not yourself.

Now as to your actual issue you're having:

Serial.println(buttonState);

Say buttonState is HIGH (or 1). This code tells it to send ASCII 1 as well as the new line character, so you'll actually be sending 49 followed by 10. Neither of those are equal to LOW (or 0). Since you want the actual value, and don't want to encode the data in ASCII, you should be using Serial.write.

I've made the changes but it still stays on

rparag01: I've made the changes

But you're not going to show us this changes (properly)?

//SENDER
const int buttonPin = 2;

int buttonState = 0;

void setup() {
Serial.begin(9600);
pinMode(buttonPin, OUTPUT);
}

void loop(){
buttonState = digitalRead(buttonPin);
Serial.write(buttonState);
delay(500); // delay 5 seconds
}

int ledPin = 2;
int buttonState = 0;

void setup()
{
Serial.begin(9600); //start serial port at 9600bps
pinMode(ledPin, OUTPUT);
}

void loop(){
if (Serial.available() > 0)
{
while(Serial.available()>0)
{
buttonState=Serial.write(Serial.read());
}

if (buttonState == HIGH)
{
digitalWrite(ledPin, LOW); // if button is pressed then alarm is OFF
}

else {digitalWrite(ledPin, HIGH);} // if button is not pressed then alarm in ON
}
}

Again, put code in CODE tags. Next time, I'm just not going to bother responding unless its put in CODE tags.

buttonState=Serial.write(Serial.read());

What exactly do you think this is doing? Notice that this wasn't the line I quoted when I was referring to using Serial.write.