No Slide Title

Download Report

Transcript No Slide Title

Designing Embedded Systems with PIC Microcontrollers:

Principles and Applications

2 nd Edition. Tim Wilmshurst

Chapter 6 Working with Time: Interrupts, Counters and Timers

• • • • • • • •

The aims of this chapter are to introduce: Why we need interrupts and counter/timers; The underlying interrupt hardware structure; The 16F84A interrupt structure; How to write simple programs with interrupts; The underlying microcontroller counter/timer hardware structure; The 16F84A Timer 0 structure; Simple applications of the counter/timer; The Sleep mode.

Instructors using

Designing Embedded Systems with PIC Microcontrollers

are welcome to use or change these slides as they see fit. Feedback, to

[email protected]

,

is welcomed

.

The copyright to all diagrams is held by Microchip Technology, or T. Wilmshurst, unless otherwise stated

An Interrupt Review

An Interrupt is an external input to the CPU. The interrupt facility allows the processor to respond rapidly to external changes.

When an Interrupt is detected by the CPU, it: - completes the current instruction, - stores the address of the next instruction, and possibly other key variables (e.g. contents of Accumulator and Condition Code Register), onto the stack, - jumps to an interrupt service routine (ISR), whose address is determined by an "interrupt vector".

• Many interrupts can be

masked

, ie disabled, by setting a bit in a control register. In some processors however (but not PIC), some interrupts are not maskable.

• If an Interrupt is masked, then there is a possibility that it will not be detected. • Therefore there are also

Interrupt Flags

, bits in SFRs, which are set whenever an associated interrupt occurs. These record the fact that an interrupt has occurred, even if the CPU is unable to respond to it. • An Interrupt that has occurred, but has not received CPU response, is called a

Pending Interrupt.

• In the case of several interrupts, one ISR is completed before the next interrupt is responded to.

A Generic Interrupt Structure

Ot her replicated for all other maskable interrupts maskable int errupt s Int errupt X Enable*

In te rru pt X

S Q Int errupt input s t o CP U or program) Int errupt Flag*

Non -m as k abl e In te rru pt

* bit s in a Special Funct ion Regist er

Recalling Interrupt-Related Points that have already Come up

Control SFR(s) Microcontroller Core Peripheral Data Transfer SFR(s) Interrupt(s) Microcontroller Interaction with Peripherals, via SFR and Interrupt "Outside World" Interrupt Routine always starts here The Reset Vector

The PIC 16F84A Interrupt Structure

Timer Overflow Interrupt Flag External Interrupt Port B Change EEPROM Write Complete Note that the interrupt flags are set by the interrupt action, but must be cleared in the program, during the ISR. What happens if this isn’t done?

Global Interrupt Enable 1 18

RA1

P ort A, Bit 1

RA0

P ort A, Bit 0 External Interrupt input Ground

V O S C 2/C LKO UT

Supply volt age

RB7

P ort B, Bit 7

RB6

P ort B, Bit 6

RB5

P ort B, Bit 5 10

RB4

P ort B, Bit 4 *also Count er/T imer clock input **also ext ernal Int errupt input

The PIC 16F84A INTCON Register

The PIC 16 Series Interrupt Response

Note that this diagram shows what the PIC microcontroller itself does as an interrupt occurs. The programmer need not worry about any of these actions, but needs to know that they’re happening.

Interrupt Detected Complete Current Instruction Save Program Counter on Stack Clear GIE Reload PC with 0004H Continue Program Execution

main program is running ISR execution starts

No Instruction is RETFIE?

Yes Set GIE to 1 Load PC from Stack Continue Program Execution

main program continues

Programming with Single Interrupts

It is comparatively easy to write simple programs with just one interrupt. For success, the essential points to watch are: • Start the ISR at the Interrupt Vector, location 0004; • Enable the interrupt that is to be used, by setting enable bits in the

INTCON

and/or

PIE

registers; • Set the Global Enable bit,

GIE

; • Once in the ISR, clear the interrupt flag; • End the ISR with a

retfie

instruction; • Ensure that the interrupt source, for example Port B or Timer 0, is actually set up to generate interrupts!

A Simple Interrupt Application

Try Programming Exercise 6.1

;******************************************************** ;Int_Demo1 ;This program demonstrates simple interrupts. ;Intended for simulation.

;tjw rev.14.2.09 Tested in simulation 14.9.09

;******************************************************** ...

...

org 00 goto start ; org goto 04 ;here if interrupt occurs Int_Routine ; org 0010 ...

...

;Comment in or out following instruction to change ;interrupt edge ; bcf option_reg,intedg bcf bsf bsf wait movwf status,rp0 ;select bank 0 intcon,inte ;enable external interrupt intcon,gie ;enable global int movlw porta 0a ;set up initial port output values nop movlw movwf 15 porta goto wait ; org 0080 Int_Routine movlw movwf bcf retfie end porta 00 intcon,intf ;clear the interrupt flag

Interrupt Example 1

The INTCON Register of a PIC 16F84A is set as shown in a) below.

a) Determine which interrupts are enabled. b) An interrupt occurs, and the INTCON register is found to have changed to b). Which interrupt source has called? c) Which bit must the user change before the end of the ISR?

10101000

a) b)

1 INTCON

Interrupt Example 2

An inexperienced programmer writes the code opposite for a 16F84A to respond to an external interrupt. He correctly enables the interrupt, and no other interrupts are enabled.

a) How should the INTCON register be set?

b) What are the errors in the program excerpt?

org 0000 goto start org 0014 goto my_interrupt ;this is the interrupt routine my_interrupt movlw 0f addwf counter1,1 btfsc clrf return flags,2 ;test motor run flag overflow ;Program starts here start … bsf status,5

Moving to Multiple Interrupts – Identifying the Source

As we have seen, the 16F84A has four interrupt sources, but only one interrupt vector. Therefore, if more than one interrupt is enabled, it is not obvious at the beginning of an ISR which interrupt has occurred. In this case the programmer must write the ISR so that at its beginning it tests the flags of all possible interrupts and determines from this which one has been called. This is shown in the example ISR below.

interrupt btfsc intcon,0 ;test RBIF goto portb_int btfsc intcon,1 ;test external interrupt flag goto ext_int btfsc intcon,2 ;test timer overflow flag goto timer_int portb_int ...

place portb change ISR here

...

bcf intcon,0 ;and clear the interrupt flag retfie ext_int ...

place external interrupt ISR here

...

bcf intcon,1 ;and clear the interrupt flag retfie timer_int ...

place timer overflow ISR goes here

...

bcf intcon,2 ;and clear the interrupt flag retfie

Context Saving

Because an interrupt can occur at any time, it has the power to be extremely destructive. The program fragment below is written to illustrate this. ;This subroutine adds two 16-bit numbers, stored in phi-plo, and qhi-qlo, ;and stores result in rhi-rlo. 16-bit overflow in Carry flag at end. Double_add movf plo,0 ;move plo to the W reg addwf qlo,0 movwf rlo btfsc status,0 incf phi,1 ;add lower bytes ;add in Carry movf phi,0 addwf qhi,0 movwf rhi return ;add upper bytes Int_Routine bcf status,0 ;clear the Carry flag movlw 0ff ;change W reg value bcf intcon,intf retfie end

Try Programming Exercises 6.2 and 6.3

The temporary data being used in a particular activity in the CPU is called its

context

. In the PIC 16 Series this includes at least the W register value and the Status register. It is clearly important to save the context when an interrupt occurs. Some microcontrollers do this automatically, but PIC 16 Series microcontrollers do not. Therefore, it is up to the programmer to ensure that whatever context saving that is needed is done in the program.

Critical Regions and Masking

In certain program parts we will not want to accept the intrusion of an interrupt under any circumstances, with or without context saving. We call these

critical regions

. We can disable, or

mask

, the interrupts for their duration, by manipulating the enable bits in the

INTCON

register. Critical regions may include: • times when the microcontroller is simply not readied to act on the interrupt (for example during initialization – hence only enable interrupts after initialization is complete); • time-sensitive activity, including timing loops and multi-instruction setting of outputs; • any calculation made up of a series of instructions where the ISR makes use of the result.

The Digital Counter Reviewed

It is very easy to make a digital counter using flip-flops. Counters can be made which count up, count down, which can be cleared back to zero, pre-loaded to a certain value, and which by the provision of an overflow output can be cascaded with other counters. A simple example is shown.

The Counter as Timer

If the incoming clock pulses are regular in frequency, the counter can also measure time. In this example time is being measured between two pulses.

Clock Pulse Input 1 2 3 4 5

T T c n

If

T C

is clock period, and

n

cycles are counted, then the period during which counting has taken place is

nT C .

Example: clock frequency is 1 MHz, clock period is therefore 1us, before overflow counter can count: 8-bit 255us 16-bit 24-bit 32-bit 65535us = 65.5ms

16.78 secs 4,295 secs = 1hr, 11minutes

The 16F84A TIMER0 Module

Input edge select Multiplexer selecting counting source Multiplexer selecting prescaler 8-bit Counter

The 16F84A OPTION Register

Application 1: Object or Event Counting

The simplest application of Timer 0 is to use it as a counter, counting pulses entering the microcontroller through the external input. This demo program configures the Timer 0 module to count paddle presses on the Ping-pong hardware. ;******************************************************************** ;cntr_demo ;TJW 15.4.05

...

...

list ; p=16F84A #include p16f84A.inc

org ; Initialise bsf 00 status,rp0 Counter Demonstration ;This program demos Timer 0 as counter, using ping-pong hardware Tested 15.4.05

;******************************************************************** ;select memory bank 1 movlw B'00011000' movwf movlw movwf movlw trisa 00 ;port A according to above pattern trisb ;all port B bits outout B'00101000';set up TMR0 for external input, +ve edge, ;no prescale

Try Programming Exercise 6.4

movwf bcf TMR0 ;as we are in Bank 1, this addresses OPTION status,rp0 ;select bank 0 ; loop movlw 04 ;switch on "out of play" led to show power is on movwf porta goto loop end movf TMR0,0 ;Continuously display Timer 0 on Port B movwf portb

Application 2: Hardware-Generated Time Delays

We saw in an earlier lecture how program loops could be used to generate time delays. Here we hand over that delay function to the Timer. The internal oscillator signal is now used as clock source. The example below shows part of the initialisation, as well as the delay routine. How useful is this program change, compared to the previous software loop? ...

;Initialise org Start bsf movlw movwf movlw movwf 0010 status,5 B'00011000' trisa 00 trisb movlw movwf B'00000010' TMR0 bcf status,5 ; ...

...

;introduces delay of 5ms approx delay5 movlw D’131’ ;select memory bank 1 ;port A according to above pattern ;all port B bits op ;set up TMR0 for internal input, prescale by 8 ;as we are in Bank 1, this addresses OPTION select bank 0 ;preload counter, so that 125 cycles, each ;of 40us, occur before timer overflow movwf TMR0 del1 btfss intcon,2 goto del1 bcf intcon,2 return ;test for Timer Overflow flag ;loop if not set ;clear Timer Overflow flag

Try Programming Exercise 6.5

Taking Things Further: Interrupt Latency

The purpose of the interrupt is to attract the attention of the CPU quickly, but actually how quickly does this happen? The time between the interrupt occurring and the CPU responding to it is called the

latency

. This depends on certain aspects of hardware and on the characteristics of the program running. This timing diagram shows how the mid-range PIC family responds to an enabled external interrupt.

End of Lecture Note