🛠 Bouton et console série interactive
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
- 1 × Arduino MKR WiFi 1010
- 1 × push button
- Jumper wires: button between D2 and GND (no external resistor needed, internal pull-up)
- Micro-USB cable
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
- Button wired to 3.3 V instead of GND: the logic is inverted, prefer the standard pull-up wiring described here.
while (!Serial);in setup: on SAMD, this blocks indefinitely if the monitor is never opened; avoid it or limit it with a timeout.- Forgetting debouncing: a single press then triggers multiple toggles.
Serial.readwithout testingavailablereturns -1 and pollutes the logic.
Other tutorials for this board
Code examples for this board
scan-wifi.inoArduinoconnexion-wpa2.inoArduinohttp-get.inoArduinoserveur-web-led.inoArduinohorloge-ntp.inoArduinoudp-diffusion.inoArduino