🛠 Clavier USB HID via l'USB-OTG natif (TinyUSB)

ESP32-S3 · avance · Schéma : IMG-esp32-s3-avance-1-esp32-s3-usb-otg-hid-clavier.svg — ESP32-S3 connecté par GPIO19/GPIO20 (USB-OTG) à un ordinateur et se faisant reconnaître comme clavier USB, avec un bouton physique sur GPIO1 déclenchant une frappe.

Objectives

Transform the ESP32-S3 into a USB HID peripheral (keyboard) thanks to its native USB-OTG controller on GPIO19 (D-) and GPIO20 (D+), via the TinyUSB stack integrated into the Arduino core. This is one of the major differences from the classic ESP32: no additional chip is required. You will also discover the major constraint of the S3's dual USB: the "TinyUSB (OTG)" mode and the "Hardware CDC and JTAG" mode compete for the same pins; you cannot do everything at the same time without a second physical connector.

Hardware

Complete code

// Clavier HID sur USB-OTG natif (GPIO19/20) via TinyUSB
// Outils Arduino : USB Mode = "TinyUSB Device" (ou "OTG"), USB CDC = Disabled
#include "Arduino.h"
#include "USB.h"
#include "USBHIDKeyboard.h"

USBHIDKeyboard Keyboard;
const uint8_t BTN = 1;
uint8_t etatPrecedent = HIGH;
unsigned long dernierBord = 0;

void setup {
  pinMode(BTN, INPUT_PULLUP);
  Keyboard.begin;
  if (!USB.begin) {
    // pas de hot-plug possible ici : le host verra le HID au prochain branchement
  }
}

void loop {
  uint8_t etat = digitalRead(BTN);
  if (etat == LOW && etatPrecedent == HIGH && millis - dernierBord > 120) {
    dernierBord = millis;
    Keyboard.begin;                 // s'assure que le HID est pret
    Keyboard.print("ESP32-S3 dit bonjour ");
    Keyboard.write(KEY_RETURN);
    Keyboard.end;
  }
  etatPrecedent = etat;
  delay(10);
}

Expected verification

After uploading and reconnecting the cable, the computer detects a new "USB Keyboard" (hidusb) device without a driver. Pressing the button enters the line "ESP32-S3 says hello" followed by Enter into any active text field. The USB enumeration goes through GPIO19/20, the only pins connected to the S3's OTG controller.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials