#include "MIDIUSB.h"

#define N_POTS 2

const uint8_t MIDICC = 0x0B;
const int potPin[] = {0, 1};
const uint8_t potCN[] = {0x07, 0x27};

const int toggleLPin = 9;
const int toggleRPin = 11;
const uint8_t toggleLCN = 0x50;
const uint8_t toggleRCN = 0x51;

uint8_t potValues[N_POTS];
uint8_t potValuePrev[] = {0, 0};

void setup() {
pinMode(toggleLPin,INPUT);
pinMode(toggleRPin,INPUT);
}

void loop() {
readPots();
sendMIDI();
sendToggle();
MidiUSB.flush();
}

void readPots() {
for (int i=0; i < N_POTS; i++) {
int val = analogRead(potPin[i]);
potValues[i] = (uint8_t) (map(val, 0, 1023, 0, 127));
}
}

void controlChange(byte channel, byte control, byte value) {
midiEventPacket_t event = {0x0B, 0xB0 | channel, control, value};
MidiUSB.sendMIDI(event);
}

void sendMIDI()
{
for (int i=0; i < N_POTS; i++) {
if (abs(potValuePrev[i] - potValues[i]) > 1)
{
potValuePrev[i] = potValues[i];
controlChange(0, potCN[i], potValues[i]);
}
}
}

void sendToggle() {
if (digitalRead(toggleLPin) == HIGH)
controlChange(0, toggleLCN, 1);
else if (digitalRead(toggleRPin) == HIGH)
controlChange(0, toggleRCN, 1);
}