🛠 Un instrument MIDI USB en 10 minutes : Bounce, boutons et règle d'or du drain

Teensy 3.2 · debutant · Schéma : IMG-teensy-32-debutant-3-teensy32-usb-midi-instrument.svg — Teensy 3.2 avec trois boutons poussoirs sur les broches 1, 2 et 3, câble USB vers un ordinateur affichant une fenêtre de séquenceur (DAW) où apparaît l'entrée MIDI « Teensy » ; note de musique C4 au-dessus du premier bouton.

Objectives

Turn the Teensy 3.2 into a USB musical instrument: its 12 Mbit/s USB device port is reconfigurable at will (Serial, MIDI, MIDIx4/MIDIx16, Audio, Keyboard, Mouse, Joystick, Flightsim, RawHID…) via Tools > USB Type. This tutorial builds a mini-keyboard with 3 buttons using the Bounce library, applying the golden rule of MIDI controllers stated by PJRC: always drain incoming messages, otherwise USB buffers fill up and everything freezes.

Hardware

Complete Code

Official example from PJRC's USB MIDI tutorial (original comments):

#include <Bounce.h>   // Bounce library makes button change detection easy
const int channel = 1;

Bounce button1 = Bounce(1, 5);  // 5 = 5 ms debounce time
Bounce button2 = Bounce(2, 5);  // appropriate for good quality
Bounce button3 = Bounce(3, 5);  // mechanical pushbuttons

void setup {
  pinMode(1, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
}

void loop {
  button1.update;
  button2.update;
  button3.update;
  // Note On when each button is pressed
  if (button1.fallingEdge) usbMIDI.sendNoteOn(60, 99, channel); // 60 = C4
  if (button2.fallingEdge) usbMIDI.sendNoteOn(61, 99, channel); // 61 = C#4
  if (button3.fallingEdge) usbMIDI.sendNoteOn(62, 99, channel); // 62 = D4
  // Note Off on release
  if (button1.risingEdge) usbMIDI.sendNoteOff(60, 0, channel);
  if (button2.risingEdge) usbMIDI.sendNoteOff(61, 0, channel);
  if (button3.risingEdge) usbMIDI.sendNoteOff(62, 0, channel);

  // MIDI controllers should discard incoming MIDI messages,
  // otherwise USB buffers fill up
  while (usbMIDI.read) { }
}

Uploading

Set Tools > USB Type : MIDI BEFORE compiling, then upload normally (Teensy Loader). The board is then recognized as a USB MIDI class-compliant device — no driver installation required on Windows, macOS, or Linux. This is the reason for the Teensy's success in DIY MIDI controllers.

Expected Verification

Open your DAW or MIDI-OX: the Teensy appears as a MIDI input. Each press triggers C4/C#4/D4 (notes 60/61/62, velocity 99) and the release sends the corresponding Note Off. Now test the drain rule: if your sequencer sends messages back (aftertouch, MIDI clock, MTC synchronization…), the absence of the while (usbMIDI.read) { } loop fills the USB buffers and freezes the controller after a few minutes — this is the most reported bug.

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials