
Arduino Quick Start
Chain Captain button input related APIs and sample programs.
M5.update() must be called in the main loop to refresh the button states. Keep the loop as non-blocking as possible; otherwise, button state changes may not be captured in time.3.3.10-aM5ChainCaptain0.3.00.3.0#include <M5Unified.h>
static void drawButtons(bool a, bool b, bool c)
{
M5.Display.startWrite();
M5.Display.fillScreen(TFT_BLACK);
M5.Display.setTextDatum(middle_center);
M5.Display.setFont(&fonts::FreeSansBold12pt7b);
M5.Display.setTextColor(TFT_WHITE, TFT_BLACK);
M5.Display.drawString("Press A / B / C", 120, 36);
const uint16_t colors[3] = {TFT_GREEN, TFT_YELLOW, TFT_BLUE};
const bool pressed[3] = {a, b, c};
const char* labels[3] = {"A", "B", "C"};
for (int i = 0; i < 3; ++i) {
const int x = 12 + i * 76;
const uint16_t fill = pressed[i] ? colors[i] : 0x2124;
M5.Display.fillRoundRect(x, 92, 64, 64, 10, fill);
M5.Display.drawRoundRect(x, 92, 64, 64, 10, TFT_WHITE);
M5.Display.setTextColor(TFT_WHITE, fill);
M5.Display.drawString(labels[i], x + 32, 124);
}
M5.Display.setFont(&fonts::FreeSans9pt7b);
M5.Display.setTextColor(TFT_WHITE, TFT_BLACK);
M5.Display.drawCenterString("Light when pressed", 120, 190);
M5.Display.endWrite();
}
void setup()
{
delay(500);
auto cfg = M5.config();
cfg.serial_baudrate = 115200;
M5.begin(cfg);
M5.Display.setRotation(0);
M5.Display.setBrightness(128);
drawButtons(false, false, false);
}
void loop()
{
M5.update();
static bool lastA = false;
static bool lastB = false;
static bool lastC = false;
// Keys are active low; M5Unified enables the pull-ups.
const bool a = M5.BtnA.isPressed();
const bool b = M5.BtnB.isPressed();
const bool c = M5.BtnC.isPressed();
if (a != lastA || b != lastB || c != lastC) {
lastA = a;
lastB = b;
lastC = c;
drawButtons(a, b, c);
}
if (M5.BtnA.wasPressed()) Serial.println("KEYA pressed");
if (M5.BtnB.wasPressed()) Serial.println("KEYB pressed");
if (M5.BtnC.wasPressed()) Serial.println("KEYC pressed");
if (M5.BtnA.wasClicked()) Serial.println("KEYA clicked");
if (M5.BtnB.wasClicked()) Serial.println("KEYB clicked");
if (M5.BtnC.wasClicked()) Serial.println("KEYC clicked");
delay(10);
}The screen shows three button boxes. While a button is held, its box is filled in green, yellow, or blue for A, B, and C respectively. The serial monitor outputs press and click events.
The Chain Captain button section uses the Button_Class from the M5Unified library. For more related button APIs, refer to the following document: