// Connect the button to ESP32-C3
// Write the code to read the status of the button
// and display the status on monitor when press and release the button
// Bonus: connect to the LED
// use interrupt + Debouncing
// // No Interrupt
// #define BUTTON_PIN 9
// #define LED_PIN 19
// int led_state = LOW;
// void setup() {
// Serial.begin(9600);
// pinMode(BUTTON_PIN, INPUT_PULLUP);
// pinMode(LED_PIN, OUTPUT);
// }
// void loop() {
// int button_state = digitalRead(BUTTON_PIN);
// if (button_state == LOW) {
// Serial.println("press");
// led_state = !led_state; // toggle state of LED
// digitalWrite(LED_PIN, led_state);
// delay(200);
// }
// }
// // Development
#define BUTTON_PIN 9
#define LED_PIN 19
int led_state = LOW;
int button_state = LOW; // có thể dùng bool chỉ có hai giá trị
void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
if (digitalRead(BUTTON_PIN) != button_state){
button_state = digitalRead(BUTTON_PIN);
if (button_state == LOW) {
Serial.println("press");
led_state = !led_state; // toggle state of LED
digitalWrite(LED_PIN, led_state);
}
}
delay(10); // delay nhỏ để quay lại vòng lặp nhanh và tránh bouncing
}
// // Interrupt + Debouncing (Chưa chuẩn lắm)
// #define BUTTON_PIN 9
// #define LED_PIN 19
// int led_state = LOW;
// volatile bool button_pressed = false; // Biến để theo dõi trạng thái nút bấm (volatile do dùng trong ISR)
// int number = 0; // Biến kiểm tra bouncing
// unsigned long button_time = 0;
// unsigned long last_button_time = 0;
// void IRAM_ATTR isr_button() { // Hàm ISR (Interrupt Service Routine) IRAM_ATTR để lưu trong RAM
// button_time = millis();
// if (button_time - last_button_time > 250){
// number++;
// led_state = !led_state;
// button_pressed = true;
// last_button_time = button_time;
// }
// }
// void setup() {
// Serial.begin(9600);
// pinMode(BUTTON_PIN, INPUT_PULLUP);
// pinMode(LED_PIN, OUTPUT);
// attachInterrupt(BUTTON_PIN, isr_button, FALLING);
// }
// void loop() {
// if(button_pressed){
// Serial.println("Button is pressed " + String(number) + " times");
// // Serial.printf("Button is pressed %u times \n", number);
// digitalWrite(LED_PIN, led_state);
// button_pressed = false;
// }
// }