jueves, 11 de abril de 2024

Pedalera MIDI USB con Arduino e Impresa en 3D


Código Fuente:

#include "MIDIUSB.h"

const int N_BUTTONS = 18; //  total numbers of buttons
const int BUTTON_ARDUINO_PIN[18] = {2, 3, 4, 5, 6, 7, 14, 15, 18, 19, 20, 21};  // pins of each button connected straight to the Arduino
const int BUTTON_NOTES[18] = {64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75};

int buttonCState[N_BUTTONS] = {};  // stores the button current value
int buttonPState[N_BUTTONS] = {};  // stores the button previous value

// debounce
unsigned long lastDebounceTime[N_BUTTONS] = { 0 };  // the last time the output pin was toggled
unsigned long debounceDelay = 50;                   // the debounce time; increase if the output flickers

//---------------------MIDI----------------------
byte midiCh = 0;  // MIDI channel to be used - start with 1 for MIDI.h lib or 0 for MIDIUSB lib

//---------------------SETUP----------------------
void setup() {
  for (int i = 0; i < N_BUTTONS; i++) {
    pinMode(BUTTON_ARDUINO_PIN[i], INPUT_PULLUP);
  }
}

//---------------------LOOP----------------------
void loop() {
  buttons();
}

//---------------------BUTTONS----------------------
void buttons() {

  for (int i = 0; i < N_BUTTONS; i++) {

    buttonCState[i] = digitalRead(BUTTON_ARDUINO_PIN[i]);  // read pins from arduino

    if ((millis() - lastDebounceTime[i]) > debounceDelay) {

      if (buttonPState[i] != buttonCState[i]) {
        lastDebounceTime[i] = millis();

        if (buttonCState[i] == LOW) {
          controlChange(midiCh, BUTTON_NOTES[i], 127);  // channel, note, velocity
          MidiUSB.flush();
        } 
        else {
          controlChange(midiCh, BUTTON_NOTES[i], 0);  // channel, note, velocity
          MidiUSB.flush();
        }
        buttonPState[i] = buttonCState[i];
      }
    }
  }
}

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