Arduino midi in and out

MIDI (Troyka-модуль)

Troyka-MIDI (Musical Instrument Digital Interface — цифровой интерфейс музыкальных инструментов) — это модули, которые позволяют подключиться к профессиональным музыкальным инструментам.


Подключение и настройка

Стандарт MIDI подразумевает общение устройств между собой по асинхронному протоколу, аналогичному UART. Отличие в том, что данные передаются не уровнем напряжения, а током. Поэтому мы будем подключать модули к Serial-порту управляющей платы.


Простой MIDI-сниффер можно сделать, используя Troyka Slot Shield и Troyka-модуль MIDI IN.

В мониторе порта вы увидите MIDI-сообщения.

Arduino Leonardo

Iskra JS

Тот же пример можно выполнить и на Iskra JS. Добавим расшифровку MIDI-сообщений: номер ноты, номер MIDI-канала и сила нажатия клавиши.

Arduino Uno

В Arduino Uno подключение к компьютеру происходит по единственному Serial-соединению. Чтобы иметь возможность наблюдать MIDI-команды в мониторе порта, изменим схему и создадим программный последовательный порт.


Troyka-модуль MIDI OUT подключается к пину TX микроконтроллера. Есть особенность при использовании модуля вместе с Troyka Slot Shield. В этом случае придётся подать питание на модуль через ножки микроконтроллера.

Мы используем Arduino Uno, поэтому в коде используется объект Serial . Если вы используете Arduino Leonardo или Iskra Neo, используйте Serial1 .



Некоторые синтезаторы обладают только одним или двумя MIDI-разъёмами, без MIDI THRU. Поэтому их не удаётся подключить классическим способом. Подключить же MIDI-входы параллельно друг другу не получится. В этом случае ток в токовой петле будет распределяться между входами непредсказуемым образом. Но проблему подключения таких синтезаторов можно решить, используя Troyka MIDI IN и горсть Troyka MIDI OUT. Для подключения модулей удобно использовать несколько Troyka Pad 1×2 и Power Bank.

Индикатор нажатия клавиш

Используем цветную светодиодную ленту для индикации номера и силы нажатия клавиши синтезатора.


Analog To Midi

With this tutorial you use the Audio Frequency Meter Library and the Arduino Midi USB library and build a device that recognizes an input frequency and outputs it to MIDI as the nearest corresponding note of the chromatic scale.

This tutorial relies on these other two tutorials:

Hardware Required

Arduino MKR1000 Board

2x 100k resistor

2x 47k resistor

1x 100n capacitor

The Circuit

In order to get the most dynamic range even from low level inputs, the circuit consist of a non-inverting amplifier that brings the amplitude of the signal to the full input voltage range supported by the ADC. Sampling at full resolution means a better accuracy.

The 10k trimpot allows to adjust the gain of the amplifier matching the signal level with the ADC input range. This adjustment should be made looking at the output on the Arduino Software (IDE) Serial Monitor: when the note reading is stable while playing the same note, the gain is properly set.

As an alternative, you may purchase the Electret microphone amplifier — MAX4466 with adjustable gain that was designed specifically for this purpose.

Works on: MKR1000 and Zero boards.


Software Essentials


Library that creates a MIDI device through USB Host port; the device outputs notes in MIDI format and needs a sound generator.

Defines the correspondence between audio frequencies and notes of the 88 keys scale. Part of MIDIUSB

Defines the correspondence between notes and MIDI note values. Part of MIDIUSB

Functions defined in the sketch:

searchForNote(float frequency) Search for the nearest frequency that is in the vector of frequencies noteFrequency [ ]

noteOn(byte channel, byte pitch, byte velocity) Sends out to MIDI the event to turn on the note of the specified pitch on the specified MIDI Channel

void noteOff(byte channel, byte pitch, byte velocity) Sends out to MIDI the event to turn off the note of the specified pitch on the specified MIDI Channel


Lab: MIDI Output using an Arduino


This lab covers only the details of MIDI communication on the Arduino module. For a more general introduction to MIDI on a microprocessor, see the the MIDI notes.

MIDI, the Musical Instrument Digital Interface, is a useful protocol for controlling synthesizers, sequencers, and other musical devices. MIDI devices are generally grouped in to two broad classes: controllers (i.e. devices that generate MIDI signals based on human actions) and synthesizers (including samplers, sequencers, and so forth). The latter take MIDI data in and make sound, light, or some other effect.

What You’ll Need to Know

To get the most out of this lab, you should be familiar with the following concepts. You can check how to do so in the links below:

Things You’ll Need

Figure 1-9 are the parts that you need for this lab.

MIDI appoaches: Serial, SoftwareSerial, or MIDIUSB

There are three approaches you can take to MIDI output, depending on the board you’re using and the application you have in mind.

If you’re communicating with a MIDI sound module like a synthesizer or sampler, you’ll need to use either Serial or SoftwareSerial output. On the Uno, SoftwareSerial is best. On most other Arduino models, there is a second hardware serial port, Serial1, that you can use for MIDI output.

If you’re communicating with a MIDI program like Ableton, GarageBand, or a soundFont synth like Sforzando, either on a laptop or mobile device, then MIDIUSB is the way to go. The Uno can’t communicate using MIDIUSB, but the Nano 33 IoT, the MKR series, the Leonardo, Micro, or Due can.

SoftwareSerial Approach

If you’re using an Uno or any board with only one serial port, the SoftwareSerial library is your best bet. This section describes how to wire and program your board for SoftwareSerial.

Prepare the breadboard

Connect power and ground on the breadboard to power and ground from the microcontroller. On the Arduino module, use the 5V and any of the ground connections (Figure 10):

For the Nano 33 IoT version or any of the MIDIUSB versions (see below), you won’t need a MIDI jack.

Connect the sensors

Connect an analog sensor to analog pins 0 like you did in the analog lab (Figure 11). Connect a switch to digital pin 10 like you did in the digital lab (Figure 12).

Build the MIDI Circuit

Add the MIDI out jack and a 220-ohm resistor to digital pin 3, as shown in Figure 13-14:

This circuit doesn’t actually match the MIDI specification, but it works with all the MIDI devices we’ve tried it with. This circuit includes an analog and a digital sensor to allow for physical interactivity, but those aren’t necessary to send MIDI data.

Play Notes

Once you’re connected, sending MIDI is just a matter of sending the appropriate bytes. In the code below, you’ll use the SoftwareSerial library to send data on digital pin 3, so that you can keep the hardware serial available for debugging purposes.

The bytes have to be sent as binary values, but you can format them in your code as decimal or hexadecimal values. The example below uses hexadecimal format for any fixed values, and a variable for changing values. All values are sent serially as raw binary values, using the BYTE modifier to .print() (Many MIDI tables give the command values in hex, so this was done in hex for the sake of convenience):

Alternatives to SoftwareSerial

There are two alternatives to SoftwareSerial, but they are only available on boards other than the Uno. You could use the second hardware serial port if you have one. Or, if you’re using one of the MKR series boards or a Nano 33 IoT or an M0-based derivative board, you can use MIDIUSB.

Second Hardware Serial Port

If you’re using any board that has two hardware serial ports, you don’t have to use SoftwareSerial. That includes almost any of the official Arduino boards except the Uno: the Nano 33 IoT, the Due, the Mega, the MKR series, the Leonardo, the Micro and the 101 all have two hardware serial ports. You could also use any M0- or 32U4-based derivative board like Adafruit’s Feather and Trinket boards. If you are using one of those boards, copy the circuits above but move the MIDI connector’s pin 4 to the TX1 pin of your board. Then change your code as follows. First, remove the first line that includes the SoftwareSerial library. Then remove the line that initializes SoftwareSerial. Then change midiSerial.begin() to Serial1.begin() . Then change all midiSerial calls to Serial1 calls. Here’s the changed code:


If you’re using an ARM board like the MKR series, the Nano 33 IoT, the Due, or any of the M0-based derivatives, you can also use MIDIUSB. When you do this, your microcontroller shows up to your computer like a USB MIDI device. This is handy for when you’re connecting to a laptop. It’s less handy for connecting to dedicated synthesizers or samplers.

To do this, dispose of the MIDI socket. You’ll be connecting through your USB connector, and yes, the serial connection to the Serial Monitor will still work as well. Change your code as follows. First include the MIDIUSB library (you might need to install it using the Library Manager) at the top of your code. Then remove the Serial1.begin() line in the setup. Then replace the Serial1.write() lines in the noteOn function with the MIDI code shown below:

Note on MIDIUSB and Serial Ports

The MIDIUSB library on the SAMD boards (MKRZero, MKR1xxx, Nano 33IoT) has an unusual behavior: using it changes the serial port enumeration. When you include the MIDIUSB library in a sketch, your board’s serial port number will change. For example, on MacOS, if the port number is /dev/cu.usbmodem14101 , then adding the MIDIUSB library will change it to /dev/cu.usbmodem14102 . Removing the MIDIUSB library will change it back to /dev/cu.usbmodem14101 . Similarly, if you double-tap the reset button to put the board in bootloader mode, the serial port will re-enumerate to its original number.

Windows and MIDIUSB

You may have trouble getting these MIDI sketches to work on Windows. On Windows, the default Arduino drivers must be uninstalled so the system can recognize the Arduino as both serial device and MIDI device. Read this issue and follow the instructions there.

Allow a Person to Play Notes

The previous example will just play notes, no interactivity. The example below uses an analog input to set the pitch, and a digital input (a switch) to start and stop the note:

Make an Instrument

Now that you’ve got the basics, make a musical instrument. Consider a few things in designing your instrument:

  • Do you want to play discrete notes (like a piano), or sliding pitches (like a theremin)? How do you program to achieve these effects?
  • Do you want to control the tempo and duration of a note?
  • Do you want the same physical action to set both the pitch and the velocity (volume) of a note?
  • Do you want to be able to play more than one note at a time (e.g. chords)?

All of these questions, and many more, will affect what sensors you use, how you read them, and how you design both the physical interface and the software.

For more on MIDI, music, and instruments, see these notes, and this overview of MIDI on the Arduino.


MIDI Note Player

This tutorial shows how to send MIDI notes from an Arduino board to a MIDI instrument connected through the standard 5 poles DIN cable.

MIDI, the Musical Instrument Digital Interface, is a useful protocol for controlling synthesizers, sequencers, and other musical devices. MIDI devices are generally grouped in to two broad classes: controllers (i.e. devices that generate MIDI signals based on human actions) and synthesizers (including samplers, sequencers, and so forth). The latter take MIDI data in and make sound, light, or some other effect.

MIDI is a serial protocol that operates at 31,250 bits per second. The board built-in serial port (all of them on the Mega as well) can send data at that rate.

MIDI bytes are divided into two types: command bytes and data bytes. Command bytes are always 128 or greater, or 0x80 to 0xFF in hexadecimal. Data bytes are always less than 127, or 0x00 to 0x7F in hex. Commands include things such as note on, note off, pitch bend, and so forth. Data bytes include things like the pitch of the note to play, the velocity, or loudness of the note, amount of pitch bend and so forth. For more details, see the MIDI specification or one of the many MIDI Protocol Guides on the Web.

MIDI data is usually notated in hexadecimal because MIDI banks and instruments are grouped in groups of 16.

Hardware Required

Female MIDI jack

2 220 ohm resistors

MIDI enabled device (optional, for testing)


All MIDI connectors are female, by definition of the MIDI spec. Here’s how to wire the connector to the board:

MIDI jack pin 5 connected to Digital pin 1 through a 220 ohm resistor

MIDI jack pin 2 connected to ground

MIDI jack pin 4 connected to +5V through a 220 ohm resistor


Attention If you’re using a board with ATmega32U4 like DUE or Leonardo, please replace Serial with Serial1 in the sketch below.

See Also

ASCIITable — Demonstrates Arduino’s advanced serial output functions.

Dimmer — Move the mouse to change the brightness of an LED.

Graph — Send data to the computer and graph it in Processing.

MultiSerialMega — Use two of the serial ports available on the Arduino Mega.

PhysicalPixel — Turn a LED on and off by sending data to your board from Processing or Max/MSP.

ReadASCIIString — Parse a comma-separated string of integers to fade an LED.

SerialCallResponse — Send multiple variables using a call-and-response (handshaking) method.

SerialCallResponseASCII — Send multiple variables using a call-and-response (handshaking) method, and ASCII-encode the values before sending.

SerialEvent — Demonstrates the use of serialEvent().

VirtualColorMixer — Send multiple variables from Arduino to your computer and read them in Processing or Max/MSP.