Search code examples
embeddedmicrocontrollerinterruptkeypress

Button press and hold detection in microcontroller


I'm trying to implement a logic to detect a keypress and hold from a RF remote. Currently I'm able to detect the button press in my controller RF receiver. I'm getting the interrupt callback for every press. Now how do I detect a press and hold for 5 sec in the code?

I checked in the oscilloscope that when I press and hold a key in remote, I get the RF data in my receiver every 34ms.

All I can think of is to count the number of sequential interrupts with the same data in 5 secs and validate it but I'm not sure its the right way.

Any suggestions how to implement it. I will try it.

Thanks


Solution

  • A good idea with any button, direct, or as in this case remote, is to detect both press and release. Then apply the press and hold timing on top of that. In that way physical and remote buttons can be handled in the same manner.

    In this case you could detect release by setting a 50ms timer that is restarted on every 35ms button interrupt. Then if the 50ms timer expires, the button has been released (or gone out of range).

    Then for the 5 second hold, you could have 5 second timer that can be started on button down, and cancelled on button release. Similarly, if that timer expires you trigger the hold event.

    The timers could be implemented in software or hardware, although it might be a poor use of resources to dedicate two hardware timers to one button.

    See also Pressing button for 3 seconds and how to measure its time with Atmega8 1MHz?. Given press/release detection as described above, you could apply the higher level hold timing as in the accepted answer to that question.