
Arduino Quick Start
APIs and example programs related to the touchscreen of CoreP4X.
3.3.10-aM5CoreP4X0.3.10.3.1#include <M5Unified.h>
M5Canvas canvas(&M5.Display);
static bool lastPressed = false;
static bool lastPointValid = false;
static int lastX = 0;
static int lastY = 0;
static uint32_t clickCount = 0;
static void drawTouchScreen(bool pressed, int x, int y)
{
char coordText[40];
char countText[32];
canvas.fillSprite(TFT_BLACK);
canvas.setFont(&fonts::FreeSansBold18pt7b);
canvas.setTextDatum(middle_center);
canvas.setTextColor(TFT_WHITE, TFT_BLACK);
canvas.drawString("CoreP4X Touch", 240, 52);
canvas.setFont(&fonts::FreeSans12pt7b);
canvas.setTextColor(pressed ? TFT_GREEN : TFT_DARKGREY, TFT_BLACK);
canvas.drawString(pressed ? "PRESSED" : "RELEASED", 240, 108);
canvas.drawRect(36, 146, 408, 210, TFT_DARKGREY);
canvas.drawFastVLine(240, 146, 210, 0x2124);
canvas.drawFastHLine(36, 251, 408, 0x2124);
if (pressed || lastPointValid) {
const int markerX = constrain(x, 42, 438);
const int markerY = constrain(y, 152, 350);
canvas.fillCircle(markerX, markerY, 12, pressed ? TFT_SKYBLUE : TFT_DARKGREY);
canvas.drawLine(markerX - 24, markerY, markerX + 24, markerY, TFT_WHITE);
canvas.drawLine(markerX, markerY - 24, markerX, markerY + 24, TFT_WHITE);
}
if (pressed || lastPointValid) {
snprintf(coordText, sizeof(coordText), "X: %03d Y: %03d", x, y);
} else {
snprintf(coordText, sizeof(coordText), "X: --- Y: ---");
}
snprintf(countText, sizeof(countText), "Clicks: %lu",
static_cast<unsigned long>(clickCount));
canvas.setFont(&fonts::FreeSansBold18pt7b);
canvas.setTextColor(TFT_WHITE, TFT_BLACK);
canvas.drawString(coordText, 240, 402);
canvas.setFont(&fonts::FreeSans12pt7b);
canvas.drawString(countText, 240, 450);
canvas.pushSprite(0, 0);
}
void setup()
{
auto cfg = M5.config();
cfg.serial_baudrate = 115200;
M5.begin(cfg);
M5.Display.setRotation(0);
M5.Display.setBrightness(128);
canvas.createSprite(M5.Display.width(), M5.Display.height());
drawTouchScreen(false, 0, 0);
}
void loop()
{
M5.update();
const auto touch = M5.Touch.getDetail();
const bool pressed = touch.isPressed();
const bool clicked = touch.wasClicked();
if (clicked) {
++clickCount;
Serial.printf("Touch clicked at %d, %d\n", touch.x, touch.y);
}
if (clicked ||
pressed != lastPressed ||
(pressed && (touch.x != lastX || touch.y != lastY))) {
lastPressed = pressed;
lastX = touch.x;
lastY = touch.y;
lastPointValid = lastPointValid || pressed || clicked;
drawTouchScreen(pressed, lastX, lastY);
}
delay(10);
}After uploading, the screen displays whether the touch is pressed, the current or last touch coordinates, and the cumulative click count; the serial monitor also outputs the position of each click.
The touch section of CoreP4X uses the Touch_Class in the M5Unified library. For more touch APIs, refer to the documentation below: