Lesson 5 - counting presses improved by debouncing switch

For makers who have purchased an Adafruit Starter Pack, get help with the tutorials here!

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
beep
 
Posts: 3
Joined: Sun Apr 26, 2009 8:54 pm

Lesson 5 - counting presses improved by debouncing switch

Post by beep »

The counting presses sketch was often counting releases too.
I think this was caused by bounce in the switch contacts when releasing the switch.
I added a 10 msec delay as suggested by Banzi in "Getting Started with Arduino"
http://oreilly.com/catalog/9780596155513/
The delay eliminated the unwanted keypress messages.

Code: Select all

/*
 *  Counting presses
 */

int switchPin = 2;              // switch is connected to pin 2
int val;                        // variable for reading the pin status
int buttonState;                // variable to hold the button state
int buttonPresses = 0;          // how many times the button has been pressed

void setup() {
  pinMode(switchPin, INPUT);    // Set the switch pin as input

  Serial.begin(9600);           // Set up serial communication at 9600bps
  buttonState = digitalRead(switchPin);   // read the initial state
}

void loop(){
  val = digitalRead(switchPin);      // read input value and store it in val

  if (val != buttonState) {          // the button state has changed!
    if (val == LOW) {                // check if the button is pressed
      buttonPresses++;               // increment the buttonPresses variable
      Serial.print("Button has been pressed ");
      Serial.print(buttonPresses);
      Serial.println(" times");
    }
  }
  buttonState = val;                 // save the new state in our variable
  delay(10);                         // de-bounce mechanical switch contacts
}

beep
 
Posts: 3
Joined: Sun Apr 26, 2009 8:54 pm

Re: Lesson 5 - counting presses improved by debouncing switch

Post by beep »

Oops! Today I saw that Tutorial 5 has a "Brooklyn Debounce" section that teaches a better way of debouncing.

Locked
Please be positive and constructive with your questions and comments.

Return to “Arduino Starter Pack”