Você está na página 1de 51

Licenciatura em Telecomunicações e

Informática

Arquitetura e Tecnologia de Computadores


interrupções

Paulo Cardoso
Grupo de Sistemas Embebidos
Departamento de Eletrónica Industrial
Escola de Engenharia
Universidade do Minho
Sumário

l Definições
l Caraterização
l Interrupções no 8051
l Configuração
l Operação
Interrupções
definição

l Interrupções
l Qualquer evento que interrompe a execução
normal do processador
l Externo ou interno ao processador
l Exemplos
l Lidar com um interruptor externo
l Receção de dados
l Polling
l Outra técnica de lidar com os eventos
l Ficar a aguardar que o evento ocorra
l O que fizemos até agora com os botões de pressão por
exemplo
Interrupções
definição

l Tipos de interrupções
l Interrupções de hardware
l Eventos externos (através da ativação de pinos do
processador ou através dos periféricos)
l Traps
l Eventos causados pelo programador (síncronos)
l Através de uma instrução própria do ISA
l Não existem na família 8051
l Exceções
l Eventos causadas pela execução “ilegal” do código
l Exemplo: divisão por zero, page fault
l Não existem na família MSC51
Interrupções
caraterização

l Fases
l O programa está a executar (A)
l É gerada a interrupção (B)
l Sinal externo num pino do micro ou periférico
l Pedindo a atenção ao processador
l Através da lógica interna do hardware do processador
l Programa em execução é suspenso
l Rotina de atendimento à interr. é executada (C)
l Também designadas por ISR (Interrupt Service Routine)
l ISR termina (D)
l Programa em execução é retomado (E)
Interrupções
caraterização

l Caraterização – graficamente
programa
(A) em execução
Endereço da próxima
instrução interrompida é
guardado na pilha
(B) Interrupção

Rotina de
atendimento da
(C) interrupção
(ISR)

(D) Retorno

(E) Endereço da próxima


instrução é removida da
programa pilha e colocada no
em execução Program Counter
Interrupções
caraterização

l Podemos usar a seguinte analogia


l Estamos a ver um filme em streaming (A)
l Toca a campainha (B)
l Paramos o filme
l Vamos atender quem chegou (C)
l A nossa “ISR”
l Fechamos a porta e voltamos para o sofá (D)
l Retomamos o filme (E)
Interrupções
caraterização

l Caraterização – suspensão da execução


l Quando surge um sinal de interrupção
l O CPU interrompe a instrução atual?
l NÃO!!!
l No ciclo de funcionamento fetch-decode-execute
l Após o EXECUTE o CPU verifica se surgiu uma interrupção
l No seu sistema interno de deteção de interrupções
l No caso de arquiteturas pipelined a coisa complica-se...
l Se as interrupções estiverem desativadas
l Através da configuração de registos
l Não há interrupção da execução atual e salto para a ISR...
l Podemos verificar a flag de interrupção por polling
l Como fizemos com o timer
l while (!TF0)
Interrupções
caraterização

l Caraterização – atendimento à interrupção


l Interrupção vetorizada
l Diferentes interrupções (externa, timer, porta série...)
l O processador salta para a respetiva posição de memória
(vetores de interrupção)
l Definidos por hardware
l Executando o código que aí se encontra (ISR)

l Interrupção não vetorizada


l Existe apenas um vetor
l O processador salta sempre para a mesma posição
l A ISR necessita descobrir a fonte de interrupção
l Acede a registos específicos
l Pode então executar o código apropriado para lidar com a interrupção
Interrupções
interrupções no 8051

l Interrupção no 8051
l Não são um “periférico”
l São um mecanismo que existe em qualquer processador
l No entanto, tal como nos periféricos
l A utilização das interrupções
l Está dividida em duas partes
l Configuração
l Parametrizadas através de registos de configuração (SFRs)
l Operação
l Envolve também manipulação de bits de SFRs
Interrupções
interrupções no 8051

l Fontes de interrupção no 8051


l Pinos externos
l Int0 (P3.2)
l Int1 (P3.3)
l Periféricos
l Timer 0
l Timer1
l Porta série
l Outros membros da família podem ter fontes
adicionais
Interrupções
interrupções no 8051

l FontesC8051F388/9/A/B
de interrupção no C8051F388
l Compatíveis com o 8051 Table 16.1. Interrupt Summary
Interrupt Source Interrupt Priority Pending Flag Enable Priority

Address?

by HW?
Cleared
Vector Order Flag Control

Bit
Reset 0x0000 Top None N/A N/A Always Always
Enabled Highest
External Interrupt 0 0x0003 0 IE0 (TCON.1) Y Y EX0 (IE.0) PX0 (IP.0)
(INT0)
Timer 0 Overflow 0x000B 1 TF0 (TCON.5) Y Y ET0 (IE.1) PT0 (IP.1)
External Interrupt 1 0x0013 2 IE1 (TCON.3) Y Y EX1 (IE.2) PX1 (IP.2)
(INT1)
Timer 1 Overflow 0x001B 3 TF1 (TCON.7) Y Y ET1 (IE.3) PT1 (IP.3)
UART0 0x0023 4 RI0 (SCON0.0) Y N ES0 (IE.4) PS0 (IP.4)
TI0 (SCON0.1)
Timer 2 Overflow 0x002B 5 TF2H (TMR2CN.7) Y N ET2 (IE.5) PT2 (IP.5)
TF2L (TMR2CN.6)

l Outras fontes
SPI0 0x0033 6 SPIF (SPI0CN.7)
WCOL (SPI0CN.6)
MODF (SPI0CN.5)
Y N ESPI0
(IE.6)
PSPI0
(IP.6)

l ... SMB0 0x003B 7


RXOVRN (SPI0CN.4)
SI (SMB0CN.0) Y N ESMB0 PSMB0
(EIE1.0) (EIP1.0)
Reserved 0x0043 8 N/A N/A N/A N/A N/A
ADC0 Window Com- 0x004B 9 AD0WINT Y N EWADC0 PWADC0
pare (ADC0CN.3) (EIE1.2) (EIP1.2)
ADC0 Conversion 0x0053 10 AD0INT (ADC0CN.5) Y N EADC0 PADC0
Complete (EIE1.3) (EIP1.3)
Interrupções
configuração no 8051

l Fontes de interrupção no 8051


l Configuração
l 1. Priorização da interrupções (se necessário)
l 2. Configuração de interrupções externas ao micro (se
necessário)
l 3. Ativação/desativação das interrupções
Interrupções
configuração no 8051

l 1. Priorização da interrupções
l Pode ser alterada a prioridade de uma interrupção
l Alta prioridade ou baixa prioridade
l Uma interrupção de alta prioridade pode interromper outra de
baixa prioridade
l Por defeito todas têm a mesma prioridade
Bit 7 6 5 4 3 2 1 0

Interrupções Name

Type R
PSPI0

R/W
PT2

R/W
PS0

R/W
PT1

R/W
PX1

R/W
PT0

R/W
PX0

R/W
configuração no 8051 Reset 1 0 0 0 0 0 0 0
C8051F388/9/A/B
SFR Address = 0xB8; SFR Page = All Pages; Bit-Addressable
Bit Name Function

l 1. Priorização da interrupções
7

SFR
Unused
6 Definition
PSPI0 Serial
Read = 1b, Write = Don't Care.

16.2. Peripheral Interface


IP: Interrupt (SPI0) Interrupt Priority Control.
Priority

Registo IP
This bit sets the priority of the SPI0 interrupt.
0: SPI0 interrupt set to low priority level.
l Bit 7 6 5 4 3 2 1 0
1: SPI0 interrupt set to high priority level.
Name
5 PT2 PSPI0
Timer 2 InterruptPT2 PS0
Priority Control. PT1 PX1 PT0 PX0

Type R This bit


R/Wsets the priority
R/W of the R/W Timer 2 interrupt.
R/W R/W R/W R/W
0: Timer 2 interrupt set to low priority level.
Reset 1 1: Timer0 2 interrupt 0set to high priority
0 level. 0 0 0 0

SFR
4 Address
PS0= 0xB8; SFR Interrupt
UART0 Page = AllPriority
Pages;Control.
Bit-Addressable
Bit Name This bit sets the priority of the UART0 interrupt. Function
7 0: UART0
Unused Read = 1b,interrupt set toCare.
Write = Don't low priority level.
1: UART0 interrupt set to high priority level.
6 PSPI0 Serial Peripheral Interface (SPI0) Interrupt Priority Control.
3 PT1 Timer 1 Interrupt Priority Control.
This bit sets the priority of the SPI0 interrupt.
This
0: bit interrupt
SPI0 sets the priority of the
set to low Timer
priority 1 interrupt.
level.
0: Timer 1 interrupt set to low priority
1: SPI0 interrupt set to high priority level. level.
1: Timer 1 interrupt set to high priority level.
5 PT2 Timer 2 Interrupt Priority Control.
2 PX1 External Interrupt 1 Priority Control.
This bit sets the priority of the Timer 2 interrupt.
This bit sets
0: Timer the priority
2 interrupt set tooflowthepriority
External Interrupt 1 interrupt.
level.
0: Timer
1: External Interruptset
2 interrupt 1 set to low
to high priority
priority level.
level.
1: External Interrupt 1 set to high priority level.
4 PS0 UART0 Interrupt Priority Control.
1 PT0 Timer 0 Interrupt Priority Control.
This bit sets the priority of the UART0 interrupt.
This
0: bit sets
UART0 the priority
interrupt set tooflowthepriority
Timer 0level.
interrupt.
0: Timer 0 interrupt set to low priority
1: UART0 interrupt set to high priority level. level.
1: Timer 0 interrupt set to high priority level.
3 PT1 Timer 1 Interrupt Priority Control.
0 PX0 External Interrupt 0 Priority Control.
This bit sets the priority of the Timer 1 interrupt.
This bit sets
0: Timer the priority
1 interrupt set tooflowthepriority
External Interrupt 0 interrupt.
level.
0: Timer
1: External Interruptset
1 interrupt 0 set to low
to high priority
priority level.
level.
1: External Interrupt 0 set to high priority level.
2 PX1 External Interrupt 1 Priority Control.
Interrupções
configuração no 8051

l 1. Priorização da C8051F388/9/A/B
interrupções
l Se as interrupções têm a mesma prioridade Table 16.1. Interrupt Summary

O hardware atendeInterrupt
primeiro
Source
de acordo
Interrupt Priority
com a tabelaEnable
Pending Flag

Address?

by HW?
Cleared
l Vector Order Flag

Bit
l Na verdade funciona como uma priorização
Reset 0x0000 Top None N/A N/A Always
Enabled
External Interrupt 0 0x0003 0 IE0 (TCON.1) Y Y EX0 (IE.0)
(INT0)
Timer 0 Overflow 0x000B 1 TF0 (TCON.5) Y Y ET0 (IE.1)
External Interrupt 1 0x0013 2 IE1 (TCON.3) Y Y EX1 (IE.2)
(INT1)
Timer 1 Overflow 0x001B 3 TF1 (TCON.7) Y Y ET1 (IE.3)
UART0 0x0023 4 RI0 (SCON0.0) Y N ES0 (IE.4)
TI0 (SCON0.1)
Timer 2 Overflow 0x002B 5 TF2H (TMR2CN.7) Y N ET2 (IE.5)
TF2L (TMR2CN.6)
SPI0 0x0033 6 SPIF (SPI0CN.7) Y N ESPI0
WCOL (SPI0CN.6) (IE.6)
MODF (SPI0CN.5)
RXOVRN (SPI0CN.4)
SMB0 0x003B 7 SI (SMB0CN.0) Y N ESMB0
(EIE1.0)
Reserved 0x0043 8 N/A N/A N/A N/A
ADC0 Window Com- 0x004B 9 AD0WINT Y N EWADC0
pare (ADC0CN.3) (EIE1.2)
ADC0 Conversion 0x0053 10 AD0INT (ADC0CN.5) Y N EADC0
Complete (EIE1.3)
Interrupções
configuração no 8051

