🛠 Bouton et console série : Serial (USB) vs Serial1 (broches 0/1)

Arduino Leonardo — Board Fiche · debutant · Schéma : IMG-leonardo-debutant-2-leonardo-bouton-console-serie.svg — Bouton câblé entre la broche 2 et GND sur une Leonardo, moniteur série affiché à l'écran

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials