Digital Switch strange results

I am not always printing the message “switch open interrupt!” when I open a closed switch.
I use D6 and set it high and connect to D7 via a digital closed switch. With this setup the D7 blue led is on, but getting strange results when opening switch multiple times. Is this a correct setup to monitor a closed switch and generate an interrupt when it goes open?

int switch = D7;
int sethigh3v = D6;

void setup() {
    Serial.begin(9600);    
    pinMode(sethigh3v, OUTPUT);
    digitalWrite(sethigh3v, HIGH);  
  
    pinMode(switch, INPUT_PULLDOWN);    
    attachInterrupt(switch, isrEvent, FALLING);
}

void loop() {
	//check digital switch
	checkEvents();
}

void isrEvent() { 
    if (digitalRead(button)==HIGH && systemHasNoticed == false) {     
      systemHasNoticed = true;   
    }
}
void checkEvents() {   
 if(digitalRead(button)==HIGH && systemHasNoticed == true) {    
     Serial.println("switch open interrupt!");
     systemHasNoticed = false;    
    }
}

When triggering on a falling edge you’d usually use INPUT_PULLUP and close the switch to GND.

Also we can’t see your declaration of systemHasNoticed - this boolean should be marked volatile.

2 Likes

Yes declaration of systemHasNoticed is marked volatile, but I changed the
attachInterrupt(switch, isrEvent, FALLING); to attachInterrupt(switch, isrEvent, RISING);
and using switch as normally open rather than normally closed.

This seems to have cleared up the issue.

thanks for your help.

3 Likes

Thanks for the assist!

1 Like