l 2. Configuração de interrupções externas


l Pinos específicos (dois) do micro podem ser
configurados para gerar interrupções
l INT0 e INT1
l Estes pinos podem funcionar de duas formas
l Sensíveis ao nível
l Sensíveis à transição
Interrupções
caraterização

l Caraterização - Sinal externo de interrupção


l Sensível ao nível (level) Como o sinal se mantém “low” a rotina
de interrupção é novamente chamada
INT

programa rotina de rotina de programa


interrupção RETI interrupção RETI

l Sensível à transição (edge)


Como não há nova transição, a rotina
de interrupção é mais chamada

INT

programa rotina de programa


interrupção RETI
Interrupções
Bit 7 6 5 4 3 2 1 0

NameDefinition
SFR TF1 25.3.
TR1 TF0 Control
TCON: Timer TR0 IE1 IT1 IE0 IT0

configuração no 8051
Type
Bit
R/W
7
R/W
6
R/W
5
R/W
4
R/W
3
R/W
2
R/W
1
R/W
0
Reset 0 0 0 0 0 0 0 0
Name TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
SFR Address = 0x88; SFR Page = All Pages; Bit-Addressable

2. Configuração de interrupções externas


Type Name
Bit R/W R/W R/W R/W R/W
Function R/W R/W R/W
7
Reset TF1
0 Timer0 1 Overflow0 Flag. 0 0 0 0 0
l
Set to 1 by hardware when Timer 1 overflows. This flag can be cleared by software
SFR Address = 0x88;but
SFR Page = All Pages;
is automatically Bit-Addressable
cleared when the CPU vectors to the Timer 1 interrupt service

l É necessário definir se são edge ou level triggered


Bit
7
6
Name
TF1
TR1
routine.
Timer 1 RunOverflow Flag.
Control.
Function

Set to 11 is
Timer byenabled
hardware
bywhen Timer
setting 1 overflows.
this bit to 1. This flag can be cleared by software
l INT0, INT1
5 TF0
but is automatically cleared when the CPU vectors to the Timer 1 interrupt service
Timer 0 Overflow Flag.
routine. C8051F388/9/A/B
Set to 1 by hardware when Timer 0 overflows. This flag can be cleared by software
6 TR1 Timer 1 Run Control.
but is automatically cleared when the CPU vectors to the Timer 0 interrupt service
Timer
routine.1 is enabled by setting this bit to 1.
5
4 TF0
TR0 Timer 0 Overflow
Run Control. Flag.
SFR Definition 25.3.
Set toTCON:
Timer 01 is Timer
byenabled
hardware Control
bywhen Timer
setting 0 overflows.
this bit to 1. This flag can be cleared by software
but is automatically cleared when the CPU vectors to the Timer 0 interrupt service
3 IE1 External Interrupt 1.
routine.
Bit 7 6 is set by5hardware when
This flag 4 an edge/level 3 of type2 defined by 1IT1 is detected.
0 It
4 TR0 Timer 0 Run Control.
can be cleared by software but is automatically cleared when the CPU vectors to the
Name TF1 TR1
Timer 0 isInterrupt TF0by settingTR0
enabled 1.IE1
this bitintoedge-triggered IT1 IE0 IT0
External 1 service routine mode.
3
Type
2 IE1
R/W
IT1 External
R/W Interrupt
Interrupt 1 Type R/W 1.
Select. R/W R/W R/W R/W R/W
This flag
bit is set by hardware when an edge/level of type defined by IT1 is detected. It
Reset 0 0 selects whether0 the configured
0 INT1
0 interrupt will
0 be edge 0 or level sensitive.
0
can be cleared by software but is automatically cleared when the CPU
INT1 is configured active low or high by the IN1PL bit in the IT01CF register (see vectors to the
SFR Address = 0x88;External
SFR Interrupt
SFRDefinition
Page 1 service
16.7).
= All Pages; routine in edge-triggered mode.
Bit-Addressable
Bit
2 Name
IT1 0: INT1 is 1level
Interrupt Typetriggered.
Select. Function
7 TF1 1: INT1
This bit is edge
selects triggered.
whether
Timer 1 Overflow Flag. the configured INT1 interrupt will be edge or level sensitive.
1 IE0 INT1
Set tois1configured
External byInterrupt
hardware active
0. whenlow or high
Timer by the IN1PL
1 overflows. Thisbit in can
flag the be
IT01CF register
cleared (see
by software
SFR
This Definition
but isflag 16.7).
automatically cleared when the
is set by hardware CPU vectors
an edge/level to the
of type Timer by
defined 1 interrupt service It
IT1 is detected.
0: INT1
routine.
can is level by
be cleared triggered.
software but is automatically cleared when the CPU vectors to the
1: INT1 isInterrupt
External edge triggered.
0 service routine in edge-triggered mode.
6 TR1 Timer 1 Run Control.
1
0 IE0
IT0 External
Interrupt
Timer Interrupt
1 is 0enabled 0. setting this bit to 1.
Type Select.
by
This flag is set by
bit0selects hardware
whether when an edge/level of type defined by IT1 is detected. It
5 TF0 Timer Overflow Flag.the configured INT0 interrupt will be edge or level sensitive.
can be
INT0 is cleared
configuredby software butorishigh
active low automatically cleared
by the IN0PL bit inwhen theIT01CF
register CPU vectors to the
(see SFR
Set to 1 by
External hardware when Timer 0 overflows. This flag can be cleared by software
DefinitionInterrupt
16.7). 0 service routine in edge-triggered mode.
but is automatically cleared when the CPU vectors to the Timer 0 interrupt service
0 IT0 0: INT0 is level triggered.
Interrupt
routine. 0 Type Select.
1: INT0
This is edge whether
bit selects triggered.
the configured INT0 interrupt will be edge or level sensitive.
Interrupções
configuração no 8051

