Search code examples
arduinoledxbee

the led didn't switch on


i have a strange problem :o i make a connection between two xbee when i click on a button a led connected to the pin 13 light on and then the xbee coordinator send an information to switch on a led connected to the pin D3 of the xbee router. the problem is when i click on the button some times the led switch on sometimes not. i didn't know the problem is in the code or it is just a connection problem

int led = 13;
const int bouton = 2;
boolean state;
boolean laststate; 
void setup() {
  // put your setup code here, to run once:
pinMode(led, OUTPUT);
Serial.begin(9600);
pinMode(bouton, INPUT);
  digitalWrite(led, LOW);


}
void loop() {
  // put your main code here, to run repeatedly:
 state = digitalRead(bouton);
  digitalWrite(led, state);
  if (state == HIGH) {
    Serial.println("on");
    setRemoteState(5);
    delay(5000);
  } else {
    Serial.println("off");
    setRemoteState(4);
    delay(5000);

  }
}  

void setRemoteState(char value){
  Serial.write(0x7E); // start byte
  Serial.write((byte)0x0);
  Serial.write(0x10);
  Serial.write(0x17);
  Serial.write((byte)0x0);
  // id of recipient or use 0xFFFF for broadcast
  Serial.write((byte)00);
  Serial.write((byte)00);
  Serial.write((byte)00);
  Serial.write((byte)00);
  Serial.write((byte)00);
  Serial.write((byte)00);
  Serial.write(0xFF);
  Serial.write(0xFF);
  // 16 bit of reciepent 
  Serial.write(0xFF);
  Serial.write(0xFE);  
  
   Serial.write(0x02); 
   
   Serial.write('D');
   Serial.write('2');
   
   Serial.write(value);
   
   long sum = 0x17 + 0xFF + 0xFF + 0xFF + 0xFE + 0x02 + 'D' + '2' + value;
   Serial.write(0xFF - ( sum & 0xFF) );
   Serial.println(sum,HEX);
}
   
   


Solution

  • It looks like the problem is in the delay(5000) the micro-controller will wait 5 seconds between a sample of the button's state. if you remove the delay statement it should be on and off instantly.

    you should try to trigger the setRemoteState only on state change, so it will not send it constantly. something like

    loop() {
    state = digitalRead(bouton);
      digitalWrite(led, state);
    if(state != lastState)
    {
      if (state == HIGH) {
        Serial.println("on");
        setRemoteState(5);
      } else {
        Serial.println("off");
        setRemoteState(4);
    
      }
    }
      lastState = state
    }