|
| 1 | +/* |
| 2 | + * Copyright (c) 2024 Titouan Christophe |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + * |
| 6 | + * @file |
| 7 | + * @brief Sample application for USB MIDI 2.0 device class |
| 8 | + */ |
| 9 | + |
| 10 | +#include <sample_usbd.h> |
| 11 | + |
| 12 | +#include <zephyr/device.h> |
| 13 | +#include <zephyr/input/input.h> |
| 14 | +#include <zephyr/usb/class/usb_midi.h> |
| 15 | + |
| 16 | +#include <zephyr/logging/log.h> |
| 17 | +LOG_MODULE_REGISTER(sample_usb_midi, LOG_LEVEL_INF); |
| 18 | + |
| 19 | +static const struct device *const midi = DEVICE_DT_GET(DT_NODELABEL(usb_midi)); |
| 20 | + |
| 21 | +/* On boards that have a user button; button press/release -> MIDI note on/off */ |
| 22 | +#if DT_NODE_EXISTS(DT_NODELABEL(user_button)) |
| 23 | +static const struct device *const button = DEVICE_DT_GET(DT_PARENT(DT_NODELABEL(user_button))); |
| 24 | + |
| 25 | +static void key_press(struct input_event *evt, void *user_data) |
| 26 | +{ |
| 27 | + uint8_t command = evt->value ? MIDI_NOTE_ON : MIDI_NOTE_OFF; |
| 28 | + |
| 29 | + usb_midi_send(midi, &UMP_MIDI1(0, command, 0, 0x40, 0x7f)); |
| 30 | +} |
| 31 | +INPUT_CALLBACK_DEFINE(button, key_press, NULL); |
| 32 | +#endif |
| 33 | + |
| 34 | +static void on_midi_packet(const struct device *dev, const union ump *midi_packet) |
| 35 | +{ |
| 36 | + LOG_INF("Received MIDI packet (MT=%X)", midi_packet->mt); |
| 37 | + |
| 38 | + /* Only send MIDI1 channel voice messages back to the host */ |
| 39 | + if (midi_packet->mt == MT_MIDI1_CHANNEL_VOICE) { |
| 40 | + const struct ump_midi1 *midi1 = &midi_packet->midi1; |
| 41 | + |
| 42 | + LOG_INF("Send back MIDI1 message chan=%d status=%d %02X %02X", midi1->channel, |
| 43 | + midi1->status, midi1->p1, midi1->p2); |
| 44 | + usb_midi_send(dev, midi_packet); |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +int main(void) |
| 49 | +{ |
| 50 | + struct usbd_context *sample_usbd; |
| 51 | + |
| 52 | + if (!device_is_ready(midi)) { |
| 53 | + LOG_ERR("MIDI device not ready"); |
| 54 | + return -1; |
| 55 | + } |
| 56 | + |
| 57 | + usb_midi_set_callback(midi, on_midi_packet); |
| 58 | + |
| 59 | + sample_usbd = sample_usbd_init_device(NULL); |
| 60 | + if (sample_usbd == NULL) { |
| 61 | + LOG_ERR("Failed to initialize USB device"); |
| 62 | + return -1; |
| 63 | + } |
| 64 | + |
| 65 | + if (!usbd_can_detect_vbus(sample_usbd) && usbd_enable(sample_usbd)) { |
| 66 | + LOG_ERR("Failed to enable device support"); |
| 67 | + return -1; |
| 68 | + } |
| 69 | + |
| 70 | + LOG_INF("USB device support enabled"); |
| 71 | + return 0; |
| 72 | +} |
0 commit comments