🛠 Bouton-poussoir et console série

Arduino Mega ADK (Rev3) · debutant · Schéma : IMG-mega-adk-debutant-2-mega-adk-bouton-console.svg — Mega ADK, bouton-poussoir entre la broche 2 et GND (pull-up interne), console série sur l'ordinateur

Objectives

Read a push button and report each press on the serial console. This introduces digital inputs, internal pull-up resistors (20–50 kΩ), external interrupts (pins 2, 3, 18, 19, 20, 21 on the ATmega2560), and the console enabled by the ATmega8U2, the USB-to-serial chip on the board — an 8U2, unlike the Mega 2560 Rev3 which uses a 16U2. A simple time-window debounce completes the exercise.

Hardware

Complete code

// mega-adk-bouton-console.ino — Board: "Arduino Mega ADK"
const byte BOUTON = 2;

volatile unsigned long nbAppuis = 0;
unsigned long dernierMs = 0;

void onAppui {
  unsigned long now = millis;
  if (now - dernierMs > 50) {   // anti-rebond 50 ms
    dernierMs = now;
    nbAppuis++;
  }
}

void setup {
  Serial.begin(9600);
  pinMode(BOUTON, INPUT_PULLUP);          // pull-up interne 20-50 kΩ
  attachInterrupt(digitalPinToInterrupt(BOUTON), onAppui, FALLING);
  Serial.println(F("Prêt : appuyez sur le bouton broche 2"));
}

void loop {
  static unsigned long lastReported = 0;
  noInterrupts;
  unsigned long n = nbAppuis;             // lecture atomique du compteur 32 bits
  interrupts;
  if (n != lastReported) {
    lastReported = n;
    Serial.print(F("Appui n°"));
    Serial.println(n);
  }
  delay(5);
}

Expected verification

Each press prints "Press #1", "Press #2", etc. A clean press prints only one line; mechanical bouncing is filtered by the 50 ms window. Wait ~1 s after opening the serial monitor (DTR auto-reset) before concluding that the console is silent.

Common errors

  1. Button wired pin → 5 V without an external resistor: with INPUT_PULLUP, the button must go to GND, otherwise the state never changes (or is simply inverted).
  2. INPUT instead of INPUT_PULLUP without an external resistor: floating input, spurious messages in all directions.
  3. Counter shared with the interrupt not declared volatile: the compiler optimizes it away and the main loop never sees the value change.
  4. Forgetting the critical section (noInterrupts/interrupts) around reading an unsigned long: this 8-bit AVR reads 32-bit integers byte by byte, an interrupt in the middle can corrupt the value.
  5. Silent console: check the USB cable (some are charge-only) and the "Arduino Mega ADK" selection in the IDE.

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials