nrf-rs / microbit

A Rust crate for BBC micro:bit development
BSD Zero Clause License
276 stars 61 forks source link

Multiple interrupt triggers on single button press when running example #97

Closed videbar closed 2 years ago

videbar commented 2 years ago

I have flashed the gpio-hal-printbuttons example on the microbit-v2. This example should print either Button pressed "A", Button pressed "B" or Button pressed "A + B", as soon as the buttons on the microbit board are pressed.

I noticed that, on occasions, pressing a button once causes the statement to be printed multiple times, which seems to indicate that the interrupt is triggering more than once for a single button press.

mattheww commented 2 years ago

Yes, that's what the hardware does: the button often "bounces".

In practice it's often easiest to sample the button state in a timer interrupt instead of using GPIO interrupts.

The "DAL" C++ micro:bit runtime does this using the same 6ms timer as for the display. It goes further than simply sampling and "debounces" the input using a counter, but I don't think that's necessary for the built-in buttons.

videbar commented 2 years ago

I suspected that it may be caused by the hardware, thanks for pointing me to the button bounce.

If I want a function that runs when the button is pressed and I use a timer interrupt to sample the button state, if the button is kept being pressed, the function will continue to run each e.g. 6ms right?

I must also keep track of the previous state so I can call the function when previous state = not pressed and current state = pressed.

mattheww commented 2 years ago

Yes, that's the usual thing to do.

videbar commented 2 years ago

Ok, thanks a lot for the explanation, I'll close the issue now.