🛠 USB HID + CDC et BLE simultanés
Objectives
Leverage the dual interface of the nRF52840: the native USB controller (TinyUSB: CDC, HID, MIDI, mass storage) AT THE SAME TIME as the BLE radio (SoftDevice). You will build a mini emergency keyboard: pressing the USER button triggers a USB keyboard keystroke (HID), telemetry on the CDC serial port, and a BLE alert to the phone. This is the hallmark of this SoC: the only mainstream BLE chip with native USB and sufficient RAM (256 KB).
Hardware
- 1× Adafruit Feather nRF52840 Express + data-capable micro-USB cable
- Libraries: Adafruit TinyUSB Arduino, Adafruit Bluefruit nRF52 Libraries
- Smartphone with Bluefruit LE Connect
Complete Code
// nrf52840-usb-hid-cdc-ble.ino
#include <bluefruit.h>
#include "Adafruit_TinyUSB.h"
BLEUart bleuart;
const uint8_t BTN = 9; // >
// Descripteur HID clavier de demarrage standard
static const uint8_t hid_kbd_desc[] = {
0x05,0x01,0x09,0x06,0xA1,0x01,0x05,0x07,0x19,0xE0,0x29,0xE7,
0x15,0x00,0x25,0x01,0x75,0x01,0x95,0x08,0x81,0x02,0x95,0x01,
0x75,0x08,0x81,0x03,0x95,0x06,0x75,0x08,0x15,0x00,0x25,0xFF,
0x05,0x07,0x19,0x00,0x29,0xFF,0x81,0x00,0xC0 };
Adafruit_USBD_HID usb_kbd;
uint8_t kbd_report[8] = {0};
void setup {
Serial.begin(115200); // CDC USB (telemetrie)
pinMode(BTN, INPUT_PULLUP);
usb_kbd.setPollingInterval(10);
usb_kbd.begin(hid_kbd_desc, sizeof(hid_kbd_desc), 1, 1, 0); // HID clavier
Bluefruit.begin; // BLE en parallele de l'USB
Bluefruit.setName("52840-Alerte");
bleuart.begin;
Bluefruit.Advertising.addService(bleuart);
Bluefruit.Advertising.start(0);
}
void loop {
if (!digitalRead(BTN)) { // appui : frappe 'A' en HID
kbd_report[2] = 0x04; // usage HID 'A'
usb_kbd.sendReport(0, kbd_report, sizeof(kbd_report));
bleuart.printf("ALERTE bouton a %lu ms\n", millis);
Serial.println("HID: A envoye, alerte BLE transmise");
delay(300);
kbd_report[2] = 0;
usb_kbd.sendReport(0, kbd_report, sizeof(kbd_report));
}
}
Expected Verification
In a word processor, each press of the USER button types “A” (proving HID works); the serial monitor displays CDC telemetry (both coexist because they are different USB interfaces); the Bluefruit app receives “ALERT button…”. All three channels work concurrently.
Common Errors
- Forgetting to wait for
usb_kbd.readybefore sending the first reports: on Windows, HID enumeration can take ~1 s. - Confusing
Serial(CDC) and HID: one goes to the serial monitor, the other to the system as a keyboard — two interfaces on the same cable. - Hard timing with BLE active: the SoftDevice takes priority over your code; avoid critical delays in callbacks.
- Incorrect HID descriptor: a poorly sized report causes USB enumeration to fail (unknown device).
Other tutorials for this board
Code examples for this board
neopixel_pulsation.pyPythonled_bouton.pyPythonentrees_num.pyPythonanalogique_lumiere.pyPythonservo_pwm.pyPythonscanner_i2c.pyPython