Microcontrolador II
Sistemas Electrnicos
por
Fabin Inostroza
2 de septiembre de 2015
Contenido
1 Interrupciones
2 Timers
3 Mdulos PWM
4 Mdulo PWM mejorado
2/39
Interrupciones
Interrupciones
3/39
Qu son?
Definicin1
Evento externo al proceso en ejecucin que provoca un cambio en
el flujo normal de ejecucin de instrucciones; generalmente es
provocado por dispositivos externos a la CPU
Interrupciones 1 De
Design and Implementation of the FreeBSD Operating System
4/39
Polling vs Interrupciones
Detectar canto de una seal
Polling
Interrupcin
.
.
while(1){
pin = PORTA0;
if( pin != pin_1 ){
// bravo.. canto detectado
funcion_muy_util();
}
pin_1 = pin;
}
void interrupt isr(){
funcion_muy_util();
}
Interrupciones
main()
{
config();
while(1){
// muchas cosas utiles
}
}
5/39
Interrupciones PIC18F4550 (I)
Mltiples fuentes de interrupcin
USART, USB, Timers, I2 C, Pines, Comparadores
Tres bits controlan comportamiento de interrupciones
IPEN Activacin de prioridad de interrupciones.
Si IPEN = 0, todas son consideradas de alta
prioridad.
GIEH Activacin de interrupciones de prioridad alta.
Si IPEN = 0, activa interrupciones globales.
GIEL Activacin de interrupciones de prioridad baja.
Si IPEN = 0, activa interrupciones de perifricos.
Tres bits asociados a cada interrupcin
XIE Activacin de interrupcin
XIP Prioridad de interrupcin
XIF Flag de interrupcin
Interrupciones
6/39
Interrupciones PIC18F4550 (II)
FIGURE 9-1:
INTERRUPT LOGIC
No necesitan PEIE=1
cuando IPEN=0
Peripheral Interrupt Flag bit
Peripheral Interrupt Enable bit
Peripheral Interrupt Priority bit
TMR1IF
TMR1IE
TMR1IP
From USB
Interrupt Logic
TMR0IF
TMR0IE
TMR0IP
RBIF
RBIE
RBIP
INT0IF
INT0IE
Wake-up if in Sleep Mode
Interrupt to CPU
Vector to Location
0008h
INT1IF
INT1IE
INT1IP
INT2IF
INT2IE
INT2IP
GIE/GIEH
IPEN
IPEN
USBIF
USBIE
USBIP
PEIE/GIEL
IPEN
Additional Peripheral Interrupts
High-Priority Interrupt Generation
Low-Priority Interrupt Generation
Peripheral Interrupt Flag bit
Peripheral Interrupt Enable bit
Peripheral Interrupt Priority bit
From USB
Interrupt Logic
RBIF
RBIE
RBIP
USBIF
USBIE
USBIP
Additional Peripheral Interrupts
Interrupciones
Interrupt to CPU
Vector to Location
0018h
TMR0IF
TMR0IE
TMR0IP
TMR1IF
TMR1IE
TMR1IP
PEIE/GIEL
GIE/GIEH
INT1IF
INT1IE
INT1IP
INT2IF
INT2IE
INT2IP
7/39
Atencin de interrupciones (I)
Dos vectores de interrupcin
PC<20:0>
CALL, RCALL, RETURN,
RETFIE, RETLW, CALLW,
21
Stack Level 1
Stack Level 31
Bootloader
Reset Vector
// cdigo queda en 0x0008?
void interrupt HISR()
{
}
0000h
High-Priority Interrupt Vector 0008h
Usuario
1000h
On-Chip
Program Memory
7FFFh
8000h
User Memory Space
Low-Priority Interrupt Vector 0018h
// cdigo queda en 0x0018?
void interrupt low_priority LISR()
{
}
Read 0
1FFFFFh
200000h
Interrupciones
8/39
Atencin de interrupciones (II)
Ejemplo de interrupcin de Timer 0
Revisar flag
Limpiar flag
Atender interrupcin
A veces es necesario
revisar si interrupcin est
activa
Interrupciones
void interrupt HISR()
{
if( TMR0IF ){
TMR0IF = 0;
// Atender interrupcin
}
}
9/39
Consideraciones prcticas (I)
Interrupciones deben ser cortas!
Interrupciones
10/39
Consideraciones prcticas (I)
delay()
sin()
cos()
log()
pow()
Interrupciones
while(){
}
exp()
sqrt()
11/39
Consideraciones prcticas (II)
Evitar llamar otras funciones dentro de ISR.
Variables globales usadas en ISR deben ser declaradas
volatile
Desactivar interrupciones si acceso a variable no es
atmico y variable es modificada en ISR.
Interrupciones
volatile uint16_t x = 0;
void interrupt HISR(){
if( TMR0IF ){
TMR0IF = 0;
x++;
}
}
void main(){
config();
while(1){
if( [Link] ){
GIE = 0;
x = 0;
GIE = 1;
}
}
}
12/39
Consideraciones prcticas (III)
// rutina de atencin de interrupcin
HISR:
btfss INTCON,2; // TMR0IF==0?
goto
i2u1_41
goto
i2u1_40
i2u1_41: goto
i2l10; // ayayai
i2u1_40:
// incrementar LSB de x, si resultado no
// es cero, saltar siguiente instruccin
infsnz x;
// incrementar MSB de x
incf
x+1;
i2l10: retfie f; // salir de interrupcin
// 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 x
goto l602
Interrupciones
13/39
Interrupciones ATmega328P
Table 11-6.
Program
Address(2)
Source
Interrupt Definition
0x0000(1)
RESET
External Pin, Power-on Reset, Brown-out Reset and Watchdog System Reset
0x0002
INT0
External Interrupt Request 0
0x0004
INT1
External Interrupt Request 1
0x0006
PCINT0
Pin Change Interrupt Request 0
0x0008
PCINT1
Pin Change Interrupt Request 1
0x000A
PCINT2
Pin Change Interrupt Request 2
0x000C
WDT
Watchdog Time-out Interrupt
0x000E
TIMER2 COMPA
Timer/Counter2 Compare Match A
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
Interrupciones
Reset and Interrupt Vectors in ATmega328P
VectorNo.
USART, UDRE
USART, Data Register Empty
21
0x0028
USART, TX
USART, Tx Complete
22
0x002A
0x0026
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
14/39
Timers
Timers
15/39
Qu son?
Son contadores que sirven para:
Contar eventos
Generar interrupcin por:
overflow
comparacin
Base de tiempo en mdulos PWM
Iniciar conversion anlogo-digital
PIC18F4550 dispone de 4 timers
Timer0,1,3: 16 bits
Timer2: 8 bits
Contadores del PIC18F4550 solo cuentan hacia arriba
Timers
16/39
Timer 0
Reloj externo o interno
Interrupcin por overflow
Canto ext. configurable
Configurable: 8 (T08BIT=1)
o 16 bits (T08BIT=0)
Preescaler de 8 bits
FIGURE 11-2:
TIMER0 BLOCK DIAGRAM (16-BIT MODE)
FOSC/4
0
1
1
Programmable
Prescaler
T0CKI pin
T0SE
T0CS
Sync with
Internal
Clocks
TMR0
High Byte
TMR0L
Set
TMR0IF
on Overflow
(2 TCY Delay)
Read TMR0L
T0PS2:T0PS0
Write TMR0L
PSA
TMR0H
Activacin del timer con T0ON=1
8
8
Internal Data Bus
Note:
Upon Reset, Timer0 is enabled in 8-bit mode with clock input from T0CKI maximum prescale.
Como variar el periodo de esta interrupcin?
Timers
17/39
Timer 1
16 bits
Acceso: 8 o 16 bits
Puede ser reloj de CPU
FIGURE 12-1:
Reloj: externo o interno
Interrupcin por overflow
Puede ser RTC
TIMER1 BLOCK DIAGRAM
Timer1 Oscillator
On/Off
T1OSO/T13CKI
1
FOSC/4
Internal
Clock
T1OSI
1
Synchronize
Prescaler
1, 2, 4, 8
Detect
0
2
T1OSCEN(1)
Sleep Input
TMR1CS
T1CKPS1:T1CKPS0
Timer1
On/Off
T1SYNC
TMR1ON
Clear TMR1
(CCP Special Event Trigger)
TMR1L
TMR1
High Byte
Set
TMR1IF
on Overflow
Note 1: When enable bit, T1OSCEN, is cleared, the inverter and feedback resistor are turned off to eliminate power drain.
Timers
18/39
Timer 2
FIGURE 13-1:TIMER2 BLOCK DIAGRAM
4
T2OUTPS3:T2OUTPS0
T2CKPS1:T2CKPS0
FOSC/4
1:1 to 1:16
Postscaler
Set TMR2IF
1:1, 1:4, 1:16
Prescaler
TMR2 Output
(to PWM or MSSP)
Reset
TMR2
8
TMR2/PR2
Match
Comparator
8
PR2
8
Internal Data Bus
Activacin del timer con T2ON=1
8 bits
Prescaler y postscalador
Valor mx. controlable
Timers
Interrupcin comparador
Timer usado para PWM
19/39
Periodo del Timer 2
n
4
T2OUTPS3:T2OUTPS0
T2CKPS1:T2CKPS0
1:1 to 1:16
Postscaler
TMR2 Output
(to PWM or MSSP)
T2CLK
FOSC/4
Set TMR2IF
1:1, 1:4, 1:16
Prescaler
Reset
TMR2
8
TMR2/PR2
Match
Comparator
8
PR2
8
Internal Data Bus
TMR2 se incrementa en 1 por cada ciclo de reloj T2CLK
Si TMR2 == PR2, TMR2 se resetea. Comparacin en cada
ciclo
T2CLK = Fosc/(4*m), m = valor del prescaler
Interrupcin TMR2 ocurre por cada n reseteos del TMR2,
n = valor del postscaler
Timers
20/39
Periodo del Timer 2
n
4
T2OUTPS3:T2OUTPS0
T2CKPS1:T2CKPS0
1:1 to 1:16
Postscaler
TMR2 Output
(to PWM or MSSP)
T2CLK
FOSC/4
Set TMR2IF
1:1, 1:4, 1:16
Prescaler
Reset
TMR2
8
TMR2/PR2
Match
Comparator
8
PR2
8
Internal Data Bus
TMR2 se incrementa cada
TT2CLK =
Timers
4m
s
Fosc
20/39
Periodo del Timer 2
n
4
T2OUTPS3:T2OUTPS0
T2CKPS1:T2CKPS0
1:1 to 1:16
Postscaler
TMR2 Output
(to PWM or MSSP)
T2CLK
FOSC/4
Set TMR2IF
1:1, 1:4, 1:16
Prescaler
Reset
TMR2
8
TMR2/PR2
Match
Comparator
8
PR2
8
Internal Data Bus
Para que llegue desde cero a PR2 (segn el comparador) se
necesitan
4m (PR2+1)
s
Fosc
Timers
20/39
Periodo del Timer 2
n
4
T2OUTPS3:T2OUTPS0
T2CKPS1:T2CKPS0
1:1 to 1:16
Postscaler
TMR2 Output
(to PWM or MSSP)
T2CLK
FOSC/4
Set TMR2IF
2
TMR2/PR2
Match
Reset
1:1, 1:4, 1:16
Prescaler
Comparator
TMR2
PR2
8
Internal Data Bus
Ejemplo: PR2=4
TMR2 out
TMR2
T2CLK
Comparaciones
Timers
20/39
Periodo del Timer 2
n
4
T2OUTPS3:T2OUTPS0
T2CKPS1:T2CKPS0
1:1 to 1:16
Postscaler
TMR2 Output
(to PWM or MSSP)
T2CLK
FOSC/4
Set TMR2IF
1:1, 1:4, 1:16
Prescaler
TMR2/PR2
Match
Reset
TMR2
Comparator
PR2
8
Internal Data Bus
Periodo de interrupciones del Timer 2
4mn (PR2+1)
s
Fosc
Timers
20/39
Ejemplo: Interrupcin TMR0
void interrupt HISR(){
if( TMR0IF ){
TMR0IF = 0;
LATC1 ^= 1;
}
}
void config(void){
TRISC1 = OUTPUT;
T0CONbits.T0PS = 7; // preescaler = 16
T08BIT = 0; // TMR0 de 16bits
// periodo = 16*4/(65535+1)
T0CS = 0; // reloj interno
PSA = 0; // usar preescaler
TMR0IE = 1; // act int timer0
IPEN = 0; // sin prioridad
TMR0ON = 1; // encender timer0
GIE = 1; //
act int. globales
}
Timers
21/39
Ejemplo: Interrupcin TMR2
void interrupt HISR(){
if( TMR2IF ){
TMR2IF = 0;
LATC1 ^= 1;
}
}
void config(void){
TRISC1 = OUTPUT;
T2CONbits.T2CKPS =
T2CONbits.T2OUTPS0
T2CONbits.T2OUTPS1
T2CONbits.T2OUTPS2
T2CONbits.T2OUTPS3
3; // preesc=16
= 1; // postsc=16
= 1; // postsc=16
= 1; // postsc=16
= 1; // postsc=16
PR2 = 255; // T=4*16*16*(255+1)/48e6
TMR2IE = 1; // act int timer2
IPEN = 0; // sin prioridad
TMR2ON = 1; // encender timer2
PEIE = 1; // act int. perifericos
GIE = 1; // act int. globales
}
Timers
22/39
Mdulos PWM
Mdulos PWM
23/39
Intro
El PIC18F4550 tiene dos mdulos PWM
Resolucin mxima de 10 bits en ciclo de trabajo
Resolucin de 8 bits para la frecuencia
Uno de ellos es un PWM con ms funciones
Se pueden configurar para otras funciones
Comparador
Captura de eventos
Pueden generar interrupciones
En modo PWM utilizan el Timer 2
Modo comparador se puede usar para generar frecuencia
variable
Mdulos PWM
24/39
Mdulo PWM simple
.
FIGURE 15-3:
SIMPLIFIED PWM BLOCK
DIAGRAM
Duty Cycle Registers
CCPxCON<5:4>
CCPRxH=CCPRxL
CCPRxH
CCPRxL
TMR2
PR2
CCPRxL
CCPRxH (Slave)
R
Comparator
TMR2
Comparator
PR2
(Note 1)
Q
CCPx
Output
Clear Timer,
CCPx pin and
latch D.C.
Corresponding
TRIS bit
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.
Mdulos PWM
t
Pin CCPx
1
0
25/39
Ciclo de trabajo
El periodo lo da el Timer 2, ver slide 20
El 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 resolucin
Por qu en la frmula no se usa
4 CCPRxL + CCPxCON<5:4>+1?
Notar que bajo operacin normal CCPRxL no debe ser
mayor a PR2, por qu?
Mdulos PWM
26/39
Configuracin
1. Escribir PR2 de acuerdo al periodo deseado, ver slide 20
2. Escribir CCPRxL y CCPxCON<5:4> ([Link]) de
acuerdo al ciclo de trabajo deseado
3. Configurar el pin CCPx, CCP1 = RC2, CCP2 = RC1
4. Configurar el preescalador del Timer2 y activar el timer,
ver slide 20
5. Configurar mdulo PWM
Si se usa CCP1, escribir 0 en CCP1CONbits.P1M (modo PWM
simple)
Escribir 0b11xx en [Link]
6. Orden no tan importante
Mdulos PWM
27/39
Ejemplo
void config(void){
TRISC2 = OUTPUT;
T2CONbits.T2CKPS = 3; // preesc=16
PR2 = 76; // T=4*16*(76+1)/48e6, aprox 10 kHz
TMR2ON = 1; // encender timer2
CCPR1L = 76/2; // aprox 50% duty
CCP1CONbits.P1M = 0; // modo PWM simple
CCP1CONbits.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;
}
}
}
Mdulos PWM
28/39
Tarea
Programar el microcontrolador para que genere
una seal sinusoidal (+ offset) usando el mdulo
PWM e interrupciones.
Mdulos PWM
29/39
Mdulo PWM mejorado
Mdulo PWM mejorado
30/39
Caractersticas
Generacin de seales complementarias (medio puente)
Generacin de banda muerta
Polaridad de seal configurable
Generacin de seales para puente H (4 transistores)
Se implementa solo en el mdulo CCP1
Mdulo PWM mejorado
31/39
Configuracin (I)
Configuracin es similar a modo PWM bsico,
adicionalmente se debe considerar:
Seleccionar modo mejorado escribiendo en
CCP1CONbits.P1M
P1M=1 Modo puente completo, P1D modulada, P1A
activa, P1B y P1C inactiva
P1M=2 Modo medio puente, P1A y P1B moduladas, con
banda muerta, P1C y P1D no usadas
P1M=3 Modo puente completo, P1B modulada, P1C
activa, P1A y P1D inactiva
Mdulo PWM mejorado
32/39
Configuracin (II)
Seleccionar polaridad escribiendo en
CCP1CONbits.CCP1M
CCP1M=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 banda
muerta escribiendo en ECCP1DEL
Mdulo PWM mejorado
33/39
Configuracin: Medio puente
Standard Half-Bridge Circuit (Push-Pull)
V+
PIC18FX455/X550
FET
Driver
+
V
-
P1A/RC2
Load
FET
Driver
+
V
-
P1B/RD5
V-
Mdulo PWM mejorado
34/39
Configuracin: Puente completo
FIGURE 16-7:
EXAMPLE OF FULL-BRIDGE APPLICATION
V+
PIC18FX455/X550
FET
Driver
QC
QA
FET
Driver
P1A/RC2
Load
P1B/RD5
FET
Driver
P1C/RD6
FET
Driver
QD
QB
VP1D/RD7
Mdulo PWM mejorado
35/39
Configuracin: Polaridad
FIGURE 16-2:
PWM OUTPUT RELATIONSHIPS (ACTIVE-HIGH STATE)
CCP1CON
<7:6>
00
(Single Output)
SIGNAL
PR2 + 1
Duty
Cycle
Period
P1A Modulated
Delay(1)
Delay(1)
P1A Modulated
10
(Half-Bridge)
P1B Modulated
P1A Active
01
(Full-Bridge,
Forward)
P1B Inactive
P1C Inactive
P1D Modulated
P1A Inactive
11
(Full-Bridge,
Reverse)
P1B Modulated
P1C Active
P1D Inactive
Mdulo PWM mejorado
36/39
Configuracin: Banda muerta
Period
Period
td = Dead-Band Delay
Duty Cycle
P1A(2)
Note 1: At this time, the TMR2 register is equal to the
PR2 register.
td
2: Output signals are shown as active-high.
td
P1B(2)
(1)
(1)
(1)
Tiempo de banda muerta es mltiplo de un ciclo de instruccin
Banda muerta [s] =
Mdulo PWM mejorado
4 ECCP1DEL
Fosc
37/39
Ejemplo: HB y DB (I)
void config(void){
TRISC2 = OUTPUT;
TRISD5 = OUTPUT;
T2CONbits.T2CKPS = 3; // preesc=16
PR2 = 76; // T=4*16*(76+1)/48e6, aprox 10 kHz
CCPR1L = 76/2; // aprox 50% duty
CCP1CONbits.P1M = 2; // modo PWM simple
CCP1CONbits.CCP1M = 0b1100; // modo PWM
ECCP1DEL = 100;
TMR2ON = 1; // encender timer2
}
Mdulo PWM mejorado
38/39
Ejemplo: HB y DB (II)
Mdulo PWM mejorado
39/39