Module 8Módulo 8

Digital I/OE/S Digital

How the CPU reads a button and lights an LED, one bit at a time. Cómo la CPU lee un botón y enciende un LED, bit a bit.

Santi Scagliusi, PhD

▶Simulator: M8 · Demo: Botón por sondeo con pull-upSimulador: M8 · Demo: Botón por sondeo con pull-up

Room sign: free (green) / busy (red)Cartel de sala: libre (verde) / ocupado (rojo)

sondeo:  bit.b #BIT1, &P1IN   ; S1 = P1.1
         jz    ocupado         ; 0 = pulsado
         bic.b #BIT0, &P1OUT  ; libre: rojo off
         bis.b #BIT7, &P9OUT  ; verde on
         jmp   sondeo
ocupado: bis.b #BIT0, &P1OUT  ; rojo on
         bic.b #BIT7, &P9OUT  ; verde off
         jmp   sondeo
Pause and predictPausa y predice

Holding S1, what does P1IN.1 read?Con S1 pulsado, ¿qué lee P1IN.1?

0 or 1? The answer is the whole module.¿0 o 1? La respuesta es todo el módulo.

A pin is a memory addressUn pin es una dirección de memoria

The same instruction that writes RAM writes a port. The address decides.La misma instrucción que escribe RAM escribe un puerto. La dirección decide.

CPU BIS.B write a 1escribe un 1 0x0202 ADDRESS SPACEESPACIO DE DIRECC. 0x1C00 RAM 0x0202 P1OUT 0x4400 codecódigo bit 0 = 1bit 0 = 1 P1.0 3.3 V pinpin 3.3 V LED1

Writing a 1 into address 0x0202 puts a voltage on physical pin P1.0. Escribir un 1 en la dirección 0x0202 pone tensión en el pin físico P1.0.

Six registers wire to one pinSeis registros cablean un pin

PxDIR steers the pin in or out. The others drive it or read it.PxDIR decide si el pin es entrada o salida. Los demás lo accionan o lo leen.

PxOUT output levelnivel de salida PxDIR 0 = input0 = entrada 1 = output1 = salida direction muxmux de dirección PxREN pull enablepull on/off PxIN read-only sensesensor de lectura Px.n physical pinpin físico level read backnivel leído PxSEL0 / PxSEL1 00 = GPIO, else hand the pin to a peripheral00 = GPIO, si no cede el pin a un periférico

Ten ports, four can interruptDiez puertos, cuatro interrumpen

P1 to P10 are 8-bit. Pairs combine into 16-bit word ports PA to PE.P1 a P10 son de 8 bits. Las parejas forman puertos de 16 bits PA a PE.

PA = P2 : P1PA = P2 : P1
P2
high byte · bits 15-8byte alto · bits 15-8
P1
low byte · bits 7-0byte bajo · bits 7-0

Only P1, P2, P3, P4 have edge-interrupt logic. P5 to P10 and PJ do not. Solo P1, P2, P3, P4 tienen lógica de interrupción por flanco. P5 a P10 y PJ no.

The LaunchPad LEDs and buttonsLos LEDs y botones de la LaunchPad

EXP430FR6989: two LEDs, two buttons, fixed pins.EXP430FR6989: dos LEDs, dos botones, pines fijos.

EXP430FR6989 LaunchPad MSP430 FR6989 LED1 P1.0 LED2 P9.7 S1 · P1.1 S2 · P1.2

LEDs are active-high. A pressed button ties the pin to ground, so it reads 0: active-low. Los LEDs son activos a nivel alto. Un botón pulsado lleva el pin a masa, así que lee 0: lógica negativa.

Three lines before any I/OTres líneas antes de cualquier E/S

After reset, the FR6989 pins are locked in high impedance.Tras el reset, los pines del FR6989 están bloqueados en alta impedancia.

mov.w #__STACK_END, SP ; stackpila
mov.w #WDTPW|WDTHOLD, &WDTCTL ; stop watchdogpara el watchdog
bic.w #LOCKLPM5, &PM5CTL0 ; unlock the pinsdesbloquea los pines

Skip the third line and the LED never lights. Sin la tercera línea, el LED no se enciende nunca.

Output: set the bit, light the pinSalida: pon el bit, enciende el pin

Direction first, then the level. P1.0 = LED1.Primero la dirección, luego el nivel. P1.0 = LED1.

P1OUT
0
0
0
0
0
0
0
0
7
6
5
4
3
2
1
0
P1.0 · LED1
OFFAPAGADO
bis.b #BIT0, &P1DIR ; outputsalida
bis.b #BIT0, &P1OUT ; onenciende
xor.b #BIT0, &P1OUT ; toggleconmuta
xor.b #BIT0, &P1OUT ; toggleconmuta
bic.b #BIT0, &P1OUT ; offapaga

Three idioms, one maskTres modismos, una máscara

Same start byte, same mask #BIT2|BIT0. Only the named bits change.Mismo byte inicial, misma máscara #BIT2|BIT0. Solo cambian los bits nombrados.

maskmáscara
00000101
#BIT2|BIT0
BIS.Bset to 1pone a 1
10000110
OR maskOR máscara
10000111
BIC.Bclear to 0pone a 0
10000110
AND ~maskAND ~máscara
10000010
XOR.Bflip / toggleinvierte
10000110
XOR maskXOR máscara
10000011

Start 1000 0110 in all three. Bits outside the mask never change. Las tres parten de 1000 0110. Los bits fuera de la máscara no cambian.

▶Simulator: M8 · Demo: BIS, BIC y XOR con una máscaraSimulador: M8 · Demo: BIS, BIC y XOR con una máscara

Three idioms, then one mistakeTres modismos y un error

mov.b #0xF0, &P1OUT   ; 1111 0000
bis.b #BIT0, &P1OUT   ; 0xF1
xor.b #BIT0, &P1OUT   ; 0xF0
xor.b #BIT0, &P1OUT   ; 0xF1
bic.b #BIT0, &P1OUT   ; 0xF0
mov.b #BIT0, &P1OUT   ; P1OUT = ?
Pause and predictPausa y predice

What is P1OUT after the last MOV?¿Cuánto vale P1OUT tras el último MOV?

What happened to bits 4..7?¿Qué ha pasado con los bits 4..7?

Reading a pin: PxIN and active-lowLeer un pin: PxIN y lógica negativa

Pull-up to Vcc, button to ground. Pressed wins and pulls the pin to 0.Pull-up a Vcc, botón a masa. Pulsado gana y lleva el pin a 0.

Vcc (3.3 V) releasedreposo REN P1.1 PxIN = 1PxIN = 1 S1 GND pressed: pin → 0pulsado: pin → 0
BIT.B #BIT1, &P1IN ; test S1probar S1
JZ pressed ; 0 = pressed0 = pulsado

Enabling the internal pull-upActivar el pull-up interno

A button to ground needs three writes before it reads cleanly.Un botón a masa necesita tres escrituras para leerse bien.

bic.b #BIT1, &P1DIR
P1.1 as inputP1.1 como entrada
bis.b #BIT1, &P1REN
enable the internal resistorhabilita la resistencia interna
bis.b #BIT1, &P1OUT
OUT = 1 selects pull-UPOUT = 1 elige pull-UP
P1.1 · S1
floating, undefinedflotante, indefinido
Without a resistor the level is noise.Sin resistencia el nivel es ruido.

Worked example: free / busy signEjemplo: cartel libre / ocupado

S1 held = busy (LED1 red); released = free (LED2 green). Polling loop.S1 pulsado = ocupado (LED1 rojo); suelto = libre (LED2 verde). Bucle de sondeo.

        bis.b #BIT0, &P1DIR   ; LED1 (red) out
        bis.b #BIT7, &P9DIR   ; LED2 (green) out
        bic.b #BIT1, &P1DIR   ; S1 in
        bis.b #BIT1, &P1REN   ; resistor on
        bis.b #BIT1, &P1OUT   ; ...pull-up
sondeo: bit.b #BIT1, &P1IN    ; Z = 1 if pressed
        jz    ocupado
        ; libre / ocupado: swap the two LEDs
        jmp   sondeo

Mechanical buttons bounceLos botones mecánicos rebotan

One press, several edges in the first milliseconds.Una pulsación, varios flancos en los primeros milisegundos.

1 0 timetiempo RAW pinpin CRUDO chatterrebote presspulsa wait, then re-read → one clean edgeespera y relee → un flanco limpio
Software:Software: wait, then re-read the pin.espera y vuelve a leer el pin.
Hardware:Hardware: an RC filter on the line.un filtro RC en la línea.
▶Simulator: M8 · Demo: Contar pulsaciones (detectar el flanco)Simulador: M8 · Demo: Contar pulsaciones (detectar el flanco)

Count the edge, not the levelCuenta el flanco, no el nivel

leer:    mov.b &P1IN, R6
         and.b #BIT1, R6      ; R6 = ahora
         cmp.b R5, R6         ; R5 = antes
         jeq   leer           ; sin cambio
         mov.b R6, R5
         ; ...retardo antirrebote...
         tst.b R5
         jnz   leer           ; 0→1: soltar
         inc.w R10            ; 1→0: contar
         jmp   leer
Pause and predictPausa y predice

Hold S1 down. Does R10 keep climbing?Mantén S1 pulsado. ¿R10 sigue subiendo?

Watch R5 and R6. And on the board, without the delay?Mira R5 y R6. ¿Y en la placa, sin el retardo?

From polling to port interruptsDe sondeo a interrupciones de puerto

An edge sets the flag. If the gates are open, the CPU jumps to the ISR.Un flanco pone la bandera. Si las puertas están abiertas, la CPU salta a la ISR.

PxIES pin edgeflanco PxIFG set to 1se pone a 1 AND PxIE AND GIE jump to ISRsalta a la ISR vector 0xFFDA · P1 the ISR must clear PxIFG before RETIla ISR debe borrar PxIFG antes de RETI

Same dispatch as Module 7. Here the source is a pin edge on P1 to P4. Mismo despacho que el Módulo 7. Aquí la fuente es un flanco en un pin de P1 a P4.

PxIV tells you which pin firedPxIV dice qué pin disparó

One vector serves all eight pins of the port. PxIV decodes the highest priority.Un vector sirve a los ocho pines del puerto. PxIV decodifica el de mayor prioridad.

no pendingnada pendiente0x00
P1.00x02
P1.10x04
P1.20x06
…(pin+1) × 2(pin+1) × 2
ADD.W &P1IV, PC + offset+ desplaz. +0 JMP done +2 JMP isr_P1.0 +4 JMP isr_P1.1 +6 JMP isr_P1.2 reading PxIV auto-clears that flagleer PxIV borra esa bandera

Worked example: button interrupt + LPMEjemplo: interrupción de botón + LPM

The CPU sleeps. Each press wakes it and toggles the LED.La CPU duerme. Cada pulsación la despierta y conmuta el LED.

main:
mov.w #__STACK_END, SP
mov.w #WDTPW|WDTHOLD, &WDTCTL
bic.w #LOCKLPM5, &PM5CTL0
bis.b #BIT0, &P1DIR ; P1.0 output (LED)
bic.b #BIT1, &P1DIR ; P1.1 input (S1)
bis.b #BIT1, &P1REN ; resistor
bis.b #BIT1, &P1OUT ; pull-up
bis.b #BIT1, &P1IES ; falling edge
bic.b #BIT1, &P1IFG ; clear pending
bis.b #BIT1, &P1IE ; enable P1.1 IRQ
bis.w #GIE+LPM4, sr ; sleep with interrupts on
P1ISR:
xor.b #BIT0, &P1OUT ; toggle LED
bic.b #BIT1, &P1IFG ; clear the flag
reti
.intvec PORT1_VECTOR, P1ISR

Run it in the simulatorPruébalo en el simulador

Click "LaunchPad" in the I/O panel first: P1.0 = LED1, P1.1 = S1, P1.2 = S2.Pulsa "LaunchPad" en el panel de E/S primero: P1.0 = LED1, P1.1 = S1, P1.2 = S2.

M8 · Digital I/O
M8 · Demo: BIS, BIC y XOR con una máscara

Step it: watch P1OUT bits set, clear and flip.Paso a paso: mira los bits de P1OUT ponerse, borrarse y conmutar.

M8 · Digital I/O
M8 · Demo: Botón por sondeo con pull-up

Hold S1: green (free) turns to red (busy).Mantén S1: verde (libre) pasa a rojo (ocupado).

M8 · Digital I/O
M8 · Demo: Contar pulsaciones (detectar el flanco)

R5 vs R6: only the press edge adds 1 to R10.R5 frente a R6: solo el flanco de pulsar suma 1 a R10.

Three ideas to take with youTres ideas para llevarte

Digital I/O is just reads and writes to memory-mapped bits.La E/S digital son solo lecturas y escrituras de bits mapeados en memoria.

DIR · OUT · IN

Configure, then drive.Configura y luego actúa.

Set PxDIR first. Write PxOUT, read PxIN. Reset leaves every pin an input.Pon PxDIR primero. Escribe PxOUT, lee PxIN. Tras reset todo pin es entrada.

BIS · BIC · XOR

Touch only your bits.Toca solo tus bits.

A byte mask and the .B suffix change one pin and leave the rest of the port intact.Una máscara de byte y el sufijo .B cambian un pin y dejan el resto del puerto intacto.

REN · IES · IFG

Buttons are active-low.Los botones son lógica negativa.

Pull-up holds high, pressed reads 0. P1 to P4 can interrupt on the edge.El pull-up mantiene alto, pulsado lee 0. P1 a P4 interrumpen en el flanco.