Arduino Example

Arduino Button Debounce Example

Debounce a push button in software.

Wiring

Check pinout, power supply, common GND and voltage levels before connecting the module.

Full code

const int buttonPin = 2;
const int ledPin = 13;
int lastReading = HIGH;
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  int reading = digitalRead(buttonPin);
  if (reading != lastReading) lastDebounceTime = millis();
  if ((millis() - lastDebounceTime) > debounceDelay) {
    digitalWrite(ledPin, reading == LOW ? HIGH : LOW);
  }
  lastReading = reading;
}

How it works

This lesson matches the page title and gives a clean starting point for this exact example.

Common mistakes

Check board selection, wiring, libraries, power supply and serial monitor baud rate.

Frequently asked questions

Can I copy this code?

Yes. Adapt pins, credentials and libraries for your board.

Why does it not compile?

Install required libraries and select the correct board.