Module 5Módulo 5

Interrupts & PowerInterrupciones y Energía

Mastering the art of doing nothing. How to sleep efficiently and wake up instantly. Dominando el arte de no hacer nada. Cómo dormir eficientemente y despertar al instante.

Santi Scagliusi, PhD

Low Power Modes (LPM)Modos de Bajo Consumo (LPM)

The MSP430 is a sleep champion. Configure the 4 bits in the Status Register (SR) to shut down clocks and save battery. El MSP430 es un campeón del bajo consumo. Configura los 4 bits en el Registro de Estado (SR) para apagar relojes y ahorrar batería.

SCG1
0
SCG0
0
OSCOFF
0
CPUOFF
0
memory
CPU
speed
MCLK
hub
SMCLK
schedule
ACLK
Select a mode to see effects...Selecciona un modo para ver los efectos...

The Evolution of AttentionLa Evolución de la Atención

refresh

1. Polling

The CPU constantly asks: "Are you ready? Are you ready?" La CPU pregunta constantemente: "¿Estás listo? ¿Estás listo?"

  • × Wastes CPU cyclesDesperdicia ciclos de CPU
  • × Slow response timeTiempo de respuesta lento
  • check Simple hardwareHardware sencillo
link

2. Daisy Chain

Hardware passes the signal down the line. First come, first served. El hardware pasa la señal en cadena. El primero en llegar, el primero en ser atendido.

  • check Better efficiencyMayor eficiencia
  • ~ Medium complexityComplejidad media
  • Priority based on positionPrioridad basada en posición
MSP430
call_split

3. Vectored3. Vectorizado

Direct jump to the handler function. Fastest response. Salto directo a la función manejadora. La respuesta más rápida.

  • check Instant response (6 cycles)Respuesta instantánea (6 ciclos)
  • check No software overheadSin sobrecarga de software
  • check Priorities fixed by IndexPrioridades fijadas por índice

The Interrupt LifecycleEl Ciclo de Vida de una Interrupción

1

The Event & The FlagEl Evento y el Flag

A peripheral (Timer, GPIO) sets its flag IFG = 1. The CPU checks if IE = 1 and global GIE = 1. Un periférico (Timer, GPIO) activa su flag IFG = 1. La CPU comprueba si IE = 1 y el global GIE = 1.

2

Context Save (Hardware Magic)Guardado de Contexto (Magia del Hardware)

The CPU automatically does this (taking ~6 cycles):La CPU hace esto automáticamente (en ~6 ciclos):

  • Check current instruction matches interrupt (finishes instr).Comprueba la instrucción actual y la finaliza.
  • PUSH PC (Save return address).PUSH PC (Guarda dirección de retorno).
  • PUSH SR (Save status/mode).PUSH SR (Guarda estado/modo).
  • Clear SR (Disable GIE, Wake up CPU).Limpia SR (Desactiva GIE, despierta la CPU).
3

Vector Fetch & ISRLectura del Vector e ISR

The CPU reads the address from the Vector Table (0xFF80 - 0xFFFF) and jumps to your ISR code. La CPU lee la dirección de la Tabla de Vectores (0xFF80 - 0xFFFF) y salta a tu código ISR.

4

RETI (Return from Interrupt)RETI (Retorno de Interrupción)

Special instruction. It POPs SR and PC back from the stack. The CPU returns to exactly where it was (and importantly, returns to sleep if it was sleeping!). Instrucción especial. Hace POP de SR y PC desde la pila. La CPU regresa exactamente donde estaba (¡y vuelve a dormir si estaba en reposo!).

Complete Example: Toggle LED on Button PressEjemplo Completo: Alternar LED con Pulsador
Setup (in main)Configuración (en main)
BIS.B #BIT0, &P1DIR    ; P1.0 = output (LED)
BIC.B #BIT1, &P1DIR    ; P1.1 = input (BTN)
BIS.B #BIT1, &P1REN    ; Enable pull resistor
BIS.B #BIT1, &P1OUT    ; Pull-up
BIC.B #BIT1, &P1IFG    ; Clear flag first!
BIS.B #BIT1, &P1IE     ; Enable interrupt
BIS.W #GIE+LPM3, SR   ; Sleep + enable GIE
ISR (Port 1 handler)ISR (Manejador del Puerto 1)
P1_ISR:
XOR.B #BIT0, &P1OUT    ; Toggle LED
BIC.B #BIT1, &P1IFG    ; Clear flag
RETI                    ; Return & sleep

; --- Vector Table ---
.intvec PORT1_VECTOR, P1_ISR

Handling Multiple Sources (P1IV)Manejo de Múltiples Fuentes (P1IV)

Simulating Port 1 Interrupts. Click pins to set flags.
Hardware Priority: P1.0 (Highest) > P1.7.
Simulando interrupciones del Puerto 1. Haz clic en los pines para activar flags.
Prioridad hardware: P1.0 (Mayor) > P1.7.

Port 1 Inputs (Click to trigger)Entradas del Puerto 1 (Clic para activar)
P1.0
P1.1
P1.2
P1.3
P1.4
P1.5
P1.6
P1.7

Hardware Logic (P1IV)Lógica Hardware (P1IV)

ReadOnly RegisterRegistro de Solo Lectura
&P1IV = 0x00

*Automatically clears its flag when read! *¡Limpia automáticamente su flag al leerlo!

ISR CodeCódigo ISR
Waiting...Esperando...
vs Polling: Without P1IV, you'd have to write BIT.B #BIT0, &P1IFG eight times! vs Polling: Sin P1IV, ¡tendrías que escribir BIT.B #BIT0, &P1IFG ocho veces!

The Golden Rules of ISRsLas Reglas de Oro de las ISR

speed

Keep it ShortSé Breve

Do the minimum (set a flag, copy a byte) and exit. Leave heavy processing for main(). Haz lo mínimo (activa un flag, copia un byte) y sal. Deja el procesamiento pesado para main().

block

No Blocking CodeSin Código Bloqueante

NEVER use __delay_cycles() or polling loops inside an ISR. You will freeze the system. NUNCA uses __delay_cycles() ni bucles de polling dentro de una ISR. Congelarás el sistema.

flag

Clear Flags FirstLimpia los Flags Primero

Clear an interrupt flag (e.g., P1IFG) BEFORE enabling the interrupt to avoid instant unplanned jumps. Limpia el flag de interrupción (ej., P1IFG) ANTES de habilitar la interrupción para evitar saltos no deseados.

layers

Volatile VariablesVariables Volatile

Variables shared between main() and ISRs must be declared volatile so the compiler doesn't optimize them away. Las variables compartidas entre main() e ISR deben declararse volatile para que el compilador no las optimice.