Skip to content

Instantly share code, notes, and snippets.

@LeoAdamek
Created May 6, 2017 18:22
Show Gist options
  • Save LeoAdamek/53f1717799625f68712d4dcf3dc365a6 to your computer and use it in GitHub Desktop.
Save LeoAdamek/53f1717799625f68712d4dcf3dc365a6 to your computer and use it in GitHub Desktop.
usb audio synth thing
#include <Audio.h>
#include <MIDI.h>
AudioSynthWaveformSine debugTone;
AudioOutputUSB audioRet;
AudioConnection patchCord1 (debugTone, 0, audioRet, 0);
AudioConnection patchCord2 (debugTone, 0, audioRet, 1);
void setup() {
AudioMemory(15);
// Serial will be used for debugging messages.
Serial.begin(9600);
// Callbacks for note handling.
usbMIDI.setHandleNoteOff(OnNoteOff);
usbMIDI.setHandleNoteOn(OnNoteOn);
debugTone.amplitude(1);
debugTone.frequency(440);
}
void loop() {
// Continuously read and handle MIDI messages.
usbMIDI.read();
}
void OnNoteOn(byte channel, byte note, byte vel) {
Serial.printf("Note ON: %x // V: %x // C: %x\n", note, vel, channel);
debugTone.amplitude(1);
debugTone.frequency(noteToFreq(note));
}
void OnNoteOff(byte channel, byte note, byte vel) {
Serial.printf("Note OFF: %x // V: %x // C: %x\n", note, vel, channel);
debugTone.amplitude(0);
}
// Convert MIDI note to tonal freq.
//
// Formula: 440 * 2^( midi_note_val - 69) / 12)
float noteToFreq(byte note) {
float freq = 440 * pow(2, (float(note - 69) / 12));
Serial.printf("Note: %x // Freq: %.2fHz\n", note, freq);
return freq;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment