Skip to content

Instantly share code, notes, and snippets.

@remisarrailh
Created May 8, 2020 15:13
Show Gist options
  • Save remisarrailh/d403c4da157c41404e985ff94d3771d7 to your computer and use it in GitHub Desktop.
Save remisarrailh/d403c4da157c41404e985ff94d3771d7 to your computer and use it in GitHub Desktop.
/* Example of a sound being triggered by MIDI input.
Demonstrates playing notes with Mozzi in response to MIDI input,
using Arduino MIDI library v4.2
(https://github.com/FortySevenEffects/arduino_midi_library/releases/tag/4.2)
Circuit:
MIDI input circuit as per http://arduino.cc/en/Tutorial/Midi
Note: midi input on rx pin, not tx as in the illustration on the above page.
Midi has to be disconnected from rx for sketch to upload.
Audio output on digital pin 9 on a Uno or similar.
Mozzi documentation/API
https://sensorium.github.io/Mozzi/doc/html/index.html
Mozzi help/discussion/announcements:
https://groups.google.com/forum/#!forum/mozzi-users
Tim Barrass 2013-14, CC by-nc-sa.
*/
#include "MIDIUSB.h"
#include <MozziGuts.h>
#include <Oscil.h> // oscillator template
#include <tables/sin2048_int8.h> // sine table for oscillator
#include <mozzi_midi.h>
#include <ADSR.h>
const byte NOTEON = 0x09;
const byte NOTEOFF = 0x08;
long audio_data;
long envelope_data;
long audio_final_data;
// use #define for CONTROL_RATE, not a constant
#define CONTROL_RATE 64 // Hz, powers of 2 are most reliable
// audio sinewave oscillator
Oscil <SIN2048_NUM_CELLS, AUDIO_RATE> aSin(SIN2048_DATA);
// envelope generator
ADSR <CONTROL_RATE, AUDIO_RATE> envelope;
void HandleNoteOn(byte channel, byte note, byte velocity) {
aSin.setFreq(mtof(float(note)));
envelope.noteOn();
}
void HandleNoteOff(byte channel, byte note, byte velocity) {
//envelope.noteOff();
}
void setup() {
Serial.begin(115200);
envelope.setADLevels(255, 64);
envelope.setTimes(50, 200, 10000, 200); // 10000 is so the note will sustain 10 seconds unless a noteOff comes
aSin.setFreq(440); // default frequency
startMozzi(CONTROL_RATE);
}
void updateControl() {
midiEventPacket_t rx = MidiUSB.read();
switch (rx.header) {
case 0:
break;
case NOTEON:
if (rx.byte3 == 0x00) {
HandleNoteOff(rx.byte1, rx.byte2, rx.byte3);
}
HandleNoteOn(rx.byte1, rx.byte2, rx.byte3);
case NOTEOFF:
HandleNoteOff(rx.byte1, rx.byte2, rx.byte3);
}
if (rx.header != 0) {
/*
Serial.print(rx.header, HEX);
Serial.print("-");
Serial.print(rx.byte1, HEX);
Serial.print("-");
Serial.print(rx.byte2, HEX);
Serial.print("-");
Serial.println(rx.byte3, HEX);
*/
}
envelope.update();
Serial.print(envelope_data);
Serial.print(",");
Serial.print(audio_data);
Serial.print(",");
Serial.println(audio_final_data);
MidiUSB.flush();
}
int updateAudio() {
envelope_data = envelope.next();
audio_data = aSin.next();
audio_final_data = (envelope_data * audio_data) >> 12;
return (int) audio_final_data;
}
void loop() {
audioHook(); // required here
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment