Arduino Switch Button Edge Detection And Debouncing Tutorial

preview_player
Показать описание
Let’s say we have this push button. And we want to use it to trigger single shot actions such as a counter or toggling an output.

It is wired between an Arduino input pin and ground.

First we have to ensure, that the input stays high, if the switch is not pressed.

So a pullup resistor between the input pin and VCC is required.

Mechanical switches tend to be bouncy. So a capacitor is required to smooth out the input signal.

But wait! Are all those components really required?

This test setup only consists of an Arduino Pro Micro, a push button and an LED with current limiting resistor.

No pullp resistor and no capacitor!

This example sketch can be downloaded on my GitHub

The button is connected to pin 4 and the LED to pin 10

First, we want to eliminate the pullup resistor

So we just set the pin mode to INPUT_PULLUP instead of INPUT

This enables the internal pullup resistor.

The next step is to write 2 macros for the detection of rising and falling edges.

What they basically do is to record and store the pin states in an endless loop.

To detect a debounced rising edge, we need to detect 4 times zero, followed by 4 times one

To detect a debounced falling edge, we need to detect 4 times one, followed by 4 times zero

The readButtons() function shows how to call the macros.

To provide additional debouncing, it is executed every 5 milliseconds.
You can vary this interval to see, what works best for you

The rising edge example just prints a message and the value of the detected
button state variable

The falling edge example is toggling the LED and prints a message

Of course you can also do other things like menu navigation and adjusting variables

Now let’s test the functionality of the test setup

I hope this little tutorial was helpful and will allow you to simplify your button wiring

Рекомендации по теме
Комментарии
Автор

Very elegant. It will help improve my current instal... thank you so much!

carlospitcher
Автор

I really enjoy ur video, Thx u so much!!
I have a "odd "question:

your code:


if (DRE(digitalRead(BUTTON1), button1RisingState)) {

Serial.print ("Rising edge (pulled high by internal pullup resistor). State variable: ");
Serial.println (button1RisingState);


In this part ""(digitalRead(BUTTON1)"", I would like not to use it instead I would like to use
MACROS like this "(~PIND & 1<<BUTTON1)". I've been trying it but I know something is missing.

thank you and sorry for my bad english!!

leonardoperalta
Автор

why is there a rising
Edge detected when I open the serial monitor and haven't even pressed the button

davidjarck