|
1 | 1 |
|
| 2 | +#ifndef ARDUINO_USB_MODE |
| 3 | +#error This ESP32 SoC has no Native USB interface |
| 4 | +#elif ARDUINO_USB_MODE == 1 |
| 5 | +#warning This sketch should be used when USB is in OTG mode |
| 6 | +void setup() {} |
| 7 | +void loop() {} |
| 8 | +#else |
| 9 | +#include "USB.h" |
| 10 | +#include "USBHID.h" |
| 11 | +USBHID HID; |
| 12 | + |
| 13 | +static const uint8_t report_descriptor[] = { |
| 14 | + // 8 axis |
| 15 | + 0x05, 0x01, // Usage Page (Generic Desktop Ctrls) |
| 16 | + 0x09, 0x04, // Usage (Joystick) |
| 17 | + 0xa1, 0x01, // Collection (Application) |
| 18 | + 0xa1, 0x00, // Collection (Physical) |
| 19 | + 0x05, 0x01, // Usage Page (Generic Desktop Ctrls) |
| 20 | + 0x09, 0x30, // Usage (X) |
| 21 | + 0x09, 0x31, // Usage (Y) |
| 22 | + 0x09, 0x32, // Usage (Z) |
| 23 | + 0x09, 0x33, // Usage (Rx) |
| 24 | + 0x09, 0x34, // Usage (Ry) |
| 25 | + 0x09, 0x35, // Usage (Rz) |
| 26 | + 0x09, 0x36, // Usage (Slider) |
| 27 | + 0x09, 0x36, // Usage (Slider) |
| 28 | + 0x15, 0x81, // Logical Minimum (-127) |
| 29 | + 0x25, 0x7f, // Logical Maximum (127) |
| 30 | + 0x75, 0x08, // Report Size (8) |
| 31 | + 0x95, 0x08, // Report Count (8) |
| 32 | + 0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position) |
| 33 | + 0xC0, // End Collection |
| 34 | + 0xC0, // End Collection |
| 35 | +}; |
| 36 | + |
| 37 | +class CustomHIDDevice : public USBHIDDevice { |
| 38 | +public: |
| 39 | + CustomHIDDevice(void) { |
| 40 | + static bool initialized = false; |
| 41 | + if (!initialized) { |
| 42 | + initialized = true; |
| 43 | + HID.addDevice(this, sizeof(report_descriptor)); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + void begin(void) { |
| 48 | + HID.begin(); |
| 49 | + } |
| 50 | + |
| 51 | + uint16_t _onGetDescriptor(uint8_t *buffer) { |
| 52 | + memcpy(buffer, report_descriptor, sizeof(report_descriptor)); |
| 53 | + return sizeof(report_descriptor); |
| 54 | + } |
| 55 | + |
| 56 | + bool send(uint8_t *value) { |
| 57 | + return HID.SendReport(0, value, 8); |
| 58 | + } |
| 59 | +}; |
| 60 | + |
| 61 | +CustomHIDDevice Device; |
| 62 | + |
| 63 | +const int buttonPin = 0; |
| 64 | +int previousButtonState = HIGH; |
| 65 | +uint8_t axis[8]; |
| 66 | + |
| 67 | +void setup() { |
| 68 | + Serial.begin(115200); |
| 69 | + Serial.setDebugOutput(true); |
| 70 | + pinMode(buttonPin, INPUT_PULLUP); |
| 71 | + Device.begin(); |
| 72 | + USB.begin(); |
| 73 | +} |
| 74 | + |
| 75 | +void loop() { |
| 76 | + int buttonState = digitalRead(buttonPin); |
| 77 | + if (HID.ready() && buttonState != previousButtonState) { |
| 78 | + previousButtonState = buttonState; |
| 79 | + if (buttonState == LOW) { |
| 80 | + Serial.println("Button Pressed"); |
| 81 | + axis[0] = random() & 0xFF; |
| 82 | + Device.send(axis); |
| 83 | + } else { |
| 84 | + Serial.println("Button Released"); |
| 85 | + } |
| 86 | + delay(100); |
| 87 | + } |
| 88 | +} |
| 89 | +#endif /* ARDUINO_USB_MODE */ |
| 90 | + |
0 commit comments