English
English
简体中文
日本語

Arduino Quick Start

2. Devices & Examples

5. Extensions

6. Applications

CoreP4X USB2 HOST Keyboard and Mouse Input

APIs and example programs related to the CoreP4X USB2 HOST interface and USB keyboard and mouse input.

USB2 HOST Interface

Interface D+ D− 5V Control
USB-A (Host) USB2_HOST_P USB2_HOST_N M5IOE1 PYG2 (PYB_USBA_OUT_EN)

The program uses M5.Power.setUsbOutput(true) to enable this 5V output.

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 uses EspUsbHost to start the USB2 High-Speed Host and read HID input from a keyboard and mouse. Once device enumeration is complete, the state switches to READY according to the HID interface protocol, without pressing a key or moving the mouse first.

Note
Connecting the keyboard or mouse directly to the USB-A port is recommended. The High-Speed Host of the current ESP32-P4 is not recommended to be extended through a generic USB hub; when both a keyboard and a mouse are needed, prefer a composite HID device with keyboard and mouse interfaces.
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
#include <M5Unified.h>
#include <EspUsbHost.h>
#include <string.h>

M5Canvas canvas(&M5.Display);
EspUsbHost usb;

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 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 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", 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-A 5V OUTPUT FAILED";
    statusColor = TFT_RED;
  } else if (!hostReady) {
    status = "USB 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("USB2 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 / USB2 High-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());

  usbPowerReady = M5.Power.setUsbOutput(true);

  usb.setKeyboardLayout(ESP_USB_HOST_KEYBOARD_LAYOUT_EN_US);
  usb.onDeviceConnected(onDeviceConnected);
  usb.onDeviceDisconnected(onDeviceDisconnected);
  usb.onKeyboard(onKeyboard);
  usb.onMouse(onMouse);

  EspUsbHostConfig hostConfig;
  hostConfig.port = ESP_USB_HOST_PORT_HIGH_SPEED;
  hostReady = usb.begin(hostConfig);

  if (!hostReady) {
    snprintf(hostError, sizeof(hostError), "%s", usb.lastErrorName());
  }

  Serial.printf("USB host init: %s\n", hostReady ? "OK" : "FAILED");
  Serial.printf("USB-A 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 keyboard area is displayed at the top and the mouse area at the bottom; after plugging in a keyboard or mouse, the upper-right corner of the corresponding area changes from WAIT to READY. The keyboard area displays the last key and the input text, and the mouse area displays the pointer, X/Y coordinates, and the states of the left, right, and middle buttons.

The serial port outputs the HOST initialization status and device information when a device connects or disconnects, for example:

USB host init: OK
USB-A 5V: ON
USB connected: device: address=1 portId=0x01 vid=046d pid=c31c class=0x00(per-interface) speed=full-speed product="USB Keyboard"

API

The CoreP4X USB2 HOST example mainly uses the following interfaces:

  • M5.Power.setUsbOutput(true): enables the 5V output of the USB-A port.
  • EspUsbHost::begin(): initializes the USB Host stack, the USB2 High-Speed PHY, and the background event task.
  • EspUsbHostConfig::port = ESP_USB_HOST_PORT_HIGH_SPEED: selects the USB2 High-Speed Host.
  • EspUsbHost::onDeviceConnected() / getInterfaces(): identifies the keyboard and mouse during device enumeration.
  • EspUsbHost::onKeyboard() / onMouse(): reads keyboard input and mouse state.

For more related APIs, refer to:

Page Tools
PDF
On This Page