pdf-icon

Arduino Quick Start

2. Devices & Examples

6. Applications

Chain DualKey USB HID

APIs and example programs related to Chain DualKey USB HID.

Example Program

Build Requirements

  • M5Stack Board Manager version ≥ 3.2.4
  • Board option = M5ChainDualKey
  • M5Unified library version ≥ 0.2.11
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
#include "USB.h"
#include "USBHIDKeyboard.h"
#include "USBHIDMouse.h"
#include "M5Unified.h"

#define pin_Key1 0
#define pin_Key2 17

m5::Button_Class Key1;
m5::Button_Class Key2;
USBHIDKeyboard Keyboard;
USBHIDMouse Mouse;

void setup() {
  pinMode(pin_Key1, INPUT);
  pinMode(pin_Key2, INPUT);

  Keyboard.begin();
  Mouse.begin();
  USB.begin();
}

void loop() {
  uint32_t ms = millis();
  Key1.setRawState(ms, !digitalRead(pin_Key1));
  Key2.setRawState(ms, !digitalRead(pin_Key2));

  if (Key1.wasPressed()) {
    // Keyboard.print("123 ABC def ,?#");
  }
  if (Key1.wasReleased()) {
    // Keyboard.write(KEY_RETURN);
  }
  if (Key1.wasHold()) {
    // Keyboard.press(KEY_LEFT_GUI);  // Command key in macOS, Windows key in Windows
    Keyboard.press(KEY_LEFT_CTRL);
    Keyboard.press('c');
    delay(500);
    Keyboard.releaseAll();
  }

  if (Key2.wasPressed()) {
    Mouse.move(50, 50);  // x, y
  }
  if (Key2.wasHold()) {
    Mouse.click(MOUSE_RIGHT);
  }

  delay(10);
}

Copy the code above into Arduino IDE, build and upload it to Chain DualKey. After uploading, holding Key1 will trigger the Ctrl + C key combination on Windows to copy (for macOS, the Command key mapping is noted in the code comments). Pressing Key2 moves the mouse cursor diagonally down-right by a small distance, and holding Key2 triggers a right-click. You can also uncomment the commented sections in the code to explore more USB HID keyboard features (be careful about logical conflicts between different button trigger conditions and USB HID events).

If the buttons do not respond after uploading, you can reboot the device: move the switch to the middle position, disconnect the USB-C data cable, and reconnect it (do not hold Key1).

If the Chain DualKey has already been programmed as a USB HID device, you must put it back into download mode before uploading a new sketch: disconnect the USB-C cable, move the switch to the middle position, hold Key1 while reconnecting the USB-C cable, then release Key1.

API

The Chain DualKey USB HID part uses the built-in USB library from arduino-esp32. For more APIs, see:

On This Page