🛠 Bouton et console série interactive

Arduino MKR WiFi 1010 · debutant · Schéma : IMG-mkr-wifi-1010-debutant-2-mkrwifi-bouton-console.svg — Bouton poussoir câblé entre la broche D2 et GND avec résistance de pull-up interne activée, liaison USB vers le moniteur série de l'ordinateur.

Objectives

Read a push button using an internal pull-up resistor and control the board from the serial console: pressing the button turns on LED D6, typing “s” in the monitor displays a status. We discover digitalRead, INPUT_PULLUP, and non-blocking reading of Serial.

Hardware

Complete code

// Bouton sur D2 (vers GND), LED sur D6, commandes série.
const uint8_t PIN_BTN = 2;
bool ledOn = false;

void setup {
  Serial.begin(115200);
  pinMode(PIN_BTN, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.println("MKR WiFi 1010 prete - bouton sur D2, tapez s pour statut");
}

void loop {
  static bool etatPrec = HIGH;
  bool etat = digitalRead(PIN_BTN);
  if (etat == LOW && etatPrec == HIGH) {   // front descendant = appui
    ledOn = !ledOn;
    digitalWrite(LED_BUILTIN, ledOn);
    Serial.println(ledOn ? "LED ON" : "LED OFF");
    delay(30);                              // anti-rebond grossier
  }
  etatPrec = etat;

  if (Serial.available) {                 // commande non bloquante
    char c = Serial.read;
    if (c == 's' || c == 'S')
      Serial.printf("statut: led=%d bouton=%d\n", ledOn, digitalRead(PIN_BTN));
  }
}

Expected verification

When the button is pressed, LED D6 toggles and a message appears in the serial monitor (115200 baud). Typing s + Enter displays the line statut: led=... bouton=... without blocking the loop. The button reads HIGH at rest and LOW when pressed: this is the effect of the internal pull-up.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials