Skip to content

Instantly share code, notes, and snippets.

@sandyjmacdonald
Created October 2, 2020 18:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sandyjmacdonald/5fd3d57ffb912d6db2af3f37b849e788 to your computer and use it in GitHub Desktop.
Save sandyjmacdonald/5fd3d57ffb912d6db2af3f37b849e788 to your computer and use it in GitHub Desktop.
USB MIDI CC controller with Adafruit Trinket M0 and Pimoroni Potentiometer Breakout.
// USB MIDI CC controller with Trinket M0 and Pimoroni Potentiometer Breakout.
// Adapted from Chris Parrot's Potentiometer example.
#include <IOExpander.h>
#include <Adafruit_DotStar.h>
#include <MIDIUSB.h>
// Global constants
static const unsigned int DELAY_MS = 1000 / 30;
static const byte PIN_RED = 1;
static const byte PIN_GREEN = 7;
static const byte PIN_BLUE = 2;
static const byte POT_ENC_A = 12;
static const byte POT_ENC_B = 3;
static const byte POT_ENC_C = 11;
static constexpr float BRIGHTNESS = 1.0f;
static constexpr unsigned int PERIOD = (unsigned int)(255.0f / BRIGHTNESS);
static const bool INVERT_OUTPUT = true;
// Global variables / definitions
IOExpander ioe(Wire, 0x0e);
#define NUMPIXELS 1
#define DATAPIN 7
#define CLOCKPIN 8
Adafruit_DotStar strip = Adafruit_DotStar(NUMPIXELS, DATAPIN, CLOCKPIN, DOTSTAR_BGR);
// Set everything up
void setup()
{
Serial.begin(9600);
delay(1000);
Wire.begin();
if(!ioe.initialise())
{
while(true)
delay(10);
}
ioe.setMode(POT_ENC_A, IOExpander::PIN_OUT);
ioe.setMode(POT_ENC_B, IOExpander::PIN_OUT);
ioe.setMode(POT_ENC_C, IOExpander::PIN_ADC);
ioe.output(POT_ENC_A, 1);
ioe.output(POT_ENC_B, 0);
ioe.setPwmPeriod(PERIOD);
ioe.setPwmControl(2);
ioe.setMode(PIN_RED, IOExpander::PIN_PWM, false, INVERT_OUTPUT);
ioe.setMode(PIN_GREEN, IOExpander::PIN_PWM, false, INVERT_OUTPUT);
ioe.setMode(PIN_BLUE, IOExpander::PIN_PWM, false, INVERT_OUTPUT);
strip.begin();
strip.setBrightness(16);
strip.show();
}
// Function to send MIDI CC message
void controlChange(byte channel, byte control, byte value) {
midiEventPacket_t event = {0x0B, 0xB0 | channel, control, value};
MidiUSB.sendMIDI(event);
}
// Main loop to set the LEDs and send MIDI CC
void loop()
{
float analog = ioe.inputAsVoltage(POT_ENC_C); // Read pot. voltage
byte r = 255 - round((analog / 3.30) * 255); // Values for RGB LEDs
byte g = round((analog / 3.30) * 255);
byte b = 0;
ioe.output(PIN_RED, r); // Set pot. LED
ioe.output(PIN_GREEN, g);
ioe.output(PIN_BLUE, b);
strip.setPixelColor(0, r, g, b); // Set DotStar LED
strip.show();
int cc = 127 - round((analog / 3.30) * 127); // Map voltage to 0-127 range
controlChange(0, 1, cc);
MidiUSB.flush();
delay(DELAY_MS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment