Skip to content

Instantly share code, notes, and snippets.

@lyneca
Last active August 20, 2018 11:52
Show Gist options
  • Save lyneca/89902fc476971bfdca015cb81bf7fc41 to your computer and use it in GitHub Desktop.
Save lyneca/89902fc476971bfdca015cb81bf7fc41 to your computer and use it in GitHub Desktop.
Debounce Example
/*
* Adapted from the [completely broken] DFRobot example sketches
* by Luke Tuthill:
* https://www.dfrobot.com/blog-662.html
*
*
* This sketch shows how to debounce a button. Sometimes, when you press
* a button, it's not perfect - sometimes it 'bounces' up and down slightly,
* and registers multiple presses.
*
* We can fix this by ignoring all input from the button for a certain duration
* after the button is pressed, in this case, 50ms.
*/
// Attach the button to pin 2
int BUTTON = 2;
// Attach an LED_PIN to pin 3
int LED_PIN = 13;
// The delay (in ms) to ignore button bounces after press
long DEBOUNCE_DELAY = 50;
// Variable to store the LED_PIN state
int ledState = HIGH;
// The last button state; what the button
// was _last time_ we checked
int lastButtonState = LOW;
// The time in milliseconds that the button was last pressed
long lastDebounceTime = 0;
void setup() {
// Setup pin modes
pinMode(BUTTON, INPUT);
pinMode(LED_PIN, OUTPUT);
// Set initial LED_PIN state
digitalWrite(LED_PIN, ledState);
// Begin serial connection to show values
Serial.begin(9600);
}
void loop() {
// Get the value of the button, HIGH or LOW
int state = digitalRead(BUTTON);
// Print it to the serial terminal
Serial.println(state);
// If the current time minus the last time that the button
// is pressed is greater than the delay we have set
if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
// Get the time in milliseconds, and store it in lastDebounceTime
lastDebounceTime = millis();
// If the button's state is different to what it was before:
if (state != lastButtonState) {
// Save the new button state
lastButtonState = state;
// If the button is on, switch the LED's state.
if (state == HIGH) {
/*
* The ! before the variable here is called a 'not',
* and it means:
* - If ledState is a 1, return 0
* - If ledState is a 0, return 1
* This is then fed back into ledState, so
* ledState will become the opposite of what
* it was before - known as 'inverting'.
*/
ledState = !ledState;
}
}
}
// Set the LED to ledState
digitalWrite(LED_PIN, ledState);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment