Skip to content
systemcoding.dev
Embedded

Add a USB MIDI Interface to a Microcontroller With TinyUSB

Make a microcontroller a class-compliant USB MIDI device with TinyUSB: the 4-byte event packet, note and control change messages, and receiving from the host.

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

MIDI over USB is one of the friendliest classes to implement. Windows 10 and later, macOS, Linux, iOS and Android all ship drivers for class-compliant USB MIDI devices, so a controller you build shows up in every music program with no installer. The firmware work is a descriptor, a four-byte packet format and a loop. This post adds a USB MIDI interface to any microcontroller that TinyUSB supports (the examples use TinyUSB 0.17), sends notes and control changes, and reads messages from the host. The packet format is defined in the USB Device Class Definition for MIDI Devices 1.0 from the USB-IF, and the messages themselves come from the MIDI 1.0 specification.

The USB-MIDI event packet

Classic MIDI is a serial stream at 31,250 baud with variable-length messages. USB cannot carry a bare byte stream usefully, so USB-MIDI wraps the messages in fixed 32-bit event packets. Every packet is four bytes:

ByteContent
0Cable number (high nibble) and code index number, CIN (low nibble)
1MIDI status byte
2First data byte, or 0
3Second data byte, or 0

The cable number selects one of up to 16 virtual MIDI ports on the device, 0 for a single-port device. The code index number tells the host how many of the following bytes are valid, so it can split packets without parsing the MIDI stream. The values worth knowing:

CINMessageBytes used
0x8Note Off3
0x9Note On3
0xAPolyphonic key pressure3
0xBControl change3
0xCProgram change2
0xDChannel pressure2
0xEPitch bend3
0xFSingle byte (system real-time such as clock)1

For channel voice messages the CIN equals the high nibble of the status byte, which makes building packets mechanical. A note-on for middle C (note 60) at velocity 100 on channel 1 (channel numbers are zero-based in the status byte) is the MIDI message 90 3C 64 and the USB packet 09 90 3C 64. System exclusive messages (sysex) of arbitrary length are split across packets with CINs 0x4 to 0x7, which tud_midi_stream_write handles for you.

Configuration and descriptors

Enable the class in tusb_config.h, with buffers sized for the traffic you expect:

tusb_config.hc
#define CFG_TUD_MIDI             1
#define CFG_TUD_MIDI_RX_BUFSIZE  64
#define CFG_TUD_MIDI_TX_BUFSIZE  64
#define CFG_TUD_MIDI_EP_BUFSIZE  64

TinyUSB generates the audio control and MIDI streaming interfaces through a single macro. The configuration descriptor is:

usb_descriptors.cc
enum { ITF_NUM_MIDI = 0, ITF_NUM_MIDI_STREAMING, ITF_NUM_TOTAL };

#define EPNUM_MIDI_OUT 0x01
#define EPNUM_MIDI_IN  0x81
#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_MIDI_DESC_LEN)

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_MIDI_DESCRIPTOR(ITF_NUM_MIDI, 4, EPNUM_MIDI_OUT,
			    (0x80 | EPNUM_MIDI_IN), 64),
};

TUD_MIDI_DESCRIPTOR(itfnum, stridx, epout, epin, epsize) emits an audio control interface (class 1, subclass 1), a MIDI streaming interface (subclass 3) with its class-specific descriptors, and one bulk OUT and one bulk IN endpoint. The epin argument carries the direction bit (0x80), which the macro expects explicitly. String index 4 is the name host software shows for the port, so make it descriptive, such as "Pedalboard". The device descriptor uses class 0 (defined at the interface level) and your vendor and product ID.

Sending and receiving

The main loop sends events and polls the stack:

main.cc
#include "tusb.h"

static void note_on(uint8_t ch, uint8_t note, uint8_t vel)
{
	uint8_t msg[3] = { (uint8_t)(0x90 | (ch & 0x0F)), note, vel };
	tud_midi_stream_write(0, msg, 3);
}

static void note_off(uint8_t ch, uint8_t note)
{
	uint8_t msg[3] = { (uint8_t)(0x80 | (ch & 0x0F)), note, 0 };
	tud_midi_stream_write(0, msg, 3);
}

static void control_change(uint8_t ch, uint8_t cc, uint8_t val)
{
	uint8_t msg[3] = { (uint8_t)(0xB0 | (ch & 0x0F)), cc, val };
	tud_midi_stream_write(0, msg, 3);
}

int main(void)
{
	board_init();
	tusb_init();

	for (;;) {
		tud_task();

		if (!tud_midi_mounted())
			continue;

		if (button_pressed())
			note_on(0, 60, 100);
		if (button_released())
			note_off(0, 60);

		uint8_t v = read_pot_7bit();
		static uint8_t last = 0xFF;
		if (v != last) {
			control_change(0, 74, v);        /* filter cutoff */
			last = v;
		}

		uint8_t pkt[4];
		while (tud_midi_packet_read(pkt)) {
			/* pkt[1] is the status byte of a message from the host */
			if ((pkt[1] & 0xF0) == 0x90 && pkt[3] > 0)
				led_on();
			else
				led_off();
		}
	}
}

Pressing the button now sends one packet and releasing it sends another. Monitor them on a Linux host with ALSA's aseqdump:

Shell
aseqdump -l
aseqdump -p "Pedalboard"
Text
Port    Client name                      Port name
 14:0    Midi Through                     Midi Through Port-0
 20:0    Pedalboard                       Pedalboard MIDI 1

Waiting for data. Press Ctrl+C to end.
Source  Event                  Ch  Data
 20:0   Note on                 0, note 60, velocity 100
 20:0   Note off                0, note 60, velocity 0
 20:0   Controller              0, controller 74, value 64

aseqdump numbers channels from 0, the same way the status byte does, which is why "channel 1" in a music program is "Ch 0" here. tud_midi_stream_write(cable, bytes, len) is the convenient call: it accepts a raw MIDI byte stream, works out the CIN and packs the packets. tud_midi_packet_write takes a ready four-byte packet if you build them yourself.

Details that decide whether it works in a DAW

Note off. A note-on with velocity 0 is also a valid note off, and some controllers use it to save running status. Sending a proper 0x80 note off is the safer choice for software instruments. Do not flood the bus. A pot read every loop iteration sends a control change for every one-count change, many hundreds a second with a noisy ADC. Send only when the 7-bit value changes, add hysteresis, and cap the rate near 100 messages per second per controller. **Wait for tud_midi_mounted(). Before the host configures the device, writes go nowhere. The cable number. For a multi-port device, add a second set of jacks in a custom descriptor; the macro above creates one port. Timing. USB-MIDI bulk transfers are scheduled by the host, so latency has a floor of about one millisecond at full speed. That is below what a musician perceives, and the jitter is a few hundred microseconds, less than DIN MIDI's 320 microseconds per byte on the serial line. Windows names.** Windows caches the product string by VID, PID and serial; changing the name during development can need a registry cleanup or a new PID before the old name goes away.

Clock, transport and the rest of a MIDI controller

A device that only sends notes needs no more than the code above, but three features turn a demo into an instrument. The first is MIDI clock: a host sequencer sends the single-byte real-time message 0xF8 24 times per quarter note, and a device that wants to follow tempo counts those packets (CIN 0xF, one byte) and derives its own beat. The start (0xFA), continue (0xFB) and stop (0xFC) messages arrive the same way, and they are what make a step sequencer or an arpeggiator lock to the host. The second is the active-sensing and reset behavior: on a USB connection, there is no need for active sensing, and a device that sends it only creates traffic. The third is note management on disconnect: if the cable is pulled while a key is held, the host's synthesizer may keep the note sounding forever because it never received a note off. Keep a table of notes you have switched on, and send an all-notes-off control change (controller 123, value 0) on every channel when you detect a new mount, so the host's state and yours agree after a reconnect.

For a quick check of a new device without any music software, amidi -l lists raw MIDI ports on Linux and amidi -p hw:1,0,0 -d dumps the incoming bytes, which is useful for confirming that the packet-to-byte conversion in the host driver produced exactly the status and data bytes you meant to send. On macOS the Audio MIDI Setup utility shows the device and its MIDI studio window, and on Windows tools such as MIDI-OX display each message; a device that appears in all three is a device that will appear in any digital audio workstation.

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.