Skip to content

Instantly share code, notes, and snippets.

@YuuichiAkagawa
Created November 23, 2022 22:58
Show Gist options
  • Save YuuichiAkagawa/3462197cc2080b7c601c11f3bdefd190 to your computer and use it in GitHub Desktop.
Save YuuichiAkagawa/3462197cc2080b7c601c11f3bdefd190 to your computer and use it in GitHub Desktop.
USB MIDI to CV/GATE converter
/*
* USB MIDI to CV/GATE converter
* (C)2022 Yuuichi Akagawa
*/
#include <UHS2-MIDI.h>
#include <Wire.h>
#define MCP4725_ADDRESS 0x60
#define GATE_PIN 2
// 12bit DACを使用。VCCは5V。
// MIDI Noteのレンジは0-127なので、128Step。
// 4096/128 = 32 (DAC Value/halftone)
// 5V時
// 32 * (5/4096) = 39.0625mV
// OpAmpのゲインは2.13333333333333倍。(1/12/0.0390625)
#define NOTE_CONVRATE 32
USB Usb;
UHS2MIDI_CREATE_DEFAULT_INSTANCE(&Usb);
void writeDACreg(uint16_t val)
{
//MCP4725 Fast Mode Write
uint8_t v2 = val & 0xff;
uint8_t v1 = (val >> 8) & 0x0f;
Wire.beginTransmission(MCP4725_ADDRESS);
Wire.write(v1);
Wire.write(v2);
Wire.endTransmission();
}
void handleNoteOn(byte inChannel, byte inNumber, byte inVelocity)
{
if ( inVelocity == 0 ) { //note off
digitalWrite(GATE_PIN, LOW);
} else {
uint16_t dacdata = (uint16_t)inNumber * NOTE_CONVRATE;
writeDACreg(dacdata);
digitalWrite(GATE_PIN, HIGH);
}
}
void handleNoteOff(byte inChannel, byte inNumber, byte inVelocity)
{
digitalWrite(GATE_PIN, LOW);
}
void setup()
{
//init I2C for DAC
Wire.begin();
Wire.setClock(400000);
//GATE pin
pinMode(GATE_PIN, OUTPUT);
digitalWrite(GATE_PIN, LOW);
MIDI.begin();
MIDI.setHandleNoteOn(handleNoteOn);
MIDI.setHandleNoteOff(handleNoteOff);
if (Usb.Init() == -1) {
while (1); //halt
}
delay( 200 );
}
void loop()
{
Usb.Task();
MIDI.read();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment