🛠 Lire un bouton poussoir avec résistance de pull-up interne

Arduino Mega 2560 (Rev3) · debutant · Schéma : IMG-mega-2560-debutant-2-bouton-pull-up.svg — bouton poussoir entre la broche 2 et la masse, résistance de pull-up interne activée, LED témoin sur la broche 13

Objectives

Learn how to read a digital input on the Mega 2560 using the internal pull-up resistor (20 to 50 kΩ according to official documentation), avoid mechanical bouncing with debouncing logic, and turn on an LED when the button is pressed.

Hardware

The button is connected between pin 2 and ground (GND), without an external resistor: the logic is inverted (LOW = pressed) because the internal pull-up keeps the pin at 5 V when idle. The Mega 2560 has 54 digital pins, so the pins with external interrupts (2, 3, 18, 19, 20, 21) remain available for more advanced projects.

Complete code

// Bouton + pull-up interne — Arduino Mega 2560
const uint8_t BTN_PIN = 2;
const uint8_t LED_PIN = 13;

uint8_t etatPrecedent = HIGH;
uint32_t dernierRebond = 0;
bool etatStable = false;          // false = relâché

void setup {
  pinMode(BTN_PIN, INPUT_PULLUP); // pull-up interne 20-50 kΩ
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(115200);
}

void loop {
  uint8_t lecture = digitalRead(BTN_PIN);
  uint32_t maintenant = millis;
  if (lecture != etatPrecedent) {
    dernierRebond = maintenant;   // rebond détecté
  }
  if (maintenant - dernierRebond > 30) {
    bool etat = (lecture == LOW); // logique inversée
    if (etat != etatStable) {
      etatStable = etat;
      Serial.println(etat ? F("bouton pressé") : F("bouton relâché"));
    }
  }
  etatPrecedent = lecture;
  digitalWrite(LED_PIN, etatStable ? HIGH : LOW);
}

Expected verification

Open the serial monitor at 115200 bauds: each press displays "button pressed" only once (no bursts due to bouncing) and the LED follows the state of the button. When idle, the LED is off.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials