🛠 Lire un bouton poussoir et gérer le rebond

Raspberry Pi Pico · debutant · Schéma : IMG-pico-debutant-2-pico-bouton-gpio.svg — Pico avec un bouton poussoir câblé entre GP2 et GND, résistance de pull-up interne représentée sur la puce

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials