I'm not able to get interrupts to work as expected. I am using a Due.
I have a microswitch connected to the Due and set pinmode to INPUT_PULLUP. When initialising, to check all is correct, I call digitalRead() for that pin and get a HIGH reading - as expected. I then attach a RISING interrupt. When I press the switch, for some reason the interrupt gets triggered. That shouldn't happen as the voltage is falling. When I release the switch, the interrupt gets triggered again.
So my observations are:
1- a RISING interrupt shouldn't be triggered when I press the switch;
2- I also get two interrupts when I press even though I have a 1s delay in my loop (see source below). (Note: I keep my finger on the switch for several seconds);
3- If I instead use a FALLING interrupt, it only gets triggered when I press the switch, not when I release - which is correct. (However, I still get two interrupts when I press.)
4- CHANGE works as expected - though again with 2 interrupts instead of 1;
5- when using a LOW triggered interrupt, I only get one interrupt when I press the switch but then get two when I release. I shouldn't get any when I release.
6- These anomolies can't surely be to do with switch bounce, a) because I shouldn't get a RISING interrupt when I press and b) I have a 1s delay in my loop.
When using a LOW interrupt and keeping the switch pressed for several seconds before releasing, I get the following output:
top is HIGH
top switch down
top is LOW
top switch down
top is HIGH
Thoughts?
My code:
#include <stdlib.h>
#include <Arduino.h>
#define TOP_TRIP_PIN 2
volatile bool g_top_switch_down;
// Interrupt service routines
void ISR_top_switch_down()
{
g_top_switch_down = true;
}
void setup()
{
Serial.begin( 115200 );
pinMode( TOP_TRIP_PIN, INPUT_PULLUP );
attachInterrupt( digitalPinToInterrupt( TOP_TRIP_PIN ), ISR_top_switch_down, LOW );
if( digitalRead( TOP_TRIP_PIN ) == LOW )
Serial.println( "top is LOW" );
if( digitalRead( TOP_TRIP_PIN ) == HIGH )
Serial.println( "top is HIGH" );
g_top_switch_down = false;
}
void loop()
{
if( g_top_switch_down )
{
detachInterrupt( digitalPinToInterrupt(TOP_TRIP_PIN) );
g_top_switch_down = false;
Serial.println( "top switch down" );
delay(1000); // to remove debounce issues
if( digitalRead( TOP_TRIP_PIN ) == LOW )
Serial.println( "top is LOW" );
if( digitalRead( TOP_TRIP_PIN ) == HIGH )
Serial.println( "top is HIGH" );
attachInterrupt( digitalPinToInterrupt( TOP_TRIP_PIN ), ISR_top_switch_down, LOW );
}
}