guÍa de ejercicios resueltos tema 4

35
Prof. Luis Zurita 1 Microcontroladores I GUÍA DE EJERCICIOS RESUELTOS TEMA 5: TIMER 0 E INTERRUPCIONES

Upload: luis-zurita

Post on 25-May-2015

8.711 views

Category:

Education


9 download

TRANSCRIPT

Page 1: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 1 Microcontroladores I

GUÍA DE EJERCICIOS RESUELTOS

TEMA 5:

TIMER 0 E INTERRUPCIONES

Page 2: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 2 Microcontroladores I

1. Genere una señal cuadrada de 200 Hz. Diseño libre.

Paso 1. Enunciado y delimitación del problema:

Como no se ha especificado por cual pin del microcontrolador saldrá la

señal, asumiremos RB0.

Cuando se trabaja con el Timer 0, se deben incluir los cálculos que se

hayan realizado para generar el retardo deseado.

Para una frecuencia de 200 Hz, tendremos un período de:

ܨ =1

ݎ ݑݍ =

1

ܨ=

1

200 ݖܪ= 5 ݏ

Como no se ha especificado el ciclo de trabajo, asumiremos el 50 %, por

lo que el período en alto y en bajo serán iguales, es decir 2,5 ms

Hagamos los cálculos para 2,5 ms:

De la fórmula proporcionada en la Unidad IV, despejando nos quedará:

ெ ோை = ݎ ݖ ó

4 ∗ ݏ ∗ ݎ ݒ 0ܯݎݏ

Sustituyendo los valores (Como no se nos especificó el oscilador,

asumiremos el estándar de 4 MHz:

ெ ோை =2,5 ݏ

4 ∗ ቀ1

∗ቁݖܪܯ4 64= 39,0625 ≅ 39

ெ ோை = 256 − ݎ 0ܯ → ݎ ܯ 0 = 256 − ெ ோை = 256 − 39 = 217

Por lo que el valor a cargar en el TMR0= 217

Page 3: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 3 Microcontroladores I

Paso 2. Diagrama de Flujo:

INICIO

ConfigurarOPTION_REG

InicializamosPORTB

ConfigurarPuerto B

RB0=1

DELAY5MS

Borramos elSeñalizador TOIF

¿TOIF=1?

SI

NO

return

FORMA A

Cargamos valor calculadoen el TIMER0

DELAY5MS

RB0=0

DELAY5MS

Page 4: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 4 Microcontroladores I

Paso 3. Lenguaje ensamblador:

FORMA A. POR EXPLORACIÓN (POLLING) DEL BIT TOIF:

list P=16F84A

include P16F84A.inc

org 00H

goto INICIO

;***************************

;***PROGRAMA PRINCIPAL***

;***************************

INICIO bsf STATUS,5 ;Zona de configuraciones

clrf TRISB

movlw B'00010101' ;Predivisor= 128

movwf OPTION_REG

Page 5: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 5 Microcontroladores I

bcf STATUS,5

clrf PORTB ;Inicializamos el Puerto B

nop

CICLO bsf PORTB,0 ;Señal a nivel alto

call DELAY2_5MS ;Llamamos subrutina 2,5 ms

bcf PORTB,0 ;Señal a nivel bajo

call DELAY2_5MS ;Llamamos subrutina 2,5 ms

goto CICLO ;Repetimos ciclo

DELAY2_5MS movlw .217 ;Cargamos TMR0 con valor

movwf TMR0 ;calculado previamente

bcf INTCON,2 ;Borramos el señalizador

ESPERA btfss INTCON,2 ;Se desbordó el TMR0?

goto ESPERA ;No. Seguimos esperamos

return ;Si, han transcurrido 2,5 ms

end

FORMA B. POR INTERRUPCIÓN

list P=16F84A

include P16F84A.inc

org 00H

goto INICIO

org 04H

goto RSI

;********************************

;***RUTINA DE INTERRUPCIÓN***

;********************************

RSI bcf INTCON,7 ;Deshabilitamos las interrupciones

btfss INTCON,2 ;La causa de la interrupción es desborde

;del TIMER0 TOIF=1?

goto SALIR ;No, Salimos

bcf INTCON,2 ;Si, borramos el señalizador TOIF

movlw .01

xorwf PORTB,1

movlw .217 ;Cargamos el valor del TMR0

Page 6: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 6 Microcontroladores I

movwf TMR0 ;Para una nueva temporización

SALIR bsf INTCON,7 ;Habilitamos las interrupciones

retfie

;***************************

;***PROGRAMA PRINCIPAL***

;***************************

INICIO bsf STATUS,5

clrf TRISB

movlw B'00010101' ;Predivisor= 128

movwf OPTION_REG

movlw B'10100000' ; Habilitamos las interrupciones

movwf INTCON ;Con GIE=1 y TOIE=1

bcf STATUS,5

clrf PORTB ;Inicializamos el Puerto B

movlw .217 ;Cargamos el TMR0 con el

movwf TMR0 ;valor previamente calculado

SINFIN clrwdt ;Usamos esta instrucción para

goto SINFIN ;evitar reinicio del programa

;De resto, el programa se queda en este bucle sin fin esperando el desborde

;del TMR0, que ocurrirá según sea el tiempo calculado.

end

Nota: Generalmente cuando los puertos A y/o B pueden sufrir modificaciones

dentro de la rutina de interrupción, se salva el entorno (Se verán en los

ejemplos 3, 4 y 5), sin embargo para este ejemplo, no se modifican otros bits

de los puertos, por lo que no es necesario salvar el entorno.

Page 7: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 7 Microcontroladores I

2. Genera la siguiente señal. (Use Timer 0 e interrupción)

Paso 1. Enunciado y delimitación del problema:

Como no se ha especificado por cual pin del microcontrolador saldrá la

señal, asumiremos RB0.

Cuando se trabaja con el Timer 0, se deben incluir los cálculos que se

hayan realizado para generar el retardo deseado.

En la gráfica, podemos extraer el período de la señal cuadrada cuyo

valor es de 100 ms, y asumiendo un ciclo de trabajo del 50 %, tendremos que la

señal en alto es igual a la señal en bajo, por lo tanto su duración o período será

de 50 ms.

Hagamos los cálculos para 50 ms:

De la fórmula proporcionada en la Unidad IV, despejando nos quedará:

ெ ோை = ݎ ݖ ó

4 ∗ ݏ ∗ ݎ ݒ 0ܯݎݏ

Sustituyendo los valores (Como no se nos especificó el oscilador),

asumiremos el estándar de 4 MHz:

ெ ோை =50 ݏ

4 ∗ ቀ1

∗ቁݖܪܯ4 256= 195,31 ≅ 195

ெ ோை = 256 − ݎ 0ܯ → ݎ 0ܯ = 256 − ெ ோை = 256 − 195= 61

Por lo que el valor a cargar en el TMR0= 61

100 ms

2 segundos

Page 8: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 8 Microcontroladores I

¿Por qué el predivisor de 256?

Sencillo, repasando la teoría, recordaremos que el valor del Timer 0 a

cargar no podrá exceder bajo ningún concepto 256. Si colocamos otro

predivisor del rango disponible, el resultado será mayor a 256.

¿Cómo encaro el problema?

En esta señal solicitada, si nos damos cuenta, la señal cuadrada se

genera 10 veces, dando un tiempo de 1 segundo, si la señal entera, antes de que

se repita el ciclo nuevamente, es de 2 segundos, vale decir que durante 10

veces el tiempo de 100 ms, la señal no bascula u oscila, por lo que podemos

utilizar un contador de temporización para determinar si la señal oscilará o no.

Durante las primeras 20 temporizaciones de 50 ms, la señal de salida

oscilará, durante las siguientes 20 temporizaciones de 50 ms, la señal de salida

no oscilará, utilizando el contador resolveremos este problema.

¿Y dónde utilizo el contador?

El desarrollo de la señal se fundamenta en una interrupción por desborde

del Timer0 para los 50 ms calculados, por lo tanto el contador se utilizará

dentro de la rutina de servicio de la interrupción. Veamos el Diagrama de flujo

para entenderlo mejor:

Page 9: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 9 Microcontroladores I

Paso 2. Diagrama de Flujo:

Paso 3. Lenguaje ensamblador:

list P=16F84A

include P16F84A.inc

CONTADOR equ 20H ;Declaramos el registro

org 00H

goto INICIO

org 04H

goto RSI

INICIO

ConfigurarINTCON y OPTION_REG

InicializamosCONTADOR y PORTB

ConfigurarPuerto A y B

DeclararCONTADOR

Cargamos valor calculadoen el TIMER0

Para evitar un reinicio del programaLimpiamos el Perro Guardián

RSI

¿Contador>20?

Borramos elSeñalizador TOIF

SI

NO

DeshabilitarInterrupciones

¿TOIF=1?

SI

NOSALIR

Bascular RB0

SALIR

HabilitarInterrupciones

retfie

CONTADOR=CONTADOR+1

¿Contador>40?

CONTADOR=0

Page 10: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 10 Microcontroladores I

;********************************

;***RUTINA DE INTERRUPCIÓN***

;********************************

RSI bcf INTCON,7 ;Deshabilitamos las interrupciones

btfss INTCON,2 ;La causa de la interrupción es

;desborde del TIMER0 TOIF=1?

goto SALIR ;No, Salimos

bcf INTCON,2 ;Si, borramos el señalizador TOIF

movlw .20

subwf CONTADOR,0 ;Contador-20.

btfsc STATUS,0 ;C=0? ó Contador < 20?

goto NOBASCULA ;No.

BASCULA movlw .01 ;Si.

xorwf PORTB,1 ;Basculamos (Toggle) RB0

goto SUBECONT

NOBASCULA movlw .40

subwf CONTADOR,0 ;Contador-40. Contador>40?

btfsc STATUS,0 ;C=0?

goto LIMPIAR

SUBECONT incf CONTADOR,1 ;Contador=Contador+1

movlw .61 ;Cargamos el valor del TMR0

movwf TMR0 ;Para una nueva temporización

bsf INTCON,7 ;Habilitamos las interrupciones

retfie ;Salimos de la RSI

LIMPIAR clrf CONTADOR ;Limpiamos el contador

SALIR bsf INTCON,7 ;Habilitamos las interrupciones

retfie ;Salimos de la RSI

;***************************

;***PROGRAMA PRINCIPAL***

;***************************

INICIO bsf STATUS,5 ;Zona de configuraciones

clrf TRISB

movlw B'00010111' ;Predivisor=256

movwf OPTION_REG

movlw B'10100000' ;Habilitamos las interrupciones

movwf INTCON ;Con GIE=1 y TOIE=1

bcf STATUS,5

Page 11: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 11 Microcontroladores I

clrf PORTB

clrf CONTADOR

bcf PORTB,0

movlw .61 ;Cargamos el valor del TMRO

movwf TMR0 ;Previamente calculado

SINFIN clrwdt

goto SINFIN

end

Señal en el osciloscopio del Proteus

R1

330R

X1CRYSTAL

D1LED-GREEN

OSC1/CLKIN16

RB0/INT6

RB17

RB28

RB39

RB410

RB511

RB612

RB713

RA017

RA118

RA21

RA32

RA4/T0CKI3

OSC2/CLKOUT15

MCLR4

U1

PIC16F84A

C1

22p

C2

22p

VDD

VSS

VSS

A

B

C

D

Page 12: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis

3. Diseñe un control de nivel para un tanque.

Se tiene un interruptor selector de “MODO”

Si “MODO” es manual, las bombas se activan sin importar el nivel del

tanque subterráneo.

Si “MODO” es automático, la activación de las bombas dependerá de:

Si el nivel del agua está por debajo del nivel mínimo, se activará la

bomba 1 hasta que se alcance el nivel Máximo, y procederá a

apagarse.

Si el nivel del agua está por encima del nivel mínimo, pero por debajo

del nivel máximo, se activará la bomba 2 hasta que se alcance el nivel

Máximo y procederá a apagarse.

Se debe monitorear si ha cambiado el “MODO”.

Importante: Si no hay agua en el tanque subterráneo, se deben

apagar las bombas hasta que el nivel del tanque de trabajo alcance al

sensor de operación

Paso 1.

embargo

Par

de salida

informaci

Com

nivel de R

Zuri

Enun

debe

a lo

, con

ón.

o e

B0,

MODO

l

Manua

o

Aut

PARADA

ta

ciado y delimita

mos delimitar el h

grar esta tarea de

la finalidad de s

l sensor de parad

este será configur

OPERACIÓN

12 Microcontroladores I

SOLUCIÓN:

ción del Hardware: Tenemos el enunciado, sin

ardware.

bemos asignar los pines de control de Entrada y

aber qué vamos a controlar y quién nos dará la

a se va a utilizar por interrupción de cambio de

ado como entrada

Page 13: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 13 Microcontroladores I

Debemos identificar cuales elementos son entrada y cuales salida:

ENTRADA ¿Qué pin

Asignamos?

SALIDA ¿Qué pin

Asignamos?

Interruptor “INICIO” RA0 Bomba B1 RB3

Sensor Máximo RA1 Bomba B2 RB1

Sensor Mínimo RA2 Indicador

Manual

RB2

Sensor Parada RB0 Indicador Auto RB3

Sensor Operación RA3

¿Y si quiero asignar otros pines? Perfecto, queda a libre elección.

R11k

R31k

OSC1/CLKIN16

RB0/INT6

RB17

RB28

RB39

RB410

RB511

RB612

RB713

RA017

RA118

RA21

RA32

RA4/T0CKI3

OSC2/CLKOUT15

MCLR4

U1

PIC16F84A

X1

C1

22p

C2

22p

VDD

VDD

R21k

VDD

VSS

VSSVSS

VSS

VSS

VSS

NIVEL MÁXIMO

VSS

MANUAL

AUTO

RB2

RB2

SENSOR NIVEL ALTO

SENSOR NIVEL BAJO

PARADA

OPERACIÓN

TANQUEPRINCIPAL

B1M1 B2 M2

TANQUE SUBTERRÁNEO

MODO

RA0

RA0

RA1

RA1RA2

RA2

RB1

RB

1

RB

3

R1A1k

VDD

VSS

RB0

R1B1k

VDD

VSS

RA3

RB3

RB0

RA3VDD

RB4

RB4

Page 14: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 14 Microcontroladores I

Paso 2. Diagrama de Flujo:

INICIO

ConfigurarPuerto A y B

Bomba 1= OFFBomba 2=OFF

¿Manual?Bomba 1= ONBomba 2= ON

¿NivelMínimo?

¿NivelMáximo?

Bomba 1= ONBomba 2= OFF

¿NivelMáximo?

Bomba 1= OFFBomba 2= OFF

Bomba 1= OFFBomba 2= ON

M

M

M

SI

NO

SI

NO

SI

NO

SI

NO

ConfigurarINTCON

RSI

Salvar entorno

¿Llegó aNoperación?

Bomba 1= OFFBomba 2= OFF

SI

NO

DeshabilitarInterrupciones

¿INTF=1?

SI

NOSALIR

Restaurar entorno

SALIR

HabilitarInterrupciones

INTF=0

retfie

Auto

Page 15: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 15 Microcontroladores I

Paso 3. Del Diagrama de Flujo al Lenguaje Ensamblador:

list P=16F84A

include P16F84A.INC

WTEMP equ 20H ;Declaramos registros para

PBTEMP equ 21H ;Utilizarse para salvar y restaurar

STATEMP equ 22H ;El entorno

org 00H ;Vector de Inicio

goto INICIO

org 04H ;Vector de Interrupción

goto RSI

;*************************************

;***Rutina de servicio de Interrupción***

;*************************************

RSI bcf INTCON,7 ;Interrupciones deshabilitadas

PUSH movwf WTEMP ;Salvamos el entorno

movf STATUS,0

movwf STATEMP

movf PORTB,0

movwf PBTEMP

btfss INTCON,1 ;INTF=1? Fue por RB0/INT?

goto PULL ;No. Salimos de la RSI

SI bcf PORTB,2

bcf PORTB,3 ;Bomba 1= OFF

bcf PORTB,1 ;Bomba 2= OFF

OPER btfsc PORTA,3 ;Nivel de Operación?

goto OPER ;No. Esperamos a que se alcance el

;nivel de operación

PULL movf PBTEMP,0 ;Restauramos el entorno

movwf PORTB

movf STATEMP,0

movwf STATUS

movf WTEMP,0

bcf INTCON,1 ;Borramos el señalizador

bsf INTCON,7 ;Interrupciones habilitadas

retfie ;Salimos de las interrupciones

Page 16: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 16 Microcontroladores I

;***********************

;***Programa Principal***

;***********************

INICIO bsf STATUS,5 ;Vamos al banco 1 a configurar

movlw 1FH

movwf TRISA

movlw B'00000001' ;RB0= Entrada, Resto Salidas

movwf TRISB

movlw B'10010000' ;Habilitamos las interrupciones

movwf INTCON ;Con GIE=1 y INTE=1

movlw B'01000000' ;Configuramos el tipo de flanco

movwf OPTION_REG ;De activación de RB0/INT

bcf STATUS,5 ;Vamos al banco 0 a trabajar

clrf TRISB ;Bombas=OFF

MODO btfsc PORTA,0 ;MODO AUTO?

goto AUTO

MANUAL bsf PORTB,2 ;No. Modo manual= ON

bcf PORTB,4 ;Modo Auto=OFF

bsf PORTB,3 ;Bomba 1=ON

bsf PORTB,1 ;Bomba 2=ON

goto MODO

AUTO btfsc PORTA,2 ;MÍNIMO?

goto DOS ;Hay Agua

bsf PORTB,2 ; Modo Auto=ON

bcf PORTB,4 ;Modo Manual=OFF

bsf PORTB,3 ;Bomba 1=ON

bcf PORTB,1 ;Bomba 2=OFF

CERR btfss PORTA,1 ;(NHA)MÁXIMO?

goto CERR ;No Hay Agua

MODO2 bcf PORTB,2 ; Modo Auto=OFF

bcf PORTB,3 ;Bomba 1=ON

bcf PORTB,1 ;Bomba 2=OFF

goto MODO

DOS btfsc PORTA,1 ;(NHA)MÁXIMO?

goto MODO ;HA

MODO1 bcf PORTB,2 ; Modo Auto=OFF

bcf PORTB,3 ;Bomba 1=OFF

bsf PORTB,1 ;Bomba 2=ON

goto CERR

end

Page 17: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 17 Microcontroladores I

4. Realice la automatización de la mezcladora de pinturas, mostrada en la

figura siguiente, bajo la siguiente secuencia de funcionamiento:

El sistema de mezclado se inicia al pulsarse “MARCHA”, mediante el cual,

se activa B1, por espacio de por espacio de 10 minutos. B2, MM, VD, MA

deben estar apagados. Se enciende un led verde que indica que el

sistema esta en marcha.

Transcurrido este tiempo, se enciende B2. B1, MM, VD, MA, deben estar

apagados.

B2 se mantiene encendido hasta que el sensor “Nivel alto” se activa,

mediante el cual se detiene B2, se activa MM. B1, VD, MA, se mantienen

apagados.

MM se mantiene encendido por espacio de 2 minutos. B1, B2, VD, MA se

mantienen apagados. Una vez transcurrido este tiempo, se detiene MM.

Se activa VD, hasta que se activa el sensor “Nivel bajo”, mediante el

cual se cierra VD y se activa MA por espacio de 7,5 minutos,

reiniciándose el proceso nuevamente.

El sistema cuenta con un pulsador de “PARE”, que al activarse en

cualquier momento detiene todo el proceso, apagando B1, B2, VD, MM y

MA, activando un led rojo y apagando al led verde, indicando que existe

una parada del proceso.

Para reiniciar el proceso nuevamente en donde se quedó al momento de

detenerlo, se debe pulsar “REINICIO”.

Nota: Utilice el TMR0 para generar la rutina de 1 segundo.

Page 18: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 18 Microcontroladores I

MEZCLADORA DE PINTURAS

TANQUE MEZCLADOR

MM

PINTURA 2PINTURA 1

Nivel Alto

Nivel Bajo

B1 B2

VD

PINTURA

LISTA

MA

PINTURA

LISTA

Page 19: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 19 Microcontroladores I

Nomenclaturas:

B1: Bomba 1

B2: Bomba 2

MM: Motor de Mezclado

VD: Válvula de Desagüe

MA: Motor de Avance

Paso 1. Enunciado y delimitación del Hardware: Tenemos el enunciado, sin

embargo debemos delimitar el hardware.

Debemos identificar cuales elementos son entrada y cuales salida:

ENTRADA ¿Qué pin

Asignamos?

SALIDA ¿Qué pin

Asignamos?

Pulsador “MARCHA” RA0 Led Marcha RB1

Pulsador “REINICIO” RA1 Led PARE RB2

Sensor Nivel Alto RA2 Válvula

Pintura 1

RB3

Sensor Nivel Bajo RA3 Válvula

Pintura 2

RB4

Sensor “PARE” RB0 Motor

Mezclado

RB5

Válvula

Desagüe

RB6

Motor

Avance

RB7

Page 20: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 20 Microcontroladores I

El circuito quedaría de la siguiente manera:

PINTURA 1 PINTURA 2

NIVEL ALTO

NIVEL BAJO

CAJA DE CONTROL

MARCHA

PARE

REINICIO

TANQUE

MEZCLADOR

MOTOR MZ

MOTOR AVANCE

VÁLVULA DESAGUE

VDD

VDD

RA2

RA3

VSS

VSS

RB

3

RB

4

RB

5

VSS

RB6

VSS

RB

7

VSS

VDD

VDD

VDD

RA0

RB0

RA1

RB1

RB2

PINTURA

LISTA

PINTURA

LISTA

RB7

Page 21: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 21 Microcontroladores I

Paso 2. Diagramas de Flujo:

INICIO

ConfigurarPuerto A y B

Limpiar Registros en generaly Puerto B

¿MARCHA=0?

B1=ONB2=OFFMM=OFFVD=OFFMA=OFF

LMARCHA=ONLPARE=OFF

SI

NO

ConfigurarINTCON y OPTION_REG

Declarar Registros detrabajo

LEYENDA:VD=Válvula de Desagüe

B1= Válvula de Llenado Pintura 1B2= Válvula de Llenado Pintura 2

LMARCHA= Led MarchaLPARE= Led Pare

NALTO= Sensor Nivel AltoNBAJO=Sensor Nivel Bajo

MM= Motor MezcladoMA= Motor de Avance

MARCHA= Pulsador de inicioPARE= Pulsador de parada

REINICIO= Pulsador de reinicio del procesoLógica de los sensores=

0=Activado1= Desactivado

¿NALTO=0?

NO

SI

B2=OFFMM=ON

VD=ON

¿NBAJO=0?

NO

SI

1

VD=OFFMA=ON

RET7_5S

1

A

RET13SEG

B1=OFFB2=ON

LMARCHA=ONLPARE=OFF

RET1M

MM=OFF

MA=OFF

1

RSI

Salvar entorno

¿REINICIO=0?

SI

NO

DeshabilitarInterrupciones

¿INTF=1?

SI

NOSALIR

Restaurar entorno

SALIR

HabilitarInterrupciones

INTF=0

retfie

LPARE=OFF

B1=OFFB2=OFFMM=OFFVD=OFFMA=OFF

LMARCHA=OFFLPARE=ON

Page 22: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 22 Microcontroladores I

Paso 3. Lenguaje Ensamblador:

list P=16F84A

include p16F84A.inc

W_TEMP equ 20H ;Declaramos los registros

ESTADO_TEMP equ 21H ;A utilizar para salvar y restaurar

PB_TEMP equ 22H ;El entorno

REGAUX1 equ 23H ;Registros para generar retardos

REGAUX2 equ 24H ;Por Software

org 00H

goto INICIO

org 04H

goto RSI

;***********************************

;***Rutina de Servicio de Interrupción***

;***********************************

RSI btfss INTCON,1 ;INTF=1?

goto SALIR ;No. Salimos de la Interrupción

movwf W_TEMP ;Salvamos el entorno

swapf W_TEMP,1

movf STATUS,0

movwf ESTADO_TEMP

movf PORTB,0

movwf PB_TEMP

movlw b'00000100' ;Si. Todo OFF. LPARE= ON

movwf PORTB ;(ROJO=ON)

REINI btfsc PORTA,1 ;Se pulsó REINICIO?

goto REINI ;Esperamos

bcf INTCON,1 ;Borramos señalizador INTF

movf PB_TEMP,0 ;Restauramos el entorno

movwf PORTB

movf ESTADO_TEMP,0

movwf STATUS

swapf W_TEMP,0

SALIR bsf INTCON,7 ;Habilitamos las interrupciones

retfie ;Salimos de la RSI

Page 23: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 23 Microcontroladores I

;**********************

;***Programa Principal ***

;**********************

INICIO bsf STATUS,5 ;Configuramos los Puertos

movlw 01FH

movwf TRISA ;PA como entrada

movlw b'00000001'

movwf TRISB ;PB como entrada/salida

movlw b'01000111' ;Prescaler= 256

movwf OPTION_REG ;Y configuramos el flanco de RBO/INT

movlw b'10010000' ;GIE= 1 y INTE=1

movwf INTCON

bcf STATUS,5

clrf PORTB ;Limpiamos el Puerto B

EMPIEZA btfsc PORTA,0 ;Se pulsó “INICIO”

goto EMPIEZA ;No. Esperamos

REPITE bsf PORTB,3 ;B1= ON

bsf PORTB,1 ;Led Marcha=ON (Verde= ON)

bcf PORTB,2 ;Led PARE=OFF

bcf PORTB,4 ;B1=OFF

bcf PORTB,5 ;MM=OFF

bcf PORTB,6 ;VD=OFF

bcf PORTB,7 ;MA=OFF

call RET13 ;Llamamos a Subrutina de 13 seg.

bcf PORTB,3 ;B1= OFF

bsf PORTB,4 ;B2= ON

NAOK btfsc PORTA,2 ;Nivel Alto= 0?

goto NAOK ;No. Esperamos

bcf PORTB,4 ;B2= OFF

bsf PORTB,5 ;MM= ON

call RET1M ;Llamamos subrutina de 1 minuto.

bcf PORTB,5 ;MM= OFF

bsf PORTB,6 ;VD= ON

NBOK btfsc PORTA,3 ;Nivel Bajo= 0?

goto NBOK ;No. Esperamos

bcf PORTB,6 ;VD= OFF

bsf PORTB,7 ;MA= ON

call RET7_5 ;Subrutina de 7,5 seg

Page 24: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 24 Microcontroladores I

bcf PORTB,7

goto REPITE

;**************************

;***Rutina de 7,5 segundos***

;**************************

RET7_5 bcf INTCON,2

movlw d'114'

movwf REGAUX1

RECAR75 bcf INTCON,2

clrf TMR0

ESPERA1 btfss INTCON,2

goto ESPERA1

decfsz REGAUX1,1

goto RECAR75

return

;**************************

;***Rutina de 13 segundos***

;**************************

RET13 bcf INTCON,2

movlw d'198'

movwf REGAUX1

RECAR13 bcf INTCON,2

clrf TMR0

ESPERA2 btfss INTCON,2

goto ESPERA2

decfsz REGAUX1,1

goto RECAR13

return

;**********************

;***Rutina de 1 minuto***

;**********************

RET1M movlw d'30' ;Original= 60, se cambió para la simulación

movwf REGAUX2

RECAR4 movlw d'15'

movwf REGAUX1

RECAR5 bcf INTCON,2

clrf TMR0

ESPERA4 btfss INTCON,2

Page 25: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 25 Microcontroladores I

goto ESPERA4

decfsz REGAUX1,1

goto RECAR5

decfsz REGAUX2,1

goto RECAR4

return

end ;Fin del programa

Page 26: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 26 Microcontroladores I

5. Se desea automatizar una lavadora “CHACACHACA” bajo dos modos de

lavado (uno de Lavado Rápido de 30 minutos de duración y otro de

Lavado Lento de 50 minutos de duración), el sistema constará de un

pulsador de “INICIO” y un interruptor selector de modo de lavado.

Automatice bajo las siguientes condiciones:

Se elige entre lavado rápido ó lento

Se presiona “INICIO” y realiza lo siguiente:

Se llena la CHACACHACA hasta el nivel de agua máximo; lava ó “bate”

por la mitad del tiempo; se detiene; se vacía; se llena otra vez de agua;

lava ó “bate” hasta que falten tres minutos; se detiene; se vacía; se llena

otra vez de agua; lava ó “bate” por el resto del tiempo; se vacía

nuevamente y emite una alarma sonora por espacio de 10 segundos; y se

detiene a la espera de un nuevo proceso de lavado.

Si no hay agua en el depósito de agua, se detiene el lavado, se cierra la

válvula de llenado y se emite una alarma sonora hasta que se solucione el

problema agregando agua al depósito hasta el nivel mínimo de lavado.

ML: Motor de Lavadora. VD: Válvula de Desagüe. VLL: Válvula de

Llenado.

Nmínimo, Nmáximo, Nmínimo de lavado, Nivel de alarma: Sensores

de nivel.

Page 27: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 27 Microcontroladores I

Nota: Utilice el TMR0 para generar la rutina de 1 segundo.

Paso 1. Enunciado y delimitación del Hardware: Tenemos el enunciado, sin

embargo debemos delimitar el hardware.

Debemos identificar cuales elementos son entrada y cuales salida:

ENTRADA ¿Qué pin

Asignamos?

SALIDA ¿Qué pin

Asignamos?

Interruptor “MODO”

de Lavado

RA0 Motor de

Lavadora

RB1

Pulsador “INICIO” RA1 Válvula de

Desagüe

RB2

Sensor Nivel Mínimo RA2 Válvula de

Llenado

RB3

Sensor Nivel Máximo RA3 Led

“INICIO”

RB4

Sensor Nivel Mínimo

de lavado

RA4 Led

“Rápido”

RB5

Sensor Nivel de

Alarma

RB0 Led “Lento” RB6

ALARMA RB7

Como podemos observar, de manera común, se asignan las entradas al

puerto A y las salidas al puerto B.

Page 28: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 28 Microcontroladores I

El circuito del hardware a simular quedaría de la siguiente manera:

NIVEL ALTO

NIVEL BAJO

PANEL DE CONTROL

INICIO

LAVADO

LAVADORA

MOTOR MZ VÁLVULA DESAGUE

VDD

VDD

RA3

RA2

VSS

RB

3

RB

1

VSS

RB2

VSS

VSS

VDD

VDD

VDD

RA1

RB0

RA4

RB4

RB5

VSS

DEPÓSITO

DE AGUA

NIVEL DE ALARMA

NMÍNIMO DE LAVADO

VÁLVULA DE LLENADO

VDD

RA0RB6

ON

RÁPIDO

LENTO

RB

7

VSS

ALARMA

Page 29: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 29 Microcontroladores I

Paso 2. Diagramas de Flujo:

INICIO

ConfigurarPuerto A y B

Limpiar Registros en generaly Puerto B

¿INTLAV?

Led Rápido=ONLed Lento=OFFContaMed=22ContaLav=45

¿INICIO?

SI

NO

ConfigurarINTCON y OPTION_REG

(Rápido)

Declarar Registros detrabajo

Led Rápido=OFFLed Lento=ONContaMed=12ContaLav=25

(Lento)

NO

SI

VD=OFFLed Inicio=ON

VLL=ON

LEYENDA:VD=Válvula de DesagüeVLL= Válvula de Llenado

NMAX= Sensor Nivel MáximoNMIN=Sensor Nivel Mínimo

NMINLAV=Sensor Nivel Mínimo de LavadoMotorL= Motor Lavadora

CONTA=Contador de minutosCONTAMEDIO=Contador precargado con la

mitad del tiempoCONTALAV=Contador precargado con el

tiempo total de lavadaLógica de los sensores=

0=Activado1= Desactivado

¿NMAX=0?NO

SI

VLL=OFFMotorL=ON

¿CONTA=CONTAMEDIO?

NO SI

RET1MIN

CONTA=CONTA+1

1

VLL=OFFMotorL=OFF

VD=ON

¿NMIN=0?NO

SI

1

VD=OFFVLL=ON

¿NMAX=0?NO

SI

VLL=OFFMotorL=ON

CONTALAV=CONTALAV-3

¿CONTA=CONTALAV?

NO

SI

RET1MIN

CONTA=CONTA+1

2

VLL=OFFMotorL=OFF

VD=ON

¿NMIN=0?NO

SI

A

Page 30: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 30 Microcontroladores I

SI

VD=OFFVLL=ON

¿NMAX=0?NO

SI

VLL=OFFMotorL=ON

RET1MIN

2

RET1MIN

RET1MIN

VLL=OFFMotorL=OFF

VD=ON

¿NMIN=0?NO

SI

RET10SEG

A

Vamos al Iniciodel programa

para una nuevalavada

RSI

Salvar entorno

¿Llegó aNMINLAV?

ALARMA=ONMotorL= OFF

VLL= OFFVD=OFF

SI

NO

DeshabilitarInterrupciones

¿INTF=1?

SI

NOSALIR

Restaurar entorno

SALIR

HabilitarInterrupciones

INTF=0

retfie

ALARMA=OFF

Page 31: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 31 Microcontroladores I

Paso 3. Lenguaje Ensamblador:

LIST P=16F84A

INCLUDE P16F84A.INC

;Declaraciones de registros:

RET4 EQU 2DH ;Registros para generar

RET5 EQU 2EH ;Rutinas de retardo

RET6 EQU 2FH

W_TEMP EQU 30H ;Registros para salvar el

STATUS_TEMP EQU 31H ;Entorno durante la interrupción

PA_TEMP EQU 32H

PB_TEMP EQU 33H

PC_TEMP EQU 34H

CONTA EQU 35H ;Registro contador de comparación

CONTAMED EQU 20H ;Registro que se cargará con el tiempo

;medio de la duración del lavado

CONTALAV EQU 21H ;Registro que posee el tiempo total de

;lavado

CONTASEG EQU 22H ;Registro contador de segundos

ORG 00H

GOTO INICIO

ORG 04H

GOTO RUTIN

;***********************************

;***Rutina de Servicio de Interrupción***

;***********************************

RUTIN BCF INTCON,7 ;Deshabilitamos las interrupciones

BTFSS INTCON,5

GOTO SALIR

MOVWF W_TEMP ;Salvamos el entorno durante la

SWAPF W_TEMP,1 ;Interrupción al modificarse el Puerto B

MOVF STATUS,0 ;dentro de la RSI

MOVWF STATUS_TEMP

MOVF PORTA,0

MOVWF PA_TEMP

MOVF PORTB,0

MOVWF PB_TEMP

ESPERA BSF PORTB,7 ;SSONORA=ON

Page 32: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 32 Microcontroladores I

BCF PORTB,1 ;ML=OFF

BCF PORTB,2 ;VD=OFF

BCF PORTB,3 ;VLL=OFF

BTFSC PORTA,4 ;NMINLAV?

GOTO ESPERA

BCF PORTB,7 ;SSONORA=OFF

POP MOVF PB_TEMP,0

MOVWF PORTB

MOVF PA_TEMP,0

MOVWF PORTA

MOVF STATUS_TEMP,0

MOVWF STATUS

SWAPF W_TEMP,1

MOVF W_TEMP,0

BCF INTCON,1 ;INTF=0

SALIR BSF INTCON,7 ;GIE=1

RETFIE

;*********************

;***Programa Principal***

;*********************

INICIO BSF STATUS,5 ;Configuramos los Puertos A y B

MOVLW 1FH

MOVWF TRISA

MOVLW B'00000001' ;RB0 como entrada

MOVWF TRISB

BCF OPTION_REG,6 ;Configuramos el flanco de RB0/INT

MOVLW B'10010000' ;Activamos GIE y INTE

MOVWF INTCON

BCF STATUS,5

NUEVOLAV CLRF CONTASEG ;Inicializamos los registros

CLRF CONTA ;Y el Puerto B

CLRF PORTB

MODO BTFSS PORTA,0 ;¿Qué MODO es?

GOTO MODOLENTO ;Ir al modo lento

BSF PORTB,5 ;Modo RÁPIDO= ON

BCF PORTB,6 ;LENTO OFF

Page 33: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 33 Microcontroladores I

MOVLW D'12' ;Precargamos los valores

MOVWF CONTAMED ;Para el lavado rápido

MOVLW D'25'

MOVWF CONTALAV

GOTO MARCHA ;Va a preguntar si se pulsó INICIO

MODOLENTO BCF PORTB,5 ;Activamos el MODO lento

BSF PORTB,6

MOVLW D'22' ;Y precargamos los valores

MOVWF CONTAMED ;de este modo

MOVLW D'45'

MOVWF CONTALAV

GOTO MARCHA

MARCHA BTFSC PORTA,1 ;¿INICIO?

GOTO MODO ;No, vamos a explorar el MODO

ESPLL1 BSF PORTB,4 ;LEDINI=ON

BSF PORTB,3 ;VLL ON

BTFSC PORTA,3 ;NMAX?

GOTO ESPLL1

BCF PORTB,3 ;VLL OFF

BSF PORTB,1 ;ML ON

SUBEMIN1

CALL RET1s ;PARA SIMULACION, ES UN MINUTO

INCF CONTA,1

MOVF CONTAMED,0

SUBWF CONTA,0 ;CONTA=CONTAMED?

BTFSS STATUS,2 ;Z=1?

GOTO SUBEMIN1

ESPVAC BCF PORTB,3 ;VLL OFF

BCF PORTB,1 ;ML OFF

BSF PORTB,2 ;VD ON

BTFSC PORTA,2 ;NMIN?

GOTO ESPVAC

ESPLL2 BCF PORTB,2 ;VD OFF

BSF PORTB,3 ;VLL ON

BTFSC PORTA,3 ;NMAX=0?

GOTO ESPLL2

BCF PORTB,3 ;VLL OFF

BSF PORTB,1 ;ML ON

Page 34: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 34 Microcontroladores I

DECF CONTALAV,1

DECF CONTALAV,1

DECF CONTALAV,1 ;A FALTA DE 3 MINUTOS

SUBEMIN2 CALL RET1s ;PARA SIMULACION, ES UN MINUTO

INCF CONTA,1

MOVF CONTALAV,0

SUBWF CONTA,0 ;CONTA=CONTALAV?

BTFSS STATUS,2 ;Z=1?

GOTO SUBEMIN2

ESPVAC2 BCF PORTB,3 ;VLL OFF

BCF PORTB,1 ;ML OFF

BSF PORTB,2 ;VD ON

BTFSC PORTA,2 ;NMIN?

GOTO ESPVAC2

ESPLL3 BCF PORTB,2 ;VD OFF

BSF PORTB,3 ;VLL ON

BTFSC PORTA,3 ;NMAX?

GOTO ESPLL3

BCF PORTB,3 ;VLL OFF

BSF PORTB,1 ;ML ON

CALL RET1s

CALL RET1s ;ESPERA 3 MINUTOS FINALES

CALL RET1s ;(SE SIMULA CON 1 SEG)

ESPVAC3 BCF PORTB,3 ;VLL OFF

BCF PORTB,1 ;ML OFF

BSF PORTB,2 ;VD ON

BTFSC PORTA,2 ;NMIN?

GOTO ESPVAC3

BCF PORTB,2 ;VD OFF

PITAZO BSF PORTB,7 ;ALARMA SONORA ON

CALL RET1s

INCF CONTASEG,1

MOVLW D'10'

SUBWF CONTASEG,0

BTFSS STATUS,2 ;10 SEG?

GOTO PITAZO

BCF PORTB,7 ;ALARMA SONORA OFF

GOTO NUEVOLAV

Page 35: GUÍA DE EJERCICIOS RESUELTOS TEMA 4

Prof. Luis Zurita 35 Microcontroladores I

;***************************************

;***Rutina de 1 segundo. Generada por PDEL***

;***************************************

RET1s movlw .14 ; 1 set numero de repeticion (C)

movwf RET4 ; 1 |

PLoop0 movlw .72 ; 1 set numero de repeticion (B)

movwf RET5 ; 1 |

PLoop1 movlw .247 ; 1 set numero de repeticion (A)

movwf RET6 ; 1 |

PLoop2 clrwdt ; 1 clear watchdog

decfsz RET6, 1 ; 1 + (1) es el tiempo 0 ? (A)

goto PLoop2 ; 2 no, loop

decfsz RET5, 1 ; 1 + (1) es el tiempo 0 ? (B)

goto PLoop1 ; 2 no, loop

decfsz RET4, 1 ; 1 + (1) es el tiempo 0 ? (C)

goto PLoop0 ; 2 no, loop

PDelL1 goto PDelL2 ; 2 ciclos delay

PDelL2 clrwdt ; 1 ciclo delay

return ; 2+2 Fin.

END