l 2. Configuração de interrupções externas


l INT0, INT1
l No C8051F388 é possível fazer configurações adicionais
l No registo IT01CF (SFR 0xE4, Page 0)
l É possível definir se as interrupções externas são ativas a high ou
low (valor por defeito)
l É possível definir outros pinos para as interrupções externas
Interrupções
configuração no 8051

l 3a. Ativação/desativação das interrupções


como um todo (“interruptor geral”)
l Registo IE, flag EA
C8051F388/9/A/B

SFR Definition 16.1. IE: Interrupt Enable

Bit 7 6 5 4 3 2 1 0

Name EA ESPI0 ET2 ES0 ET1 EX1 ET0 EX0

Type R/W R/W R/W R/W R/W R/W R/W R/W

Reset 0 0 0 0 0 0 0 0

SFR Address = 0xA8; SFR Page = All Pages; Bit-Addressable


Bit Name Function
7 EA Enable All Interrupts.
Globally enables/disables all interrupts. It overrides individual interrupt mask settings.
0: Disable all interrupt sources.
1: Enable each interrupt according to its individual mask setting.
6 ESPI0 Enable Serial Peripheral Interface (SPI0) Interrupt.
This bit sets the masking of the SPI0 interrupts.
0: Disable all SPI0 interrupts.
1: Enable interrupt requests generated by SPI0.
Name EA ESPI0 ET2 ES0 ET1 EX1 ET0 EX0

Interrupções Type

Reset
R/W

0
R/W

0
R/W

0
R/W

0
R/W

0
R/W

0
R/W

0
R/W

0
configuração no 8051 SFR Address = 0xA8; SFR Page = All Pages; Bit-Addressable
Bit Name Function
7 EA Enable All Interrupts. C8051F388/9/A/B
3b. Ativação de interrupções específicas
Globally enables/disables all interrupts. It overrides individual interrupt mask settings.
0: Disable all interrupt sources.
l 1: Enable each interrupt according to its individual mask setting.

Registo IE
6 Definition
SFR ESPI0 Enable
16.1. Serial Peripheral
IE: Interrupt Interface (SPI0) Interrupt.
Enable
l This bit sets the masking of the SPI0 interrupts.
0: Disable all SPI0 interrupts.
Bit 7 6 5 4 3 2 1 0
1: Enable interrupt requests generated by SPI0.
Name EA ESPI0 ET2 ES0 ET1 EX1 ET0 EX0
5 ET2 Enable Timer 2 Interrupt.
Type R/W This bitR/W
sets the masking
R/W of theR/W Timer 2 interrupt.
R/W R/W R/W R/W
0: Disable Timer 2 interrupt.
Reset 0 0 0 0 0 0 0 0
1: Enable interrupt requests generated by the TF2L or TF2H flags.
SFR
4 Address
ES0 = 0xA8; SFRUART0
Enable Page =Interrupt.
All Pages; Bit-Addressable
Bit Name This bit sets the masking of the UART0Function
interrupt.
7 EA 0: Disable
Enable AllUART0 interrupt.
Interrupts.
1: Enable UART0 interrupt.
Globally enables/disables all interrupts. It overrides individual interrupt mask settings.
3 ET1 0: Disable
Enable all interrupt
Timer sources.
1 Interrupt.
This bit sets the maskingaccording
1: Enable each interrupt to its
of the Timer individual mask setting.
1 interrupt.
6 ESPI0 0: Disable
Enable all Timer
Serial 1 interrupt.
Peripheral Interface (SPI0) Interrupt.
1: Enable interrupt requests
This bit sets the masking of thegenerated by the TF1 flag.
SPI0 interrupts.
2 EX1 0: Disable
Enable all SPI0Interrupt
External interrupts.
1.
1: Enable
This interrupt
bit sets requests
the masking generated
of External by SPI0.
Interrupt 1.
5 ET2 0: Disable
Enable external
Timer interrupt 1.
2 Interrupt.
1: Enable interrupt requests generated
This bit sets the masking of the Timer 2by the INT1 input.
interrupt.
1 ET0 0: Disable
Enable Timer
Timer 2 interrupt.
0 Interrupt.
1: Enable
This interrupt
bit sets requests
the masking generated
of the Timer 0by the TF2L or TF2H flags.
interrupt.
4 ES0 0: Disable
Enable all Timer
UART0 0 interrupt.
Interrupt.
1: Enable interrupt requests generated
This bit sets the masking of the UART0 by the TF0 flag.
interrupt.
0 EX0 0: Disable
Enable UART0Interrupt
External interrupt.0.
1: Enable
This UART0
bit sets interrupt.
the masking of External Interrupt 0.
3 ET1 0: Disable
Enable external
Timer interrupt 0.
1 Interrupt.
1: Enable interrupt requests generated
This bit sets the masking of the Timer 1by the INT0 input.
interrupt.
Interrupções
configuração no 8051

l Ativação de interrupções
l Para ativar as interrupções deve-se executar 3b. e
depois 3a.
Interrupções
operação no 8051

l Fontes de interrupção no 8051


l Operação
l Cada fonte de interrupção tem uma flag de interrupção
pendente (em SFRs)
l Essas flags são bits de registos do micro
l Exemplo: A flag TF0 sinaliza o transbordo do timer 0
l É um bit do registo TCON C8051F388/9/A/B

