🛠 Bouton et console série : Serial (USB) vs Serial1 (broches 0/1)
Objectives
Read a push button with digitalRead, display messages in the Serial Monitor, and understand the major pitfall of the Leonardo when migrating from an Uno: here Serial refers to the USB port (CDC), while the TTL UART on pins 0 and 1 is called Serial1. The button will use the internal pull-up resistor (20 to 50 kΩ), so it is an active-LOW configuration.
Hardware
- 1 Arduino Leonardo + micro-USB cable
- 1 push button
- 1 wire connecting one leg of the button to GND (no external resistor needed thanks to the internal pull-up)
Complete code
// Broche 2 = aussi une interruption matérielle (int1) sur Leonardo
const uint8_t BUTTON_PIN = 2;
void setup {
pinMode(BUTTON_PIN, INPUT_PULLUP); // pull-up interne 20-50 kOhm, actif-LOW
Serial.begin(9600); // ATTENTION : sur Leonardo, Serial = USB CDC, PAS les broches 0/1 !
while (!Serial) { /* attend l'ouverture du moniteur */ }
Serial.println("Leonardo prete : appuyez sur le bouton (broche 2).");
}
void loop {
if (digitalRead(BUTTON_PIN) == LOW) { // bouton enfoncé = LOW
Serial.println("Bouton presse !");
delay(200); // anti-rebond logiciel simple
}
}
Expected verification
Open the IDE's Serial Monitor at 9600 baud: the welcome message appears. Each press of the button prints a line. The while (!Serial) waits for the USB CDC port to be opened by the computer — a specificity of the Leonardo's native USB that does not exist on the Uno.
Common errors
- Confusing
SerialandSerial1: on the Leonardo, connecting a GPS module or another microcontroller to pins 0/1 requiresSerial1.begin(...). WritingSerialmeans talking to the computer, not to the pins. - Wiring reversed: without the pull-up enabled (
INPUT_PULLUP), the pin floats and the message prints in a loop. - Inverted logic: the configuration is active-LOW;
HIGHmeans the button is released. - Known AVR core bug:
serialEventis not triggered for the USB CDC (issue #206); preferSerial.availableinloop.
Other tutorials for this board
- Faire clignoter la LED intégrée (broche 13)
- Lire un capteur analogique : potentiomètre et ADC 10 bits
- Clavier USB : taper du texte avec la bibliothèque Keyboard
- Souris USB : déplacer le curseur avec la bibliothèque Mouse
- Asservir un servo moteur avec un potentiomètre (PWM)
- Programmer aux registres : interruption Timer/Counter1
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinoclavier-auto-tape.inoArduinosouris-cercle.inoArduinotelecommande-media.inoArduinobouton-clic-souris.inoArduino