Skip to main content
Visitor II
November 25, 2019
Solved

Debouncing

  • November 25, 2019
  • 12 replies
  • 21187 views

Can anyone help me with debounce code in C for Rising and falling edge interrupt??

    This topic has been closed for replies.
    Best answer by waclawek.jan

    As the first thing, forget about the EXTI interrupt, and *never* use it again, when it comes to mechanical switches.

    Perform the sampling based on a timer, or timer-controlled process (either in timer interrupt, or based on flag set in timer interrupt, or any other mechanism ensuring you will do it regularly but not too often). You want to sample once in a few milliseconds, and you want to sample a few times - say four to twelve - basically for the duration of bouncing of the switch. Have a variable with several states controlling your process - "stable 0", "bouncing 1", "stable 1", "bouncing 0" - and then the transition between "bouncing x" to "stable x" is the "output edge" upon which you perform the action you want to do when the button is pressed/released.

    You also have to work more to remove the input noise, as Ozone said above.

    JW

    12 replies

    Visitor II
    December 13, 2022

    A bit of a late reply...

    BUT.. you can use EXTI, set for both edges.

    EXTI interrupt starts a timer if not started (say 1ms intervals). It also sets a counter to say 5.

    Each Timer interrupt you decrement the counter (but not past 0), when it reaches 0, you read the IO line and save it as its new value then stop the timer.

    This is a simple 5ms debounce using EXTI and TIM.

    The advantage is its not running if the input is static. Also since it sets a time base, you can run as many inputs as you want.

    Simon

    Graduate II
    April 17, 2024

    I made a tutorial on how to debounce a button and more tricks

    https://youtu.be/o0qhmXR5LD0?si=q97OaJehxHzC3Z9Z