SFR Definition 25.3. TCON: Timer Control

Bit 7 6 5 4 3 2 1 0

Name TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0

Type R/W R/W R/W R/W R/W R/W R/W R/W

Reset 0 0 0 0 0 0 0 0

SFR Address = 0x88; SFR Page = All Pages; Bit-Addressable


Bit Name Function
7 TF1 Timer 1 Overflow Flag.
Interrupções
operação no 8051

l Fontes de interrupção no 8051


l Operação
l Cada fonte de interrupção tem uma flag de interrupção
pendente (em SFRs)
l Quando surge um evento (de pino externo ou periférico)
l A respetiva flag de interrupção pendente é colocada a 1
(sinalizando ao processador o pedido de interrupção)
l O processador salta para a ISR
l Portanto, uma chamada de interrupção pode ser considerada uma
invocação assíncrona de uma função
l O que acontece se as interrupções não estiverem ativas?
l O A ISR não é invocada
l A flag é na mesma colocada 1
l Podendo assim o evento ser monitorizado por polling
l Exemplo: “while (!TF0)”: polling à flag TF0 do Timer0
Interrupções
operação no 8051

l Flags ativadas pelas interrupções


C8051F388/9/A/B
C8051F388/9/A/B
l Timers C8051F388/9/A/B
SFR Definition 25.3. TCON: Timer Control
l Registo TCON, bits TF0 e TF1
SFR Definition 25.3. TCON: Timer Control
Bit 7 6 5 4 3 2 1 0
SFR Definition 25.3. TCON: Timer Control
Name TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
Bit 7 6 5 4 3 2 1 0
Type
Bit R/W
7 R/W
6 R/W
5 R/W
4 R/W
3 R/W
2 R/W
1 R/W
0
Name TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
Reset
Name 0
TF1 0
TR1 0
TF0 0
TR0 0
IE1 0
IT1 0
IE0 0
IT0
Type R/W R/W R/W R/W R/W R/W R/W R/W
SFR
TypeAddress = 0x88; SFR
R/W R/W Page = AllR/W Pages; Bit-Addressable
R/W R/W R/W R/W R/W
Reset 0 0 0 0 0 0 0 0
Bit Name Function
Reset 0 0 0 0 0 0 0 0
SFR
7 Address
TF1= 0x88;Timer
SFR Page 1 Overflow
= All Pages;
Flag. Bit-Addressable
Bit Address
SFR Name= 0x88;Set
SFR to Page
1 by hardware when
= All Pages; FunctionThis flag can be cleared by software
Timer 1 overflows.
Bit-Addressable
Bit
7 Name
TF1 but is automatically
Timer 1 Overflow Flag. cleared when the CPU vectors to the Timer 1 interrupt service
Function
routine.
7 TF1 Set
Timer to 1 by hardware
Overflow when Timer 1 overflows. This flag can be cleared by software
Flag.
6 TR1 Timer
but is
Set 11 by
Run Control.
to automatically
hardware cleared when 1the
when Timer CPU vectors
overflows. This to thecan
flag Timer 1 interrupt
be cleared service
by software
routine.
Timer
but 1 is enabled by
is automatically settingwhen
cleared this bit
thetoCPU
1. vectors to the Timer 1 interrupt service
6
5 TR1
TF0 routine.
Timer 0
Timer 1 Overflow
Run Control.Flag.
6 TR1 Timer
Timer 1 1 is enabled
Run
Set to by hardware bywhen
Control. setting this bit
Timer to 1.
0 overflows. This flag can be cleared by software
5 TF0 but is automatically
Timer
Timer 10 is cleared
enabled Flag.
Overflow by settingwhen thetoCPU
this bit 1. vectors to the Timer 0 interrupt service
routine.
5 TF0 Set to 10 by
Timer hardware
Overflow when Timer 0 overflows. This flag can be cleared by software
Flag.
4 TR0 Timer
but is 0 Run Control.
automatically cleared
Set to 1 by hardware when Timer when 0the CPU vectors
overflows. This to thecan
flag Timer 0 interrupt
be cleared service
by software
routine.
Timer 0 is enabled by
but is automatically settingwhen
cleared this bit
thetoCPU
1. vectors to the Timer 0 interrupt service
4
3 TR0
IE1 routine.
Timer 0 Run Control.
External Interrupt 1.
4 TR0 Timer
Timer
This 00 is
flag isenabled
Run by settingwhen
setControl.
by hardware this bit
anto 1.
edge/level of type defined by IT1 is detected. It
3 IE1 can
Timer be
External cleared by
0 isInterrupt software
enabled by but is automatically
1. setting this bit to 1. cleared when the CPU vectors to the
Interrupções
Name TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0

Type R/W R/W R/W R/W R/W R/W R/W R/W


SFR Definition 25.3. TCON: Timer Control
operação no 8051 Reset 0 0 0

BitAddress 7= 0x88; SFR6 Page = All 5Pages; Bit-Addressable


4
0

3
0 0

2 1
0

0
0

SFR
Bit Name Function
Name TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
7 TF1 Timer 1 Overflow Flag.

l Flags ativadas pelas interrupções


Type

Reset
R/W

0
SetR/W
to 1 by hardware
but is0automatically
routine.
R/W when Timer R/W 1 overflows.

0 cleared when
R/W This flag

0 the CPU0 vectors to the


R/Wcan be cleared
R/W by software

0 Timer 1 interrupt
0
R/W
service
0

l INT0, INT1 (interrupções externas)


SFR
6 Address
Bit
TR1= 0x88;Timer
Name
SFR Page
1 Run=Control.
C8051F388/9/A/B
All Pages; Bit-Addressable
Timer 1 is enabled by setting this bit to 1.
Function
7 TF1 Timer 1 Overflow Flag.

Registo TCON, bits IE0 e IE1


5 TF0 Timer 0 Overflow Flag.
Set to 1 by hardware when Timer 1 overflows. This flag can be cleared by software
l Set to 1 by hardware when Timer 0 overflows. This flag can be cleared by software
but is automatically cleared when the CPU vectors to the Timer 1 interrupt service
but is automatically cleared when the CPU vectors to the Timer 0 interrupt service
routine.
SFR Definition 25.3. TCON: Timer Control
routine.
6 TR1 Timer 1 Run Control.
4 TR0 Timer 0 Run Control.
Timer 1 is enabled by setting this bit to 1.
Bit 7 Timer60 is enabled 5 by setting this
4 bit to 1. 3 2 1 0
5 TF0 Timer 0 Overflow Flag.
3 IE1 External Interrupt 1.
Name TF1 Set TR1
to 1 by hardwareTF0 when Timer TR0 0 overflows. IE1 This flag IT1can be cleared
IE0 by softwareIT0
This flag is set by hardware when an edge/level of type defined by IT1 is detected. It
Type R/W but R/W
is automatically R/W cleared when the CPU
R/Wis automatically
R/W vectors toR/W the Timer 0 interrupt service
can be cleared by software but cleared when the R/W CPU vectorsR/W to the
routine.
External Interrupt 1 service routine in edge-triggered mode.
Reset
4 TR00 Timer0 0 Run Control. 0 0 0 0 0 0
2 IT1 Interrupt 1 Type Select.
SFR Address = 0x88;Timer
SFRbit0Page
This
is enabled
selects= All by setting
Pages;
whether
this bit to 1.
Bit-Addressable
the configured INT1 interrupt will be edge or level sensitive.
Bit
3 Name
IE1 External Interrupt active
INT1 is configured 1. low or high by Function
the IN1PL bit in the IT01CF register (see
7 TF1 SFR
This
Timer Definition
flag 16.7).
is set by hardware
1 Overflow Flag. when an edge/level of type defined by IT1 is detected. It
0: INT1
can
Set to is
bylevel
be1cleared triggered.
by
hardware software
when but is automatically
Timer 1 overflows. This cleared
flag when
can bethe CPU vectors
cleared to the
by software
External
1: INT1
but isInterrupt 1 cleared
service routine
edge triggered.
is automatically when the in edge-triggered
CPU vectors tomode. the Timer 1 interrupt service
2
1 IT1
IE0 routine.
Interrupt 1 Type Select.
External Interrupt 0.
6 TR1 This
Timer bit1selects
Run Control.
whether
flag is set by hardware the configured INT1 interrupt
when an edge/level of type will be edge
defined by or
IT1level sensitive.It
is detected.
INT1 is configured
can be1cleared
Timer active
by software
is enabled low
by setting or
but high by the
is automatically
this bit to 1. IN1PL bit in the IT01CF register
cleared when the CPU vectors (see
to the
SFR Definition 16.7).
External Interrupt 0 service routine in edge-triggered mode.
5 TF0 Timer 0 Overflow Flag.
0 IT0 0: INT1 is 0level
Interrupt Typetriggered.
Select.
Set to 1 is
1: INT1 byedge
hardware when Timer 0 overflows. This flag can be cleared by software
triggered.
This bit selects whether
but is automatically cleared the when
configured
the CPU INT0vectors
interrupt will Timer
to the be edge or level sensitive.
0 interrupt service
1 IE0 External
INT0 is
routine. Interrupt
configured 0.
active low or high by the IN0PL bit in register IT01CF (see SFR
Definition
This flag is16.7).
setControl.
by hardware when an edge/level of type defined by IT1 is detected. It
4 TR0 Timer 0 Run
0: INT0
can is level by
be cleared triggered.
software but is automatically cleared when the CPU vectors to the
Timer
External
1: INT0 0 is
isInterrupt
enabled
edge 0by settingroutine
service
triggered. this bitintoedge-triggered
1. mode.
Interrupções
operação no 8051

l Resumindo...
C8051F388/9/A/B

l Repetindo um slide anterior Table 16.1. Interrupt Summary


Interrupt Source Interrupt Priority Pending Flag Enable Priority

Address?

by HW?
Cleared
Vector Order Flag Control

Bit
Reset 0x0000 Top None N/A N/A Always Always
Enabled Highest
External Interrupt 0 0x0003 0 IE0 (TCON.1) Y Y EX0 (IE.0) PX0 (IP.0)
(INT0)
Timer 0 Overflow 0x000B 1 TF0 (TCON.5) Y Y ET0 (IE.1) PT0 (IP.1)
External Interrupt 1 0x0013 2 IE1 (TCON.3) Y Y EX1 (IE.2) PX1 (IP.2)
(INT1)
Timer 1 Overflow 0x001B 3 TF1 (TCON.7) Y Y ET1 (IE.3) PT1 (IP.3)
UART0 0x0023 4 RI0 (SCON0.0) Y N ES0 (IE.4) PS0 (IP.4)
TI0 (SCON0.1)
...
Timer 2 Overflow 0x002B 5 TF2H (TMR2CN.7)
TF2L (TMR2CN.6)
Y N ET2 (IE.5) PT2 (IP.5)

SPI0 0x0033 6 SPIF (SPI0CN.7) Y N ESPI0 PSPI0


WCOL (SPI0CN.6) (IE.6) (IP.6)
MODF (SPI0CN.5)
RXOVRN (SPI0CN.4)
SMB0 0x003B 7 SI (SMB0CN.0) Y N ESMB0 PSMB0
(EIE1.0) (EIP1.0)
Reserved 0x0043 8 N/A N/A N/A N/A N/A
ADC0 Window Com- 0x004B 9 AD0WINT Y N EWADC0 PWADC0
pare (ADC0CN.3) (EIE1.2) (EIP1.2)
ADC0 Conversion 0x0053 10 AD0INT (ADC0CN.5) Y N EADC0 PADC0
Complete (EIE1.3) (EIP1.3)
Interrupções
operação no 8051

l As ISR (Interrupt Service Routine)


l São funções em C invocadas assincronamente
l Sempre que há uma interrupção (e desde que ativadas)
l Cada fonte de interrupção poderá ter a sua ISR
l Fontes de interrupção
3.8. INTERRUPT SERVICE ROUTINES CHAPTER 3. USING SDCC

Interrupt # Description Vector Address


0 External 0 0x0003
1 Timer 0 0x000b
2 External 1 0x0013
3 Timer 1 0x001b
4 Serial 0x0023
5 Timer 2 (8052) 0x002b
... ...
n 0x0003 + 8*n

If the interrupt service routine is defined without __using a register bank or with register bank 0 (__using 0), the

Este conceito não existe na programação desktop


compiler will save the registers used by itself on the stack upon entry and restore them at exit, however if such an
l interrupt service routine calls another function then the entire register bank will be saved on the stack. This scheme
may be advantageous for small interrupt service routines which have low register usage.

Nem sequer existe o conceito de interrupção


If the interrupt service routine is defined to be using a specific register bank then only a, b, dptr & psw are saved
l and restored, if such an interrupt service routine calls another function (using another register bank) then the entire
register bank of the called function will be saved on the stack. This scheme is recommended for larger interrupt
service routines.

3.8.3 HC08 Interrupt Service Routines


Interrupções
operação no 8051

l As ISR
l São funções em C com um protótipo específico
void nomeFunc (void) __interrupt (#interrupt ) [__using (#banco)]

l __interrupt
l Indica qual a interrupção a ISR diz respeito
l E.g.:
3.8. void
INTERRUPT timer0_isr
SERVICE ROUTINES (void) __interrupt
CHAPTER 3. USING SDCC (1)

Interrupt # Description Vector Address


0 External 0 0x0003
1 Timer 0 0x000b
2 External 1 0x0013
3 Timer 1 0x001b
4 Serial 0x0023
5 Timer 2 (8052) 0x002b
... ...
n 0x0003 + 8*n

l __using
If the interrupt service routine is defined without __using a register bank or with register bank 0 (__using 0), the
compiler will save the registers used by itself on the stack upon entry and restore them at exit, however if such an
l permite alterar o banco de registos a usar
interrupt service routine calls another function then the entire register bank will be saved on the stack. This scheme
may be advantageous for small interrupt service routines which have low register usage.
If the interrupt service routine is defined to be using a specific register bank then only a, b, dptr & psw are saved
Não vamos usar nas aulas
and lrestored, if such an interrupt service routine calls another function (using another register bank) then the entire
register bank of the called function will be saved on the stack. This scheme is recommended for larger interrupt
Interrupções
operação no 8051

l Exemplo
#include <c8051f380.h>
char p2_digits[10] = {0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8, 0x80, 0x98};

volatile signed char total_half_secs = 0;// Numero total de meios segundos contados
volatile char cycle_cnt = 0;

void init_timer0();
void toggle_p27_half_second();
void display_time(char time);

// ISR configura o timer 0;


// Sempre que cycle_cnt==4 foi contado meio segundo
void timer0_isr (void) __interrupt (1) {

//Faz qualquer coisa...


}
Interrupções
operação no 8051

l Exemplo (cont.)

void init_timer0(void) {
CKCON |= 0x02; // Divide clk por 48 => T=2us
TMOD |= 0x01; // Modo 16 bits
ET0 = 1; // Ativa interrupcao do timer 0

TH0 = 0; // Inicializa reg de contagem


TL0 = 0; // Inicializa reg de contagem
cycle_cnt = 0;
total_half_secs = 0;
}

void start_timer0(void) {
TR0 = 1; // Inicia contagem
}

void stop_timer0(void) {
TR0 = 0; // Para contagem
}
Interrupções
operação no 8051

l Ao desenhar as ISR
l O código deve ser o mais curto possível
l Apenas o processamento mais importante deve ser
executado
l O restante é passado para o programa principal
l Visto que a execução de uma ISR está a bloquear
l Outras ISRs de menor ou igual prioridade
l O programa principal
Interrupções
operação no 8051

l Ao desenhar as ISR
l Não misturar interrupções com polling
l As prioridades de interrupção devem ser
cuidadosamente ponderadas
l Prioridade de interrupções críticas que requerem a
resposta rápida deve ser definida como alta
l Solicitações simultâneas de interrupções da
mesma prioridade levam ao atraso no seu
atendimento
l Solicitações múltiplas e simultâneas da mesma
interrupção podem causar falha no atendimento
de algumas delas
Interrupções
operação no 8051

l Ao desenhar as ISR
l Configurar o periférico e inicializar as variáveis
necessárias antes de ativar a interrupção respetiva
l Cada interrupção ativada deve ter uma ISR
Interrupções
operação no 8051

l As ISR são uma forma básica de concorrência


l Partilha variáveis com o programa principal/ISRs
l Declaração de variáveis com keyword volatile
l Evita que o compilador otimize as variáveis
l Em situações, p. ex, em que no código principal nunca é alterada
l O compilador tem tentação de a substituir por uma constante
l Quando na verdade a variável é alterada na ISR

l Acesso atómico
l É um problema genérico no acesso a dados partilhados
l Não depende da arquitetura do micro
l Não vamos abordar aqui (à UC de Sistemas Operativos)
l É um problema no 8051 quando por exemplo usamos int
l O micro é de 8 bits à privilegiar signed char/unsigned char
l Operações de 16 bits (int p.ex) são mais demoradas
Interrupções
operação no 8051

l As ISR são uma forma básica de concorrência


l Partilha de variáveis (cont.)
l Acesso atómico
l Problema genérico
l Não depende da arquitetura do micro

l Estas questões existem em qualquer processador


l Não têm a ver como 8051
Interrupções
operação no 8051

l As ISR são uma forma básica de concorrência


l Partilha de variáveis (cont.)
l Acesso atómico (particularidades do 8051)
l Soma de dois inteiros em C
z = x + y;
l Traduzido para assembly
l x está em r6 e r7
l y está em r4 e r5
O que acontece se
l z está em dph e dpl
surgir aqui uma
interrupção que altere
o valor de x ou y? mov a,r4 Termina aqui o cálculo da parte
add a,r6 menos significativa da soma
mov dpl,a
INT
mov a,r5 Termina aqui o cálculo da parte
addc a,r7 mais significativa da soma
mov dph,a;
Interrupções
operação no 8051

l As ISR são uma forma básica de concorrência


l Partilha de variáveis (cont.)
l Acesso atómico – outro exemplo
l Soma de dois inteiros em C
z++;
l Traduzido para assembly
l z está em a e b (por cálculos anteriores)
l Depois dos cálculos, z fica em r6 e r7
O que acontece se Soma 1 à parte menos significativa de z.
surgir aqui uma Guarda o resultado em r6.
interrupção que altere
o valor de z? add a,#0x01
mov r6,a Para o cálculo da parte mais significative,
clr a limpa a (a=0) e soma com b, tendo em
INT conta o carry da operação anterior.
addc a,b
mov r7,a Termina guardando o resultado em r7.
Interrupções
operação no 8051

l As ISR são uma forma básica de concorrência


l Partilha de variáveis (cont.)
l Acesso atómico – um exemplo ainda mais básico
z = 300;

l Traduzido para assembly


O que acontece se
l z fica em r6 e r7 surgir aqui uma
interrupção que altere
o valor de z?
mov r6,#0x2C
INT mov r7,#0x01
Interrupções
operação no 8051

l As ISR são uma forma básica de concorrência


l Partilha de variáveis inteiras
l Em ambos os casos anteriores há problema
l O acesso à variável não é atómico
l Outros exemplos
l Imagine-se instrução “counter += 8;”
l O acesso também não é atómico!
l Há problemas se a execução de depender de acesso atómico
l Imagine-se a instrução “flags |= 0x80;”
l O acesso não é atómico se a variável está na memória externa
l Solução
l Mecanismo de acesso atómico (exclusão mútua) aos recursos
Interrupções
operação no 8051

l Acesso atómico
l Por desativação de interrupções na secção crítica
l O compilador fornece um mecanismo para este efeito
l Keyword __critical
l O sistema deixa de responder a todas as interrupções
l Potencial problema: A execução das interrupções foi atrasada
l Potencial problema: Se entretanto surgiu outra interrupção do
mesmo tipo só uma vez será executada
l Logo que reativadas as interrupções pendentes são executadas

l Pelas razões acima, o tempo de desativação deve ser o menor


possível
l Este problema pode ser mitigado através da desativação seletiva das
interrupções
Interrupções
operação no 8051

l Acesso atómico
l Por desativação de interrupções na secção crítica
l Desativar as interrupções para uma função
int func() __critical {
...
}

l Desativar as interrupções para um bloco de código


__critical {
...
}

l Esta desativação é global!


l O compilador não fornece mecanismos de desativação seletiva
l Para isso é necessário recorrer à configuração do registo IE
Interrupções
operação no 8051

l Uma nota sobre programação


l Combinar char com unsigned char
l Seja em atribuições
l Seja em comparações
l Explicita ou implicitamente
void to_buffer( unsigned char c ) {
unsigned char head, tail;
if( head != (unsigned char)(tail-1) ) /* cast necessario*/
….
}

l Como se corre o risco de o lado direito ser negativo


l Há assim a promoção de tipo para int da comparação
l Com as implicações que isso tem...
Interrupções
operação no 8051

l No exemplo do slide anterior


l Duas implementações: com e sem type cast
l Com type cast
; C:\8051projetcs\timers.c:27: if( head != (unsigned char)(tail-1) ) {

mov r7,_tail
dec r7
mov a,r7
cjne a,_head,00124$
sjmp 00103$
Interrupções
operação no 8051

l No exemplo do slide anterior


l Duas implementações: com e sem type cast
l Sem type cast
; C:\8051projetcs\timers.c:28: if( head != (tail-1) ) {

mov r6,_tail
mov r7,#0x00
dec r6
cjne r6,#0xff,00123$
dec r7
00123$:
mov r4,_head
mov r5,#0x00
mov a,r4
cjne a,ar6,00124$
mov a,r5
cjne a,ar7,00124$
sjmp 00103$
Interrupções
operação no 8051

l Outra nota sobre programação


l Fazer o toggle de uma variável tipo bit

__bit b;
b = ~b; /* ERRADO!!! Não faz o toggle Faz b=1!!!*/
b = !b; /* faz toggle de b */
Interrupções
operação no 8051

l Pilha
l Sempre que há uma interrupção
l O endereço de retorno é guardado na pilha
l Pelo hardware
l Os registos usados na ISR são guardados na pilha
l O compilador gera código para isso acontecer
l Se houver outras utilizações da pilha
l Invocações de interrupções dentro de outras interrupções
l Invocações de funções dentro de funções e, no limite
recursividade

l Tudo isto pode gerar um overflow da pilha


l Nas invocações mais “profundas”
Interrupções
operação no 8051

l Todos estes tipos de problemas


l Perda de interrupções
l Atraso na execução de interrupções
l Partilha de variáveis
l Código não reentrante
l Overflow da pilha

l São difíceis de detetar


l O debugger não os apanha!!!
Interrupções
Obrigado

Você também pode gostar