#define LED_PIN 19
#define BOTON_PIN 5
volatile bool botonPulsa = 0;
volatile bool botonSuelta = 0;
volatile bool timer_activated = false;
volatile bool parpadeo_activated = false;
volatile bool change = false;
volatile int interrupt_counter = 0;
volatile int estado = 1;
hw_timer_t *timer = NULL; // Puntero al timer del hardware.
// Lo he llamado "timer" por simplificar, pero podría haberlo llamado como quisiera. P.ej.:
// hw_timer_t *temporizador_0 = NULL;
hw_timer_t *tparpadeo = NULL;
int timer_frequency = 1000000; // Frecuencia del timer en Hz (como de rápido cuenta el timer)
int timer_parpadeo = 1000000;
void IRAM_ATTR boton()
{
if (digitalRead(BOTON_PIN) == LOW)
{
timerStart(timer); // Habilitar timer
botonPulsa = true;
interrupt_counter = 0;
change = 1;
}
else
{
botonSuelta = true;
timerStop(timer);
}
}
// Callback ISR interrupción del timer
void IRAM_ATTR timerInterrupt()
{
interrupt_counter++; // Se incrementa el contador de interrupciones del timer
timer_activated = true; // Se indica que ha habido una interrupción del timer
}
// Callback ISR parpadeo LED
void IRAM_ATTR parpadeo()
{
parpadeo_activated = !parpadeo_activated;
}
void setup()
{
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
pinMode(BOTON_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(BOTON_PIN), &boton, CHANGE);
estado = 1;
timer = timerBegin(timer_frequency); // Inicializar el timer que contará a la frecuencia timer_frequency
timerAttachInterrupt(timer, &timerInterrupt); // Adjuntar la función de manejo de interrupción
// Establecer la alarma del timer temporizador (parámetro 1) para que llame a timerInterrupt cada segundo (parámetro 2 - valor en microsegundos)
// Poner a true que se repita la alarma (parámetro 3) y lo haga de forma indefinida (parámetro 4 - 0=indefinido)
timerAlarm(timer, 1000000, true, 0);
timerStop(timer);
tparpadeo = timerBegin(timer_parpadeo);
timerAttachInterrupt(tparpadeo, &parpadeo);
timerAlarm(tparpadeo, 500000, true, 0);
Serial.println("estoy en el estado 1");
}
void loop()
{
switch (estado)
{
case 1:
digitalWrite(LED_PIN, LOW);
timer_activated = false;
if (botonPulsa && botonSuelta && interrupt_counter < 1)
{
estado = 2;
botonSuelta = false;
botonPulsa = false;
Serial.println("estoy en el estado 2");
}
else if (botonPulsa && botonSuelta && interrupt_counter >= 1)
{
estado = 3;
botonSuelta = false;
botonPulsa = false;
Serial.println("estoy en el estado 3");
}
break;
case 2:
if (change)
{
digitalWrite(LED_PIN, !digitalRead(LED_PIN));
change = 0;
}
if (botonPulsa && botonSuelta)
{
estado = 1;
botonPulsa = false;
botonSuelta = false;
Serial.println("estoy en el estado 1");
}
break;
case 3:
digitalWrite(LED_PIN, parpadeo_activated);
if (botonPulsa && botonSuelta)
{
estado = 1;
botonPulsa = false;
botonSuelta = false;
Serial.println("estoy en el estado 1");
}
break;
}
delay(10); // this speeds up the simulation
}