#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
// --- Pines ---
#define LED_PIN_TMR3 5 // LED del Timer 3
#define LED_PIN_TMR2 12 // LED del Timer 2 (Ejemplo 4)
#define TFT_CS 15
#define TFT_RST 4
#define TFT_DC 2
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);
// --- Punteros para los 4 Timers ---
hw_timer_t *timer0_tft = NULL;
hw_timer_t *timer1_ej3 = NULL;
hw_timer_t *timer2_ej4 = NULL; // Renombrado para Ejemplo 4
hw_timer_t *timer3_led = NULL;
// --- Variables Volátiles (para ISRs) ---
volatile int32_t tftSecondCounter = 0; // Tarea 1
volatile bool printEj3Flag = false; // Tarea 2
volatile bool ledStateTmr2 = false; // Tarea 3 (Ejemplo 4)
volatile bool ledStateTmr3 = false; // Tarea 4
// --- Variables de seguimiento ---
int32_t lastTftSecond = -1;
// ISR para Timer 0 (1 segundo)
void IRAM_ATTR onTimer0_TFT() {
tftSecondCounter++;
}
// ISR para Timer 1 (0.2 segundos)
void IRAM_ATTR onTimer1_Ej3() {
printEj3Flag = true;
}
// ISR para Timer 2 (5 segundos - Ejemplo 4)
void IRAM_ATTR onTimer2_Ej4() {
ledStateTmr2 = !ledStateTmr2;
digitalWrite(LED_PIN_TMR2, ledStateTmr2);
}
// ISR para Timer 3 (3.5 segundos)
void IRAM_ATTR onTimer3_LED() {
ledStateTmr3 = !ledStateTmr3;
digitalWrite(LED_PIN_TMR3, ledStateTmr3);
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN_TMR3, OUTPUT);
digitalWrite(LED_PIN_TMR3, LOW);
pinMode(LED_PIN_TMR2, OUTPUT);
digitalWrite(LED_PIN_TMR2, LOW);
tft.begin();
tft.setRotation(1);
tft.fillScreen(ILI9341_BLACK);
tft.setTextColor(ILI9341_GREEN);
tft.setTextSize(2);
tft.setCursor(10, 10);
tft.println("Demo 4 Timers (Con Ej. 4)");
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(3);
// --- Configurar los 4 Timers en orden ---
// 1. Timer 0 (TFT @ 1s)
timer0_tft = timerBegin(1000000);
timerAttachInterrupt(timer0_tft, &onTimer0_TFT);
timerAlarm(timer0_tft, 1000000, true, 0);
// 2. Timer 1 (Ejemplo 3 @ 0.2s)
timer1_ej3 = timerBegin(5000000);
timerAttachInterrupt(timer1_ej3, &onTimer1_Ej3);
timerAlarm(timer1_ej3, 1000000, true, 0);
// 3. Timer 2 (Ejemplo 4 @ 5s)
// Frecuencia: 2MHz (equiv. Prescaler 40)
timer2_ej4 = timerBegin(2000000);
timerAttachInterrupt(timer2_ej4, &onTimer2_Ej4);
// Alarma: 10,000,000 ticks = 5s * 2,000,000 Hz
timerAlarm(timer2_ej4, 10000000, true, 0);
// 4. Timer 3 (LED @ 3.5s)
timer3_led = timerBegin(1000000);
timerAttachInterrupt(timer3_led, &onTimer3_LED);
timerAlarm(timer3_led, 3500000, true, 0);
}
void loop() {
// Tarea 1: Actualizar TFT (basado en Timer 0)
if (tftSecondCounter != lastTftSecond) {
lastTftSecond = tftSecondCounter;
tft.fillRect(50, 80, 150, 40, ILI9341_BLACK);
tft.setCursor(50, 80);
tft.print("Seg: ");
tft.print(tftSecondCounter);
}
// Tarea 2: Imprimir "Ejemplo 3" (basado en Timer 1)
if (printEj3Flag) {
printEj3Flag = false;
Serial.println("Interrupción TMR1 cada 0.2 s");
}
// Tareas 3 y 4 (LEDs) se manejan 100% en sus interrupciones
}