🛠 Lire un bouton sur une broche GPIO libre
Objectives
Wire a push button to a truly free pin (GP0-GP22), read it using an internal pull-up, detect presses with software debouncing, and note which pins are forbidden on the Pico 2 W: GP23-GP25 and GP29 carry the power supply, CS, IRQ, and SPI clock for the CYW43.
Hardware
- Pico 2 W
- Push button
- Breadboard and connecting wires
- Serial console (115200 baud) or two test LEDs
Complete code
// main.c - bouton sur GP15, pull-up interne, appui = niveau bas
#include "pico/stdlib.h"
#define BOUTON 15
int main(void) {
stdio_init_all;
gpio_init(BOUTON);
gpio_set_dir(BOUTON, GPIO_IN);
gpio_pull_up(BOUTON); // pas de resistance externe necessaire
uint32_t dernier = 0;
bool etat_prec = true;
while (true) {
bool relache = gpio_get(BOUTON);
uint32_t maintenant = to_ms_since_boot(get_absolute_time);
if (relache != etat_prec && maintenant - dernier >= 20) {
dernier = maintenant;
etat_prec = relache;
if (!relache) {
printf("Appui !\n"); // anti-rebond logiciel 20 ms
}
}
sleep_ms(1);
}
}
Expected verification
Each press prints exactly one line Appui ! on the serial output, without duplicates. At startup, with no press, the pin remains high thanks to the internal pull-up; releasing the button does not trigger any spurious messages.
Common errors
- Wiring to GP23-GP25 or GP29: these pins are consumed by the radio (power-on, SPI CS, IRQ, SPI CLK shared with the VSYS monitor) and are not free inputs.
- Forgetting
gpio_pull_up: the pin floats, resulting in random states. - Without debouncing, a single press generates multiple detected presses.
- RP2350-E9 errata on early boards: high-impedance inputs may remain stuck near 2.2 V; an external pull-down of maximum 8.2 kOhm fixes the issue.
Other tutorials for this board
Code examples for this board
clignotante.pyPythonbouton-interruption.pyPythonpwm-servo.pyPythonlecture-adc.pyPythonneopixel.pyPythonoled-i2c.pyPython