#include <Arduino.h>
#include <esp32/rom/ets_sys.h>
#include <esp_timer.h>
const int switchPin = 34; // GPIO pin where the switch is connected
const int pulsePin = 18; // GPIO pin where the clock pulse output will be sent
volatile bool pulseEnabled = false; // Flag to track whether pulse generation is enabled
esp_timer_handle_t timer_handle; // Handle for the hardware timer
portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED; // Mutex for timer ISR access
void IRAM_ATTR timer_callback(void* arg) {
// Toggle the pulse pin state
digitalWrite(pulsePin, !digitalRead(pulsePin));
}
void setup() {
pinMode(switchPin, INPUT_PULLUP); // Enable internal pull-up resistor for the switch
pinMode(pulsePin, OUTPUT);
digitalWrite(pulsePin, LOW); // Ensure pulse pin starts low
// Configure hardware timer
const esp_timer_create_args_t timer_args = {
.callback = &timer_callback,
.name = "clock_timer"
};
ESP_ERROR_CHECK(esp_timer_create(&timer_args, &timer_handle));
}
void IRAM_ATTR switch_isr() {
portENTER_CRITICAL_ISR(&timerMux);
if (digitalRead(switchPin) == LOW) { // Switch pressed
if (!pulseEnabled) {
ESP_ERROR_CHECK(esp_timer_start_periodic(timer_handle, 1000000)); // Start timer, 1ms period
pulseEnabled = true;
}
} else { // Switch released
if (pulseEnabled) {
ESP_ERROR_CHECK(esp_timer_stop(timer_handle)); // Stop the timer
digitalWrite(pulsePin, LOW); // Ensure pulse pin is low
pulseEnabled = false;
}
}
portEXIT_CRITICAL_ISR(&timerMux);
}
void loop() {
attachInterrupt(digitalPinToInterrupt(switchPin), switch_isr, CHANGE);
delay(100); // Delay to avoid bouncing
}
not able to generate clock using hardware timer in esp32