🛠 Bouton et console USB
Objectives
Read a push button and display presses on the USB serial console. Understand that the MKR NB 1500 has native USB (no FTDI chip): Serial is the USB CDC port, and the GPIO logic is at 3.3 V.
Hardware
- 1 MKR NB 1500 board + micro-USB data cable
- 1 push button
- 1 connecting wire (pin D2 → button, other leg → GND); the internal
INPUT_PULLUPresistor eliminates the need for any external resistor
Complete code
// Bouton sur D2 + console USB — MKR NB 1500
#include <MKRGSM.h>
GSM gsm; // sert uniquement a eteindre le modem
const uint8_t BTN = D2; // D2 accepte aussi l'entree analogique (AIN18)
void setup {
Serial.begin(9600);
while (!Serial); // USB natif : attendre l'ouverture du port CDC
pinMode(BTN, INPUT_PULLUP);
// Couper le modem pour eviter qu'il cherche un reseau en pure perte
gsm.begin;
gsm.shutdown;
}
void loop {
static uint8_t last = HIGH;
uint8_t now = digitalRead(BTN);
if (now != last) {
Serial.println(now == LOW ? "Bouton appuye" : "Bouton relache");
last = now;
}
delay(20); // petit anti-rebond logiciel
}
Expected verification
Open the serial console (9600 baud) after uploading: "Button pressed" / "Button released" are displayed on each press. No additional components are required thanks to the internal pull-up resistor.
Common errors
- Forgetting
while (!Serial);: on native USB, the firstSerial.printcalls occur before the port opens and seem "lost". - Wiring the button to 5 V with an external resistor to D2: possible, but unnecessary here, and note that all MKR pins are 3.3 V max.
- Not turning off the modem: it consumes power and may interfere with measurements;
gsm.shutdownsilences it. - Console set to 115200 while the code uses
Serial.begin(9600): with USB CDC, the baud rate matters little, but keep it consistent.
Other tutorials for this board
Code examples for this board
attente-lte-nbiot.inoArduinochoix-bande.inoArduinopublish-mqtt-minimal.inoArduinoeconomie-energie.inoArduinogeoloc-cellules.inoArduinotest-coverage.inoArduino