|
| 1 | +#include <MIDI.h> |
| 2 | +#include "noteList.h" |
| 3 | +#include "pitches.h" |
| 4 | + |
| 5 | +#ifdef ARDUINO_SAM_DUE // Due has no tone function (yet), overriden to prevent build errors. |
| 6 | +#define tone(...) |
| 7 | +#define noTone(...) |
| 8 | +#endif |
| 9 | + |
| 10 | +// This example shows how to make a simple synth out of an Arduino, using the |
| 11 | +// tone() function. It also outputs a gate signal for controlling external |
| 12 | +// analog synth components (like envelopes). |
| 13 | + |
| 14 | +static const unsigned sGatePin = 13; |
| 15 | +static const unsigned sAudioOutPin = 10; |
| 16 | +static const unsigned sMaxNumNotes = 16; |
| 17 | +MidiNoteList<sMaxNumNotes> midiNotes; |
| 18 | + |
| 19 | +// ----------------------------------------------------------------------------- |
| 20 | + |
| 21 | +void handleGateChanged(bool inGateActive) |
| 22 | +{ |
| 23 | + digitalWrite(sGatePin, inGateActive ? HIGH : LOW); |
| 24 | +} |
| 25 | + |
| 26 | +void pulseGate() |
| 27 | +{ |
| 28 | + handleGateChanged(false); |
| 29 | + delay(1); |
| 30 | + handleGateChanged(true); |
| 31 | +} |
| 32 | + |
| 33 | +// ----------------------------------------------------------------------------- |
| 34 | + |
| 35 | +void handleNotesChanged() |
| 36 | +{ |
| 37 | + if (midiNotes.empty()) |
| 38 | + { |
| 39 | + handleGateChanged(false); |
| 40 | + noTone(sAudioOutPin); |
| 41 | + } |
| 42 | + else |
| 43 | + { |
| 44 | + byte currentNote = 0; |
| 45 | + if (midiNotes.getTail(currentNote)) |
| 46 | + { |
| 47 | + tone(sAudioOutPin, sNotePitches[currentNote]); |
| 48 | + pulseGate(); // Retrigger envelopes. Remove for legato effect. |
| 49 | + } |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +// ----------------------------------------------------------------------------- |
| 54 | + |
| 55 | +void handleNoteOn(byte inChannel, byte inNote, byte inVelocity) |
| 56 | +{ |
| 57 | + midiNotes.add(MidiNote(inNote, inVelocity)); |
| 58 | + handleNotesChanged(); |
| 59 | +} |
| 60 | + |
| 61 | +void handleNoteOff(byte inChannel, byte inNote, byte inVelocity) |
| 62 | +{ |
| 63 | + midiNotes.remove(inNote); |
| 64 | + handleNotesChanged(); |
| 65 | +} |
| 66 | + |
| 67 | +// ----------------------------------------------------------------------------- |
| 68 | + |
| 69 | +void setup() |
| 70 | +{ |
| 71 | + pinMode(sGatePin, OUTPUT); |
| 72 | + pinMode(sAudioOutPin, OUTPUT); |
| 73 | + MIDI.setHandleNoteOn(handleNoteOn); |
| 74 | + MIDI.setHandleNoteOff(handleNoteOff); |
| 75 | + MIDI.begin(); |
| 76 | +} |
| 77 | + |
| 78 | +void loop() |
| 79 | +{ |
| 80 | + MIDI.read(); |
| 81 | +} |
0 commit comments