The new button code is different from the old button code in that it lets the MIDI note play during the whole time the button is being pressed. The note being played stops right when the button is unpressed. The new code also lets multiple MIDI notes be played at the same time.
int ledPin = 11;
int buttonPin1 = 33;
bool lastButton1State = LOW;
bool button1State = LOW;
int buttonPin2 = 34;
bool lastButton2State = LOW;
bool button2State = LOW;
int buttonPin3 = 35;
bool lastButton3State = LOW;
bool button3State = LOW;
int buttonPin4 = 36;
bool lastButton4State = LOW;
bool button4State = LOW;
int potValue = 0;
int lastPotValue = 0;
int mappedPotVal = 0;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin1, INPUT);
pinMode(buttonPin2, INPUT);
pinMode(buttonPin3, INPUT);
pinMode(buttonPin4, INPUT);
Serial.begin(9600);
}
void loop() {
checkButton1();
checkButton2();
checkButton3();
checkButton4();
lastPotValue = mappedPotVal;
potValue = analogRead(A18);
mappedPotVal = map(potValue, 0, 1023, 10, 20);
if (mappedPotVal != lastPotValue) {
Serial.println(mappedPotVal);
}
}
void checkButton1() {
lastButton1State = button1State;
button1State = digitalRead(buttonPin1);
if (lastButton1State == LOW and button1State == HIGH) {
usbMIDI.sendNoteOn(60, 127, 1);
digitalWrite(ledPin, HIGH);
delay(5);
} else if (lastButton1State == HIGH and button1State == LOW) {
usbMIDI.sendNoteOff(60, 0, 1);
digitalWrite(ledPin, LOW);
delay(5);
}
}
void checkButton2() {
lastButton2State = button2State;
button2State = digitalRead(buttonPin2);
if (lastButton2State == LOW and button2State == HIGH) {
usbMIDI.sendNoteOn(64, 127, 1);
digitalWrite(ledPin, HIGH);
delay(5);
} else if (lastButton2State == HIGH and button2State == LOW) {
usbMIDI.sendNoteOff(64, 0, 1);
digitalWrite(ledPin, LOW);
delay(5);
}
}
void checkButton3() {
lastButton3State = button3State;
button3State = digitalRead(buttonPin3);
if (lastButton3State == LOW and button3State == HIGH) {
usbMIDI.sendNoteOn(67, 127, 1);
digitalWrite(ledPin, HIGH);
delay(5);
} else if (lastButton3State == HIGH and button3State == LOW) {
usbMIDI.sendNoteOff(67, 0, 1);
digitalWrite(ledPin, LOW);
delay(5);
}
}
void checkButton4() {
lastButton4State = button4State;
button4State = digitalRead(buttonPin4);
if (lastButton4State == LOW and button4State == HIGH) {
usbMIDI.sendNoteOn(71, 127, 1);
digitalWrite(ledPin, HIGH);
delay(5);
} else if (lastButton4State == HIGH and button4State == LOW) {
usbMIDI.sendNoteOff(71, 0, 1);
digitalWrite(ledPin, LOW);
delay(5);
}
}