Hi,
I have an ESP32 with 4 buttons control an assigned LED to each but it looks like only 2 LEDs are blinking while the rest cannot be toggled. Is there an issue with my code that I could have overlooked?
const int buttonPins[] = {33, 32, 35, 34}; // {33, 32, 35, 34}
const int ledPins[] = {13, 12, 14, 27}; // {13, 12, 14, 27}
const int numButtons = 4; // calculate the number of buttons
const int numLeds = 4; // calculate the number of LEDs
int ledStates[] = {LOW, LOW, LOW, LOW}; // an array to store the state of each LED
unsigned long lastPressTime[numButtons] = {0}; // array to store the last press time for each button
unsigned long lastDebounceTime[numButtons] = {0}; // array to store the last debounce time for each button
int lastButtonState[numButtons] = {LOW}; // array to store the last button state for each button
int buttonState[numButtons] = {LOW}; // array to store the last button state for each button
const unsigned long pressInterval = 100; // Interval for button press in milliseconds
const unsigned long debounceDelay = 50; // Debounce time in milliseconds
void setup() {
Serial.begin(9600);
for (int i = 0; i < numButtons; i++) {
pinMode(buttonPins[i], INPUT_PULLUP); // Using internal pull-up resistor for each button
pinMode(ledPins[i], OUTPUT);
digitalWrite(ledPins[i], ledStates[i]); // Initialize LED states
}
}
void loop() {
for (int i = 0; i < numButtons; i++) {
int reading = digitalRead(buttonPins[i]);
if (reading != lastButtonState[i]) {
lastDebounceTime[i] = millis(); // Reset the debounce timer
}
if ((millis() - lastDebounceTime[i]) > debounceDelay) {
// If the button state has been stable for the debounce delay
if (reading != buttonState[i]) {
buttonState[i] = reading; // Update the button state
Serial.print(i);Serial.print(" ");Serial.println(buttonState[i]);
// If the button is pressed
if (buttonState[i] == HIGH) {
// Check if press interval has passed since last press
if (millis() - lastPressTime[i] >= pressInterval) {
ledStates[i] = !ledStates[i]; // Toggle LED state
digitalWrite(ledPins[i], ledStates[i]); // Update LED state
lastPressTime[i] = millis();// Update last press time
}
}
}
}
lastButtonState[i] = reading;
}
}
and something like that below: