Cómo usar interrupciones en Arduino y ESP32
Apariencia
Introducción
Las interrupciones permiten que el microcontrolador reaccione inmediatamente a un evento externo (botón, sensor, señal) sin necesidad de consultarlo constantemente en el loop. Son esenciales para proyectos que requieren respuesta inmediata.
Conceptos básicos
- ISR (Interrupt Service Routine): Función que se ejecuta cuando ocurre el evento
- Pin interrupt: Se dispara cuando cambia el estado de un pin digital
- Timer interrupt: Se dispara cada cierto tiempo con precisión
Interrupciones de pin en Arduino
volatile bool botonPresionado = false;
void IRAM_ATTR onBoton() {
botonPresionado = true;
}
void setup() {
pinMode(2, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(2), onBoton, FALLING);
}
void loop() {
if (botonPresionado) {
Serial.println("Botón presionado!");
botonPresionado = false;
}
}
El modificador volatile es obligatorio para variables compartidas entre el ISR y el loop.
IRAM_ATTR en ESP32
En el ESP32, las ISRs deben declararse con el atributo IRAM_ATTR para que se carguen en RAM y ejecuten rápidamente.
Reglas de las ISRs
- Mantenerlas lo más cortas posible
- No usar delay() dentro de una ISR
- No llamar funciones que usen Serial, I2C o SPI dentro de una ISR
- Usar variables volatile para comunicación ISR ↔ loop
Interrupciones por timer
El ESP32 tiene 4 timers hardware con alta precisión:
hw_timer_t *timer = timerBegin(0, 80, true); timerAttachInterrupt(timer, &onTimer, true); timerAlarmWrite(timer, 1000000, true); // 1 segundo timerAlarmEnable(timer);