Question about debouncing - delay of state change Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)Debouncing buttonsdigitalRead sampling rate for Arduino UnoHow to eliminate the forbidden state in an SR latch?Debouncing by ignoring data?Hardware buttons debouncing crosstalkA question about a debouncing circuitButtons and encoder debouncingDelay on 12v sort of debouncing circuit?Latching Soft ON/OFF ButtonLED Circuit design (4 switches, 1 potentiometer)

Disembodied hand growing fangs

Converted a Scalar function to a TVF function for parallel execution-Still running in Serial mode

How fail-safe is nr as stop bytes?

How would a mousetrap for use in space work?

How do living politicians protect their readily obtainable signatures from misuse?

Central Vacuuming: Is it worth it, and how does it compare to normal vacuuming?

Did Deadpool rescue all of the X-Force?

Do wooden building fires get hotter than 600°C?

Do I really need to have a message in a novel to appeal to readers?

What is the difference between globalisation and imperialism?

What is the topology associated with the algebras for the ultrafilter monad?

Morning, Afternoon, Night Kanji

If Windows 7 doesn't support WSL, then what does Linux subsystem option mean?

What is this clumpy 20-30cm high yellow-flowered plant?

Time to Settle Down!

Is there hard evidence that the grant peer review system performs significantly better than random?

Should I use a zero-interest credit card for a large one-time purchase?

Can a new player join a group only when a new campaign starts?

Trademark violation for app?

Crossing US/Canada Border for less than 24 hours

Amount of permutations on an NxNxN Rubik's Cube

Can anything be seen from the center of the Boötes void? How dark would it be?

Question about debouncing - delay of state change

Denied boarding although I have proper visa and documentation. To whom should I make a complaint?



Question about debouncing - delay of state change



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)Debouncing buttonsdigitalRead sampling rate for Arduino UnoHow to eliminate the forbidden state in an SR latch?Debouncing by ignoring data?Hardware buttons debouncing crosstalkA question about a debouncing circuitButtons and encoder debouncingDelay on 12v sort of debouncing circuit?Latching Soft ON/OFF ButtonLED Circuit design (4 switches, 1 potentiometer)



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2












$begingroup$


I have a very simple project where I needed to debounce a button (in software). Logically, my thought process is:



  • If the state's been stable for a while, and it changes, then immediately signal an event.


  • Ensure that the next state is stable before allowing another state change.


So if a button isn't pressed and has been that way for a while, but all of the sudden I read a changed input, I don't think I should need to wait to confirm that the changed input has been stable (I know that there has been an actual physical change to the button state). I can simply signal an event, but disallow new events for some set period of time to prevent false button bounces from signaling events.



Here's arduino code for a function getAction() done this way:



static int buttonBounceState = BUTTON_STATE_UP; // "Bouncing" state
static int buttonState = BUTTON_STATE_UP; // Debounced state
static unsigned long lastChangeMillis = 0; // Time of last state transition
unsigned long currentMillis;

buttonBounceState = digitalRead(BUTTON_PIN);

if (buttonBounceState != buttonState)
// Only allow state change if it's been 20 millis since last
currentMillis = millis()
if (currentMillis >= lastChangeMillis + 20)
buttonState = buttonBounceState; // Change state
lastChangeMillis = currentMillis; // Only update timings at state transition
// Button state has changed, so return an action
if (buttonState == BUTTON_STATE_DOWN) return ACT_PRESS;
else return ACT_RELEASE;


// No button state change. Return no action.
return ACT_NONE;


However, it seems that everywhere I look, the way debouncing is done is that the initial state transition needs to become stable before actually performing a software state change/event signaling. For example, the bottom picture here: https://www.baldengineer.com/arduino-de-bounce-a-button-with-micros.html



My question: is it better to do debouncing this way? Is there something about my method that might fail that I'm not thinking about - i.e., some sort of noise while button is stable-open or stable-closed? If not, it seems that my method would give more accurate timings; and I don't miss very quick button taps (but delay until stable would). Also, how do these two software methods relate to hardware debouncing. How would a hardware debouncer be implemented that can time things similar to my method?










share|improve this question









New contributor




