🛠 Les 4 boutons du pavé comme sélecteurs de couleur
Objectives
Learn how to read digital inputs from the Esplora: the four push buttons arranged in a diamond (SWITCH_UP, SWITCH_DOWN, SWITCH_LEFT, SWITCH_RIGHT) plus the central joystick button. Each button will light up a different color on the RGB LED. You will also discover a specific pitfall of this board: these buttons are read via an analog multiplexer, not directly on GPIO pins.
Hardware
- An Arduino Esplora and its micro-USB cable.
- Arduino IDE 2.x with the
arduino:avrcore and the Esplora library. - No external components: everything is on-board.
Complete Code
/* Chaque bouton du losange allume une couleur de la LED RVB.
Les boutons ne sont pas sur des broches dédiées : la bibliothèque
les lit sur un multiplexeur analogique (A0-A3 en adresse, A4 en ADC). */
#include <Esplora.h>
void setup {
Serial.begin(9600); // pour observer l'état des boutons
}
void loop {
if (Esplora.readButton(SWITCH_UP) == PRESSED) {
Esplora.writeRGB(255, 0, 0); // haut = rouge
Serial.println("UP");
} else if (Esplora.readButton(SWITCH_DOWN) == PRESSED) {
Esplora.writeRGB(0, 255, 0); // bas = vert
Serial.println("DOWN");
} else if (Esplora.readButton(SWITCH_LEFT) == PRESSED) {
Esplora.writeRGB(0, 0, 255); // gauche = bleu
Serial.println("LEFT");
} else if (Esplora.readButton(SWITCH_RIGHT) == PRESSED) {
Esplora.writeRGB(255, 255, 0); // droite = jaune
Serial.println("RIGHT");
} else {
Esplora.writeRGB(0, 0, 0); // aucun bouton = éteinte
}
delay(50);
}
Expected Verification
Press each button: the LED takes on the corresponding color and the serial monitor (9600 baud) displays the button name. Release it: the LED turns off. Also test the central joystick button with Esplora.readButton(SWITCH_JOYSTICK) — note that, unlike the four diamond buttons, it does not have a hardware pull-up resistor; the library compensates by enabling a software pull-up when reading this channel.
Common Errors
- Confusing PRESSED and HIGH:
readButtonreturnsPRESSED(internal logic circuit + multiplexing), never a simpleHIGHfromdigitalRead. - Trying to read two buttons "at the same time": multiplexed channels share a single analog-to-digital converter; reading is sequential with settling time. Chaining
readButtoncalls in theloopis designed for this, but do not hack interrupts on top of it. - Flaky joystick button: without the library's fix (software pull-up), it floats and triggers on its own — never use
digitalReadon the common pin A4 for this button. - Forgetting the
delay(50): without a small delay, you will flood the serial monitor with lines; multiplexing also needs this time between two channel changes.
Other tutorials for this board
Code examples for this board
joystick-couleur.inoArduinojeu-boutons.inoArduinoslider-luminosite.inoArduinothermometre-couleur.inoArduinosonometre.inoArduinoaccelerometre-tilt.inoArduino