Created
May 1, 2021 13:23
-
-
Save sandyjmacdonald/e4a7dea90331e1d69e90ebd0c2fe5196 to your computer and use it in GitHub Desktop.
MIDI input example for the Pimoroni Tiny 2040 board
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This example lights the RGB LED on Tiny 2040 to a different colour | |
# for each note in the octave. Listens on all MIDI channels by default. | |
import board | |
import adafruit_rgbled | |
import usb_midi | |
import adafruit_midi | |
from adafruit_midi.note_on import NoteOn | |
from adafruit_midi.note_off import NoteOff | |
# Red, green, and blue LED pins | |
RED_LED = board.LED_R | |
GREEN_LED = board.LED_G | |
BLUE_LED = board.LED_B | |
def hsv_to_rgb(h, s, v): | |
# Convert an HSV (0.0-1.0) colour to RGB (0-255) | |
if s == 0.0: | |
rgb = [v, v, v] | |
i = int(h * 6.0) | |
f = (h*6.)-i; p,q,t = v*(1.-s), v*(1.-s*f), v*(1.-s*(1.-f)); i%=6 | |
if i == 0: | |
rgb = [v, t, p] | |
if i == 1: | |
rgb = [q, v, p] | |
if i == 2: | |
rgb = [p, v, t] | |
if i == 3: | |
rgb = [p, q, v] | |
if i == 4: | |
rgb = [t, p, v] | |
if i == 5: | |
rgb = [v, p, q] | |
rgb = tuple(int(c * 255) for c in rgb) | |
return rgb | |
# Set LED up as common anode LED | |
led = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED, invert_pwm=True) | |
led.color = (0, 0, 0) | |
# Set up USB MIDI to listen on all channels | |
midi = adafruit_midi.MIDI(midi_in=usb_midi.ports[0]) | |
while True: | |
# Receive MIDI message | |
msg = midi.receive() | |
if isinstance(msg, NoteOn): | |
# If it's a note on message, turn the LED on | |
# Calculate a hue that maps the 12 notes in an octave to values from 0.0 to 1.0 | |
h = msg.note % 12 / 12 | |
s = 1.0 | |
v = 1.0 | |
r, g, b =hsv_to_rgb(h, s, v) | |
# Set LED colour | |
led.color = (r, g, b) | |
elif isinstance(msg, NoteOff): | |
# If it's a note off message, then turn the LED off | |
led.color = (0, 0, 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment