Module 7Módulo 7

Interrupts and operation modesInterrupciones y modos de operación

React to events without polling, and stay asleep until one arrives. Reaccionar a eventos sin sondear, y dormir hasta que llegue uno.

Santi Scagliusi, PhD

Two ways to notice an eventDos formas de notar un evento

The same button press, handled two different ways.La misma pulsación de botón, atendida de dos formas distintas.

PollingSondeo

The CPU loops, asking the flag over and over if the event happened.La CPU itera, preguntando al flag una y otra vez si ocurrió el evento.

loop  bit.b #BIT1, &P1IN
      jnz   loop

Burns cycles and energy while nothing happens.Quema ciclos y energía mientras no pasa nada.

MSP430MSP430
InterruptsInterrupciones

The hardware watches the flag. The event calls the CPU, not the other way around.El hardware vigila el flag. El evento llama a la CPU, no al revés.

      bis.w #GIE+LPM4, sr
; CPU sleeps until the event

Sleeps at near-zero current, wakes only when needed.Duerme con corriente casi nula, despierta solo cuando hace falta.

Three ways to route a requestTres formas de encaminar una petición

How does the CPU learn which device asked, and which routine to run?¿Cómo sabe la CPU qué dispositivo pidió, y qué rutina ejecutar?

PollingSondeo
CPU D1 D2 D3
1 line · variable latency1 línea · latencia variable
Daisy chainCadena
CPU D1 D2 D3 ACK
2 lines · position = priority2 líneas · posición = prioridad
MSP430
VectoredVectorizado
CPU D1 D2 D3
N vectors · direct jumpN vectores · salto directo

Inside the chip the lines are free, so the MSP430 gives every source its own vector.Dentro del chip las líneas son gratis, así que el MSP430 da a cada fuente su propio vector.

Three conditions to be servedTres condiciones para ser atendida

All three must hold at the same time, or the request just waits.Las tres deben cumplirse a la vez, o la petición espera.

IFG = 1 IE = 1 GIE = 1 an event arrivedllegó un evento this source enabledesta fuente habilitada global enable in SRpermiso global en SR AND SERVEDATENDIDA jump to ISRsalto a ISR

Miss any one input and the request just waits. The vector must already point at a real ISR.Si falta una entrada, la petición espera. El vector ya debe apuntar a una ISR real.

What the hardware does on acceptanceQué hace el hardware al aceptar

From the event to the first ISR instruction: six fixed steps, about 6 cycles.Del evento a la primera instrucción de la ISR: seis pasos fijos, unos 6 ciclos.

1 Finish the current instructionTerminar la instrucción actual
2 PUSH PC (return addr)(dir. retorno)
3 PUSH SR (flags + mode)(flags + modo)
4 Clear SR: Limpiar SR: GIE = 0
5 Vector word → Vector → PC
6 ISR runs, then Corre la ISR, luego RETI
StackPila
SP →SR
 PC
 . . .
PC ← vectorvector
RETI pops SR, then PCdesapila SR, luego PC

The FR6989 vector tableLa tabla de vectores del FR6989

128 bytes at 0xFF80–0xFFFE. Higher address means higher priority.128 bytes en 0xFF80–0xFFFE. Dirección más alta significa mayor prioridad.

0xFFFERESEThighestmáxima
0xFFFCSystem NMINMI sistema
0xFFFAUser NMINMI usuario
0xFFF6TB0 CCR0
0xFFF2WDT
0xFFEAADC12_B
0xFFE8TA0 CCR0
0xFFE6TA0 restresto
0xFFDAPort P1Puerto P1
0xFFD4Port P2Puerto P2
0xFFC8RTC_C
0xFFC6AES256lowestmínima

You never read these addresses by hand. .intvec NAME, ISR installs the pointer for you.Nunca lees estas direcciones a mano. .intvec NAME, ISR instala el puntero por ti.

Priority and nestingPrioridad y anidamiento

When several requests are pending at once, the address decides who goes first.Cuando varias peticiones están pendientes a la vez, la dirección decide quién va primero.

Higher address winsGana la dirección más alta priorityprioridad
0xFFFERESET
0xFFFANMI
0xFFE8TA0 CCR0
0xFFDAPort P1Puerto P1
0xFFC6AES256
No nesting by defaultSin anidamiento por defecto
entryGIE = 0entradaGIE = 0

An ISR is not interrupted unless it sets GIE again, at the cost of more stack.Una ISR no se interrumpe salvo que vuelva a poner GIE, a costa de más pila.

R2

GIE lives in the Status RegisterGIE vive en el Registro de Estado

The same SR holds the condition flags, the global enable, and the sleep bits.El mismo SR guarda los flags de condición, el permiso global y los bits de reposo.

V
8
SCG1
7
SCG0
6
OSCOFF
5
CPUOFF
4
GIE
3
N
2
Z
1
C
0

GIE (bit 3) is the global switch. EINT sets it, DINT clears it.GIE (bit 3) es el interruptor global. EINT lo activa, DINT lo limpia.

Bits 4–7 select the low-power mode. Setting them is how you go to sleep.Bits 4–7 seleccionan el modo de bajo consumo. Activarlos es cómo te duermes.

An ISR is a subroutine with rulesUna ISR es una subrutina con reglas

Hardware calls it, you do not. A few constraints follow from that.La llama el hardware, no tú. De ahí salen unas pocas restricciones.

P1ISR:
push working regsapilar registros usados
… do one short thing …… hacer una sola cosa breve …
bic.b #BIT1, &P1IFG
pop working regsdesapilar registros
reti

End with RETI, not RET. It pops SR then PC, restoring flags and sleep mode.Termina con RETI, no RET. Desapila SR y luego PC, restaurando flags y modo de reposo.

Save what you touch. PUSH and POP any working register the ISR uses.Guarda lo que toques. Apila y desapila cualquier registro de trabajo que uses.

Clear the flag. Single-source vectors auto-clear; shared flags like P1IFG you clear yourself.Limpia el flag. Los de fuente única se autoborran; los compartidos como P1IFG los limpias tú.

Stay short. Do the minimum and return. No long loops inside the ISR.Sé breve. Haz lo mínimo y vuelve. Sin bucles largos dentro de la ISR.

A button ISR, end to endUna ISR de botón, de principio a fin

Configure the source, install the vector, then let the ISR do one thing.Configura la fuente, instala el vector, y deja que la ISR haga una sola cosa.

Setup in mainConfiguración en main
main:
  bic.b #BIT1, &P1DIR  ; P1.1 input
  bis.b #BIT1, &P1REN  ; resistor on
  bis.b #BIT1, &P1OUT  ; pull-up
  bis.b #BIT1, &P1IES  ; falling edge
  bic.b #BIT1, &P1IFG  ; clear flag
  bis.b #BIT1, &P1IE   ; enable
  eint                  ; GIE = 1
The ISR and its vectorLa ISR y su vector
P1ISR:
  xor.b #BIT0, &P1OUT  ; toggle LED1
  bic.b #BIT1, &P1IFG  ; clear P1.1 flag
  reti

  .intvec PORT1_VECTOR, P1ISR

P1 is a shared vector, so the flag is cleared by hand.P1 es un vector compartido, así que el flag se limpia a mano.

Many pins, one port vectorMuchos pines, un vector de puerto

All eight P1 pins share vector 0xFFDA. Which pin fired?Los ocho pines de P1 comparten el vector 0xFFDA. ¿Qué pin disparó?

Polling P1IFG by handSondear P1IFG a mano
bit.b #BIT0, &P1IFG
jz    next
bic.b #BIT0, &P1IFG
; ... one test per bit ...

Long, and you set the priority order yourself.Largo, y tú fijas el orden de prioridad.

PreferredPreferido
Vector with P1IVVectorizar con P1IV
add.w &P1IV, PC
reti            ; 0 = none
jmp   P1_0      ; 2 = P1.0
jmp   P1_1      ; 4 = P1.1

Reading P1IV returns (pin+1)×2 and auto-clears that flag.Leer P1IV devuelve (pin+1)×2 y autoborra ese flag.

P1IV = 0none · 2 → P1.0 4 → P1.1 6 → P1.2 16 → P1.7

Value = (pin + 1) × 2. P1IV reports the highest-priority pending pin and auto-clears it.Valor = (pin + 1) × 2. P1IV informa del pin pendiente de mayor prioridad y lo autoborra.

Five low-power modesCinco modos de bajo consumo

Each mode shuts down more clocks. What stays on decides what can still wake you.Cada modo apaga más relojes. Lo que queda activo decide qué puede despertarte.

ModeModoClocks still runningRelojes activosCurrentCorriente
ActiveActivoCPU + MCLK + SMCLK + ACLKCPU + MCLK + SMCLK + ACLK~300 µA
LPM0ACLK, SMCLK (CPU/MCLK off)ACLK, SMCLK (CPU/MCLK off)
LPM1ACLK, SMCLK (DCO off if unused)ACLK, SMCLK (DCO off si no se usa)
LPM2ACLK only (SMCLK off)solo ACLK (SMCLK off)
LPM3ACLK only (RTC-capable)solo ACLK (apto para RTC)~0.9 µA
LPM4all clocks off, wake on interrupttodos los relojes off, despierta por interrupción~0.1 µA

LPM3 is the common choice: lowest current that still keeps a time base.LPM3 es la elección habitual: la menor corriente que aún mantiene una base de tiempo.

Four SR bits select the modeCuatro bits del SR eligen el modo

Pick a mode and watch which clocks survive.Elige un modo y observa qué relojes sobreviven.

SCG1
0
SCG0
0
OSCOFF
0
CPUOFF
0
memory
CPU
speed
MCLK
hub
SMCLK
schedule
ACLK
 

Sleep in main, work in the ISRDormir en main, trabajar en la ISR

The default state is asleep. Each interrupt is a short burst of work, then back to sleep.El estado por defecto es dormir. Cada interrupción es una breve ráfaga de trabajo, y a dormir.

activeactivo LPM3LPM3 ISR ISR ISR eventevento eventevento eventevento
main: enter and sleepmain: configurar y dormir
  bis.w #GIE+LPM3, sr  ; sleep
ISR: work, then wakeISR: trabajar y despertar
  bic.w #LPM3, 0(sp)  ; in stacked SR

Run it: button wakes from LPM4Ejecútalo: el botón despierta desde LPM4

The CPU sleeps in LPM4. Each press of S1 wakes it and toggles LED1.La CPU duerme en LPM4. Cada pulsación de S1 la despierta y conmuta LED1.

main:
  bis.b #BIT0, &P1DIR  ; P1.0 = LED1 out
  bic.b #BIT1, &P1DIR  ; P1.1 = S1 in
  bis.b #BIT1, &P1REN  ; resistor on
  bis.b #BIT1, &P1OUT  ; pull-up
  bis.b #BIT1, &P1IES  ; falling edge
  bic.b #BIT1, &P1IFG
  bis.b #BIT1, &P1IE
  bis.w #GIE+LPM4, sr  ; sleep

P1ISR:
  xor.b #BIT0, &P1OUT  ; toggle LED
  bic.b #BIT1, &P1IFG
  reti

  .intvec PORT1_VECTOR, P1ISR
How to runCómo ejecutarlo

Open /msp430simulator and pick M7 · Button interrupt + LPM.Abre /msp430simulator y elige M7 · Button interrupt + LPM.

Click LaunchPad in the I/O panel, press Run, then click and hold S1 (P1.1).Pulsa LaunchPad en el panel de E/S, dale a Run, y mantén pulsado S1 (P1.1).

Try it in the simulatorProbalo en el simulador

Run it: a periodic timer interruptEjecútalo: una interrupción periódica del timer

Timer_A0 counts up to CCR0, fires its own vector, and toggles an output, no CPU polling.Timer_A0 cuenta hasta CCR0, dispara su vector y conmuta una salida, sin sondeo de CPU.

main:
  mov.w #20, &TA0CCR0   ; period = CCR0+1
  mov.w #OUTMOD_4|CCIE, &TA0CCTL0
  mov.w #TASSEL_1|MC_1|TACLR, &TA0CTL
  eint               ; GIE = 1
loop:
  nop                ; timer drives the ISR
  jmp loop

TA00ISR:
  reti               ; CCR0 flag auto-clears

  .intvec TIMER0_A0_VECTOR, TA00ISR
How to runCómo ejecutarlo

Open /msp430simulator and pick M9 · Timer: square wave + IRQ.Abre /msp430simulator y elige M9 · Timer: square wave + IRQ.

Watch the Timer_A panel: TA0R ramps 0 to CCR0, CCIFG sets, the CCR0 ISR runs each period.Observa el panel Timer_A: TA0R sube de 0 a CCR0, CCIFG se activa, la ISR de CCR0 corre cada periodo.

Try it in the simulatorProbalo en el simulador

Three ideas to take with youTres ideas para llevarte

Interrupts and sleep, in three ideas.Interrupciones y reposo, en tres ideas.

IFG·IE·GIE

Three conditionsTres condiciones

A flag, its enable, and the global enable. All three, or the request waits.Un flag, su habilitación y el permiso global. Las tres, o la petición espera.

PC·SR

Hardware saves contextEl hardware guarda el contexto

Entry pushes PC and SR, clears GIE, loads the vector. RETI undoes it.La entrada apila PC y SR, limpia GIE, carga el vector. RETI lo deshace.

LPM3

Sleep, wake, repeatDormir, despertar, repetir

Sleep in main, work in the ISR, clear LPM in the stacked SR to stay awake.Duerme en main, trabaja en la ISR, limpia LPM en el SR apilado para seguir activo.