#include <Arduino.h>
const unsigned long DEBOUNCE_TIME = 20;
const int IO_COUNT = 5;
const int BTN_PINS[IO_COUNT] = {20, 8, 9, 10, 7};
const int LED_PINS[IO_COUNT] = {6, 5, 4, 3, 2};
bool ledState[IO_COUNT];
// function returns which button was pressed, or 0 if none
int checkButtons() {
static bool currState[IO_COUNT];
static bool lastState[IO_COUNT];
static unsigned long lastTime[IO_COUNT];
int btnPressed = 0;
for (int i = 0; i < IO_COUNT; i++) {
currState[i] = digitalRead(BTN_PINS[i]);
unsigned long now = millis();
if (currState[i] != lastState[i] && now - lastTime[i] >= DEBOUNCE_TIME) {
if (!currState[i]) {
btnPressed = i + 1;
Serial.print("Button ");
Serial.print(btnPressed);
Serial.println(" pressed");
} else {
//Serial.println("Button released!");
}
lastTime[i] = now;
lastState[i] = currState[i];
}
}
return btnPressed;
}
void setup() {
Serial.begin(115200);
// Set IO modes
for (int i = 0; i < IO_COUNT; i++) {
pinMode(BTN_PINS[i], INPUT_PULLUP);
pinMode(LED_PINS[i], OUTPUT);
//digitalWrite(LED_PINS[i], LOW);
}
Serial.println("ESP32-C3 Button Pad Ready!");
}
void loop() {
int btnNumber = checkButtons();
if (btnNumber) {
int index = btnNumber - 1;
ledState[index] = !ledState[index];
digitalWrite(LED_PINS[index], ledState[index]);
}
}
Loading
xiao-esp32-c3
xiao-esp32-c3