attachInterrupt set to RISING gets triggered either ways.

Hi,

I have an attachInterrupt set to RISING in my code but its also triggered when falling. It is set to pin 2 with a pull down resistor on the switch. It is a mini switch and is wired to the normally closed position. I want to use it as a damper switch to monitor if a box gets open. So it’ll be pushed down most of the time and when the box gets opened back to resting position to wake up the arduino.

What would I need to change in order to make the interrupt happen only when the voltage in RISING? The wiring is attached.

Thank you

Here’s the code :

#include "LowPower.h"

const int WakeUp = 2;
unsigned long timer;
unsigned long currentMillis;
unsigned long previousMillis = 0;

void setup() {
  Serial.begin(115200);
  pinMode(WakeUp, INPUT);
  Serial.println("I'm up!");
  attachInterrupt(0, TimerReset, RISING);
  delay(2000);
  Serial.println("Going to sleep...");
  delay(1000);
  LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
}

void loop() {
    
  Serial.println("Up again!");
  
  while ( timer < 3000) {
    Serial.println(timer);
    currentMillis = millis();
    timer = timer + (currentMillis - previousMillis);
    previousMillis = currentMillis;
  }
  
  Serial.println("Going to sleep...");
  delay(1000);
  LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

}

void TimerReset() {
  timer = 0;
}

Mechanical switches don't switch cleanly, they [u]bounce[/u].

Sounds like switch bounce indeed.

A small cap (1-100 nF) in parallel to your pull-down resistor should help to debounce it.

Why use interrupts at all? Why not poll?

MarkT:
Why use interrupts at all? Why not poll?

bpjobin:
[...] to wake up the arduino.

Sounds like a good reason to me. Polling doesn't work well when the Arduino is asleep.

Good point!

wvmarle:
Sounds like a good reason to me. Polling doesn't work well when the Arduino is asleep.

But if the interrupt is used only for this purpose - waking it up - it does not matter in any case. When woken, the Arduino can perform the debounce - in software - and go back to sleep if the box is closed/ false alarm.

Another inadequately explained question I fear, leading others to over-think the "problem". :astonished:

Indeed - in that case best to disable the interrupt the moment it's generated (no debouncing needed as it seems you just care about the button being pressed, not how often it's pressed), do what's got to be done, then enable the interrupt and go back to sleep.

Thanks all for your suggestions!

wvmarle:
A small cap (1-100 nF) in parallel to your pull-down resistor should help to debounce it.

Indeed a small cap makes it work flawlessly.