
Arduino Quick Start
CoreMatrix button input APIs and example program.
M5.update() function in the main loop to read state updates and minimize blocking as much as possible. Otherwise, button state changes may not be captured in time.3.3.10-aM5CoreMatrix0.2.290.2.36KEY1, KEY2, and KEY3 are connected to M5PM1 G0, G1, and G2 respectively, with pull-up resistors to 3V3_L1. The pins read low when pressed. M5Unified maps the three buttons to M5.BtnA, M5.BtnB, and M5.BtnC.
#include <M5Unified.h>
static void drawButtons(const bool pressed[3])
{
M5.Display.startWrite();
M5.Display.fillScreen(TFT_BLACK);
for (int i = 0; i < 3; ++i) {
const int x = 1 + i * 5;
M5.Display.drawRect(x, 3, 4, 10, TFT_WHITE);
if (pressed[i]) {
M5.Display.fillRect(x + 1, 4, 2, 8, TFT_WHITE);
}
}
M5.Display.endWrite();
M5.Display.display();
}
void setup()
{
auto cfg = M5.config();
cfg.serial_baudrate = 115200;
M5.begin(cfg);
M5.Display.setColorDepth(8);
M5.Display.setRotation(1);
M5.Display.setBrightness(128);
const bool pressed[3] = {false, false, false};
drawButtons(pressed);
}
void loop()
{
M5.update();
const bool pressed[3] = {
M5.BtnA.isPressed(),
M5.BtnB.isPressed(),
M5.BtnC.isPressed(),
};
static bool lastPressed[3] = {false, false, false};
bool changed = false;
for (int i = 0; i < 3; ++i) {
if (pressed[i] != lastPressed[i]) {
changed = true;
lastPressed[i] = pressed[i];
}
}
if (changed) {
drawButtons(pressed);
}
if (M5.BtnA.wasPressed()) Serial.println("KEY1 pressed");
if (M5.BtnB.wasPressed()) Serial.println("KEY2 pressed");
if (M5.BtnC.wasPressed()) Serial.println("KEY3 pressed");
if (M5.BtnA.wasClicked()) Serial.println("KEY1 clicked");
if (M5.BtnB.wasClicked()) Serial.println("KEY2 clicked");
if (M5.BtnC.wasClicked()) Serial.println("KEY3 clicked");
delay(10);
}The LED matrix displays three hollow boxes corresponding to KEY1, KEY2, and KEY3. The box is filled while its key is held, and the serial monitor outputs press and click events.
The CoreMatrix button section uses Button_Class from the M5Unified library. For more button-related APIs, refer to the following documentation: