I am trying to get button input to navigate little GUI and control the device.
Program should recognize duration of button was pressed. Like short presses "clicks" and long presses.
I have no problems with catching "just a press" interrupts with configuring it to to FALLING mode. Port is INPUT_PULLUP.
This way it reliably detects when button was pressed down, shorting a pin to ground.
However when I try to capture a moment when button was released (with CHANGE mode), it works, but not always reliably.
Sometimes it misses button releases, sometimes it calls multiple interrupts for a single button release. Randomly.
Reading the pin inside the interrupt function (CHANGE mode), to get its state LOW or HIGH, also work unreliably when button is released.
Code: Select all
#include <Arduino.h>
volatile ulong b5d=0, b5u=0;
String output="";
void change5() {
unsigned long m = millis();
int r=digitalRead(5);
output += "change_5:";
if (r == HIGH) b5u=m;
else b5d=m;
if (r == HIGH) {
ulong x = b5u-b5d;
output += " down:"+String(b5d)+" up:"+String(b5u)+" dur:"+String(x)+"\n";
}
else output += "\n";
}
void setup(){
Serial.begin(9600);
delay(2000);
pinMode(5, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(5), change5, CHANGE);
}
int i=0;
void loop(){
noInterrupts(); // String is not volatile, disable interrupts while accessing it
if (output!=""){
Serial.print(output);
output="";
}
interrupts();
i++;
delay(500);
}
Please help.
Thanks,
Mark