Skip to content
systemcoding.dev
Embedded

Build a USB HID Keyboard With TinyUSB on RP2040

Make an RP2040 appear as a USB keyboard with TinyUSB: the HID report descriptor, the 8-byte report, keycodes, press and release, and the LED output report.

8 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the Raspberry Pi, Arm and C logos.

A USB keyboard is a device that sends tiny reports on an interrupt endpoint and nothing else, and the host operating system already knows what to do with them. That makes HID (Human Interface Device) the easiest USB class for a first custom device: macro pads, foot pedals, barcode scanners and button boxes are all a few buttons and a report. This post builds a keyboard on the Raspberry Pi Pico (RP2040) with Pico SDK 2.0 and TinyUSB 0.17: the descriptor, the report format, sending keys with correct press and release, and the host's LED output report for caps lock. The class is defined in the USB HID 1.11 specification and the keycodes in the HID Usage Tables 1.4.

What a HID report is

A HID device describes its data in a report descriptor, a compact byte sequence of items that says "this device has eight one-bit modifier fields, one reserved byte and six key-code bytes". The host parses it, and from then on every report the device sends is interpreted through it. For keyboards, the layout is so standard that there is a fixed one, the boot protocol report, which BIOSes and bootloaders use without parsing the descriptor:

ByteContent
0Modifier bits: left control, shift, alt, GUI (bits 0 to 3), then the right-hand ones (bits 4 to 7)
1Reserved, 0
2 to 7Up to six key codes of keys currently held down

A report describes the state of the keyboard, not an event. Pressing "a" sends a report with key code 0x04 in byte 2. Releasing it sends a report with byte 2 back to 0. If you send the first and never the second, the host holds the key down and repeats it. The six key slots give the rollover limit of a standard keyboard: seven simultaneous keys do not fit, and NKRO keyboards use a different, larger report descriptor.

Descriptor and configuration

TinyUSB provides the standard keyboard report descriptor as a macro. Set CFG_TUD_HID 1 in tusb_config.h, along with the endpoint size:

tusb_config.hc
#define CFG_TUSB_MCU            OPT_MCU_RP2040
#define CFG_TUSB_OS             OPT_OS_NONE
#define CFG_TUSB_RHPORT0_MODE   (OPT_MODE_DEVICE | OPT_MODE_FULL_SPEED)
#define CFG_TUD_ENDPOINT0_SIZE  64
#define CFG_TUD_HID             1
#define CFG_TUD_HID_EP_BUFSIZE  16

The descriptors include the report descriptor and the HID interface:

usb_descriptors.cc
#include "tusb.h"

#define USB_VID 0x1209
#define USB_PID 0x0002

static const tusb_desc_device_t desc_device = {
	.bLength            = sizeof(tusb_desc_device_t),
	.bDescriptorType    = TUSB_DESC_DEVICE,
	.bcdUSB             = 0x0200,
	.bDeviceClass       = 0x00,
	.bDeviceSubClass    = 0x00,
	.bDeviceProtocol    = 0x00,
	.bMaxPacketSize0    = CFG_TUD_ENDPOINT0_SIZE,
	.idVendor           = USB_VID,
	.idProduct          = USB_PID,
	.bcdDevice          = 0x0100,
	.iManufacturer      = 0x01,
	.iProduct           = 0x02,
	.iSerialNumber      = 0x03,
	.bNumConfigurations = 0x01,
};

const uint8_t *tud_descriptor_device_cb(void)
{
	return (const uint8_t *)&desc_device;
}

static const uint8_t desc_hid_report[] = {
	TUD_HID_REPORT_DESC_KEYBOARD(),
};

const uint8_t *tud_hid_descriptor_report_cb(uint8_t instance)
{
	(void)instance;
	return desc_hid_report;
}

#define EPNUM_HID 0x81
#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_HID_DESC_LEN)

static const uint8_t desc_config[] = {
	TUD_CONFIG_DESCRIPTOR(1, 1, 0, CONFIG_TOTAL_LEN,
			      TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, 100),
	TUD_HID_DESCRIPTOR(0, 4, HID_ITF_PROTOCOL_KEYBOARD,
			   sizeof desc_hid_report, EPNUM_HID,
			   CFG_TUD_HID_EP_BUFSIZE, 10),
};

const uint8_t *tud_descriptor_configuration_cb(uint8_t index)
{
	(void)index;
	return desc_config;
}

TUD_HID_DESCRIPTOR(itf, str, protocol, report_len, epin, size, interval) emits the interface, the HID class descriptor and the interrupt IN endpoint. The last argument, 10, is the polling interval in milliseconds, so the host asks for a report at most every 10 ms. The string callback is as in the Pico serial post, with the product string "Pico Keyboard". The device class is 0, since the HID class is declared at the interface level.

Sending a key

main.cc
#include "pico/stdlib.h"
#include "tusb.h"

static void send_key(uint8_t modifier, uint8_t keycode)
{
	uint8_t keys[6] = { keycode, 0, 0, 0, 0, 0 };

	while (!tud_hid_ready())
		tud_task();
	tud_hid_keyboard_report(0, modifier, keys);
	sleep_ms(10);

	while (!tud_hid_ready())
		tud_task();
	tud_hid_keyboard_report(0, 0, NULL);     /* release all keys */
	sleep_ms(10);
}

