TKT-3500 Microcontroller systems - TUT ·  · 2011-09-14TKT-3500 Microcontroller systems ... Tim...

53
TKT-3500 Microcontroller systems Lec 3b Interrupts Ville Kaseva Department of Computer Systems Tampere University of Technology Fall 2010

Transcript of TKT-3500 Microcontroller systems - TUT ·  · 2011-09-14TKT-3500 Microcontroller systems ... Tim...

TKT-3500

Microcontroller

systems

Lec 3b – Interrupts

Ville Kaseva

Department of Computer Systems

Tampere University of Technology

Fall 2010

#2/52

Sources

Original slides by Erno Salminen

Robert Reese, Microprocessors: From Assembly

to C with the PIC18Fxx2, Charles River Media,

2005

Tim Wilmshurst, Designing Embedded Systems

with PIC Microcontrollers – Principles and

applications, Elsevier, 2007.

Wikipedia

Copyright Tampere University of Technology Department of Computer Systems

#3/52

Contents

Interrupts

Basics, program flow

Sources and control registers in PIC

Interrupt service routines, state machines

Timing

Copyright Tampere University of Technology Department of Computer Systems

Interrupts

Copyright Tampere University of Technology Department of Computer Systems

#5/52

Program flow

The order in which the individual statements, instructions or function calls of an imperative or functional program are executed or evaluated

A control flow statement decides which control flow is taken

Control flow statements can be categorized by their effect:

continuation at a different statement (jump),

executing a set of statements only if some condition is met (choice),

repeating a set of statements until some condition is met (loop),

executing a set of distant statements, after which the flow of control may possibly return (subroutines, coroutines, and continuations),

stopping the program, preventing any further execution (halt)

Copyright Tampere University of Technology Department of Computer Systems

#6/52

Program flow (2)

In machine or assembly language, control flow

instructions usually work by altering the program

counter

For example, conditional or unconditional branches

Interrupts and signals are low-level mechanisms

can alter the flow of control in a way similar to a

subroutine

usually occur as a response to some external stimulus

or event

interrupts can be though as “HW-initiated function calls”

Reset is also kind of a ”harsh interrupt”

Cause CPU to boot up. Covered in lecture 6

Copyright Tampere University of Technology Department of Computer Systems

#7/52

Interrupts

Interrupts are used to change the normal

flow of a program so that it can perform

another (specified) function

Allow external events to change (interrupt)

the normal flow of the software and then

executing code specifically designed as a

response

The interrupted part of the code does not

know what hit it

In theory, it may notice it from the RTC (real-

time clock)

Copyright Tampere University of Technology Department of Computer Systems

#8/52

Interrupts (2)

Allow processors to automatically respond to

specified events and concentrate processing

power on executing a main program

Processors without in-built interrupt support

require programs which regularly inspect

selected input lines.

This is called „polling‟ or „busy wait‟ Polling is

very expensive in terms of processing

See e.g. previous examples with USART

while (something_happened ==0) {}

process_data();

Copyright Tampere University of Technology Department of Computer Systems

#9/52

Interrupts - PIC

When an interrupt occurs 1. the instruction currently being executed is

completed

2. PC jumps to address 0x08 or 0x18 in program memory and executes the instruction stored there, practically GOTO

ORG 0X00

GOTO START

;

ORG 0X08

GOTO INT_SRVC_HI ; INT VECTOR contaisn just jumps

ORG 0X18

GOTO INT_SRVC_LO ; INT VECTOR contaisn just jumps

INT_SRVC_HI ; ACTUAL HI-PRIOR ISR HERE

………………

RETFIE ; RETURN FROM INTERRUPT

;

START ; MAIN PROGRAM GOES HERE

…………………

END

Copyright Tampere University of Technology Department of Computer Systems

#10/52

Interrupt system

Interrupts can be enabled or disabled

(masked)

a) individually per-source

b) globally (all disabled regardless of source)

Interrupts enabled by INTCON-register‟s

GIE-bit

All interrupts have a priority

PIC18 has 2 priorities: high or low

Before using interrupts, corresponding

interrupt source has to be enabled and

priority chosen

Copyright Tampere University of Technology Department of Computer Systems

#11/52

Interrupt flags

Interrupt flag bits are set

when an interrupt condition occurs,

regardless of the state of its corresponding

enable bit or the global interrupt enable bit

-> Allows software polling.

User software should ensure the appropriate

interrupt flag bits are clear prior to enabling

an interrupt

Of course, flag must be cleared also after

servicing the interrupt

Copyright Tampere University of Technology Department of Computer Systems

#12/52

Interrupt sources

Interrupts may be triggered based on

a) signal edge: rising, falling, either

b) signal level: high, low

having both levels doesn‟t make much sense

For each source following must be

configured first

1. edge or level –sensitive, active value

2. reset the flag (if set by default)

3. enable the source

Sources may

a) have separate interrupt pins, or

b) share one interrupt pinCopyright Tampere University of Technology Department of Computer Systems

#13/52

Sensivity

INT0

1. pos.edge

2. neg.edge

4. high level

5. low level

Inte

rru

pts

se

ns

itiv

ity

Sometimes certain input pins allow only subset of these choices

3. either

edge

(change)

Example usage: external

device keeps interrupt

asserted until serviced.

ISR envoked perhaps

only once (high in

example) or twice (low)

time

flag is set

Copyright Tampere University of Technology Department of Computer Systems

#14/52

Interrupt sources (2)

29 separate sources

4 external input pins INT0...INT3 multiplexed with PORTB[3:0]

4 other pins GPIO port B

Timers

Peripherals parallel slave port

AD-converter

EUSART rx, tx

MSSP

capture-compare-PWM module (CCP/ECCP)

Copyright Tampere University of Technology Department of Computer Systems

#15/52

Interrupt sources(3)

Note that

occurrence of

interrupt request

always sets the

corresponding flag

Interrupt disable

prevents the jump

to interrupt vector

Once enabled

again, the

previously set flag

will cause the

interrupt

Copyright Tampere University of Technology Department of Computer Systems

#16/52

Control registers for interrupts

10 registers are used to control interrupts

reset control RCON

interrupt control INTCON,

INTCON2,INTCON3

peripheral interrupt flags PIR1, PIR2,

PIR3

peripheral interrupt enable PIE1, PIE2,

PIE3

interrupt priority IPR1, IPR2, IPR3

Copyright Tampere University of Technology Department of Computer Systems

Interrupt service routine

(ISR)

Copyright Tampere University of Technology Department of Computer Systems

#18/52

Interrupt service routine (ISR)

Function to perform the necessary actions

Called automatically after interrupt request

Calls (GOTOs) are placed into interrupt vector

Accepts no parameters

Does not return any values

May modify global variables, though

Remember to use volatile qualifier

Must ensure not to mess up the CPU state

Two ISRs in PIC: high and low priorities

High prior. interrupt may pre-empt lower priority

but not vice versaCopyright Tampere University of Technology Department of Computer Systems

#19/52

Entering Interrupt service routine

When entering ISR

1. registers BSR, W, STATUS are saved

automatically to shadow registers

In general, all CPU‟s registers must be saved

Shadow registers allow fast save/restore but increase

area

2. Return address is pushed automatically on the

stack

3. Usually, all interrupts are disabled

a) usually implicitly

b) sometimes by the programmer

at least those with lower priority

Copyright Tampere University of Technology Department of Computer Systems

#20/52

Entering Interrupt service routine (2)

4. Programmer may store other context

information manually

In PIC, e.g. multiplier register MULH+ MULL

Any special function registers utilized in ISR

5. In PIC, the source of interrupt has to be

checked manually in ISR

Since interrupts are shared by multiple sources

Other CPUs may have

a) separate interrupt pins and ISRs

b) register denoting the source

which simplify ISR code

Copyright Tampere University of Technology Department of Computer Systems

#21/52

Exiting ISR

Actions during exit are reversed from those

during entering

Restoring context requires special attention as certain instructions affect STATUS register

Does not use the same machine-code for

return as regular functions

RETFIE instead of RETURN

No values returned

Context may restored from shadow regs instead

of stack

Interrupts must be enabled again

Copyright Tampere University of Technology Department of Computer Systems

#22/52

ISR in ASM

