Musical robots controlled by incoming MIDI messages are a popular project. This example will show how you can use MIDI in messages to affect a servo motor.
- Servo GND to Metro M4 Express GND
- Servo power to Metro M4 Express 5V
- Servo signal to Metro M4 Express pin D2
This example uses a Metro M4 Express microcontroller board. To make sure it is setup properly with CircuitPython, please follow the steps in the guide below.
Once you've finished setting up your Metro M4 Express with CircuitPython, you can access the code and necessary libraries by downloading the Project Bundle.
To do this, click on the Download Project Bundle button in the window below. It will download as a zipped folder.
# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries # SPDX-License-Identifier: MIT import board import pwmio import usb_midi import adafruit_midi from adafruit_midi.note_off import NoteOff from adafruit_midi.note_on import NoteOn from adafruit_motor import servo # pwm setup for servo pwm = pwmio.PWMOut(board.D2, duty_cycle=2 ** 15, frequency=50) # servo setup motor = servo.Servo(pwm) # midi setup midi = adafruit_midi.MIDI( midi_in=usb_midi.ports[0], in_channel=0, midi_out=usb_midi.ports[1], out_channel=0 ) while True: # receive midi input msg = midi.receive() if msg is not None: # if a NoteOn message is received... if isinstance(msg, NoteOn): # servo set to 180 degrees motor.angle = 180 # if a NoteOff message is received... if isinstance(msg, NoteOff): # servo set to 0 degrees motor.angle = 0
After downloading the Project Bundle, plug your Metro M4 Express into the computer's USB port. You should see a new flash drive appear in the computer's File Explorer or Finder (depending on your operating system) called CIRCUITPY. Unzip the folder and copy the following items to the Metro M4 Express's CIRCUITPY drive.
- lib folder
- code.py
Your Metro M4 Express CIRCUITPY drive should look like this after copying the lib folder and the code.py file.
This code is an example of having another peripheral react to a MIDI input. Every time a NoteOn
message is received, the servo turns to 180
degrees. When a NoteOff
message is received, the servo turns back to 0
degrees.
You can connect your Metro M4 via USB to either your computer or a USB MIDI host. Send MIDI NoteOn
and NoteOff
messages to the Metro and you should see the servo move back and forth accordingly.
Musical robots are a popular music technology project that often incorporate MIDI. Using techniques like this can also be useful in interactive installations where folks can see a physical reaction to a digital input.
Page last edited January 22, 2025
Text editor powered by tinymce.