BobIsNotMyName is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$











  • $begingroup$
    What happens if you get noise that changes the input for just a cycle or two as you read the input? Now it returns the press and then after 20ms blanking, the release.
    $endgroup$
    – Phil G
    5 hours ago










  • $begingroup$
    There are many different justifications, none over-riding others. It depends on the circumstances. On some instrumentation I've worked on, it's quite possible for someone to accidentally "brush by" the equipment without intending anything. And it's also quite possible, since switches are sometimes not on the circuit card itself but removed from it and installed on a chassis, to have noise that may in some circumstances be large enough to trigger an event that should be ignored. So, you make decisions based on other knowledge and experience. Few bright lines exist.
    $endgroup$
    – jonk
    4 hours ago

















2












$begingroup$


I have a very simple project where I needed to debounce a button (in software). Logically, my thought process is:



  • If the state's been stable for a while, and it changes, then immediately signal an event.


  • Ensure that the next state is stable before allowing another state change.


So if a button isn't pressed and has been that way for a while, but all of the sudden I read a changed input, I don't think I should need to wait to confirm that the changed input has been stable (I know that there has been an actual physical change to the button state). I can simply signal an event, but disallow new events for some set period of time to prevent false button bounces from signaling events.



Here's arduino code for a function getAction() done this way:



static int buttonBounceState = BUTTON_STATE_UP; // "Bouncing" state
static int buttonState = BUTTON_STATE_UP; // Debounced state
static unsigned long lastChangeMillis = 0; // Time of last state transition
unsigned long currentMillis;

buttonBounceState = digitalRead(BUTTON_PIN);

if (buttonBounceState != buttonState)
// Only allow state change if it's been 20 millis since last
currentMillis = millis()
if (currentMillis >= lastChangeMillis + 20)
buttonState = buttonBounceState; // Change state
lastChangeMillis = currentMillis; // Only update timings at state transition
// Button state has changed, so return an action
if (buttonState == BUTTON_STATE_DOWN) return ACT_PRESS;
else return ACT_RELEASE;


// No button state change. Return no action.
return ACT_NONE;


However, it seems that everywhere I look, the way debouncing is done is that the initial state transition needs to become stable before actually performing a software state change/event signaling. For example, the bottom picture here: https://www.baldengineer.com/arduino-de-bounce-a-button-with-micros.html



My question: is it better to do debouncing this way? Is there something about my method that might fail that I'm not thinking about - i.e., some sort of noise while button is stable-open or stable-closed? If not, it seems that my method would give more accurate timings; and I don't miss very quick button taps (but delay until stable would). Also, how do these two software methods relate to hardware debouncing. How would a hardware debouncer be implemented that can time things similar to my method?










share|improve this question









New contributor




BobIsNotMyName is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$











  • $begingroup$
    What happens if you get noise that changes the input for just a cycle or two as you read the input? Now it returns the press and then after 20ms blanking, the release.
    $endgroup$
    – Phil G
    5 hours ago










  • $begingroup$
    There are many different justifications, none over-riding others. It depends on the circumstances. On some instrumentation I've worked on, it's quite possible for someone to accidentally "brush by" the equipment without intending anything. And it's also quite possible, since switches are sometimes not on the circuit card itself but removed from it and installed on a chassis, to have noise that may in some circumstances be large enough to trigger an event that should be ignored. So, you make decisions based on other knowledge and experience. Few bright lines exist.
    $endgroup$
    – jonk
    4 hours ago













2












2








2





$begingroup$


I have a very simple project where I needed to debounce a button (in software). Logically, my thought process is:



  • If the state's been stable for a while, and it changes, then immediately signal an event.


  • Ensure that the next state is stable before allowing another state change.


So if a button isn't pressed and has been that way for a while, but all of the sudden I read a changed input, I don't think I should need to wait to confirm that the changed input has been stable (I know that there has been an actual physical change to the button state). I can simply signal an event, but disallow new events for some set period of time to prevent false button bounces from signaling events.



Here's arduino code for a function getAction() done this way:



static int buttonBounceState = BUTTON_STATE_UP; // "Bouncing" state
static int buttonState = BUTTON_STATE_UP; // Debounced state
static unsigned long lastChangeMillis = 0; // Time of last state transition
unsigned long currentMillis;

buttonBounceState = digitalRead(BUTTON_PIN);

if (buttonBounceState != buttonState)
// Only allow state change if it's been 20 millis since last
currentMillis = millis()
if (currentMillis >= lastChangeMillis + 20)
buttonState = buttonBounceState; // Change state
lastChangeMillis = currentMillis; // Only update timings at state transition
// Button state has changed, so return an action
if (buttonState == BUTTON_STATE_DOWN) return ACT_PRESS;
else return ACT_RELEASE;


// No button state change. Return no action.
return ACT_NONE;


However, it seems that everywhere I look, the way debouncing is done is that the initial state transition needs to become stable before actually performing a software state change/event signaling. For example, the bottom picture here: https://www.baldengineer.com/arduino-de-bounce-a-button-with-micros.html



My question: is it better to do debouncing this way? Is there something about my method that might fail that I'm not thinking about - i.e., some sort of noise while button is stable-open or stable-closed? If not, it seems that my method would give more accurate timings; and I don't miss very quick button taps (but delay until stable would). Also, how do these two software methods relate to hardware debouncing. How would a hardware debouncer be implemented that can time things similar to my method?










share|improve this question









New contributor




BobIsNotMyName is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$




I have a very simple project where I needed to debounce a button (in software). Logically, my thought process is:



  • If the state's been stable for a while, and it changes, then immediately signal an event.


  • Ensure that the next state is stable before allowing another state change.


So if a button isn't pressed and has been that way for a while, but all of the sudden I read a changed input, I don't think I should need to wait to confirm that the changed input has been stable (I know that there has been an actual physical change to the button state). I can simply signal an event, but disallow new events for some set period of time to prevent false button bounces from signaling events.



Here's arduino code for a function getAction() done this way:



static int buttonBounceState = BUTTON_STATE_UP; // "Bouncing" state
static int buttonState = BUTTON_STATE_UP; // Debounced state
static unsigned long lastChangeMillis = 0; // Time of last state transition
unsigned long currentMillis;

buttonBounceState = digitalRead(BUTTON_PIN);

if (buttonBounceState != buttonState)
// Only allow state change if it's been 20 millis since last
currentMillis = millis()
if (currentMillis >= lastChangeMillis + 20)
buttonState = buttonBounceState; // Change state
lastChangeMillis = currentMillis; // Only update timings at state transition
// Button state has changed, so return an action
if (buttonState == BUTTON_STATE_DOWN) return ACT_PRESS;
else return ACT_RELEASE;


// No button state change. Return no action.
return ACT_NONE;


However, it seems that everywhere I look, the way debouncing is done is that the initial state transition needs to become stable before actually performing a software state change/event signaling. For example, the bottom picture here: https://www.baldengineer.com/arduino-de-bounce-a-button-with-micros.html



My question: is it better to do debouncing this way? Is there something about my method that might fail that I'm not thinking about - i.e., some sort of noise while button is stable-open or stable-closed? If not, it seems that my method would give more accurate timings; and I don't miss very quick button taps (but delay until stable would). Also, how do these two software methods relate to hardware debouncing. How would a hardware debouncer be implemented that can time things similar to my method?







arduino button debounce






share|improve this question









New contributor




BobIsNotMyName is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




BobIsNotMyName is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 5 hours ago







BobIsNotMyName













New contributor




BobIsNotMyName is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 6 hours ago









BobIsNotMyNameBobIsNotMyName

133




133




New contributor




BobIsNotMyName is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





BobIsNotMyName is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






BobIsNotMyName is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











  • $begingroup$
    What happens if you get noise that changes the input for just a cycle or two as you read the input? Now it returns the press and then after 20ms blanking, the release.
    $endgroup$
    – Phil G
    5 hours ago










  • $begingroup$
    There are many different justifications, none over-riding others. It depends on the circumstances. On some instrumentation I've worked on, it's quite possible for someone to accidentally "brush by" the equipment without intending anything. And it's also quite possible, since switches are sometimes not on the circuit card itself but removed from it and installed on a chassis, to have noise that may in some circumstances be large enough to trigger an event that should be ignored. So, you make decisions based on other knowledge and experience. Few bright lines exist.
    $endgroup$
    – jonk
    4 hours ago
















  • $begingroup$
    What happens if you get noise that changes the input for just a cycle or two as you read the input? Now it returns the press and then after 20ms blanking, the release.
    $endgroup$
    – Phil G
    5 hours ago










  • $begingroup$
    There are many different justifications, none over-riding others. It depends on the circumstances. On some instrumentation I've worked on, it's quite possible for someone to accidentally "brush by" the equipment without intending anything. And it's also quite possible, since switches are sometimes not on the circuit card itself but removed from it and installed on a chassis, to have noise that may in some circumstances be large enough to trigger an event that should be ignored. So, you make decisions based on other knowledge and experience. Few bright lines exist.
    $endgroup$
    – jonk
    4 hours ago















$begingroup$
What happens if you get noise that changes the input for just a cycle or two as you read the input? Now it returns the press and then after 20ms blanking, the release.
$endgroup$
– Phil G
5 hours ago




$begingroup$
What happens if you get noise that changes the input for just a cycle or two as you read the input? Now it returns the press and then after 20ms blanking, the release.
$endgroup$
– Phil G
5 hours ago












$begingroup$
There are many different justifications, none over-riding others. It depends on the circumstances. On some instrumentation I've worked on, it's quite possible for someone to accidentally "brush by" the equipment without intending anything. And it's also quite possible, since switches are sometimes not on the circuit card itself but removed from it and installed on a chassis, to have noise that may in some circumstances be large enough to trigger an event that should be ignored. So, you make decisions based on other knowledge and experience. Few bright lines exist.
$endgroup$
– jonk
4 hours ago




$begingroup$
There are many different justifications, none over-riding others. It depends on the circumstances. On some instrumentation I've worked on, it's quite possible for someone to accidentally "brush by" the equipment without intending anything. And it's also quite possible, since switches are sometimes not on the circuit card itself but removed from it and installed on a chassis, to have noise that may in some circumstances be large enough to trigger an event that should be ignored. So, you make decisions based on other knowledge and experience. Few bright lines exist.
$endgroup$
– jonk
4 hours ago










3 Answers
3






active

oldest

votes


















0












$begingroup$

If you debounce by reacting immediately and blanking the button (ignoring subesquent stage changes for a pre-specified time), the benefit is low latency. The drawback is vulnerability to induced noise which can make or break some systems.



People don't react fast enough to notice a 10ms latency so I think it's usually best to debounce by checking that a change-of-state is stable for a few ms before reacting. That way you can prevent unexpected noise issues.



The main reason I sometimes debounce with "react immediately then blank" is when I am writing something quick and dirty test code which will ultimately be removed. I find it's usually simpler and less invasive to code the debounce this way so its faster to write and easier to remove from the final code.



Some hardware debouncers like the MAX6816 use hard-wired timers and counters. The MAX6816, in particular, waits for the state to be stable for a certain amount of time before passing it through.



On an FPGA it is also hard-wired in the sense timers, counters, and sampling register are used. You can have it react immediately then blank, or wait until the switch as stabilized before passing the signal through.



JK-flip flop debouncers change state immediately then "blank". I put blank in quotes because they do not use a time interval to ignore subsequent changes. Rather, it relies on something more akin to mechanical hysteresis. It immediately change state if and only if positive contact electrical is made. It does not react if contact is merely lost. Therefore, if contact is lost inside the switch (like due to a bounce) but no new positive contact is made, they do not change state. The switch should never be able to bounce so hard that flies far enough in the opposite direction to hit the other contact. This is similar to conservation of energy where a dropped ball should never bounce back up to the height from which it was dropped.



There are other methods of debouncing too like using low-pass filters and comparators which sort of relies on the switch to be stable for long enough, but can also be falsely triggered if the switch bounces too many times and the time constant is chosen to be too short since the capacitor will continue to charge or discharge as the switch makes contact with each bounce.






share|improve this answer











$endgroup$




















    5












    $begingroup$

    There's absolutely nothing wrong with doing "leading edge" debouncing as you describe it — in fact, it's the method that I prefer in my own projects.



    As you say, as soon as you see the first edge, you know that the user has initiated an action, so there's no reason to delay acting on it. The system will "feel" more responsive to the user.



    The only reason to use "trailing edge" debouncing (the kind you've been finding) would be if there's some reason (EMI, ESD, etc.) that an input might glitch that isn't actually caused by user action.






    share|improve this answer









    $endgroup$












    • $begingroup$
      Thanks for this. I know plenty about software, but venturing into electronics I find that it's sometimes difficult to find information simply because of a lack of vocabulary - e.g., "leading edge" and "trailing edge" (though I'm sure these concepts come up in purely software domains as well)
      $endgroup$
      – BobIsNotMyName
      3 hours ago


















    0












    $begingroup$

    There is no better way as each case can have different switches, different environment or different requirements. Your solution will work fine, if there is no false pulses for some reason. One example would be a normally closed connection, but under mechanical vibrations it might open and cause occasional false triggers, and reacting to every edge would just amplify the problem. It is a delicate balance between debouncing enough to keep unwanted noise away and not spending too much time, like polling in a tight loop for 10 milliseconds that the IO pin really stays active during that time before believing it is pushed.






    share|improve this answer









    $endgroup$













      Your Answer






      StackExchange.ifUsing("editor", function ()
      return StackExchange.using("schematics", function ()
      StackExchange.schematics.init();
      );
      , "cicuitlab");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "135"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );






      BobIsNotMyName is a new contributor. Be nice, and check out our Code of Conduct.









      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2felectronics.stackexchange.com%2fquestions%2f433306%2fquestion-about-debouncing-delay-of-state-change%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0












      $begingroup$

      If you debounce by reacting immediately and blanking the button (ignoring subesquent stage changes for a pre-specified time), the benefit is low latency. The drawback is vulnerability to induced noise which can make or break some systems.



      People don't react fast enough to notice a 10ms latency so I think it's usually best to debounce by checking that a change-of-state is stable for a few ms before reacting. That way you can prevent unexpected noise issues.



      The main reason I sometimes debounce with "react immediately then blank" is when I am writing something quick and dirty test code which will ultimately be removed. I find it's usually simpler and less invasive to code the debounce this way so its faster to write and easier to remove from the final code.



      Some hardware debouncers like the MAX6816 use hard-wired timers and counters. The MAX6816, in particular, waits for the state to be stable for a certain amount of time before passing it through.



      On an FPGA it is also hard-wired in the sense timers, counters, and sampling register are used. You can have it react immediately then blank, or wait until the switch as stabilized before passing the signal through.



      JK-flip flop debouncers change state immediately then "blank". I put blank in quotes because they do not use a time interval to ignore subsequent changes. Rather, it relies on something more akin to mechanical hysteresis. It immediately change state if and only if positive contact electrical is made. It does not react if contact is merely lost. Therefore, if contact is lost inside the switch (like due to a bounce) but no new positive contact is made, they do not change state. The switch should never be able to bounce so hard that flies far enough in the opposite direction to hit the other contact. This is similar to conservation of energy where a dropped ball should never bounce back up to the height from which it was dropped.



      There are other methods of debouncing too like using low-pass filters and comparators which sort of relies on the switch to be stable for long enough, but can also be falsely triggered if the switch bounces too many times and the time constant is chosen to be too short since the capacitor will continue to charge or discharge as the switch makes contact with each bounce.






      share|improve this answer











      $endgroup$

















        0












        $begingroup$

        If you debounce by reacting immediately and blanking the button (ignoring subesquent stage changes for a pre-specified time), the benefit is low latency. The drawback is vulnerability to induced noise which can make or break some systems.



        People don't react fast enough to notice a 10ms latency so I think it's usually best to debounce by checking that a change-of-state is stable for a few ms before reacting. That way you can prevent unexpected noise issues.



        The main reason I sometimes debounce with "react immediately then blank" is when I am writing something quick and dirty test code which will ultimately be removed. I find it's usually simpler and less invasive to code the debounce this way so its faster to write and easier to remove from the final code.



        Some hardware debouncers like the MAX6816 use hard-wired timers and counters. The MAX6816, in particular, waits for the state to be stable for a certain amount of time before passing it through.



        On an FPGA it is also hard-wired in the sense timers, counters, and sampling register are used. You can have it react immediately then blank, or wait until the switch as stabilized before passing the signal through.



        JK-flip flop debouncers change state immediately then "blank". I put blank in quotes because they do not use a time interval to ignore subsequent changes. Rather, it relies on something more akin to mechanical hysteresis. It immediately change state if and only if positive contact electrical is made. It does not react if contact is merely lost. Therefore, if contact is lost inside the switch (like due to a bounce) but no new positive contact is made, they do not change state. The switch should never be able to bounce so hard that flies far enough in the opposite direction to hit the other contact. This is similar to conservation of energy where a dropped ball should never bounce back up to the height from which it was dropped.



        There are other methods of debouncing too like using low-pass filters and comparators which sort of relies on the switch to be stable for long enough, but can also be falsely triggered if the switch bounces too many times and the time constant is chosen to be too short since the capacitor will continue to charge or discharge as the switch makes contact with each bounce.






        share|improve this answer











        $endgroup$















          0












          0








          0





          $begingroup$

          If you debounce by reacting immediately and blanking the button (ignoring subesquent stage changes for a pre-specified time), the benefit is low latency. The drawback is vulnerability to induced noise which can make or break some systems.



          People don't react fast enough to notice a 10ms latency so I think it's usually best to debounce by checking that a change-of-state is stable for a few ms before reacting. That way you can prevent unexpected noise issues.



          The main reason I sometimes debounce with "react immediately then blank" is when I am writing something quick and dirty test code which will ultimately be removed. I find it's usually simpler and less invasive to code the debounce this way so its faster to write and easier to remove from the final code.



          Some hardware debouncers like the MAX6816 use hard-wired timers and counters. The MAX6816, in particular, waits for the state to be stable for a certain amount of time before passing it through.



          On an FPGA it is also hard-wired in the sense timers, counters, and sampling register are used. You can have it react immediately then blank, or wait until the switch as stabilized before passing the signal through.



          JK-flip flop debouncers change state immediately then "blank". I put blank in quotes because they do not use a time interval to ignore subsequent changes. Rather, it relies on something more akin to mechanical hysteresis. It immediately change state if and only if positive contact electrical is made. It does not react if contact is merely lost. Therefore, if contact is lost inside the switch (like due to a bounce) but no new positive contact is made, they do not change state. The switch should never be able to bounce so hard that flies far enough in the opposite direction to hit the other contact. This is similar to conservation of energy where a dropped ball should never bounce back up to the height from which it was dropped.



          There are other methods of debouncing too like using low-pass filters and comparators which sort of relies on the switch to be stable for long enough, but can also be falsely triggered if the switch bounces too many times and the time constant is chosen to be too short since the capacitor will continue to charge or discharge as the switch makes contact with each bounce.






          share|improve this answer











          $endgroup$



          If you debounce by reacting immediately and blanking the button (ignoring subesquent stage changes for a pre-specified time), the benefit is low latency. The drawback is vulnerability to induced noise which can make or break some systems.



          People don't react fast enough to notice a 10ms latency so I think it's usually best to debounce by checking that a change-of-state is stable for a few ms before reacting. That way you can prevent unexpected noise issues.



          The main reason I sometimes debounce with "react immediately then blank" is when I am writing something quick and dirty test code which will ultimately be removed. I find it's usually simpler and less invasive to code the debounce this way so its faster to write and easier to remove from the final code.



          Some hardware debouncers like the MAX6816 use hard-wired timers and counters. The MAX6816, in particular, waits for the state to be stable for a certain amount of time before passing it through.



          On an FPGA it is also hard-wired in the sense timers, counters, and sampling register are used. You can have it react immediately then blank, or wait until the switch as stabilized before passing the signal through.



          JK-flip flop debouncers change state immediately then "blank". I put blank in quotes because they do not use a time interval to ignore subsequent changes. Rather, it relies on something more akin to mechanical hysteresis. It immediately change state if and only if positive contact electrical is made. It does not react if contact is merely lost. Therefore, if contact is lost inside the switch (like due to a bounce) but no new positive contact is made, they do not change state. The switch should never be able to bounce so hard that flies far enough in the opposite direction to hit the other contact. This is similar to conservation of energy where a dropped ball should never bounce back up to the height from which it was dropped.



          There are other methods of debouncing too like using low-pass filters and comparators which sort of relies on the switch to be stable for long enough, but can also be falsely triggered if the switch bounces too many times and the time constant is chosen to be too short since the capacitor will continue to charge or discharge as the switch makes contact with each bounce.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 2 hours ago

























          answered 4 hours ago









          ToorToor

          1,706213




          1,706213























              5












              $begingroup$

              There's absolutely nothing wrong with doing "leading edge" debouncing as you describe it — in fact, it's the method that I prefer in my own projects.



              As you say, as soon as you see the first edge, you know that the user has initiated an action, so there's no reason to delay acting on it. The system will "feel" more responsive to the user.



              The only reason to use "trailing edge" debouncing (the kind you've been finding) would be if there's some reason (EMI, ESD, etc.) that an input might glitch that isn't actually caused by user action.






              share|improve this answer









              $endgroup$












              • $begingroup$
                Thanks for this. I know plenty about software, but venturing into electronics I find that it's sometimes difficult to find information simply because of a lack of vocabulary - e.g., "leading edge" and "trailing edge" (though I'm sure these concepts come up in purely software domains as well)
                $endgroup$
                – BobIsNotMyName
                3 hours ago















              5












              $begingroup$

              There's absolutely nothing wrong with doing "leading edge" debouncing as you describe it — in fact, it's the method that I prefer in my own projects.



              As you say, as soon as you see the first edge, you know that the user has initiated an action, so there's no reason to delay acting on it. The system will "feel" more responsive to the user.



              The only reason to use "trailing edge" debouncing (the kind you've been finding) would be if there's some reason (EMI, ESD, etc.) that an input might glitch that isn't actually caused by user action.






              share|improve this answer









              $endgroup$












              • $begingroup$
                Thanks for this. I know plenty about software, but venturing into electronics I find that it's sometimes difficult to find information simply because of a lack of vocabulary - e.g., "leading edge" and "trailing edge" (though I'm sure these concepts come up in purely software domains as well)
                $endgroup$
                – BobIsNotMyName
                3 hours ago













              5












              5








              5





              $begingroup$

              There's absolutely nothing wrong with doing "leading edge" debouncing as you describe it — in fact, it's the method that I prefer in my own projects.



              As you say, as soon as you see the first edge, you know that the user has initiated an action, so there's no reason to delay acting on it. The system will "feel" more responsive to the user.



              The only reason to use "trailing edge" debouncing (the kind you've been finding) would be if there's some reason (EMI, ESD, etc.) that an input might glitch that isn't actually caused by user action.






              share|improve this answer









              $endgroup$



              There's absolutely nothing wrong with doing "leading edge" debouncing as you describe it — in fact, it's the method that I prefer in my own projects.



              As you say, as soon as you see the first edge, you know that the user has initiated an action, so there's no reason to delay acting on it. The system will "feel" more responsive to the user.



              The only reason to use "trailing edge" debouncing (the kind you've been finding) would be if there's some reason (EMI, ESD, etc.) that an input might glitch that isn't actually caused by user action.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 5 hours ago









              Dave TweedDave Tweed

              125k10155269




              125k10155269











              • $begingroup$
                Thanks for this. I know plenty about software, but venturing into electronics I find that it's sometimes difficult to find information simply because of a lack of vocabulary - e.g., "leading edge" and "trailing edge" (though I'm sure these concepts come up in purely software domains as well)
                $endgroup$
                – BobIsNotMyName
                3 hours ago
















              • $begingroup$
                Thanks for this. I know plenty about software, but venturing into electronics I find that it's sometimes difficult to find information simply because of a lack of vocabulary - e.g., "leading edge" and "trailing edge" (though I'm sure these concepts come up in purely software domains as well)
                $endgroup$
                – BobIsNotMyName
                3 hours ago















              $begingroup$
              Thanks for this. I know plenty about software, but venturing into electronics I find that it's sometimes difficult to find information simply because of a lack of vocabulary - e.g., "leading edge" and "trailing edge" (though I'm sure these concepts come up in purely software domains as well)
              $endgroup$
              – BobIsNotMyName
              3 hours ago




              $begingroup$
              Thanks for this. I know plenty about software, but venturing into electronics I find that it's sometimes difficult to find information simply because of a lack of vocabulary - e.g., "leading edge" and "trailing edge" (though I'm sure these concepts come up in purely software domains as well)
              $endgroup$
              – BobIsNotMyName
              3 hours ago











              0












              $begingroup$

              There is no better way as each case can have different switches, different environment or different requirements. Your solution will work fine, if there is no false pulses for some reason. One example would be a normally closed connection, but under mechanical vibrations it might open and cause occasional false triggers, and reacting to every edge would just amplify the problem. It is a delicate balance between debouncing enough to keep unwanted noise away and not spending too much time, like polling in a tight loop for 10 milliseconds that the IO pin really stays active during that time before believing it is pushed.






              share|improve this answer









              $endgroup$

















                0












                $begingroup$

                There is no better way as each case can have different switches, different environment or different requirements. Your solution will work fine, if there is no false pulses for some reason. One example would be a normally closed connection, but under mechanical vibrations it might open and cause occasional false triggers, and reacting to every edge would just amplify the problem. It is a delicate balance between debouncing enough to keep unwanted noise away and not spending too much time, like polling in a tight loop for 10 milliseconds that the IO pin really stays active during that time before believing it is pushed.






                share|improve this answer









                $endgroup$















                  0












                  0








                  0





                  $begingroup$

                  There is no better way as each case can have different switches, different environment or different requirements. Your solution will work fine, if there is no false pulses for some reason. One example would be a normally closed connection, but under mechanical vibrations it might open and cause occasional false triggers, and reacting to every edge would just amplify the problem. It is a delicate balance between debouncing enough to keep unwanted noise away and not spending too much time, like polling in a tight loop for 10 milliseconds that the IO pin really stays active during that time before believing it is pushed.






                  share|improve this answer









                  $endgroup$



                  There is no better way as each case can have different switches, different environment or different requirements. Your solution will work fine, if there is no false pulses for some reason. One example would be a normally closed connection, but under mechanical vibrations it might open and cause occasional false triggers, and reacting to every edge would just amplify the problem. It is a delicate balance between debouncing enough to keep unwanted noise away and not spending too much time, like polling in a tight loop for 10 milliseconds that the IO pin really stays active during that time before believing it is pushed.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 5 hours ago









                  JustmeJustme

                  2,5211413




                  2,5211413




















                      BobIsNotMyName is a new contributor. Be nice, and check out our Code of Conduct.









                      draft saved

                      draft discarded


















                      BobIsNotMyName is a new contributor. Be nice, and check out our Code of Conduct.












                      BobIsNotMyName is a new contributor. Be nice, and check out our Code of Conduct.











                      BobIsNotMyName is a new contributor. Be nice, and check out our Code of Conduct.














                      Thanks for contributing an answer to Electrical Engineering Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      Use MathJax to format equations. MathJax reference.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2felectronics.stackexchange.com%2fquestions%2f433306%2fquestion-about-debouncing-delay-of-state-change%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      How to create a command for the “strange m” symbol in latex? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)How do you make your own symbol when Detexify fails?Writing bold small caps with mathpazo packageplus-minus symbol with parenthesis around the minus signGreek character in Beamer document titleHow to create dashed right arrow over symbol?Currency symbol: Turkish LiraDouble prec as a single symbol?Plus Sign Too Big; How to Call adfbullet?Is there a TeX macro for three-legged pi?How do I get my integral-like symbol to align like the integral?How to selectively substitute a letter with another symbol representing the same letterHow do I generate a less than symbol and vertical bar that are the same height?

                      Българска екзархия Съдържание История | Български екзарси | Вижте също | Външни препратки | Литература | Бележки | НавигацияУстав за управлението на българската екзархия. Цариград, 1870Слово на Ловешкия митрополит Иларион при откриването на Българския народен събор в Цариград на 23. II. 1870 г.Българската правда и гръцката кривда. От С. М. (= Софийски Мелетий). Цариград, 1872Предстоятели на Българската екзархияПодмененият ВеликденИнформационна агенция „Фокус“Димитър Ризов. Българите в техните исторически, етнографически и политически граници (Атлас съдържащ 40 карти). Berlin, Königliche Hoflithographie, Hof-Buch- und -Steindruckerei Wilhelm Greve, 1917Report of the International Commission to Inquire into the Causes and Conduct of the Balkan Wars

                      Category:Tremithousa Media in category "Tremithousa"Navigation menuUpload media34° 49′ 02.7″ N, 32° 26′ 37.32″ EOpenStreetMapGoogle EarthProximityramaReasonatorScholiaStatisticsWikiShootMe