🛠 Lire un bouton poussoir avec résistance de pull-up interne
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
- 1 × Arduino Mega 2560 + USB cable
- 1 × push button
- 1 × LED + 1 × 330 Ω resistor
- Breadboard and wires
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
- Forgetting
INPUT_PULLUPand leaving the pin as a floating input: the state changes on its own, the LED flickers. - Forgetting the logic inversion: with a pull-up, the pressed button gives LOW, not HIGH.
- Debouncing time too short (less than 20 ms): multiple ghost presses for each press.
- Using the "button to 5 V" wiring with the internal pull-up: short circuit from 5 V to ground when pressing.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinodouble-servo.inoArduinopont-uart.inoArduinopwm-respiration.inoArduinopotentiometre-plotter.inoArduino