Search code examples
arduino-unoxbee

no synchronization between xbee


i have to xbee S2 , one as a coordinator API connected to an arduino and the other a router AT, my project is about sending a command to the router to light up a led. the coordinator send the data if i clicked a button. the problem is the router don't react immediately it takes a while to receive the data. can anyone help me please
this the code i'am using

int led = 13;
const int bouton = 2;
void setup() {
  // put your setup code here, to run once:
pinMode(led, OUTPUT);
Serial.begin(9600);
pinMode(bouton, INPUT);
}
void loop() {
  // put your main code here, to run repeatedly:
   if(digitalRead(bouton)==HIGH)
  {
    digitalWrite(led,HIGH);
    setRemoteState(0x5);
    delay(500);
  }
     if(digitalRead(bouton)==LOW)
  {
      digitalWrite(led,LOW);
      setRemoteState(0x4);
      delay(500);
  
  }
}
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.print(sum,HEX);
}
   
   


Solution

  • Right now, you're acting on the button state every 1/2 second, regardless of if it's changed from last time. You're doing a lot of unnecessary work, including sending two frames every second.

    You should fix your loop to only send a frame when the state changes:

    state = digitalRead(bouton);
    if (state != laststate) {
      laststate = state;
      digitalWrite(led, state);
      if (state == HIGH) {
        setRemoteState(5);
      } else {
        setRemoteState(4);
      }
    }    
    

    With this change, you no longer require a delay in your loop() function, so it will be more responsive to button presses. The LED should change immediately and the message will send. With your old code, it could take up to 700ms to detect the button change.