DIY 6 button MIDI foot controller that sends MIDI Program Change + LCD

I am using an Arduino Micro and would send over USB. So far, this the simpliest starting code that worked with the buttons and LEDS.

In the words of the old joke, if I was going there I wouldn't start from here.

I would in fact start from here.

// Simple MIDI output of program message through USB
// By Grumpy_Mike August 2019

#include "MIDIUSB.h"

// to add more then simply add more pins tothe list
byte ledPin[] = {A0,A1};  // list of led pins
byte buttonPin[] = {8,9};    // list of buttons pins
byte buttonState[] = {0,0};  // start off with off
byte lastButtonState[] = {0,0};  // start off with off
byte programChanges[] = {1,2};  // list of program change messages to send

byte channel = 0; // for musicians this is channel 1

void setup() {
  for(int i =0;i< sizeof(buttonPin); i++){ // initialise input pins  
    pinMode(buttonPin[i], INPUT_PULLUP); // wire all buttons between input and ground
    pinMode(ledPin[i], OUTPUT);
  }
}
 
void loop() {
  for(int i =0;i< sizeof(buttonPin); i++){  // look at all pins
  buttonState[i] = digitalRead(buttonPin[i]); 
  if(buttonState[i] == LOW && lastButtonState[i] == HIGH) { // remember how you wired your buttons LOW = pressed
    ledOffAll();
    digitalWrite(ledPin[i],HIGH);
    programChange(channel, programChanges[i]); // send the program change message
    MidiUSB.flush();
   }
   lastButtonState[i] = buttonState[i];
  }
}

void ledOffAll() {
    for(int i = 0 ; i< sizeof(ledPin); i++){
     digitalWrite(ledPin[i], LOW); 
    }
}

void programChange(byte channel, byte patch) {
  midiEventPacket_t event = {0x0C, 0xC0 | channel, patch};
  MidiUSB.sendMIDI(event);
}

As a total noob, this would be my preferred approach - the lines of the codes are presented in a beginner friendly chunks.

I am sure you would actually want to learn something rather than have code that you repeat over and over ad nauseam.

When you find yourself repeating code over and over you need to learn about arrays. In this code there are arrays that hold the lists of the pins to use and what program change messages to send. To expand this to more pins / LEDs / Program messages simply add the extra numbers to the list. Make sure there is always an equal number of numbers in each list so you have a match between push button, LED to write and program change message to send.

There is also a state change detection so that you don't continuously keep sending program change messages while a button is pressed.

Note this code is written as if the buttons are wired up correctly, that is with no external resistors and the button wired between input and ground.

1 Like