as

. Location defined by linker

because shadow registers may be taken by higher prior ISR

. Note the order! STATUS is restored last because previous restorations

W is stored first with movwf which does not affect STATUS flags.

affect the flags. Parameter 0 for retfie tells not to restore from shadow registers.

Copyright Tampere University of Technology Department of Computer Systems

#23/52

Interrupts vs. traps

A trap is a special non-maskable interrupt

Not supported by all CPUs

Higher priority than any regular interrupt

Hard trap : some type of HW failure

Soft trap: triggered by some instruction

Examples: divide-by-zero

invalid memory address

user SW calls OS function that must be executed in privileged (supervisor) mode

On this course, we will not consider traps

Copyright Tampere University of Technology Department of Computer Systems

#24/52

Program flow example

1. CPU is reset

2. Reset vector points to initialization function (usually compiler-generated)

3. Execution jumps to main()

4. Main() calls other functions

5. Function foo() is interrupted, PC points to interrupt vector

6. ISR is executed

7. Execution returns to foo() to the instruction following the last executed one

8. Function foo may call other functions

9. Execution returns from bar to foo

10. Execution returns from foo to main

11. Main remains in infinite loop unless other interrupts occur

init(){

...

GOTO main}

main(){

...

foo()

...

while(1){}

foo() {

...

bar() ...

return

bar(){

...

return

isr() {

....

retfie}

0x0rst vec

isr vec

1

2

3

4

5

6

7

8

9

10

11

Program memory

Copyright Tampere University of Technology Department of Computer Systems

#25/52

Critical Section

When the main program and ISR share

common data structures (e.g. global

variables), accessing that data is a potential

synchronization problem

The main program is at critical section when

handling/processing such data

Interrupts should be denide when the main

progarm is at critical section modifying the shared

data

Denying interrupts aka. preserving atomicity aka.

Uniterruptible

Remember volatile

ISR example

Copyright Tampere University of Technology Department of Computer Systems

#27/52

Polled IO vs. interrupt-driven

Polled IO CPU checks continuouly the status of the transfer

Wastes time for checking, cannot do anything else

Trade-off between Check often – excess overhead

Check seldom – small overhead, events may be missed

Interrupt-driven IO CPU can perofrm other tasks while transfers is

being completed by special HW

CPU can sleep while waiting for incoming data

Modern computers use interrupt-driven IO

Copyright Tampere University of Technology Department of Computer Systems

#28/52

Polled/Int-drv IO example (1)

Polled – mobile phone without ring indicator

Check mobile phone every now and then

Take it from your pocket, purse what ever...

”Hello, is someone calling?”

How often should you check?

How long will the callers wait on line for you

perhaps answering?

Ain‟t this the coolest gadget or what...

Copyright Tampere University of Technology Department of Computer Systems

#29/52

Polled/Int-drv IO example (2)

Interrupt-driven – regular mobile phone

You‟ll be noticed (interrupted) when a call or SMS

arrives

Call/SMS may arrive asynchronously

You may disable interrupts but can check the

‟flags‟ later

Seems more convenient and efficient

Interrupts may be nested – you‟ll can put the

current call on hold when some VIP calls

Important persons have higher priority

You may accept only certain calls (e.g. during night

time)

Copyright Tampere University of Technology Department of Computer Systems

#30/52

Polled IO example

unsigned char getch

(void) {

while (RCIF==0);

return (RCREG);

}

unsigned char getche

(void) {

/* called by library

function scanf */

unsigned char c;

c = getch()

putch (c); /* echo */

return c;

}

void main (void) {

char param =0;

serial_init (95,1)

/* etc. */

printf

(”Starting.”);

printf (”Feed the

input values.”);

while (1) {

scanf(”%i”, &c);

transmogrify

(param);

printf (”Result is

%i”, param);

}

}

Copyright Tampere University of Technology Department of Computer Systems

#31/52

Polled IO example (2)

Example works well, when input comes at low rate

However, transmogrify and printf may take quite a while

No values are accepted when those functions are being processed

When values come in bursts, some may be lost

If USART overrun occurs, scanf gets stuck

Aargh.

ok

time

param arrives

ok ok ok

overrun! Voi poltetun poltettu!

Copyright Tampere University of Technology Department of Computer Systems

Buffering and state

machines

Copyright Tampere University of Technology Department of Computer Systems

#33/52

Handling bursts with buffering

Data may be buffered before processing

Buffer must be larger enough accomodate the largestpossible burst

In the long run, the processing rate must be larger thanincoming data rate Otherwise, every buffer will overflow at some point

Use flow control to avoid buffer overflows

Burst are followed by period of less activity when the bufferedparams can be handled

ok

time

param arrives

ok ok ok

1. Params handled at

the same as they arrive

2. Burst is

stored

temporarily into

buffer

3. Params from

buffer are

handled

Copyright Tampere University of Technology Department of Computer Systems

#34/52

Handling bursts with buffering (2)

Buffer works with FIFO principle

Firstin, first out

The buffer may be implemented

on HW – fixed size

e.g. two-word buffer

on SW – flexible size

The appropriate size depends on data rate

and burstiness of traffic

Obviously, fixed size buffer does not work

always

Copyright Tampere University of Technology Department of Computer Systems

#35/52

SW FIFO buffer

SW buffer is an array with two pointers head – where the new data is stored

tail – from where the data is read

Data is not copied from location to another but the pointers are updated

Copyright Tampere University of Technology Department of Computer Systems

#36/52

SW FIFO buffer (2)

Pointers wrap to the beginning when incremented enough so called circular buffer

Head equals tail when FIFO is empty If head catches the tail, overrun occurs (fig c)

There are different policies for pointers, e.g. increment head and then write,

head++; buf[head] = new_data;

write and then increment head buf[head] = new_data; head++;

Be sure to document properly!

Aargh.

At most n-1 words stored:

8-slot FIFO can hold 7 data words.

Copyright Tampere University of Technology Department of Computer Systems

#37/52

Buffered interrupt-driven IO example

Let‟s modify previous example

Use circular buffer (a SW FIFO)

Interrupt service routine will place incoming

data into buffer

Example does not check overrun, though

getch() function will read from the buffer

It waits until there is some data

main() is the same, except that interrupts

are enabled

Copyright Tampere University of Technology Department of Computer Systems

#38/52

Buffered interrupt-driven IO example (2)

#define BUF_MAX 32

volatile unsigned char ibuf[bUF_MAX], head, tail;

unsigned char getch () {

/* this is called by scanf*/

while (head==tail);

tail++

tail %=BUF_MAX;

return ibuf[tail]

}

void interrupt pic_isr(void) {

if (RCIF) {

head++;

/* no check for overrrun */

head %= BUF_MAX;

ibuf[head] = RCREG;

}

void main (void) {

char param =0;

serial_init (95,1) /* etc. */

IPEN=0; RCIE=1; PEIE=1; GIE=1;

printf (”Starting.”);

printf (”Feed the input values.”);

while (1) {

scanf(”%i”, &c);

transmogrify (param);

printf (”Result is %i”, param);

}

}

/* getche() unchanged */

Copyright Tampere University of Technology Department of Computer Systems

#39/52

State machine

State changes when user

presses button connected to

RB0

Initally, led is off

Start when user presses

button

LED starts blinking

It keeps blinking until

user presses button and

switch connected RB7

goes low

Keep LED lighted until

button is pressed again

turn off the led

return to start state

Copyright Tampere University of Technology Department of Computer Systems

#40/52

State machine’s ISR

Global semaphore variables ISR updates these, main just

reads (except int_flag)

Remove bounce from button input

Clear flag bit

Notify main via global var that int occurred

Go to next state Check switch position first when

blinking

Update the led‟s status blink/on/off

Copyright Tampere University of Technology Department of Computer Systems

#41/52

State machine’s main function

After initialization, loop forever

Read semaphores updated by the ISR Control the led (RB4)

Print also state information for debug purposes

Copyright Tampere University of Technology Department of Computer Systems

#42/52

State machine’s behavior

7.8.

9.

onoff

Copyright Tampere University of Technology Department of Computer Systems

Interrupt overhead

Copyright Tampere University of Technology Department of Computer Systems

#44/52

Interrupt latency and overhead

Interrupt latency denotes the time between

1. occurrence of interrupting event

2. entering the ISR

Interrupt overhead means the CPU time

taken by the ISR

Both are critical in real-time systems

CPU must react to external events within

bounded time (small/bounded latency)

ISR prevents the main from running and may

hence distract its timing (small/bounded

overhead)

Copyright Tampere University of Technology Department of Computer Systems

#45/52

Interrupt latency and overhead (2)

Disabling interrupts increases latency! Disabled when processing critical section, such

as data structure shared/accessed by multiple entities (functions, SW/HW)

All/Lower priority interrupts are automatically disabled when entering ISR Flags must be checked when exiting ISR

The disable duration must be minimized

The duration of ISR must be minimized no printf()

Debug info must be placed into trace buffer variable and print them in main code

no wait statements

Copyright Tampere University of Technology Department of Computer Systems

#46/52

Interrupt latency and overhead (3)

Interrupts arrive asynchronously!

One cannot predict their occurrence

Must prepare for their arrival at any point

Even within another ISR

As much as possible of the work must be

done in main code whereas ISR handles the

time-critical parts

Operating system may enlongen the ISR

latency

Copyright Tampere University of Technology Department of Computer Systems

#47/52

ISR enter latency

Current instruction is finished first Note that interrupt disable causes indefinite delay

Save PC and jump to interrupt vector

Jump to ISR Note that figure is for PIC24 but the principle is the same.

Copyright Tampere University of Technology Department of Computer Systems

#48/52

ISR exit latency

Perform retfie instruction

Retrieve context

Jump back to main code

Copyright Tampere University of Technology Department of Computer Systems

#49/52

ISR overhead

IEntry - #instr cycles when entering ISR

IBody - #instr cycles within ISR

IExit - #instr cycles when exiting ISR

fISR = 1 / tISR

frequency of interrupt triggering is reciprocal of triggering

period

OverheadISR = ((IEntry + IBody + Iexit) * fISR) / fCPU

Example, IEntry =4, IBody=50, IExit=3, fCPU=40 MHZ

tISR = 10 ms means 0.01 % overhead

tISR = 1 ms means 0.14% overhead

tISR = 0.1 ms = 100 us means 1.43 % overhead

tISR = 0.01 ms = 10 us means 14.3 % overhead

Copyright Tampere University of Technology Department of Computer Systems

#50/52

Interrupt Handlers

No portable way to write interrupt handlersa) Either use assembler code stubs for interrupt

handlers

b) Or use processor/compiler specific extensions to C

This is a consequence of register allocation and stack management policies of compilers and operating systems

Ensure mutual exclusion when updating global variables from interrupt handlers E.g. main disables interrupts when accessing

global variables

Copyright Tampere University of Technology Department of Computer Systems

#51/52

Interrupt Handlers (2)

Global variables updated from interrupt handlers (semaphores) are often marked volatile

volatile char isr_rdy;

void main() {

...

while (isr_rdy == 0) {}

This way, isr_rdy is read on every loop iteration

Compiler optimization forbidden

Updates from interrupt handler are visible and while can terminaite

Copyright Tampere University of Technology Department of Computer Systems

#52/52

C syntax for ISR with PIC

# pragma interrupt function-name [tmp-section-

name][save=save-list][nosave=nosave-list]

Pragmas are preprocessor commands

Define additional information for compiler -> typically compiler

dependant, not C standard defined

This associates the user defined function-name with interrupt vector

That function becomes the ISR

[tmp-section-name]

[save-list]

List of variables or data sections to save in ISR

Compiler guesses otherwise (usually OK)

[nosave-list]

List of variables or data sections not to save in ISR

Copyright Tampere University of Technology Department of Computer Systems

#53/52

Conclusions

Interrupts allow handling of asynchronous external

events

Parallel execution, caution required!

May happen any time – come like a fax to prime minister

Interrupt service routines are very time-sensitive

Must react fast

Must not interfere with main code timing

Do as much as work as possible in main code

Compared to polled IO

Increase the performance

Achieve the same performance with lower enegy (wake

from sleep with interrupt)

Copyright Tampere University of Technology Department of Computer Systems