🛠 Lire un bouton poussoir et gérer le rebond
Objectives
Learn how to read a digital input on the Pico: configure a GPIO as an input with an internal pull-up, detect button presses, and control the onboard LED. You will also discover mechanical bounce and its software removal via debouncing, which is essential to avoid counting ten presses for a single one.
Hardware
- 1 × Raspberry Pi Pico
- 1 × push button
- Breadboard wires (no external resistor needed: the pull-up is internal)
- Wiring: one leg of the button to GP2, the other to GND; the onboard LED is on GP25
Complete code
// bouton.c — GP2 en entrée pull-up, LED GP25, anti-rebond 50 ms
#include "pico/stdlib.h"
#define BTN_PIN 2
#define LED_PIN 25
int main(void) {
gpio_init(BTN_PIN);
gpio_set_dir(BTN_PIN, GPIO_IN);
gpio_pull_up(BTN_PIN); // pull-up interne : repos = 1
gpio_init(LED_PIN);
gpio_set_dir(LED_PIN, GPIO_OUT);
uint32_t last_change = 0;
while (true) {
bool pressed = !gpio_get(BTN_PIN); // actif à l'état bas
if (pressed) {
if (time_us_64 - last_change > 50000) {
gpio_put(LED_PIN, !gpio_get(LED_PIN)); // toggle
last_change = time_us_64;
}
}
sleep_ms(1);
}
}
Expected verification
At rest, the LED keeps its state. Each firm press of the button toggles the LED only once, without flickering or double detection. By disconnecting the GND leg of the button, the input remains pulled high to 1 by the pull-up: the LED stops changing, which proves the role of the internal pull-up.
Common errors
- Forgetting
gpio_pull_up: the input floats, causing the LED to blink randomly. - Inverted logic: with a pull-up, a press gives 0, not 1.
- No debouncing: a single press is counted multiple times (the contact vibrates for ~1 ms).
- Button wired to 3V3 without a resistor: here we use GND + internal pull-up, which is the safe and component-efficient method.
- Confusing physical pin number and GPIO number: on the Pico, you always code GPx, not the connector position.
Other tutorials for this board
Code examples for this board
clignotante.pyPythonbouton-interruption.pyPythonpwm-servo.pyPythonlecture-adc.pyPythonneopixel.pyPythonoled-i2c.pyPython