static void type_hello(void)
{
	static const uint8_t seq[] = {
		HID_KEY_H, HID_KEY_E, HID_KEY_L, HID_KEY_L, HID_KEY_O,
	};
	for (unsigned i = 0; i < sizeof seq; i++)
		send_key(0, seq[i]);
	send_key(KEYBOARD_MODIFIER_LEFTSHIFT, HID_KEY_1);
}

int main(void)
{
	board_init();
	tusb_init();
	gpio_init(15);
	gpio_set_dir(15, GPIO_IN);
	gpio_pull_up(15);

	for (;;) {
		tud_task();
		if (!gpio_get(15) && tud_hid_ready()) {
			type_hello();
			while (!gpio_get(15))
				tud_task();
		}
	}
}

With the host focused on a text editor, pressing the button on GPIO 15 (wired to ground) types:

Text
hello!

The final key is shift plus 1, which is "!" on a US layout. The tud_hid_keyboard_report(report_id, modifier, keycode) helper builds the 8-byte report; passing a null keycode sends all zeros, which releases everything. The 10 ms pauses give the host time to poll at its interval, since sending two reports within one polling interval makes the host see only the later one: the press can be lost completely.

Key codes are usage IDs, not characters. The letters run from HID_KEY_A (0x04) to HID_KEY_Z (0x1D), the digits from HID_KEY_1 (0x1E) to HID_KEY_0 (0x27), and a character like "!" is the same key as 1 with the shift modifier. The host applies its keyboard layout, so the same device types "z" on a German layout where the key code for Y is pressed.

The LED output report

The host sends caps lock, num lock and scroll lock state to the keyboard as an output report, which TinyUSB delivers to a callback:

hid_cb.cc
void tud_hid_set_report_cb(uint8_t instance, uint8_t report_id,
			   hid_report_type_t report_type,
			   uint8_t const *buffer, uint16_t bufsize)
{
	(void)instance; (void)report_id;
	if (report_type == HID_REPORT_TYPE_OUTPUT && bufsize >= 1) {
		bool caps = buffer[0] & KEYBOARD_LED_CAPSLOCK;
		gpio_put(PICO_DEFAULT_LED_PIN, caps);
	}
}

uint16_t tud_hid_get_report_cb(uint8_t instance, uint8_t report_id,
			       hid_report_type_t report_type,
			       uint8_t *buffer, uint16_t reqlen)
{
	(void)instance; (void)report_id; (void)report_type;
	(void)buffer; (void)reqlen;
	return 0;
}

Bit 1 of the output report is caps lock (KEYBOARD_LED_CAPSLOCK is 0x02), so the board's LED mirrors the host's caps lock state. A keyboard that lights its own LEDs from the host's state, rather than from its own key presses, stays correct when the host changes it from another keyboard.

Pitfalls

Stuck keys. Every press report needs a release report. A program that crashes between them leaves the host with a key held down until the next report. Lost keystrokes. Reports sent faster than the polling interval overwrite each other. Wait for tud_hid_ready() and pace at the endpoint interval. Wrong characters. HID sends positions, not characters. Layout differences change the result; send the key codes for the characters on the target layout, or restrict the device to ASCII on a US layout. BIOS and bootloaders. They use the boot protocol: keep the interface subclass and protocol as keyboard, and the report layout as above, or the device will not work before the OS loads. Security. A device that types by itself is also what an attack tool looks like. Operating systems increasingly prompt before trusting new keyboards. Do not design a product that types credentials into hosts it knows nothing about.

Debouncing and real button handling

The example reads one pin and types a fixed string, which is enough to show the report flow and not enough for a real product. Mechanical switches bounce for a few milliseconds, so a single press can read as several, and a keyboard that sends five letters for one press is a keyboard nobody keeps. Sample each button every 1 to 5 ms and accept a change only when the new level has been stable for a few consecutive samples; a small state machine with a counter per key is enough, and it is the part that decides whether the device feels solid. Then map each debounced key to a key code and build the report from the whole set of pressed keys: copy up to six key codes of the keys currently down into the report, and send a new report whenever the set changes. That is how a real keyboard behaves, and it handles two keys held at once correctly, which the type-a-string example does not.

When more than six keys are down at once, the standard says to report a phantom state: fill all six slots with the error rollover code HID_KEY_ROLLOVER (0x01) so the host knows the report is not valid and ignores it, rather than reporting an arbitrary subset. Keyboards that need to register more than six simultaneous keys, which gaming boards and chorded input devices do, use a bitmap report descriptor with one bit per key instead, at the cost of losing the boot protocol format.

Remote wakeup and suspend

When the host suspends the bus, a bus-powered device is expected to drop its current draw to 2.5 mA or less within about 10 ms, which on a Pico means stopping everything non-essential. TinyUSB tells you through tud_suspend_cb(bool remote_wakeup_en) and tud_resume_cb(). A keyboard can wake a sleeping computer: if the host enabled remote wakeup (the callback's argument says so), call tud_remote_wakeup() when a key is pressed during suspend and the host resumes the bus. The configuration descriptor above advertises this with TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, so hosts know it is allowed to ask. Test it: laptops that sleep deeply sometimes disable USB wakeup in the firmware setup, and the same board that wakes a desktop does nothing on them.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.