Particle.Publish only on State Change [Solved]

I’m trying to do a “is door open or closed” project with a reed switch. Right now just trying to wrap my mind around code and simulating open/close by pushing power through D0 and reading at D5. If D5 reads HIGH, door is closed, if it reads LOW, door is open.

I only want to publish to the cloud only when there’s a state change, i.e. (open to close), publish “door is closed” once, or (close to open), publish “door is open” once. Here’s my code, right now, for every state change, i.e. (open to close) or (close to open), generates two publishes instead of one and I can’t figure out why:

int pwr = D0;
int read = D5;
int led1 = D7;
int state;

void setup() {

  pinMode(pwr, OUTPUT);
  pinMode(read, INPUT_PULLDOWN);
  pinMode(led1, OUTPUT);
  digitalWrite(led1, LOW);
  digitalWrite(pwr, HIGH);
  
}

void loop() {
  
  delay(2500);
  
  if (digitalRead(read) == LOW) {
      
      if (state != 0) {
          
          digitalWrite(led1, HIGH);
          Particle.publish("DoorStatus","OPEN",60,PRIVATE);
          state = 0;
          
        }
      
    }
  
  else if (digitalRead(read) == HIGH) {
      
      if (state != 1) {
          
          digitalWrite(led1, LOW);
          Particle.publish("DoorStatus","CLOSED",60,PRIVATE);
          state = 1;
          
        }
      
    }
  
}

I tested your code, and it works fine for me. I only get one event every time the state changes. How are you looking at your publishes?

Hi Ric, thanks for such a quick response. I realized that the particle dashboard was showing every event twice. When I flashed the code, it said “Success” twice with the same time stamp. I closed and reopened by browser and the problem is resolved. I also cleaned up my code to use if (condition1 && condition2) instead of nesting if statements. This is new to me so it’s a learning process.

Thanks again. I’ll see if there’s a way to close the topic.

1 Like

How do you have D0 & D5 connected?
Be careful about the currents the pins can source and sink.
Shorting both together without a current limiting resistance may kill either or both.