The first step is drawing a sketch of the switch circuit.
Now let's use GPIO 8 as input that is connected one swith end.
// Pin where the button is connected
const int buttonPin = 8;
void setup() {
// Initialize Serial communication
Serial.begin(9600);
// Configure button pin as input with internal pull-up resistor
pinMode(buttonPin, INPUT_PULLUP);
Serial.println("Ready! Press the button...");
}
void loop() {
// Read the button state (LOW when pressed if using INPUT_PULLUP)
int buttonState = digitalRead(buttonPin);
if (buttonState == LOW) {
Serial.println("Button pressed!");
delay(200); // small delay to avoid multiple prints due to bouncing
}
}
When you press a mechanical switch, the metal contacts don't connect perfectly and instantly.
An oscilloscope trace of a single button press without debouncing looks like this:
HIGH +-------+ +---+ +-------
| | | | |
VOLT | +---+---+ +--_--+
| |
LOW +-----------+--------------------->
TIME
The microcontroller is so fast that it might read this single press as three, four, or more separate presses.
We can solve bouncing by adding a simple circuit to filter out the noise.
The circuit consists of a pull-up resistor and a capacitor to ground on the signal line.
The RC filter turns the noisy, bouncy signal into a smooth, clean transition.
Ideal Signal Bouncy Signal Filtered Signal
+-----+ +--+ +-+ +------_
| | | | | | | '
| | | +-+ +-- | '
| | | | \
+-----+ +--------- +----------'
The capacitor resists instantaneous changes in voltage, smoothing out the curve.
We will now look at a real switch on the bench connected to an oscilloscope.
Setup 1: No Debouncing
Result:
As seen on the oscilloscope, a single press creates a very "ugly" and noisy signal.
Setup 2: Hardware Debouncing
Result:
The oscilloscope now shows a clean, beautiful transition.
If you can't or don't want to add extra hardware, you can handle debouncing in your code.
The Core Idea:
To implement this, we need to keep track of the button's state and time between reads.
We use static variables so they retain their values between calls to the `loop()` function.
// Variables to hold the switch states
static int switchCurrentState = 0;
static int switchLastState = 0;
// Variable to store the time of the last state change
static unsigned long switchDebounceStartTime = 0;
// The debounce delay period in milliseconds
long debounceDelay = 100;
Inside the loop, we read the switch and compare its current state to its last known state, but only after a delay.
The `millis()` function returns the number of milliseconds since the Arduino started.
// Read the current physical state
switchCurrentState = digitalRead(SWITCH_PIN);
// Check if the state has changed
if (switchCurrentState != switchLastState) {
// If it has changed, reset the debounce timer
switchDebounceStartTime = millis();
}
After a state change is detected and the timer is reset, we wait for the `debounceDelay` period to pass. If the button state is still the same after the delay, we can trust it as a valid press.
if ((millis() - switchDebounceStartTime) > debounceDelay) {
// If 100ms has passed and the state is stable...
// then the current state is the "real" state.
// You can now act on the button press here.
// Example: Print the stable state
if(switchCurrentState == LOW) {
Serial.println("Button Pressed!");
}
}
// Update the last state for the next loop iteration
switchLastState = switchCurrentState;
Let's upload the code and observe the Serial Monitor.
The `debounceDelay` value is important:
A value between 50ms and 150ms is typically a good starting point.
Which method is better?
Hardware Debouncing (RC Filter)
Software Debouncing
Hardware is often preferred for reliability, but software is extremely common due to its cost-effectiveness.
A downside of RC filters is that they create slow, rounded signal edges.
A Schmitt Trigger is a hardware solution to this problem.
A Schmitt trigger is a special type of input that "cleans up" signals.
Slow/Noisy Input Schmitt Trigger Output
,---.
,' `. +-----------+
/ \ | |
-' `-. | |
`--- | |
+-----------+
Hysteresis means there are two different voltage thresholds: one for a rising signal and one for a falling signal.
This gap between thresholds provides excellent noise immunity. Small fluctuations around a threshold won't cause the output to chatter.
A classic and common component for this task is the 7414 Hex Schmitt-Trigger Inverter.
The symbol for a Schmitt trigger input on a schematic often includes a small hysteresis loop inside the logic gate symbol.
For a robust, mission-critical input, you can combine these techniques:
Switch Output → RC Filter → Schmitt Trigger → Microcontroller Input