Skip to content
systemcoding.dev
Embedded

Use ESP32-S3 Native USB as a CDC Device With TinyUSB

Run a USB CDC serial port on the ESP32-S3 native USB pins with esp_tinyusb in ESP-IDF 5, and know what happens to the built-in USB serial and JTAG.

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

The ESP32-S3 has two USB features on the same pair of pins, GPIO 19 (D-) and GPIO 20 (D+). One is a fixed-function USB Serial/JTAG controller that gives a debug console and a JTAG probe with no firmware effort. The other is a USB OTG full-speed controller that you drive from software, which is what TinyUSB uses to make the chip look like a keyboard, a flash drive, a serial port or anything you describe. The two share the PHY, so you pick one, and the choice has consequences for flashing and debugging. This post uses ESP-IDF 5.2 and the esp_tinyusb managed component to make the S3 a CDC serial device, explains what you lose when you switch, and covers the traps. Check the component's README for the version you install, because its API has evolved between releases.

The two controllers

FeatureUSB Serial/JTAGUSB OTG with TinyUSB
Who runs itFixed hardware, no firmwareYour firmware, through TinyUSB
What the host seesA CDC serial port and a JTAG interface (VID 0x303A, PID 0x1001)Whatever your descriptors say
FlashingAutomatic: the ROM bootloader is reachable without buttonsYou must enter download mode manually, or flash over UART
DebuggingBuilt-in JTAGNeeds external JTAG on other pins
printf and logsConsole to the serial port by defaultYour own routing

When the firmware starts the OTG controller, it takes over the PHY from the Serial/JTAG block and the built-in port disappears from the host until the next reset. This is the part that surprises people: the board you flashed over USB seems to vanish, and the next flash attempt fails because there is no longer a port to flash through. The remedy is to hold the BOOT button (GPIO 0 low) while resetting or plugging in the board, which enters ROM download mode, where the built-in Serial/JTAG controller works again. Boards with a separate USB-UART bridge on a second connector avoid the issue entirely.

Project setup

Add the component and enable it through menuconfig:

Shell
idf.py add-dependency "espressif/esp_tinyusb"
idf.py menuconfig

In menuconfig, under "TinyUSB Stack", enable CONFIG_TINYUSB_CDC_ENABLED and set the number of CDC interfaces. Under "Component config", "ESP System Settings", move the console output away from the built-in USB so the log does not compete (for example CONFIG_ESP_CONSOLE_UART_DEFAULT on UART0), because the USB Serial/JTAG controller is gone once TinyUSB runs. Those names are the ones in ESP-IDF 5.2 and the 1.x component line; verify them with idf.py menuconfig search, since a later version may rename them.

The application

The component has two layers: a driver install call that brings up the USB device with its default descriptors, and a CDC-ACM helper for the serial port. The structure names are those of esp_tinyusb 1.4:

main.cc
#include <stdint.h>
#include <string.h>
#include "esp_log.h"
#include "tinyusb.h"
#include "tusb_cdc_acm.h"

static const char *TAG = "usb_cdc";
static uint8_t rx_buf[CONFIG_TINYUSB_CDC_RX_BUFSIZE + 1];

static void rx_cb(int itf, cdcacm_event_t *event)
{
	size_t n = 0;

	if (tinyusb_cdcacm_read(itf, rx_buf, CONFIG_TINYUSB_CDC_RX_BUFSIZE,
				&n) == ESP_OK && n) {
		tinyusb_cdcacm_write_queue(itf, rx_buf, n);   /* echo */
		tinyusb_cdcacm_write_flush(itf, 0);
	}
}

static void line_state_cb(int itf, cdcacm_event_t *event)
{
	int dtr = event->line_state_changed_data.dtr;
	int rts = event->line_state_changed_data.rts;

	ESP_LOGI(TAG, "line state: dtr=%d rts=%d", dtr, rts);
}

void app_main(void)
{
	const tinyusb_config_t tusb_cfg = {
		.device_descriptor = NULL,        /* use the component defaults */
		.string_descriptor = NULL,
		.external_phy = false,
		.configuration_descriptor = NULL,
	};
	ESP_ERROR_CHECK(tinyusb_driver_install(&tusb_cfg));

	const tinyusb_config_cdcacm_t acm_cfg = {
		.usb_dev = TINYUSB_USBDEV_0,
		.cdc_port = TINYUSB_CDC_ACM_0,
		.rx_unread_buf_sz = 64,
		.callback_rx = &rx_cb,
		.callback_rx_wanted_char = NULL,
		.callback_line_state_changed = &line_state_cb,
		.callback_line_coding_changed = NULL,
	};
	ESP_ERROR_CHECK(tusb_cdc_acm_init(&acm_cfg));
	ESP_LOGI(TAG, "USB CDC ready");
}

The log goes to the UART console, not to USB:

Text
I (421) usb_cdc: USB CDC ready
I (3050) usb_cdc: line state: dtr=1 rts=1

When a terminal opens the new port, the host asserts DTR and RTS, and the line-state callback reports it; that callback is the right place to start sending, as covered in the DTR post of this series. Whatever you type in the terminal is echoed back by rx_cb.

Three points about this code. The callbacks run in the TinyUSB task, not in the interrupt, so they may call ESP-IDF APIs, but they should not block for long. **tinyusb_cdcacm_write_queue copies the bytes** into the transmit buffer and does not send them; tinyusb_cdcacm_write_flush triggers the transfer, and its second argument is a timeout in ticks, 0 meaning do not wait. Passing NULL descriptors selects the component's defaults, which use Espressif's vendor ID and a fixed product string; for your own product, provide a device descriptor with your IDs and a string table with a unique serial number.

Custom descriptors

To set your own identity, fill tusb_desc_device_t and a string array and pass them in:

descriptors.cc
static const tusb_desc_device_t my_device = {
	.bLength            = sizeof(tusb_desc_device_t),
	.bDescriptorType    = TUSB_DESC_DEVICE,
	.bcdUSB             = 0x0200,
	.bDeviceClass       = TUSB_CLASS_MISC,
	.bDeviceSubClass    = MISC_SUBCLASS_COMMON,
	.bDeviceProtocol    = MISC_PROTOCOL_IAD,
	.bMaxPacketSize0    = CFG_TUD_ENDPOINT0_SIZE,
	.idVendor           = 0x1209,
	.idProduct          = 0x0003,
	.bcdDevice          = 0x0100,
	.iManufacturer      = 0x01,
	.iProduct           = 0x02,
	.iSerialNumber      = 0x03,
	.bNumConfigurations = 0x01,
};

static const char *my_strings[] = {
	(char[]){ 0x09, 0x04 },
	"Example Co",
	"S3 Serial",
	"0001",
};

and set .device_descriptor = &my_device and .string_descriptor = my_strings in tusb_cfg. A serial number string derived from the chip's MAC address (esp_efuse_mac_get_default) keeps boards distinguishable.

Making the console use the CDC port

ESP-IDF can send its own console and logs to a TinyUSB CDC port through esp_tusb_init_console(TINYUSB_CDC_ACM_0), which redirects the standard streams once the CDC device is ready. After that, ESP_LOGI and printf appear on the USB serial port. Two warnings: output generated before the redirect goes to the old console, and a log line printed in a path that the USB task also needs (for example in a callback holding a lock) can deadlock the port. Keep high-volume logging on the UART when debugging USB itself.

Recovering a board that will not flash

If the firmware you flashed takes over the PHY and then crashes or does not re-enumerate, you can still get back: hold BOOT (GPIO 0), tap RESET, release BOOT. The chip enters the ROM bootloader, the host sees the Serial/JTAG device again, and idf.py -p PORT flash works. If you are building a product without the BOOT button exposed, bring GPIO 0 and a reset line to a test pad, and keep a UART header for recovery.

Power, pins and board choices

The USB data pins are not free GPIOs once you use native USB. On the S3, GPIO 19 and GPIO 20 are the D- and D+ lines. Boards differ in how they expose them: development kits such as the ESP32-S3-DevKitC-1 have two USB-C connectors, one wired to a USB-UART bridge and one wired directly to GPIO 19 and 20, so you can use the bridge for logs and the native port for the CDC device and never lose your flashing path. A board with only the native connector forces the BOOT-button recovery described above. When you design your own board, ESD protection on D+ and D- and series resistors of about 22 ohms are normal, and a pull-up on D+ is not needed because the PHY provides one internally.

Bus power is the other practical point. The device descriptor you pass declares the current the configuration needs, and the default is modest, but a board that powers a radio, a display and the S3 from VBUS can exceed the 100 mA that a host guarantees before configuration, and 500 mA after. The ESP32-S3 with Wi-Fi active can draw peaks that approach that on a weak port. If the board resets when Wi-Fi starts but works from a wall adapter, the USB port is browning out, and the fix is hardware: a bulk capacitor, a better cable, or a powered hub.

Detecting that the host is gone

A CDC device is not told when the cable is pulled in the way a UART would know. The cleanest signals are the line-state callback (DTR going low when the host closes the port) and the TinyUSB mount and unmount callbacks (tud_mount_cb, tud_umount_cb), which fire when the host configures or deconfigures the device. Keep a flag from them and stop queueing output when it is false: tinyusb_cdcacm_write_queue happily fills the buffer for a port nobody reads, and a program that logs at a high rate then blocks or drops data in a way that looks like a USB bug. Make the flag part of your logging layer so that the log path degrades to a counter of dropped lines instead of stalling the task that produced 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.