const int buttonPins[8] = {12, A1, A2, A3, A4, A5, 2, 3}; // 8 nút nhấn
const int relayPins[8] = {4, 5, 6, 7, 8, 9, 11, 10}; // 8 relay/LED
bool relayState[8] = {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH};
bool lastButtonReading[8] = {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH};
bool debouncedState[8] = {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH};
unsigned long lastDebounceTime[8] = {0};
const unsigned long debounceDelay = 50; // ms
void setup() {
for (int i = 0; i < 8; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
pinMode(relayPins[i], OUTPUT);
digitalWrite(relayPins[i], relayState[i]);
}
Serial.begin(9600);
}
void loop() {
for (int i = 0; i < 8; i++) {
int reading = digitalRead(buttonPins[i]);
// nếu trạng thái khác trước thì reset timer
if (reading != lastButtonReading[i]) {
lastDebounceTime[i] = millis();
}
// chỉ chấp nhận khi ổn định > debounceDelay
if ((millis() - lastDebounceTime[i]) > debounceDelay) {
if (reading != debouncedState[i]) {
debouncedState[i] = reading;
// phát hiện nhấn (LOW, vì dùng INPUT_PULLUP)
if (debouncedState[i] == LOW) {
relayState[i] = !relayState[i];
digitalWrite(relayPins[i], relayState[i]);
Serial.print("Relay "); Serial.print(i+1);
Serial.print(" -> "); Serial.println(relayState[i] == LOW ? "ON" : "OFF");
}
}
}
lastButtonReading[i] = reading;
}
}