Go Down

Topic: Finding hard to understand de-bouncing code. (Read 849 times) previous topic - next topic


Hello All,

Here is the code(Please be aware that this code comes from the book of Massimo Banzi "Getting Started with Arduino". I kind of understand the concept behind bouncing, basically its about the switch not doing right connection and produce erratic results(e.g: the led not turning off, when I pressed the switch to turn it off). Is that right? Now, How does the delay(10) function prevents bouncing?  :~ See code below, please:

// Example 03C: Turn on LED when the button is pressed and keep it on after it is released.
// including simple de-bouncing
// Now with another new and improved formula!

const int LED = 13; // the pin for the LED
const int BUTTON = 7;  // the input pin where the pushbutton is connected.

int val = 0;  // val will be used to store the state of the input pin

int old_val= 0; //this variable stores the previous value of "val"

int state = 0; // 0 = LED off while 1 = LED on

void setup(){
  pinMode (LED, OUTPUT); //tell Arduino LED is an output
  pinMode (BUTTON, INPUT); //tell Arduino Button is an input

void loop(){
  val = digitalRead(BUTTON); // read input value and store it
  // check if the inpout is HIGH (button pressed)
  //change the state ***** This is the part that I dont understand. Why do I have to use the delay function?
  if ((val == HIGH) && (old_val == LOW)){
    state = 1 - state;
  old_val = val; //val is now old, let's store it
  if (state == 1){
    digitalWrite (LED,HIGH); // turn LED ON
  } else{
    digitalWrite (LED, LOW);

Many thanks in advance.


How does the delay(10) function prevents bouncing?

Put simply, it doesn't and cannot.
Bounce is a mechanical effect, and will take place whether or not there is a delay.

What it does do is allow the bounce to complete.
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.
I speak for myself, not Arduino.


Hello Awol! Many thanks, I understand now.  :)


olivettix, it took me a while, but debouncing is simply for the part where metal to metal contact makes place (lifting/pressing) and as you do that, where the human can barely count faster than 1 a second, the CPU on the other hand can register the button touching thousands of times in that brief moment it makes contact.

so 100ms delay is better than 10ms, but that's up to you.


so 100ms delay is better than 10ms, but that's up to you.

Or even better, debounce without delay().

Go Up