English
English
简体中文
日本語

Arduino Quick Start

2. Devices & Examples

5. Extensions

6. Applications

CoreP4X USB-C HOST Keyboard and Mouse Input

APIs and example programs related to the CoreP4X USB-C Host interface and USB keyboard and mouse input.

USB-C HOST Interface

Interface D+ D− VBUS 5V Control
USB-C (Host) G25_USBC_D+ G24_USBC_D- P4USBC_L3 M5IOE1 PYG4 (PYB_P4USBC_OUT_EN)
Note
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.
Note
USB-C keyboards and mice can be connected directly. A USB-C to USB-A adapter is required for common USB-A keyboards and mice. Connect the device directly first; compatibility with complex USB hubs must be verified for the specific device.

Example Program

Compilation Requirements

  • M5Stack Board Manager version >= 3.3.10-a
  • Board selection = M5CoreP4X
  • M5Unified library version >= 0.3.1
  • M5GFX library version >= 0.3.1
  • EspUsbHost library version >= 2.11.1

This 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.

cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
#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"

API

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:

Page Tools
PDF
On This Page