// 2209106083
// Syarifah Armilda Syahla
#include <Arduino.h>
#include "esp_timer.h"
#define LED_PIN 2
#define BTN 4
bool ledState = false;
bool timerRunning = true;
esp_timer_handle_t timer;
volatile bool buttonPressed = false;
volatile unsigned long lastInterruptTime = 0; // Waktu terakhir interrupt
const unsigned long debounceDelay = 200; // debounce 200 ms
void IRAM_ATTR onTimer(void* arg) {
ledState = !ledState;
digitalWrite(LED_PIN, ledState);
}
void IRAM_ATTR handleButtonInterrupt() {
unsigned long currentTime = millis();
if (currentTime - lastInterruptTime > debounceDelay) {
buttonPressed = true;
lastInterruptTime = currentTime;
}
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
pinMode(BTN, INPUT_PULLUP);
// Setup timer
esp_timer_create_args_t timer_args = {
.callback = &onTimer,
.arg = NULL,
.dispatch_method = ESP_TIMER_TASK,
.name = "periodic"
};
if (esp_timer_create(&timer_args, &timer) != ESP_OK) {
Serial.println("GAGAL: Membuat timer");
while (1);
}
if (esp_timer_start_periodic(timer, 1000000) != ESP_OK) {
Serial.println("GAGAL: Menjalankan timer");
while (1);
}
// Attach interrupt on falling edge (tombol ditekan)
attachInterrupt(digitalPinToInterrupt(BTN), handleButtonInterrupt, FALLING);
}
void loop() {
if (buttonPressed) {
buttonPressed = false; // Reset flag
if (timerRunning) {
esp_timer_stop(timer);
Serial.println("Timer dihentikan oleh tombol.");
} else {
esp_timer_start_periodic(timer, 1000000);
Serial.println("Timer dijalankan lagi oleh tombol.");
}
timerRunning = !timerRunning;
}
// Loop kosong, semua di-handle oleh interrupt dan flag
}
Loading
esp32-s3-devkitc-1
esp32-s3-devkitc-1