Hi. I'm working on a very basic synthesizer using the Mozzi Audio Library and rkistner's Arcore library to use USB MIDI. Everything is working great except for an annoying hiccup where any note off message received will cause all of the MIDI notes to stop sounding. I suspect that the reason for this is related to Mozzi's ADSR Class. Documentation here: Mozzi: ADSR< CONTROL_UPDATE_RATE, LERP_RATE, T > Class Template Reference
Here is the code that I am working with:
#include <MIDI.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>
MIDI_CREATE_DEFAULT_INSTANCE();
#define AUDIO_MODE STANDARD_PLUS
// use #define for CONTROL_RATE, not a constant
#define CONTROL_RATE 128 // powers of 2 please
// audio sinewave oscillator
Oscil <SIN2048_NUM_CELLS, AUDIO_RATE> aSin(SIN2048_DATA);
// envelope generator
ADSR <CONTROL_RATE, AUDIO_RATE> envelope;
#define LED 2 // shows if MIDI is being recieved
void HandleNoteOn(byte channel, byte note, byte velocity) {
aSin.setFreq(mtof(float(note)));
envelope.noteOn();
digitalWrite(LED,HIGH);
}
void HandleNoteOff(byte channel, byte note, byte velocity) {
envelope.noteOff();
digitalWrite(LED,LOW);
}
void setup() {
pinMode(LED, OUTPUT);
//envelope.setADLevels(0,0);
//envelope.setTimes(5,200000,10000,5); // 10000 is so the note will sustain 10 seconds unless a noteOff comes
aSin.setFreq(440); // default frequency
startMozzi(CONTROL_RATE);
Serial.begin(9600);
}
void updateControl(){
while(MIDIUSB.available() > 0) { // Repeat while notes are available to read.
MIDIEvent e;
e = MIDIUSB.read();
if(e.type == 0x09) { //note on message
HandleNoteOn(1, e.m2, 127);//channel, note velocity (does not include message type)
//For Debugging
/*
Serial.println("e.m1: ");
Serial.println(e.m1);
Serial.println("e.m2: ");
Serial.println(e.m2);
Serial.println("e.m3: ");
Serial.println(e.m3);
*/
}
if(e.type == 0x08) {
HandleNoteOff(1, e.m2, 0); //channel, note, velocity (does not include message type)
//For Debugging
/*
Serial.println("noteOff");
Serial.println(e.m2);
*/
}
MIDIUSB.flush();
}
envelope.update();
}
int updateAudio(){
return (int) (envelope.next() * aSin.next())>>8;
}
void loop() {
audioHook(); // required here
}
Note: It requires the Mozzi Library available here: Mozzi
and it requires the Arcore Library available here: GitHub - rkistner/arcore: MIDI-USB Support for Arduino
Any thoughts or ideas would be greatly appreciated!