Type Here to Get Search Results !

How To Handle Switch Bouncing In Your Arduino Code

As I said, we would like to improve our code, and in that case, let the user to click only once, it will turn ON and OFF, toggle between them.

We need to detect that the button was pressed and toggle the LEDs ON and OFF from the last state. if it was OFF then we will turn it ON, if it was ON let's turn that OFF, very simple meaning in that specific point where you see the blue triangle we will know that the button was pressed. however we need to handle some phenomenon that is called "switch bouncing" and let's explain that issue and how we can solve that.


while working with buttons we just can't look for the value of the switch to change from LOW to HIGH or from HIGH to LOW, as we need to handle a problem that is called "switch bouncing" and let's understand the problem over here. buttons are mechanical devices that operate much more slower than our Arduino system

in other words when we push a button down the signal we will read does not just go from LOW to HIGH. now during this bouncing time our program may translate that to several events of button press, and actually it is only one press the good news is that we can easily handle that using a software code, and it will be a good example for building a little bit more complicated sketch

now before jumping into the sketch itself, let's understand the logic of what we are planning to do. the following diagram present the status of a button during one single event, of a user pressing this button. now as you see there are two short periods of bouncing. when it is being pressed and of course released the software solution for handling switch bouncing is a little bit tricky.

but it is actually based on some simple logic, what we will do is hold the last button state in a new variable, and keep reading the current button value all the time

in case the "current" value is not HIGH, meaning someone just pressed the button then the program will wait for 5ms to let the switch status to stablize, and only than we will read it again. this will help us to avoid the bouncing period solving one part of the problem. now of course the "current" value will stay high as long as the button is being pressed, even if that for short period, and also will bounce again when it is being released

however we would like to toggle our LEDs only one time at the staring point and that's all, this is why we will check our two variables "current" button state and "last" button state. now think about for a second...., what condition we can check to assure that we will only toggle the LEDs once. well the condition will be, that's the condition we will check, let's see that in the final sketch result. Please watch this video for better understanding.



Post a Comment

0 Comments