int ledPin = 13;
int buttonPin = 2;
volatile bool ledState = false; // Trạng thái hiện tại của LED
volatile unsigned long lastDebounceTime = 0; // Thời gian cuối cùng ghi nhận nút
unsigned long debounceDelay = 50; // Thời gian chờ giữa các lần nhấn nút
volatile int buttonPressCount = 0; // Số lần nhấn nút
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP); // Sử dụng điện trở kéo lên cho nút
attachInterrupt(digitalPinToInterrupt(buttonPin), buttonPressed, FALLING); // Gắn hàm ngắt vào chân nút
}
void loop() {
// Không cần thêm code trong loop vì điều khiển LED được thực hiện thông qua ngắt
}
void buttonPressed() {
unsigned long currentMillis = millis();
// Kiểm tra xem có đủ thời gian debounce chưa
if (currentMillis - lastDebounceTime >= debounceDelay) {
// Cập nhật thời gian debounce
lastDebounceTime = currentMillis;
// Tăng biến đếm số lần nhấn nút
buttonPressCount++;
// Đảo trạng thái của LED
ledState = !ledState;
digitalWrite(ledPin, ledState);
// Nếu đã nhấn nút 2 lần, reset biến đếm
if (buttonPressCount == 2) {
buttonPressCount = 0;
}
}
}