by beep on Tue Apr 28, 2009 2:08 am

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 7:54 pm

by beep on Tue Apr 28, 2009 11:31 pm

Oops! Today I saw that Tutorial 5 has a "Brooklyn Debounce" section that teaches a better way of debouncing.
beep
 
Posts: 3
Joined: Sun Apr 26, 2009 7:54 pm