APIs and example programs related to the CoreP4X USB-C Host interface and USB keyboard and mouse input.
| Interface | D+ | D− | VBUS | 5V Control |
|---|---|---|---|---|
| USB-C (Host) | G25_USBC_D+ | G24_USBC_D- | P4USBC_L3 | M5IOE1 PYG4 (PYB_P4USBC_OUT_EN) |
M5.Power.setUsbOutput(true) controls the USB-A Host PYG2 output and does not enable the USB-C Host 5V rail. Use a separate M5IOE1 PYG4 control for the USB-C Host.3.3.10-aM5CoreP4X0.3.10.3.12.11.1This example enables the USB-C Host 5V output through M5IOE1 PYG4, starts the full-speed USB Host with EspUsbHost, and reads HID input from a keyboard or mouse. The screen layout includes keyboard input text, a mouse pointer, and button states. After enumeration, the corresponding area changes from WAIT to READY without requiring a key press or mouse movement first.
#include <M5Unified.h>
#include <EspUsbHost.h>
#include <string.h>
M5Canvas canvas(&M5.Display);
EspUsbHost usb;
static constexpr uint8_t USB_C_HOST_PWR_PIN = 3; // M5IOE1 PYG4, zero-based pin index
static portMUX_TYPE stateMux = portMUX_INITIALIZER_UNLOCKED;
static bool hostReady = false;
static bool usbPowerReady = false;
static volatile bool uiDirty = true;
static char hostError[40] = "--";
static uint8_t keyboardAddress = ESP_USB_HOST_ANY_ADDRESS;
static uint8_t mouseAddress = ESP_USB_HOST_ANY_ADDRESS;
static char lastKey[8] = "--";
static char typedText[25] = {};
static uint8_t typedLength = 0;
static int mouseX = 500;
static int mouseY = 500;
static uint16_t mouseButtons = 0;
static bool isConnected(uint8_t address)
{
return address != ESP_USB_HOST_ANY_ADDRESS;
}
static void onDeviceConnected(const EspUsbHostDeviceInfo& device)
{
bool keyboardFound = false;
bool mouseFound = false;
EspUsbHostInterfaceInfo interfaces[ESP_USB_HOST_MAX_INTERFACES] = {};
const size_t interfaceCount =
usb.getInterfaces(device.address, interfaces,
ESP_USB_HOST_MAX_INTERFACES);
for (size_t i = 0; i < interfaceCount; ++i) {
if (interfaces[i].interfaceClass != USB_CLASS_HID) continue;
if (interfaces[i].interfaceProtocol == HID_ITF_PROTOCOL_KEYBOARD) {
keyboardFound = true;
} else if (interfaces[i].interfaceProtocol == HID_ITF_PROTOCOL_MOUSE) {
mouseFound = true;
}
}
portENTER_CRITICAL(&stateMux);
if (keyboardFound) keyboardAddress = device.address;
if (mouseFound) mouseAddress = device.address;
uiDirty = true;
portEXIT_CRITICAL(&stateMux);
Serial.print("USB-C connected: ");
espUsbHostPrint(device);
}
static void onDeviceDisconnected(const EspUsbHostDeviceInfo& device)
{
portENTER_CRITICAL(&stateMux);
if (device.address == keyboardAddress) {
keyboardAddress = ESP_USB_HOST_ANY_ADDRESS;
strcpy(lastKey, "--");
typedText[0] = '\0';
typedLength = 0;
}
if (device.address == mouseAddress) {
mouseAddress = ESP_USB_HOST_ANY_ADDRESS;
mouseButtons = 0;
}
uiDirty = true;
portEXIT_CRITICAL(&stateMux);
Serial.print("USB-C disconnected: ");
espUsbHostPrint(device);
}
static void onKeyboard(const EspUsbHostKeyboardEvent& event)
{
if (!event.pressed) return;
portENTER_CRITICAL(&stateMux);
keyboardAddress = event.address;
if (event.ascii == '\r' || event.ascii == '\n') {
strcpy(lastKey, "ENTER");
} else if (event.ascii == '\b' || event.ascii == 0x7F) {
strcpy(lastKey, "BACK");
if (typedLength > 0) {
typedText[--typedLength] = '\0';
}
} else if (event.ascii >= 0x20 && event.ascii < 0x7F) {
lastKey[0] = static_cast<char>(event.ascii);
lastKey[1] = '\0';
if (typedLength < sizeof(typedText) - 1) {
typedText[typedLength++] = static_cast<char>(event.ascii);
typedText[typedLength] = '\0';
}
} else {
snprintf(lastKey, sizeof(lastKey), "%02X",
static_cast<unsigned>(event.keycode));
}
uiDirty = true;
portEXIT_CRITICAL(&stateMux);
}
static void onMouse(const EspUsbHostMouseEvent& event)
{
if (!event.moved && !event.buttonsChanged) return;
portENTER_CRITICAL(&stateMux);
mouseAddress = event.address;
if (event.moved) {
mouseX = constrain(mouseX + event.x * 4, 0, 999);
mouseY = constrain(mouseY + event.y * 4, 0, 999);
}
mouseButtons = event.buttonMask;
uiDirty = true;
portEXIT_CRITICAL(&stateMux);
}
static void drawCardFrame(int x, int y, int w, int h,
const char* title, bool connected)
{
canvas.drawRect(x, y, w, h, TFT_DARKGREY);
canvas.setTextDatum(top_left);
canvas.setFont(&fonts::FreeSansBold18pt7b);
canvas.setTextColor(TFT_WHITE, TFT_BLACK);
canvas.drawString(title, x + 18, y + 14);
canvas.setTextDatum(top_right);
canvas.setFont(&fonts::FreeSansBold12pt7b);
canvas.setTextColor(connected ? TFT_GREEN : TFT_YELLOW, TFT_BLACK);
canvas.drawString(connected ? "READY" : "WAIT", x + w - 18, y + 16);
canvas.drawLine(x + 18, y + 50, x + w - 18, y + 50, TFT_DARKGREY);
canvas.setTextDatum(middle_center);
}
static void drawButton(int x, int y, char label, bool pressed)
{
constexpr int width = 34;
constexpr int height = 22;
const char text[2] = {label, '\0'};
canvas.fillRect(x, y, width, height, pressed ? TFT_CYAN : TFT_BLACK);
canvas.drawRect(x, y, width, height, TFT_DARKGREY);
canvas.setFont(&fonts::FreeSansBold12pt7b);
canvas.setTextColor(pressed ? TFT_BLACK : TFT_WHITE,
pressed ? TFT_CYAN : TFT_BLACK);
canvas.drawString(text, x + width / 2, y + height / 2);
}
static void drawUi()
{
char lastKeyCopy[sizeof(lastKey)];
char textCopy[sizeof(typedText)];
uint16_t buttonsCopy;
int mouseXCopy;
int mouseYCopy;
bool keyboardConnected;
bool mouseConnected;
portENTER_CRITICAL(&stateMux);
strcpy(lastKeyCopy, lastKey);
strcpy(textCopy, typedText);
buttonsCopy = mouseButtons;
mouseXCopy = mouseX;
mouseYCopy = mouseY;
keyboardConnected = isConnected(keyboardAddress);
mouseConnected = isConnected(mouseAddress);
uiDirty = false;
portEXIT_CRITICAL(&stateMux);
const char* status;
uint16_t statusColor;
if (!usbPowerReady) {
status = "USB-C 5V OUTPUT FAILED";
statusColor = TFT_RED;
} else if (!hostReady) {
status = "USB-C HOST INIT FAILED";
statusColor = TFT_RED;
} else if (keyboardConnected && mouseConnected) {
status = "KEYBOARD + MOUSE READY";
statusColor = TFT_GREEN;
} else if (keyboardConnected) {
status = "KEYBOARD READY";
statusColor = TFT_GREEN;
} else if (mouseConnected) {
status = "MOUSE READY";
statusColor = TFT_GREEN;
} else {
status = "CONNECT A USB KEYBOARD OR MOUSE";
statusColor = TFT_YELLOW;
}
canvas.fillSprite(TFT_BLACK);
canvas.setTextDatum(middle_center);
canvas.setTextWrap(false);
canvas.setFont(&fonts::FreeSansBold24pt7b);
canvas.setTextColor(TFT_WHITE, TFT_BLACK);
canvas.drawString("USB-C HOST", 240, 46);
canvas.setFont(&fonts::FreeSansBold12pt7b);
canvas.setTextColor(statusColor, TFT_BLACK);
canvas.drawString(status, 240, 92);
canvas.drawLine(20, 116, 460, 116, TFT_DARKGREY);
drawCardFrame(20, 130, 440, 150, "KEYBOARD", keyboardConnected);
drawCardFrame(20, 294, 440, 160, "MOUSE", mouseConnected);
canvas.setFont(&fonts::FreeSans9pt7b);
canvas.setTextColor(TFT_DARKGREY, TFT_BLACK);
canvas.drawString("LAST KEY", 120, 196);
canvas.setFont(&fonts::FreeSansBold24pt7b);
canvas.setTextColor(keyboardConnected ? TFT_CYAN : TFT_DARKGREY, TFT_BLACK);
canvas.drawString(lastKeyCopy, 120, 238);
canvas.drawFastVLine(240, 188, 82, TFT_DARKGREY);
canvas.setFont(&fonts::FreeSans9pt7b);
canvas.setTextColor(TFT_DARKGREY, TFT_BLACK);
canvas.drawString("INPUT", 350, 196);
const char* inputText = textCopy[0] ? textCopy : "TYPE HERE";
const size_t inputLength = strlen(inputText);
if (inputLength > 16) inputText += inputLength - 16;
canvas.setFont(&fonts::FreeSans12pt7b);
canvas.setTextColor(TFT_WHITE, TFT_BLACK);
canvas.drawString(inputText, 350, 236);
constexpr int areaX = 40;
constexpr int areaY = 360;
constexpr int areaW = 180;
constexpr int areaH = 70;
canvas.drawRect(areaX, areaY, areaW, areaH, TFT_DARKGREY);
canvas.drawFastVLine(areaX + areaW / 2, areaY + 8, areaH - 16,
TFT_DARKGREY);
canvas.drawFastHLine(areaX + 8, areaY + areaH / 2, areaW - 16,
TFT_DARKGREY);
const int pointerX = map(mouseXCopy, 0, 999, areaX + 8, areaX + areaW - 8);
const int pointerY = map(mouseYCopy, 0, 999, areaY + 8, areaY + areaH - 8);
canvas.fillCircle(pointerX, pointerY, 6,
mouseConnected ? TFT_CYAN : TFT_DARKGREY);
char position[32];
snprintf(position, sizeof(position), "X %d Y %d", mouseXCopy, mouseYCopy);
canvas.setFont(&fonts::FreeSansBold18pt7b);
canvas.setTextColor(mouseConnected ? TFT_WHITE : TFT_DARKGREY, TFT_BLACK);
canvas.drawString(position, 340, 374);
drawButton(296, 410, 'L', buttonsCopy & ESP_USB_HOST_MOUSE_LEFT);
drawButton(338, 410, 'R', buttonsCopy & ESP_USB_HOST_MOUSE_RIGHT);
drawButton(380, 410, 'M', buttonsCopy & ESP_USB_HOST_MOUSE_MIDDLE);
canvas.setTextColor(TFT_DARKGREY, TFT_BLACK);
canvas.setFont(&fonts::FreeSans9pt7b);
canvas.drawString(hostReady ? "EspUsbHost / USB-C Full-Speed Host"
: hostError,
240, 468);
canvas.pushSprite(0, 0);
}
void setup()
{
auto cfg = M5.config();
cfg.serial_baudrate = 115200;
M5.begin(cfg);
M5.Display.setBrightness(128);
M5.Display.fillScreen(TFT_BLACK);
canvas.createSprite(M5.Display.width(), M5.Display.height());
auto& ioe = M5.getIOExpander(0);
// M5.Power.setUsbOutput() only controls the USB-A rail.
bool powerOk = ioe.setHighImpedance(USB_C_HOST_PWR_PIN, false);
powerOk = ioe.setDirection(USB_C_HOST_PWR_PIN, true) && powerOk;
powerOk = ioe.digitalWrite(USB_C_HOST_PWR_PIN, true) && powerOk;
usbPowerReady = powerOk;
usb.setKeyboardLayout(ESP_USB_HOST_KEYBOARD_LAYOUT_EN_US);
usb.onDeviceConnected(onDeviceConnected);
usb.onDeviceDisconnected(onDeviceDisconnected);
usb.onKeyboard(onKeyboard);
usb.onMouse(onMouse);
if (usbPowerReady) {
delay(100); // Wait for the USB-C device power rail to stabilize.
EspUsbHostConfig hostConfig;
// USB-C Host uses OTG FS on G24/G25.
hostConfig.port = ESP_USB_HOST_PORT_FULL_SPEED;
hostReady = usb.begin(hostConfig);
if (!hostReady) {
snprintf(hostError, sizeof(hostError), "%s", usb.lastErrorName());
}
}
Serial.printf("USB-C host init: %s\n", hostReady ? "OK" : "FAILED");
Serial.printf("USB-C 5V: %s\n", usbPowerReady ? "ON" : "FAILED");
drawUi();
}
void loop()
{
static uint32_t lastDraw = 0;
const uint32_t now = millis();
if (uiDirty && now - lastDraw >= 30) {
drawUi();
lastDraw = now;
}
delay(1);
}After uploading, the screen shows the USB-C Host initialization state, a keyboard area in the middle, and a mouse area below. When a keyboard or mouse is connected, its area changes from WAIT to READY. The keyboard area shows the most recent key and input text, while the mouse area shows the pointer, X/Y position, and left, right, and middle button states.
The serial monitor reports USB-C Host power, initialization, and device connection information, for example:
USB-C 5V: ON
USB-C host init: OK
USB-C connected: device: address=1 portId=0x01 vid=046d pid=c31c class=0x00(per-interface) speed=full-speed product="USB Keyboard" 

The CoreP4X USB-C HOST example mainly uses the following interfaces:
USB_C_HOST_PWR_PIN = 3: corresponds to M5IOE1 PYG4 and controls the USB-C Host 5V output through M5.getIOExpander(0).IOExpander_Base::setHighImpedance(): configures PYG4 as a push-pull output.IOExpander_Base::setDirection(): configures PYG4 as an output.IOExpander_Base::digitalWrite(): drives PYG4 high to enable the USB-C Host 5V output.EspUsbHostConfig::port = ESP_USB_HOST_PORT_FULL_SPEED: selects the ESP32-P4 full-speed USB Host.EspUsbHost::onDeviceConnected() / getInterfaces(): identifies a keyboard or mouse during device enumeration.EspUsbHost::onKeyboard() / onMouse(): reads keyboard and mouse input.For more related APIs, refer to: