back to projects

A minimalistic MIDI interface for the Raspberry Pi / play a MIDI file

Tested on a Raspberry Pi 2 and Raspberry Pi Zero W.

Works also with Raspberry Pi as USB/Bluetooth MIDI host, and you can even use the Pi-Zero's USB-client-mode-feature to recognize all the collected MIDI I/O as one MIDI device at your PC.


This schematic can also be used with 3.3V-based microcontroller-boards:

schematic
      uart2midi 6n136

(old version with rare optocoupler)

How does this work? In an official MIDI-schematic for MIDI from a MIDI-device, I found two resistors with 220 Ohm in series, but that's for 5 volts.
We only have 3.3V here. The current for the 6N136 found in the datasheet is 16mA. So we need for the resistors:
R_opto = (3.3V - 1.45V_forward) / 16mA = 116 Ohm. Or represented with two resistors in series: About two times 65 Ohm.


Set up the Pi's serial-port for MIDI:
Because MIDI has that weird non-standard baud-rate of 31250, we have to tweak so things in /boot/config.txt.
Just add this at the end of the file and reboot:

enable_uart=1
dtoverlay=pi3-miniuart-bt
dtoverlay=midi-uart0

After every reboot, you need to set the baud-rate to "38400" which, with the tweak in config.txt, is actually 31250:
stty -F /dev/serial0 38400

Now you can send MIDI-date to /dev/serial0.

Here is a way to test your MIDI-output with http://www.varal.org/ttymidi/ (needs libasound2-dev),
and the midi-player pmidi, for which a debian-package is available:

I had to add -lpthread to this line of ttymidi/Makefile:
gcc src/ttymidi.c -o ttymidi -lasound -lpthread

Add your user (pi) to the dialout group, for accessing the serial port:
sudo usermod -aG dialout pi

Then start it with:
./ttymidi -s /dev/serial0 -b 38400 &

Now we can see a MIDI-device:

aconnect -l

client 0: 'System' [type=kernel]
    0 'Timer           '
    1 'Announce        '
client 14: 'Midi Through' [type=kernel]
    0 'Midi Through Port-0'
client 128: 'ttymidi' [type=user,pid=2865]
    0 'MIDI out        '
    1 'MIDI in         '

Note that "in" is here from the perspective of ttymidi.

pmidi luno-midi-test.mid -p 128:1
plays my boring test-midi-file :)



Creative Commons License Licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

back to projects