🛠 Bouton poussoir avec anti-rebond

GD32F103 (GigaDevice) — chip + Blue-Pill-compatible boards · debutant · Schéma : IMG-gd32f103-debutant-2-bouton-antirebond.svg — bouton poussoir sur PA0 avec résistance de pull-down, commande de la LED PC13 par toggling anti-rebondi

Objectives

Read a push button on PA0 and control the LED on PC13 by toggling its state on each press, filtering mechanical bounce in software (time-based debouncing). You will learn how to configure an input, the active-HIGH logic of a button wired with a pull-down resistor, and the limitations of millis-based debouncing when handling rapid presses.

Hardware

Complete Code

// bouton_antirebond.ino — GD32F103C8, core CommunityGD32Cores
#include <Arduino.h>

const uint8_t BTN = PA0;      // appui = HIGH (pull-down externe)
const unsigned long DEBOUNCE_MS = 50;

bool etatStable = false;      // état filtré du bouton
bool dernierLu = false;       // dernière lecture brute
unsigned long dernierChangement = 0;
bool ledAllumee = false;

void setup {
  pinMode(BTN, INPUT_PULLDOWN); // pull-down interne : pas obligatoire si R externe
  pinMode(PC13, OUTPUT);
  digitalWrite(PC13, HIGH);     // LED éteinte (active-LOW)
}

void loop {
  bool brut = digitalRead(BTN);
  unsigned long maintenant = millis;

  if (brut != dernierLu) {
    dernierChangement = maintenant;   // le signal bouge : on repart
    dernierLu = brut;
  } else if (maintenant - dernierChangement >= DEBOUNCE_MS
             && brut != etatStable) {
    etatStable = brut;                // état confirmé après 50 ms stables
    if (etatStable) {                 // front montant = appui
      ledAllumee = !ledAllumee;
    }
  }
  digitalWrite(PC13, ledAllumee ? LOW : HIGH);
}

Expected Verification

A firm press turns the LED on (if it was off), a second press turns it off, with only one state change per press. When gently shaking the button, the LED should not "flicker": the debouncing is working. You can add a Serial output to count the presses and verify that there are never two counts for a single action.

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials