1.. zephyr:code-sample:: usb-midi2-device
2   :name: USB MIDI2 device
3   :relevant-api: usbd_api usbd_midi2 input_events
4
5   Implements a simple USB MIDI loopback and keyboard device.
6
7Overview
8********
9
10This sample demonstrates how to implement a USB MIDI device. It can run on
11any board with a USB device controller. This sample sends all MIDI1 messages
12sent to the device back to the host. In addition, presses and release on
13input keys (such as the board user buttons) are sent as MIDI1 note on and
14note off events.
15
16The application exposes a single USB-MIDI interface with a single bidirectional
17group terminal. This allows exchanging data with the host on a "virtual wire"
18that carries MIDI1 messages, pretty much like a standard USB-MIDI in/out adapter
19would provide. The loopback acts as if a real MIDI cable was connected between
20the output and the input, and the input keys act as a MIDI keyboard.
21
22Building and Running
23********************
24
25The code can be found in :zephyr_file:`samples/subsys/usb/midi`.
26
27To build and flash the application:
28
29.. zephyr-app-commands::
30   :zephyr-app: samples/subsys/usb/midi
31   :board: nucleo_f429zi
32   :goals: build flash
33   :compact:
34
35Using the MIDI interface
36************************
37
38Once this sample is flashed, connect the device USB port to a host computer
39with MIDI support. For example, on Linux, you can use alsa to access the device:
40
41.. code-block:: console
42
43  $ amidi -l
44  Dir Device    Name
45  IO  hw:2,1,0  Group 1 (USBD MIDI Sample)
46
47On Mac OS you can use the system tool "Audio MIDI Setup" to view the device,
48see https://support.apple.com/guide/audio-midi-setup/set-up-midi-devices-ams875bae1e0/mac
49
50The "USBD MIDI Sample" interface should also appear in any program with MIDI
51support; like your favorite Digital Audio Workstation or synthetizer. If you
52don't have any such program at hand, there are some webmidi programs online,
53for example: https://muted.io/piano/.
54
55Testing loopback
56****************
57
58Open a first shell, and start dumping MIDI events:
59
60.. code-block:: console
61
62  $ amidi -p hw:2,1,0 -d
63
64
65Then, in a second shell, send some MIDI events (for example note-on/note-off):
66
67.. code-block:: console
68
69  $ amidi -p hw:2,1,0 -S "90427f 804200"
70
71These events should then appear in the first shell (dump)
72
73On devboards with a user button, press it and observe that there are some note
74on/note off events delivered to the first shell (dump)
75
76.. code-block:: console
77
78  $ amidi -p hw:2,1,0 -d
79
80  90 40 7F
81  80 40 7F
82  90 40 7F
83  80 40 7F
84  [...]
85