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

▶Simulator: M7 · Demo: El botón despierta a la CPU (LPM4)Simulador: M7 · Demo: El botón despierta a la CPU (LPM4)

A CPU that sleeps until you pressUna CPU que duerme hasta que pulsas

       bis.b #BIT1, &P1IE     ; S1 puede interrumpir
       bis.w #GIE|LPM4, SR    ; a dormir

P1ISR: inc.w R10              ; una pulsación más
       ; LED1 = bit 0, LED2 = bit 1 de R10
       bic.b #BIT1, &P1IFG
       reti

       .intvec PORT1_VECTOR, P1ISR
Pause and predictPausa y predice

After 3 presses: R10? LEDs?Tras 3 pulsaciones: ¿R10? ¿LEDs?

And between presses, watch the PC.Y entre pulsaciones, mira el PC.

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.

▶Simulator: M7 · Demo: Error típico, olvidar GIESimulador: M7 · Demo: Error típico, olvidar GIE

One condition missingFalta una condición

       bis.b #BIT1, &P1IES    ; flanco de bajada
       bic.b #BIT1, &P1IFG
       bis.b #BIT1, &P1IE     ; fuente habilitada
       bis.w #CPUOFF, SR      ; duerme... sin GIE

P1ISR: xor.b #BIT0, &P1OUT
       bic.b #BIT1, &P1IFG
       reti
Pause and predictPausa y predice

Press S1. Why does LED1 stay off?Pulsas S1. ¿Por qué no se enciende LED1?

P1IFG says yes. Who says no?P1IFG dice que sí. ¿Quién dice que no?

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 SR cleared: SR a cero: GIE = 0 · CPU awake · CPU despierta
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
entry → GIE = 0entrada → GIE = 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 RETITermina con RETI

Save what you touchGuarda lo que toques

Clear the flagLimpia el flag

Stay shortSé breve

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

Configure the source, install the vector, then let the ISR count: LEDs show R10 in binary.Configura la fuente, instala el vector, y deja que la ISR cuente: los LEDs muestran R10 en binario.

Setup in mainConfiguración en main
main:
  bic.w #LOCKLPM5, &PM5CTL0 ; unlock pins
  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:
  inc.w R10            ; count press
  xor.b #BIT0, &P1OUT  ; LED1 = bit 0
  bit.b #BIT0, &P1OUT  ; LED1 just off?
  jnz   fin
  xor.b #BIT7, &P9OUT  ; carry → LED2
fin:
  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
P1IV = 0 → none · 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.

LPM0 to LPM4De LPM0 a LPM4

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 activosCurrent (relative)Corriente (relativa)
ActiveActivoCPU + MCLK + SMCLK + ACLKCPU + MCLK + SMCLK + ACLK
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)
LPM4all clocks off, wake on pin interrupttodos los relojes off, despierta por un pin

LPM3 is the common choice: the lowest that still keeps a time base. (LPM3.5/4.5 go deeper.)LPM3 es la elección habitual: lo más bajo que aún mantiene una base de tiempo. (LPM3.5/4.5 bajan más.)

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
▶Simulator: M7 · Demo: La ISR despierta a mainSimulador: M7 · Demo: La ISR despierta a main

The ISR wakes main upLa ISR despierta a main

dormir: bis.w #GIE|LPM0, SR  ; a dormir...
        nop                  ; ...aquí despierta
        inc.w R11            ; main trabaja
        xor.b #BIT0, &P1OUT
        jmp   dormir

P1ISR:  bic.b #BIT1, &P1IFG
        bic.w #LPM0, 0(SP)   ; SR apilado
        reti
Pause and predictPausa y predice

After 3 presses, R11 = ?Tras 3 pulsaciones, ¿R11 = ?

And without the BIC on 0(SP)?¿Y sin el BIC sobre 0(SP)?

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 adds 1 to R10; LED1/LED2 show the count in binary.La CPU duerme en LPM4. Cada pulsación de S1 la despierta y suma 1 a R10; LED1/LED2 muestran la cuenta en binario.

main:
  mov.w #WDTPW|WDTHOLD, &WDTCTL
  bic.w #LOCKLPM5, &PM5CTL0 ; unlock pins
  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:
  inc.w R10            ; R10 = presses
  ; LED1/LED2 = R10 in binary
  bic.b #BIT1, &P1IFG
  reti

  .intvec PORT1_VECTOR, P1ISR
How to runCómo ejecutarlo

M7 · Demo: El botón despierta a la CPU (LPM4)

LaunchPad → Run → hold S1.LaunchPad → Run → mantén S1.

▶ Try it in the simulatorPruébalo 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 LED1 while the CPU sleeps in LPM3.Timer_A0 cuenta hasta CCR0, dispara su vector y conmuta LED1 mientras la CPU duerme en LPM3.

main:
  mov.w #20, &TA0CCR0    ; placa: 16383
  mov.w #CCIE, &TA0CCTL0
  mov.w #TASSEL_1|MC_1|TACLR, &TA0CTL
  bis.w #GIE|LPM3, SR   ; sleep, ACLK on

TA0ISR:
  xor.b #BIT0, &P1OUT  ; LED1
  inc.w R10
  reti               ; CCIFG auto-clears
How to runCómo ejecutarlo

M7 · Demo: Parpadeo con timer en LPM3

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 simulatorPruébalo 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.