Skip to content
systemcoding.dev
Embedded

Make a Raspberry Pi Pico Act as a USB Serial Port With TinyUSB

Build a USB CDC serial device on the RP2040 with the Pico SDK and TinyUSB, from the stdio shortcut to descriptors, tusb_config.h and an echo loop.

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.

The RP2040 has a full-speed USB 1.1 device controller, and the Pico SDK includes TinyUSB, the open-source USB stack that most small-board projects use. A Pico that appears as /dev/ttyACM0 on Linux, COM3 on Windows or /dev/cu.usbmodem1101 on macOS needs no driver on the host, because the operating systems ship a CDC ACM driver (the Communications Device Class, Abstract Control Model, defined in the USB CDC 1.2 specification). This post shows two ways to get there with Pico SDK 2.0 and TinyUSB 0.17: the one-line stdio route that most projects should use, and the direct TinyUSB route that you need when the serial port is one of several USB functions or when you want control over the descriptors.

Route one: stdio over USB

The Pico SDK wraps TinyUSB in a library, pico_stdio_usb, so that printf and getchar talk to the USB serial port. The whole project is a source file and a CMake file.

main.cc
#include <stdio.h>
#include "pico/stdlib.h"

int main(void)
{
	stdio_init_all();

	while (true) {
		printf("hello from the pico, tick %u\n",
		       (unsigned)(time_us_32() / 1000000u));
		sleep_ms(1000);
	}
}
CMakeLists.txtcmake
cmake_minimum_required(VERSION 3.13)
include($ENV{PICO_SDK_PATH}/external/pico_sdk_import.cmake)
project(usb_serial C CXX ASM)
pico_sdk_init()

add_executable(usb_serial main.c)
target_link_libraries(usb_serial pico_stdlib)
pico_enable_stdio_usb(usb_serial 1)
pico_enable_stdio_uart(usb_serial 0)
pico_add_extra_outputs(usb_serial)

Build it with cmake -B build && cmake --build build, hold the BOOTSEL button while plugging in the board, and copy build/usb_serial.uf2 to the mass storage drive that appears. After the board reboots, open the port with a terminal program:

Shell
screen /dev/ttyACM0 115200
Text
hello from the pico, tick 0
hello from the pico, tick 1
hello from the pico, tick 2

The baud rate you give the terminal is ignored: USB CDC has no real baud rate, and the setting is just a number sent to the device in a control request. One caveat is that the first lines can be lost. stdio_init_all() returns before the host has enumerated the device, so a program that prints immediately prints into nothing. Wait until the host opens the port with while (!stdio_usb_connected()) sleep_ms(10); after initialization, or accept the loss.

Route two: TinyUSB directly

When you want the serial port as one function among several, or custom strings and IDs, you use TinyUSB itself. Four pieces are needed: the stack configuration, the descriptors, the main loop and the build.

Configuration. tusb_config.h tells TinyUSB which chip and mode to use and which classes to include:

tusb_config.hc
#ifndef TUSB_CONFIG_H
#define TUSB_CONFIG_H

#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_CDC             1
#define CFG_TUD_MSC             0
#define CFG_TUD_HID             0
#define CFG_TUD_MIDI            0
#define CFG_TUD_VENDOR          0

#define CFG_TUD_CDC_RX_BUFSIZE  256
#define CFG_TUD_CDC_TX_BUFSIZE  256

#endif

Descriptors. TinyUSB asks the application for them through callbacks. A CDC serial port uses two interfaces (a control interface with a notification endpoint and a data interface with a bulk pair), and TinyUSB provides macros that emit the bytes:

usb_descriptors.cc
#include "tusb.h"
#include "pico/unique_id.h"

#define USB_VID 0x1209
#define USB_PID 0x0001

static const tusb_desc_device_t desc_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           = 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;
}

enum { ITF_NUM_CDC = 0, ITF_NUM_CDC_DATA, ITF_NUM_TOTAL };

#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_CDC_DESC_LEN)
#define EPNUM_CDC_NOTIF  0x81
#define EPNUM_CDC_OUT    0x02
#define EPNUM_CDC_IN     0x82

static const uint8_t desc_config[] = {
	TUD_CONFIG_DESCRIPTOR(1, ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN,
			      TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, 100),
	TUD_CDC_DESCRIPTOR(ITF_NUM_CDC, 4, EPNUM_CDC_NOTIF, 8,
			   EPNUM_CDC_OUT, EPNUM_CDC_IN, 64),
};

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

static const char *const strings[] = {
	(const char[]){ 0x09, 0x04 },     /* 0: English (US) */
	"Example Co",                      /* 1: manufacturer */
	"Pico Serial",                     /* 2: product */
	NULL,                              /* 3: serial, filled at run time */
	"Pico CDC",                        /* 4: CDC interface */
};

static uint16_t str_buf[32];

const uint16_t *tud_descriptor_string_cb(uint8_t index, uint16_t langid)
{
	(void)langid;
	uint8_t n;
	char serial[2 * PICO_UNIQUE_BOARD_ID_SIZE_BYTES + 1];
	const char *s;

	if (index == 0) {
		str_buf[1] = 0x0409;
		n = 1;
	} else if (index < sizeof strings / sizeof strings[0]) {
		if (index == 3) {
			pico_get_unique_board_id_string(serial, sizeof serial);
			s = serial;
		} else {
			s = strings[index];
		}
		for (n = 0; n < 31 && s[n]; n++)
			str_buf[1 + n] = s[n];
	} else {
		return NULL;
	}
	str_buf[0] = (uint16_t)((TUSB_DESC_STRING << 8) | (2 * n + 2));
	return str_buf;
}

The device class of TUSB_CLASS_MISC with the IAD protocol tells the host the device uses interface association descriptors, which groups the two CDC interfaces so that Windows loads one driver for them. TUD_CDC_DESCRIPTOR emits that association descriptor, the control interface with its notification endpoint, the data interface and the two bulk endpoints.

Main loop. The stack is polled, so tud_task() must run often:

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

int main(void)
{
	tusb_init();

	for (;;) {
		tud_task();
		if (tud_cdc_available()) {
			uint8_t buf[64];
			uint32_t n = tud_cdc_read(buf, sizeof buf);
			tud_cdc_write(buf, n);
			tud_cdc_write_flush();
		}
	}
}

Typing in the terminal now echoes each character back:

Text
hello

Build. Link tinyusb_device and tinyusb_board, add the include directory holding tusb_config.h, and turn off the stdio USB option, because both cannot own the port:

CMakeLists.txtcmake
add_executable(usb_cdc main_tinyusb.c usb_descriptors.c)
target_include_directories(usb_cdc PRIVATE ${CMAKE_CURRENT_LIST_DIR})
target_link_libraries(usb_cdc pico_stdlib pico_unique_id tinyusb_device tinyusb_board)
pico_add_extra_outputs(usb_cdc)

Things that go wrong

The port never appears. tud_task() is not called often enough, or something blocks the main loop for longer than a few milliseconds during enumeration. The host gives up on devices that do not answer within about 5 seconds, and in practice a loop that stalls for tens of milliseconds can lose a request. Windows shows "Unknown device". The IAD fields in the device descriptor are missing, or the serial string is empty and the same ID is reused on two ports. Output stops after a while. The transmit buffer is full because the host is not reading: tud_cdc_write returns the number of bytes it accepted, which can be fewer than you gave it. Check the return value and retry, or check tud_cdc_write_available() first. Lost first lines. The host opened the port after you printed. Wait on tud_cdc_connected(), which is true when the host asserts DTR, a topic covered in its own post.

When to use which

For a program whose serial port is just a console, pico_enable_stdio_usb is the right answer: it is one line, it handles the details, and it is the supported path. Use TinyUSB directly when you need a second USB function, your own vendor and product IDs, or custom behavior on the line state. Both routes use the same stack underneath.

What the host actually sees

It helps to know what the board says about itself, because most failures show up in the host's view of it. On Linux, lsusb -v -d 1209:0001 prints the descriptors the firmware above produces. The interesting part is the interface association and the endpoint list: the control interface (class 2, subclass 2) owns the interrupt IN endpoint 0x81 used for serial state notifications, and the data interface (class 10, "CDC Data") owns the bulk OUT endpoint 0x02 and bulk IN endpoint 0x82. The kernel binds the cdc_acm driver to the pair and creates the /dev/ttyACM0 node, and dmesg records it:

Text
usb 1-1: new full-speed USB device number 9 using xhci_hcd
usb 1-1: New USB device found, idVendor=1209, idProduct=0001, bcdDevice= 1.00
usb 1-1: Product: Pico Serial
usb 1-1: Manufacturer: Example Co
cdc_acm 1-1:1.0: ttyACM0: USB ACM device

A line like cdc_acm 1-1:1.0: ttyACM0: USB ACM device is the confirmation that the descriptors are right. If the device enumerates but cdc_acm never binds, the interface class codes are wrong; if it fails with device descriptor read/64, error -71, firmware never answered the first request, which on the RP2040 usually means the main loop is not calling tud_task() or the clocks are misconfigured so the 48 MHz USB clock is not running.

Extending the echo into something useful

The echo loop shows the data path, and a real device needs three small additions. First, line-oriented input: collect bytes into a buffer until a newline and then act on the command, since a terminal sends keystrokes one at a time and a script on the host may send a whole line in one packet. Second, flow control: tud_cdc_write_available() tells you how many bytes the transmit FIFO can take, so a producer such as an ADC sampler can drop or throttle instead of blocking tud_task(). Third, a heartbeat that does not depend on the port being open: if your program's only sign of life is the serial output, a closed terminal looks identical to a crash, so blink the on-board LED from the main loop as well.

A small command loop built on these three ideas fits in about thirty lines and turns the Pico into a scriptable instrument: led on, adc 0 and version are enough to control it from a shell script on the host with echo "adc 0" > /dev/ttyACM0 and a read from the same device. Set the line discipline first with stty -F /dev/ttyACM0 raw -echo so that the terminal layer does not mangle binary data or echo your command back to the device.

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.