It is driving me crazy and I can't for the life of me figure out why it's acting this way.
My code is working properly, when I press the button it spits out alternating low/high into the serial monitor with a proper debounce delay. But adding the debounce delay always seems to kill my controlChange function.
For testing purposes, I copied the controlChange function, and repeated it several times in each if statement. It actually worked better that way, I have no clue why. It seems to need to be spammed for anything to read it properly.
#include <frequencyToNote.h>
#include <MIDIUSB.h>
#include <pitchToFrequency.h>
#include <pitchToNote.h>
// First parameter is the event type (0x0B = control change).
// Second parameter is the event type, combined with the channel.
// Third parameter is the control number number (0-119).
// Fourth parameter is the control value (0-127).
// controlChange(0, 10, 65); // Set the value of controller 10 on channel 0 to 65
void controlChange(byte channel, byte control, byte value) {
midiEventPacket_t event = {0x0B, 0xB0 | channel, control, value};
MidiUSB.sendMIDI(event);
}
int lastPotValue;
int lastButtonState=0;
unsigned long lastDebounce = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(A0, INPUT);
pinMode(7, INPUT_PULLUP);
}
void loop() {
unsigned long currentTime = millis();
int potValue = analogRead(A0);
int buttonValue = digitalRead(7);
if (lastPotValue != potValue){
controlChange(0, 50, potValue/7.90);
lastPotValue = potValue;
lastDebounce = currentTime;
}
if (buttonValue == LOW && currentTime - lastDebounce > 250){
if (lastButtonState == 0){
controlChange(1,51,127);
Serial.println(lastButtonState);
lastButtonState = 1;
lastDebounce = currentTime;
}
else if (lastButtonState == 1){
controlChange(1,51,127);
Serial.println(lastButtonState);
lastButtonState = 0;
lastDebounce = currentTime;
}
}
}