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;
}
}
}