Im trying to use the millis() function as a replacement for the delay() function in order to debounce a mechanical button. This is for an electric drum kit I am building. Im using a teensy Arduino to send MIDI signals from the drum pads to an external music program. The mechanical button needs to be responsible for cycling through five different states which change the MIDI signal sent from each pad, thus changing the sound, as well as lighting up one of five LEDs on my drum pad so I know which state i'm in. However I cant use delay() to debounce the button because that effects the efficiency of the drum pads, with some hits not being registered, latency etc.
Im trying to debug the code by just getting the LEDs to light up correctly when I press the button. This was the original code I wrote with the delay() function. This worked perfectly to debounce the button, but messed with my drum pads:
int but = 12;
int led0 = 7;
int led1 = 8;
int led2 = 9;
int led3 = 10;
int led4 = 11;
int ledCase = 0;
int butState = 0;
int oldButState = 0;
void setup() {
pinMode(led0, OUTPUT);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(but, INPUT_PULLUP);
}
void loop() {
oldButState = digitalRead(but);
delay(10);
butState = digitalRead(but);
if (butState != oldButState && butState == LOW) {
ledCase += 1;
oldButState = butState;
}
if (ledCase > 4) {
ledCase = 0;
}
Serial.println(ledCase);
switch (ledCase) {
case 0:
digitalWrite(led0, HIGH);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
break;
case 1:
digitalWrite(led0, LOW);
digitalWrite(led1, HIGH);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
break;
case 2:
digitalWrite(led0, LOW);
digitalWrite(led1, LOW);
digitalWrite(led2, HIGH);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
break;
case 3:
digitalWrite(led0, LOW);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, HIGH);
digitalWrite(led4, LOW);
break;
case 4:
digitalWrite(led0, LOW);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, HIGH);
break;
}
}
This is what I tried to use to replace the delay() function, but that hasn't worked. Note I added these lines in and removed the delay section:
unsigned long onTime;
unsigned long delayTime;
void setup() {
delayTime = millis() + 10;
}
void loop() {
oldButState = digitalRead(but);
onTime = millis();
if (onTime >= delayTime) {
butState = digitalRead(but);
delayTime = millis() + 10;
}
}
Any pointers as to how I can make the millis() function work to debounce this would be would be very much appreciated, thank you :)