micro_II
-
Upload
karlita-altamirano -
Category
Documents
-
view
221 -
download
4
description
Transcript of micro_II
Microcontrolador IISistemas Electrónicos
por
Fabián Inostroza
2 de septiembre de 2015
Contenido
2/39
1 Interrupciones
2 Timers
3 Módulos PWM
4 Módulo PWM mejorado
Interrupciones 3/39
Interrupciones
¿Qué son?
Interrupciones 4/39
Definición1
“Evento externo al proceso en ejecución que provoca un cambio enel flujo normal de ejecución de instrucciones; generalmente esprovocado por dispositivos externos a la CPU”
1De Design and Implementation of the FreeBSD Operating System
Polling vs Interrupciones
Interrupciones 5/39
Detectar canto de una señal
Polling..while(1){
pin = PORTA0;if( pin != pin_1 ){// bravo.. canto detectadofuncion_muy_util();
}pin_1 = pin;
}
Interrupciónvoid interrupt isr(){
funcion_muy_util();}
main(){config();while(1){// muchas cosas utiles
}}
Interrupciones PIC18F4550 (I)
Interrupciones 6/39
Múltiples fuentes de interrupciónUSART, USB, Timers, I2C, Pines, Comparadores
Tres bits controlan comportamiento de interrupcionesIPEN Activación de prioridad de interrupciones.
Si IPEN = 0, todas son consideradas de altaprioridad.
GIEH Activación de interrupciones de prioridad alta.Si IPEN = 0, activa interrupciones globales.
GIEL Activación de interrupciones de prioridad baja.Si IPEN = 0, activa interrupciones de periféricos.
Tres bits asociados a cada interrupciónXIE Activación de interrupciónXIP Prioridad de interrupciónXIF Flag de interrupción
Interrupciones PIC18F4550 (II)
Interrupciones 7/39
FIGURE 9-1: INTERRUPT LOGIC
TMR0IE
GIE/GIEH
PEIE/GIEL
Wake-up if in Sleep Mode
Interrupt to CPUVector to Location0008h
INT2IFINT2IEINT2IP
INT1IFINT1IEINT1IP
TMR0IFTMR0IETMR0IP
RBIFRBIERBIP
IPEN
TMR0IF
TMR0IP
INT1IFINT1IEINT1IPINT2IFINT2IEINT2IP
RBIFRBIERBIP
INT0IFINT0IE
PEIE/GIEL
Interrupt to CPUVector to Location
IPEN
IPEN
0018h
Peripheral Interrupt Flag bitPeripheral Interrupt Enable bitPeripheral Interrupt Priority bit
Peripheral Interrupt Flag bitPeripheral Interrupt Enable bitPeripheral Interrupt Priority bit
TMR1IFTMR1IETMR1IP
USBIFUSBIEUSBIP
Additional Peripheral Interrupts
TMR1IFTMR1IETMR1IP
High-Priority Interrupt Generation
Low-Priority Interrupt Generation
USBIFUSBIEUSBIP
Additional Peripheral Interrupts
GIE/GIEH
From USB Interrupt Logic
From USB Interrupt Logic
{No necesitan PEIE=1 cuando IPEN=0
Atención de interrupciones (I)
Interrupciones 8/39
Dos “vectores” de interrupción
PC<20:0>
Stack Level 1•
Stack Level 31
Reset Vector
Low-Priority Interrupt Vector
••
CALL, RCALL, RETURN,RETFIE, RETLW, CALLW,
21
0000h
0018h
8000h
7FFFh
On-ChipProgram Memory
High-Priority Interrupt Vector 0008h
Use
r M
em
ory
Spa
ce
Read ‘0’
1FFFFFh200000h
Boo
tloa
der
1000h
Usu
ario
// código queda en 0x0008?void interrupt HISR(){}
// código queda en 0x0018?void interrupt low_priority LISR(){}
Atención de interrupciones (II)
Interrupciones 9/39
Ejemplo de interrupción de Timer 0
Revisar flagLimpiar flagAtender interrupciónA veces es necesariorevisar si interrupción estáactiva
void interrupt HISR(){
if( TMR0IF ){TMR0IF = 0;// Atender interrupción
}}
Consideraciones prácticas (I)
Interrupciones 10/39
Interrupciones deben ser cortas!
Consideraciones prácticas (I)
Interrupciones 11/39
delay() sin()cos()
exp()sqrt()pow()
log()
while(){}
Consideraciones prácticas (II)
Interrupciones 12/39
Evitar llamar otras funciones dentro de ISR.Variables globales usadas en ISR deben ser declaradasvolatileDesactivar interrupciones si acceso a variable no esatómico y variable es modificada en ISR.volatile uint16_t x = 0;void interrupt HISR(){
if( TMR0IF ){TMR0IF = 0;x++;
}}void main(){
config();while(1){
if( PORTAbits.RA ){GIE = 0;x = 0;GIE = 1;
}}
}
Consideraciones prácticas (III)
Interrupciones 13/39
// rutina de atención de interrupciónHISR: btfss INTCON,2; // TMR0IF==0?
goto i2u1_41goto i2u1_40
i2u1_41: goto i2l10; // ayayaii2u1_40:
// incrementar LSB de x, si resultado no// es cero, saltar siguiente instruccióninfsnz x;// incrementar MSB de xincf x+1;
i2l10: retfie f; // salir de interrupción
// main(){l602: // while(1){
btfss PORTA,0; // PORTAbits.RA0 == 1?goto u21;goto u20;
u21: goto l602;u20: clrf x; // borrar LSB de x
clrf x+1; // borrar MSB de xgoto l602
Interrupciones ATmega328P
Interrupciones 14/39
Table 11-6. Reset and Interrupt Vectors in ATmega328P
VectorNo.Program
Address(2) Source Interrupt Definition
1 0x0000(1) RESET External Pin, Power-on Reset, Brown-out Reset and Watchdog System Reset
2 0x0002 INT0 External Interrupt Request 0
3 0x0004 INT1 External Interrupt Request 1
4 0x0006 PCINT0 Pin Change Interrupt Request 0
5 0x0008 PCINT1 Pin Change Interrupt Request 1
6 0x000A PCINT2 Pin Change Interrupt Request 2
7 0x000C WDT Watchdog Time-out Interrupt
8 0x000E TIMER2 COMPA Timer/Counter2 Compare Match A
9 0x0010 TIMER2 COMPB Timer/Counter2 Compare Match B
10 0x0012 TIMER2 OVF Timer/Counter2 Overflow
11 0x0014 TIMER1 CAPT Timer/Counter1 Capture Event
12 0x0016 TIMER1 COMPA Timer/Counter1 Compare Match A
13 0x0018 TIMER1 COMPB Timer/Coutner1 Compare Match B
14 0x001A TIMER1 OVF Timer/Counter1 Overflow
15 0x001C TIMER0 COMPA Timer/Counter0 Compare Match A
16 0x001E TIMER0 COMPB Timer/Counter0 Compare Match B
17 0x0020 TIMER0 OVF Timer/Counter0 Overflow
18 0x0022 SPI, STC SPI Serial Transfer Complete
19 0x0024 USART, RX USART Rx Complete
20 0x0026 USART, UDRE USART, Data Register Empty
21 0x0028 USART, TX USART, Tx Complete
22 0x002A ADC ADC Conversion Complete
23 0x002C EE READY EEPROM Ready
24 0x002E ANALOG COMP Analog Comparator
25 0x0030 TWI 2-wire Serial Interface
26 0x0032 SPM READY Store Program Memory Ready
Timers 15/39
Timers
¿Qué son?
Timers 16/39
Son contadores que sirven para:Contar eventosGenerar interrupción por:
overflowcomparación
Base de tiempo en módulos PWMIniciar conversion análogo-digital
PIC18F4550 dispone de 4 timersTimer0,1,3: 16 bitsTimer2: 8 bits
Contadores del PIC18F4550 solo cuentan hacia arriba
Timer 0
Timers 17/39
Configurable: 8 (T08BIT=1)o 16 bits (T08BIT=0)Preescaler de 8 bits
Reloj externo o internoInterrupción por overflowCanto ext. configurable
FIGURE 11-2: TIMER0 BLOCK DIAGRAM (16-BIT MODE)
Note: Upon Reset, Timer0 is enabled in 8-bit mode with clock input from T0CKI maximum prescale.
T0CKI pin
T0SE
0
1
1
0
T0CS
FOSC/4
ProgrammablePrescaler
Sync withInternalClocks
TMR0L
(2 TCY Delay)
Internal Data Bus
8
PSA
T0PS2:T0PS0
Set TMR0IFon Overflow
3
TMR0
TMR0H
High Byte
88
8
Read TMR0L
Write TMR0L
8
Activación del timer con T0ON=1
Como variar el periodo de esta interrupción?
Timer 1
Timers 18/39
16 bitsAcceso: 8 o 16 bitsPuede ser reloj de CPU
Reloj: externo o internoInterrupción por overflowPuede ser RTC
FIGURE 12-1: TIMER1 BLOCK DIAGRAM
T1SYNC
TMR1CS
T1CKPS1:T1CKPS0
Sleep InputT1OSCEN(1)
FOSC/4InternalClock
On/Off
Prescaler1, 2, 4, 8
Synchronize
Detect
1
02
T1OSO/T13CKI
T1OSI
1
0
TMR1ON
TMR1L TMR1High ByteClear TMR1
(CCP Special Event Trigger)
Timer1 Oscillator
Note 1: When enable bit, T1OSCEN, is cleared, the inverter and feedback resistor are turned off to eliminate power drain.
On/OffTimer1
Set TMR1IFon Overflow
Timer 2
Timers 19/39
FIGURE 13-1:TIMER2 BLOCK DIAGRAM
Comparator
TMR2 Output
TMR2
Postscaler
PrescalerPR2
2
FOSC/4
1:1 to 1:16
1:1, 1:4, 1:16
4T2OUTPS3:T2OUTPS0
T2CKPS1:T2CKPS0
Set TMR2IF
Internal Data Bus
8
ResetTMR2/PR2
88
(to PWM or MSSP)
Match
Activación del timer con T2ON=1
8 bitsPrescaler y postscaladorValor máx. controlable
Interrupción comparadorTimer usado para PWM
Periodo del Timer 2
Timers 20/39
Comparator
TMR2 Output
TMR2
Postscaler
PrescalerPR2
2
FOSC/4
1:1 to 1:16
1:1, 1:4, 1:16
4T2OUTPS3:T2OUTPS0
T2CKPS1:T2CKPS0
Set TMR2IF
Internal Data Bus
8
ResetTMR2/PR2
88
(to PWM or MSSP)
Match
T2CLK
m
n
TMR2 se incrementa en 1 por cada ciclo de reloj T2CLKSi TMR2 == PR2, TMR2 se resetea. Comparación en cadacicloT2CLK = Fosc/(4*m), m = valor del prescalerInterrupción TMR2 ocurre por cada n reseteos del TMR2,n = valor del postscaler
Periodo del Timer 2
Timers 20/39
Comparator
TMR2 Output
TMR2
Postscaler
PrescalerPR2
2
FOSC/4
1:1 to 1:16
1:1, 1:4, 1:16
4T2OUTPS3:T2OUTPS0
T2CKPS1:T2CKPS0
Set TMR2IF
Internal Data Bus
8
ResetTMR2/PR2
88
(to PWM or MSSP)
Match
T2CLK
m
n
TMR2 se incrementa cada
TT2CLK =4m
Foscs
Periodo del Timer 2
Timers 20/39
Comparator
TMR2 Output
TMR2
Postscaler
PrescalerPR2
2
FOSC/4
1:1 to 1:16
1:1, 1:4, 1:16
4T2OUTPS3:T2OUTPS0
T2CKPS1:T2CKPS0
Set TMR2IF
Internal Data Bus
8
ResetTMR2/PR2
88
(to PWM or MSSP)
Match
T2CLK
m
n
Para que llegue desde cero a PR2 (según el comparador) senecesitan
4m · (PR2+1)Fosc
s
Periodo del Timer 2
Timers 20/39
Comparator
TMR2 Output
TMR2
Postscaler
PrescalerPR2
2
FOSC/4
1:1 to 1:16
1:1, 1:4, 1:16
4T2OUTPS3:T2OUTPS0
T2CKPS1:T2CKPS0
Set TMR2IF
Internal Data Bus
8
ResetTMR2/PR2
88
(to PWM or MSSP)
Match
T2CLK
m
n
Ejemplo: PR2=4
T2CLK
TMR2 0 1 2 3 4 0
Comparaciones
TMR2 out
Periodo del Timer 2
Timers 20/39
Comparator
TMR2 Output
TMR2
Postscaler
PrescalerPR2
2
FOSC/4
1:1 to 1:16
1:1, 1:4, 1:16
4T2OUTPS3:T2OUTPS0
T2CKPS1:T2CKPS0
Set TMR2IF
Internal Data Bus
8
ResetTMR2/PR2
88
(to PWM or MSSP)
Match
T2CLK
m
n
Periodo de interrupciones del Timer 2
4mn · (PR2+1)Fosc
s
Ejemplo: Interrupción TMR0
Timers 21/39
void interrupt HISR(){if( TMR0IF ){
TMR0IF = 0;LATC1 ^= 1;
}}
void config(void){TRISC1 = OUTPUT;
T0CONbits.T0PS = 7; // preescaler = 16T08BIT = 0; // TMR0 de 16bits// periodo = 16*4/(65535+1)
T0CS = 0; // reloj internoPSA = 0; // usar preescaler
TMR0IE = 1; // act int timer0IPEN = 0; // sin prioridadTMR0ON = 1; // encender timer0
GIE = 1; // act int. globales}
Ejemplo: Interrupción TMR2
Timers 22/39
void interrupt HISR(){if( TMR2IF ){
TMR2IF = 0;LATC1 ^= 1;
}}
void config(void){TRISC1 = OUTPUT;T2CONbits.T2CKPS = 3; // preesc=16T2CONbits.T2OUTPS0 = 1; // postsc=16T2CONbits.T2OUTPS1 = 1; // postsc=16T2CONbits.T2OUTPS2 = 1; // postsc=16T2CONbits.T2OUTPS3 = 1; // postsc=16
PR2 = 255; // T=4*16*16*(255+1)/48e6
TMR2IE = 1; // act int timer2IPEN = 0; // sin prioridadTMR2ON = 1; // encender timer2
PEIE = 1; // act int. perifericosGIE = 1; // act int. globales
}
Módulos PWM 23/39
MódulosPWM
Intro
Módulos PWM 24/39
El PIC18F4550 tiene dos módulos PWMResolución máxima de 10 bits en ciclo de trabajoResolución de 8 bits para la frecuenciaUno de ellos es un PWM con más funciones
Se pueden configurar para otras funcionesComparadorCaptura de eventos
Pueden generar interrupcionesEn modo PWM utilizan el Timer 2Modo comparador se puede usar para generar frecuenciavariable
Módulo PWM simple
Módulos PWM 25/39
.
FIGURE 15-3: SIMPLIFIED PWM BLOCK DIAGRAM
CCPRxL
CCPRxH (Slave)
Comparator
TMR2
Comparator
PR2
(Note 1)
R Q
S
Duty Cycle Registers CCPxCON<5:4>
Clear Timer,CCPx pin andlatch D.C.
Note 1: The 8-bit TMR2 value is concatenated with the 2-bit internal Q clock, or 2 bits of the prescaler, to create the 10-bit time base.
CCPx
CorrespondingTRIS bit
Output
PR2
Pin CCPx
0
1
CCPRxH=CCPRxL
t
t
CCPRxHCCPRxLTMR2
Ciclo de trabajo
Módulos PWM 26/39
El periodo lo da el Timer 2, ver slide 20El ciclo de trabajo (en tiempo) está dado por
Duty Cycle =(4 · CCPRxL + CCPxCON<5:4>) · m
Fosc
Ignorando CCPxCON<5:4> tenemos 8 bits de resolución¿Por qué en la fórmula no se usa4 · CCPRxL + CCPxCON<5:4>+1?
Notar que bajo operación normal CCPRxL no debe sermayor a PR2, ¿por qué?
Configuración
Módulos PWM 27/39
1. Escribir PR2 de acuerdo al periodo deseado, ver slide 202. Escribir CCPRxL y CCPxCON<5:4> (CCPxCONbits.DCxB) de
acuerdo al ciclo de trabajo deseado3. Configurar el pin CCPx, CCP1 = RC2, CCP2 = RC14. Configurar el preescalador del Timer2 y activar el timer,
ver slide 205. Configurar módulo PWM
Si se usa CCP1, escribir 0 en CCP1CONbits.P1M (modo PWMsimple)Escribir 0b11xx en CCPxCONbits.CCPxM
6. Orden no tan importante
Ejemplo
Módulos PWM 28/39
void config(void){TRISC2 = OUTPUT;T2CONbits.T2CKPS = 3; // preesc=16PR2 = 76; // T=4*16*(76+1)/48e6, aprox 10 kHzTMR2ON = 1; // encender timer2CCPR1L = 76/2; // aprox 50% dutyCCP1CONbits.P1M = 0; // modo PWM simpleCCP1CONbits.CCP1M = 0b1100; // modo PWM
}void main(void){
config();uint8_t duty = 0, down = 0;while(1){
__delay_ms(5);CCPR1L = duty;if( down == 0 ){
duty++;if( duty == 76) down = 1;
}else{duty--;if( duty == 0) down = 0;
}}
}
Tarea
Módulos PWM 29/39
Programar el microcontrolador para que genereuna señal sinusoidal (+ o�set) usando el módulo
PWM e interrupciones.
Módulo PWM mejorado 30/39
MóduloPWMmejorado
Características
Módulo PWM mejorado 31/39
Generación de señales complementarias (medio puente)Generación de banda muertaPolaridad de señal configurableGeneración de señales para puente H (4 transistores)Se implementa solo en el módulo CCP1
Configuración (I)
Módulo PWM mejorado 32/39
Configuración es similar a modo PWM básico,adicionalmente se debe considerar:Seleccionar modo mejorado escribiendo enCCP1CONbits.P1MP1M=1 Modo puente completo, P1D modulada, P1A
activa, P1B y P1C inactivaP1M=2 Modo medio puente, P1A y P1B moduladas, con
banda muerta, P1C y P1D no usadasP1M=3 Modo puente completo, P1B modulada, P1C
activa, P1A y P1D inactiva
Configuración (II)
Módulo PWM mejorado 33/39
Seleccionar polaridad escribiendo enCCP1CONbits.CCP1MCCP1M=0xC0 P1A, P1B, P1C y P1D activas en alto (5v)CCP1M=0xC1 P1A y P1C activas en alto (5v), P1B y P1D
activas en bajo (0v)CCP1M=0xC2 P1A y P1C activas en bajo (0v), P1B y P1D
activas en alto (5v)CCP1M=0xC3 P1A, P1B, P1C y P1D activas en bajo (0v)En modo medio puente: seleccionar el ancho de la bandamuerta escribiendo en ECCP1DEL
Configuración: Medio puente
Módulo PWM mejorado 34/39
PIC18FX455/X550 FETDriver
FETDriver
V+
V-
Load
+V-
+V-
Standard Half-Bridge Circuit (“Push-Pull”)
P1A/RC2
P1B/RD5
Configuración: Puente completo
Módulo PWM mejorado 35/39
FIGURE 16-7: EXAMPLE OF FULL-BRIDGE APPLICATION
FETDriver
FETDriver
V+
V-
Load
FETDriver
FETDriver
QA
QB QD
QCPIC18FX455/X550
P1B/RD5
P1C/RD6
P1D/RD7
P1A/RC2
Configuración: Polaridad
Módulo PWM mejorado 36/39
FIGURE 16-2: PWM OUTPUT RELATIONSHIPS (ACTIVE-HIGH STATE)0
Period
00
10
01
11
SIGNALPR2 + 1
CCP1CON<7:6>
P1A Modulated
P1A Modulated
P1B Modulated
P1A Active
P1B Inactive
P1C Inactive
P1D Modulated
P1A Inactive
P1B Modulated
P1C Active
P1D Inactive
DutyCycle
(Single Output)
(Half-Bridge)
(Full-Bridge,Forward)
(Full-Bridge,Reverse)
Delay(1) Delay(1)
Configuración: Bandamuerta
Módulo PWM mejorado 37/39
Period
Duty Cycle
td
td
(1)
P1A(2)
P1B(2)
Period
(1) (1)
td = Dead-Band Delay
Note 1: At this time, the TMR2 register is equal to thePR2 register.
2: Output signals are shown as active-high.
Tiempo de banda muerta es múltiplo de un ciclo de instrucción
Banda muerta [s] =4 · ECCP1DEL
Fosc
Ejemplo: HB yDB (I)
Módulo PWM mejorado 38/39
void config(void){TRISC2 = OUTPUT;TRISD5 = OUTPUT;T2CONbits.T2CKPS = 3; // preesc=16PR2 = 76; // T=4*16*(76+1)/48e6, aprox 10 kHz
CCPR1L = 76/2; // aprox 50% duty
CCP1CONbits.P1M = 2; // modo PWM simpleCCP1CONbits.CCP1M = 0b1100; // modo PWMECCP1DEL = 100;TMR2ON = 1; // encender timer2
}
Ejemplo: HB yDB (II)
Módulo PWM mejorado 39/39