🛠 Bouton-poussoir et console série
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
- 1 × Arduino Mega ADK
- 1 × push button
- Wiring: one leg of the button to pin 2, the other leg to GND. No external resistor: we enable the internal pull-up (INPUT_PULLUP), so a press reads LOW.
- Pin 2 is chosen because it supports an external interrupt (useful for later steps); absolutely avoid pin 7 (MAX3421E RST).
- USB type B cable to the computer.
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
- 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).
- INPUT instead of INPUT_PULLUP without an external resistor: floating input, spurious messages in all directions.
- Counter shared with the interrupt not declared volatile: the compiler optimizes it away and the main loop never sees the value change.
- 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.
- 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
clignotante.inoArduinobouton-led.inoArduinoscan-hote-usb.inoArduinoadk-chat-android.inoArduinoadk-telemetrie.inoArduinohote-clavier-usb.inoArduino