/*
Author: Juan M. Gandarias
Date: 08/11/2024
Description: ejemplo_timer_builder-3
*/
// GPIO
#define LED_PIN 26 // LED connected to GPIO26
#define BUTTON_PIN 27 // Button connected to GPIO27
bool button_state = false; // Variable to store the button state
const uint8_t NUM_BLINKS = 10; // Constant for number of blinks. Note: one blink is off+on. 10 blinks => LED toggles 5 times
hw_timer_t *temporizador = NULL; // Pointer to the hardware timer.
// I named it "temporizador" for simplicity, but it can be any valid identifier. e.g.: hw_timer_t *my_timer_0 = NULL;
int timer_frequency = 1000000; // Timer frequency in Hz (how fast the timer counts)
volatile uint8_t interrupt_counter = 0; // Volatile variable to count how many times the interrupt occurs
volatile bool timer_activated = false; // Volatile flag that indicates the timer interrupt occurred
// ISR callback for button press
void IRAM_ATTR buttonPressed()
{
digitalWrite(LED_PIN, LOW); // Turn off the LED
interrupt_counter = 0; // Reset the timer counter
timerStart(temporizador); // Start/enable the timer
}
// ISR callback for timer interrupt
void IRAM_ATTR timerInterrupt()
{
interrupt_counter++; // Increment the timer interrupt counter
timer_activated = true; // Indicate that a timer interrupt has occurred
}
// setup function
void setup()
{
Serial.begin(115200); // Initialize serial port
pinMode(LED_PIN, OUTPUT); // Configure LED as output
pinMode(BUTTON_PIN, INPUT_PULLUP); // Configure button as input with internal pull-up
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), buttonPressed, RISING); // Configure button press interrupt
temporizador = timerBegin(timer_frequency); // Initialize the timer that will count at timer_frequency
timerAttachInterrupt(temporizador, &timerInterrupt); // Attach the interrupt handler
// Set the timer alarm (param 1) so it calls timerInterrupt every half second (param 2 - value in microseconds)
// Set true to repeat the alarm (param 3) and 0 to run indefinitely (param 4 - 0 = indefinite)
timerAlarm(temporizador, 250000, true, 0);
timerStop(temporizador); // The timer will start when the button is pressed
}
// loop function
void loop()
{
if (timer_activated) // If a timer interrupt occurred
{
if (interrupt_counter < NUM_BLINKS) // If the interrupt counter is less than the number of blinks
{
digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Toggle the LED state
}
else if (interrupt_counter == NUM_BLINKS) // If the last timer interrupt has occurred
{
digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Toggle the LED state
interrupt_counter = 0; // Reset the interrupt counter
timerStop(temporizador); // Stop the timer counting
}
timer_activated = false; // Clear the flag indicating the timer-related task has been handled
}
// Loop every 10ms => 100Hz
delay(10);
}