Code:
#include <Bounce.h>
// the MIDI channel number to send messages
const int channel = 1;
Bounce button0 = Bounce(0, 5);
Bounce button1 = Bounce(1, 5);
Bounce button2 = Bounce(2, 5);
byte current_value_1;
byte previous_value_1;
byte current_value_2;
byte previous_value_2;
byte current_value_3;
byte previous_value_3;
void setup() {
analogReadResolution(7); // set the analog read resolution to 7 bits (a range of 0 - 127)
analogReadAveraging(32); // average the analog value by averaging 16 readings
pinMode(0, INPUT_PULLUP);
pinMode(1, INPUT_PULLUP);
pinMode(2, INPUT_PULLUP);
}
void loop() {
button0.update();
button1.update();
button2.update();
current_value_1 = analogRead(A0);
current_value_2 = analogRead(A1);
current_value_3 = analogRead(A2);
if (button0.fallingEdge()) {
usbMIDI.sendNoteOn(60, 99, channel); // 60 = C4
}
if (button1.fallingEdge()) {
usbMIDI.sendNoteOn(61, 99, channel); // 61 = C#4
}
if (button2.fallingEdge()) {
usbMIDI.sendNoteOn(62, 99, channel); // 61 = C#4
}
if (button0.risingEdge()) {
usbMIDI.sendNoteOff(60, 0, channel); // 60 = C4
}
if (button1.risingEdge()) {
usbMIDI.sendNoteOff(61, 0, channel); // 61 = C#4
}
if (button2.risingEdge()) {
usbMIDI.sendNoteOff(62, 0, channel); // 62 = D4
}
if(current_value_1 != previous_value_1) {
previous_value_1 = current_value_1;
usbMIDI.sendControlChange(1, current_value_1, 1); // send continuous controller message
}
if(current_value_2 != previous_value_2) {
previous_value_2 = current_value_2;
usbMIDI.sendControlChange(2, current_value_1, 1); // send continuous controller message
}
if(current_value_3 != previous_value_3) {
previous_value_3 = current_value_3;
usbMIDI.sendControlChange(3, current_value_1, 1); // send continuous controller message
}
}
warning -
untested... not even compiled.... might have a typo or minor error yet.
This extends the code to cover pins from A0 to A2 and the CC numbers from 1 to 3. But you don't need to use those PINs or (especially) those CC numbers. You can put any value between 0 and 127 in the first value of the .sendControlChange() call.
(It's arguably clearer to put A0 rather than 0 as some think that will point a digital pin 0 even though it knows to use the analog pin sequence instead)
I've not tried to manage analog signals with just analogReadAveraging() so I don't know how good the output will be but it should work fairly well.
You will still get MIDI junk if you try this code with A0, A1 or A2 not connected to your circuit.