Upload
merryl-watts
View
219
Download
0
Embed Size (px)
Citation preview
Timer Operations
Overview
• Topics to be covered:o Free running counter
o Output compare
o Input capture
o Pulse accumulator
o Real time interrupt
• Reading: Text, Section 8.7, Chapter 11; E9 Chapter 9; HC11 Ref. Chapters 10-11
Cont..
Overview
• Registerso Control registers
TCLT1 Timer control register 1TCTL2 Timer control register 2TMSK1 Main timer interrupt mask register 1TMSK2 Miscellaneous timer interrupt mask register 2PACTL Pulse accumulator control register
o Data registersTCNT Timer counter registerTIC1-3 Timer input capture registers 1-3TOC1-5 Timer output compare registers 1-5PACNT Pulse accumulator count register
Cont..
Overview
o Status registers
TFLG1 Main timer interrupt flag register 1
TFLG2 Miscellaneous timer flag register 2
• Pinso Timer uses pins on Port
A If you’re not using a
certain timer function, you can use the pin for I/O
Cont..
OverviewOverview
• The 68HC11 supports a wide variety of timer-based applications through the use of its on-chip timero Using the timer frees the CPU for other processing
Don’t need to use time-delay loopso More accurate timing
Standard time-delay loops do not account for time spent in ISRs
• Some applications of the timer subsystemo Generating pulses (continuous streams or one-shots)o Internal timer to start and/or stop taskso Measure period (or frequency)o Measure pulse widthso Count events
Cont..
OverviewOverview
• The HC11’s “free running counter / timer” forms the basis for all timing functions and provides time information to all programs
• Free running counter description:o The (2 MHz) E-clock drives a prescaler to the countero Prescaler divides E-clock by 1, 4, 8, or 16o The counter is a 16-bit count
Counting sequence is from $0000 to $FFFF and repeatCounter value can be read from the TCNT register,
$100E,F (16-bit, 2-address register) υ Always use a 16-bit load (LDD, LDX, LDY) υ Can’t write to TCNT
TCNT reset to $0000 when HC11 is resetCont..
OverviewOverview
o When the counter value rolls over from $FFFF to $0000,Timer overflow flag bit is set (TOF -- bit 7 in TFLG2
register, $1025 -- not $1024 as in Fig 11.1)An overflow interrupt may occur if enabled (TOI -- bit 7 in
TMSK2 register, $1024)
• Prescale bit selectiono Bits PR1 and PR0, bits 1 and 0 in register TMSK2 determine
prescaler division value
o These bits are "write once" during the first 64 E-clock cycles after a reset
Cont..
OverviewOverview
Cont..
oResolution using 8 MHz system crystal
OverviewOverview
• Clearing flag bits in TFLG1 and TFLG2 interrupt flag registerso Flag bits in these registers are cleared by writing 1s to the
associated bit positions
o Use LDAA / STAA or BCLR -- not BSET!
o To clear timer overflow flag TOF, use
LDAA #$80
STAA TFLG2
or
BCLR TFLG2,X, $7F
Timer output compare functionTimer output compare function
• Uses:o Output pulse waveforms
Square wavesVariable duty-cycle wavesSingle pulses
o Elapsed time indicator (to external circuitry)o Trigger execution sequence at a specified time
Can generate an interrupt with/without external output
• Description:o There are 5 output compare functions, OC1 -- OC5
Each is associated with a 16-bit output compare register:• TOC1--TOC5
Cont..
Timer output compare functionTimer output compare function
• At addresses $1016 -- $101F
o The user or user program stores time values in these registersTimes at which the user wants something to happenUsually, you read TCNT, add a value to it (the amount of
delay), store in TOCx
o During each E-clock cycle, the values contained in all 5 of the output compare registers are compared to the value of the free running counter
o If there is a compare (a match) between one of the registers and the free running counter,The corresponding flag bit is set (OCxF in register TFLG1,
$1023)
Cont..
Timer output compare functionTimer output compare function
The state of the associated output pin(s) on port A may change, depending on configuration
Timer output compare interrupt is generated if enabled (OCxI in register TMSK1, $1022)
• Functions OC2-OC5o These functions manipulate
single output bits, bits PA6 -- PA3
Cont..
Timer output compare functionTimer output compare function
• Force Output Compareo Writing a 1 to a bit(s) in CFORC register “forces” a compare
before the timer reaches the value in TOCxo Does not generate an interrupto Drives the associated output pin according to setting of OMx
and OLx bits in TCTL1Be careful using this with “Toggle” mode
• Forcing an output does not affect the value in TOCx or the operation of the timer
• When TCNT reaches value in TOCx, it will drive the output again
o Doesn’t matter if you’re using “Drive Output High” or “Drive Output Low” modes
Cont..
Timer output compare functionTimer output compare function
o For “Toggle,” the output will toggle when you force it and then toggle back when timer reaches TOCx value
• OC1 functiono Used to control any combination of output pins PA7 - PA3
To use PA7 for OC1, you must write a 1 to DDRA7 in PACTL
o Uses 2 separate registers to control its operationOCM1, output compare 1 mask register, is used to specify
which output bits will be controlled• Set the bits to enable OC1’s control of the output pin
o OCD1, output compare 1 data register, contains the data to be sent to the port A pins upon occurrence of a compare
Cont..
Timer output compare functionTimer output compare function
For example, you can set PA3 and PA4 high and PA7 low when a successful compare occurs
No “Toggle” mode for OC1 • You can reset the output pins by writing to Port A
and disabling the OCxo Data is latched when you write to Port Ao Latch data is placed on pin when you disable counter
Cont..
Timer output compare functionTimer output compare function
Cont..
Timer output compare functionTimer output compare function
• Example: Generate a single 10 ms high pulseo This is NOT using interrupts -- one-time use of code segment
;Listing 11.1;Drive one-shot high pulse for 10 ms;with E –2 Mhz and prescale –1;REMINDER, see samples listing in Appendix E;==============================================
SEG DemoPWIDTH EQU 20000
LDD TCNT,X ;prevent preventure STD TOC2,X ;OC2 compare
PULSE ;drive PA6-OC2 high BSET PORTA, X, $40 LDAA #$80 ;configure OC2 high
Cont..
Timer output compare functionTimer output compare function
STAA TCTL1, X ;and disconn.other Ocx’s LDAA #$40 ;clear OC2F if set STAA TFLG1, X LDO TCNT, X ;arm TOC2 for 10-ms trigger ADDD #PWOTH-17 STD TOC2, X
PULSE1 ;wait for trigger BRCLR TFLG1, X, $40, PULSE1
;new output OC2F high BCLR PORTA, X, $40 ;clear latch for PA6 LDAA #$40 ;then clear OC2F STAA TFLG1, X ;before BCLR TFLG1, X, $80 ;disconnecting OC2
BRA $ ;end for now
Cont..
Timer output compare functionTimer output compare function
• Example: Generating square waveso Use “Toggle” mode and interruptso Initialization
Set OMx and OLxSet TOCxEnable timer interrupt
o Interrupt service routineUpdate TOCx (add half-period)Clear OCxF flagReturn
o See Listing 11.3 in texto Note that you must update TOCx after every interrupt to
generate a continuous signal
Cont..
Timer output compare functionTimer output compare function
• Example: Pulse width modulationo Generate a pulse at a fixed periodic intervalo Duty cycle of the pulse is based on the width of the pulse wrt
to the total period – normally specifies the percentage of time the signal is high compared to the period
o Steps to implement in EVBU:Select desired prescale valueDetermine count on TCNT that corresponds to desired
periodDetermine initial values of high and low cycle count values
(adjust values later, once code is written, if needed)Select desired OCx and specify address of output compare
interrupt service routine
Cont..
Timer output compare functionTimer output compare function
Develop the needed software to initialize timer operations and then the associated ISR
;Listing 11.4;Shows routines for handling PWM using output OC2;A main application program varies the duty cycle;by modifying 16-bit data in address OC2HI and
OC2LO.
;Duty cycle0100% * OC2HI/(OC2HI +OC2LO);User Responsibility to see up vector addresses and;other intialization as required by application.;===================================================
SEG Utility
;Subroutine INITOC2;Initializes timer output OC2 for PWM output;interrupt driven
Cont..
Timer output compare functionTimer output compare function
;Calling registers; IX= register block address;Return registers; None, except CCR attechedINIOC2
PSHA ;preserve registersPSHBLDD TCNT,X ;delay PWM generationSTD TOC2,XLDAA #$C0 ;OM2:OL2=1:1 to setSTAA TCTL1,X ;OC2 high first timeLDAA #$40 ;clear OC2F if setSTAA TFLG1,XSTAA TMSK1,X ;set OC2 to eableCLI ;interruptPULB ;restore registersPULARTS ;return
Cont..
Timer output compare functionTimer output compare function
;Service routine RTOC2;Drives OC2 output for PWM by scheduling;time delay for next edge. Also reconfigures;next edge opposite to that of current edge.;Note that routine will not work properly with;duty cycles close to 0% or 100%;Static variables (2 bytes each);Address OC2HI=OC2 time duration for high pulse;Address OC2LO=OC2 time duration for low pulse
;This routine executed after TOC2 – TCNT occurs
RTOC2LDX #REGBAS ;point to registers
;if low part of cycle;then load OC2LO
Cont..
Timer output compare functionTimer output compare function
BRCLR TCTL1,X,@40,GETOC2LOLDO OC2HI ;else load OC2HIBRA NEWTOC2
GETOC2LOLDO OC2LO
NEWTOC2 ;update TOC2ADDO TOC2,XLDAA TCTL1,X ;invert OL2 to toggleEORA #%01000000 ;next OC2 edge;STAA TCTL1,X ;by updating cntrl
reg.BCLR FTFLG1,X,$BF ;clear flag OC2FRTI ;return from service
Cont..
Timer output compare functionTimer output compare function
• Example: Use multiple output compares to generate a 1 E-clock period pulse at a rate of "period" on OC2 using polling
Cont..
Timer output compare functionTimer output compare function
• Example: Use multiple output compares to generate a 1 E-clock period pulse at a rate of "period" on OC2 using polling
INIT_PLSLDX #$1000 /” DELAY ANY OC1, OC2 COMPARES “/LDO TCNT,XSTD TOC1,XSTD TOC2,X /” WTGN1 =%010000000 “/BSET OC1M,X #$40 /”ENABLE OC1 ACTION FOR OC2”/BCLR OC1M,X #$80 /”OC2 PIN WILL BE HI FOR OC1 COMPARE”/BSET OC1D,X #$40BCLR OC1D,X #$80BCLR TCTL1,X #$40 /”OC2 PIN WILL BE LO FOR OC2COMPARE”/BSET TCTL1,X #$80
Cont..
Timer output compare functionTimer output compare function
SERVICE
SERVICE BCLR TMSK1,X #$C0 /”DISABLE OC1M OC2 INTRUPPTS”/ LDAA #BIT76HI /”BIT76HI = %11000000”/ STAA TFLG1,X /”CLEAR PREVIOUSLY SET OC1,OC2FLAGS”/ LDD TOC1,X ADDD #PERIOD STD TOC1,X /”OC1 WILL OCCURE IN “PERICO” E CLOCKS”/ ADDD #1 STD TOC2,X /”OC2 WILL OCCURE IN “PERICO+1” E CLOCKS”/ BRA POLL
POLLINGPOLL LDAA TFLG1,X BITA #BITBHI /”CHECK OC2 FLAG BIT”/ BEQ POLL BRA SERVICE
Timer input compare functionTimer input compare function
• The input capture function records the time when an active transition on a pin occurs
• Useful for:o Measuring time between events (occurring in external
hardware)Results might be speed, frequency, period, distance
traveled, fluid flow, etc.o Reacting to real-time events (do something after X occurs, or
after X occurs Y times)• Description:
o 4 input capture functions, IC1-3 plus IC4 (E9 only -- not on the A8 discussed in the text) IC1 -- PA2, IC2 -- PA1, IC3 -- PA0, IC4 -- PA3 (or use pin
as OC5/OC1)
Cont..
Timer input compare functionTimer input compare function
» Use 16-bit timer input capture registers ataddresses $1010 -- $1015 (IC1-3) and $101E-F(IC4)
o Input capture edge detectors sense when an edge occurs on the pin(s)
o If an edge detection occurs, the following will happenThe TCNT value is loaded into the timer input capture
registerThe associated status flag is setAn interrupt may occur (if enabled)
o Initialization of IC1-3:
Cont..
Timer input compare functionTimer input compare function
o Input capture pin IC4: Pin 3 of port A can be
used for general I/O, output compare operations, or input capture operations
Input capture operations are similar to IC1- 3, but initialization is different
• To use as input capture, set bit I4/O5 to 1 in the PACTL register
Flag and interrupt mask bits are bits 3 in registers TFG1 and TMSK1
Cont..
Timer input compare functionTimer input compare function
Desired edge is specified by bits EDG4b, EDG4A (bits 7 and 6) in register TCTL2
o Shares interrupt service routine vector $FFE0-1 with OC5
Pulse width measurement exampleo Measure the width of a pulse on IC1
Won’t work if pulse is too short or too longo Pseudo code:
Wait for and record time of rising edgeWait for and record time of falling edgeDifference between the 2 is the pulse width
Cont..
Timer input compare functionTimer input compare function
;Listing 11.8;Measure time between a rising and a falling edge on IC1.
;=========================================================
SEG Demo
LDAA #$10 ;config 10 compare rising edgeSTAA TCTL2,XLDAA #$04 ;clear flag IC1F if netSTAA TFLG1,X
POLLRISE ;Wait for rising edgeBRCLR TFLG1,X,$04, POLLRISELDD TIC1,X ;store the rise timeSTD RISETIMELDAA #$40 ;config to capture falling edge
Cont..
Timer input compare functionTimer input compare function
STAA TCTL2,XLDAA #$04 ; clear flag IC1FSTAA TFLG1,X
POLLFALL ;wait for falling edgeBRCLR TFLG1,X,$04, POLLFALLLDD TIC1,X ; read the fall timeSUBD RISETIME ; width = fall – riseSTD PULSEWIDTH ; store widthBRA $ ; stop here for now
•Period calculation exampleo Determine the period of a periodic waveform on input IC1o Must capture the times of consecutive rising (or falling) edgeso Remember to initialize ISR vectors and to scale result (if
needed)
Cont..
Timer input compare functionTimer input compare function
;Listing 11.9;Service routines to measure period between two rising;edges at the IC1 pin.Results valid in range of ;~27E cycles to 65,535 TCNT cycles lowers ignored
;=========================================================
SEG Page0IC1DUN DS 1 ;flag:0=not done, 1=pulse measuredIC1MOD DS 1 ;mode flag:FF off, 0-1st,1 last edgePER DS 2 ;period 16 bits
;=========================================================
; IC1DUN=0; IC1MOD=$FF, means measurement has no started
Cont..
Timer input compare functionTimer input compare function
INITIC1PSHA ;present registerLDAA #$10 ;EDG1B : EDG1A = 0:1 for rising edgeSTAA TCTL2,XLDAA #$1F ;mode flag offSTAA IC1MODCLR IC1DUN ;single period not done
BCLR TFLG1,X, $FB ;clear IC1F at setBSET TMSK1,X, $04 ;enable IC1 interruptCLI ;enable interruptsPULA ;restore registersRTS ;and return
Cont..
Timer input compare functionTimer input compare function
;Service routine RTIC1;Handles input capture IC1 interrupts;Return variables on first edge; IC1MOD = 0; PER = first capture time;On record rising edge calculates period and disables;further rising edge interrupts;Return variables on second edge; IC1MOD = 1; PER = period; IC1DUN = 1RTIC1
LDX #REGBAS ;point to registerINC IC1MOD ;$ff -> 0 at first edge
;0 -> 1 at second edgeBNE EDGE2 ;if not 0 then this is second edge
Cont..
Timer input compare functionTimer input compare function
EDGE1 ;process first edgeLDD TIC1,X ;capture first edge timeSTD PER ;and save itLDAA #$04 ;clear flag IC1FSTAA TRLG1,XTRI ;and return
EDGE2 ;process second edgeLDD TIC1,X ;capture second edge timeSUBD PER ;second time – first timeSTD PER ;is low 2 bytes of resultsBCLR TCTL2,X, $30LDAA #1 ;and signal period measuredSTAA IC1DUN
EXITRIC1BCLR TFLG1,X,$FBTRI ;and return from service routine
Cont..
Timer input compare functionTimer input compare function
• Measuring long periodso What if pulse is longer than 65,536 TCNT clock cycles?
First, change the pre-scale factor for the free running clock• Maximum measurable pulse would be 524.3 ms
Otherwise, you must count the number of times the timer overflows
• Overflow doesn’t matter if pulse width is less than 65,536 TCNT cycles
Listing 11.10 shows one way to do this• This gets complicated• Also, there is a bug in the listingo Need a branch after the TST instruction (near label
EDGE2)• Can count pulses up to 16,777,215 TCNT cycleso About 8.38 seconds with 8 MHz crystal and pre-scale
set to 1
Pulse accumulator function
• Pulse accumulator is an 8-bit counter that counts edges (events) or tracks the pulse width
• Description:o Input is on PA7 (conflicts with OC1)o Initialization and control is via bits in PACTL:
DDRA7: data direction set to 0PAEN: pulse accumulator enablePAMOD: mode bit -- 0 for event counting, 1 for gated
time accumulationPEDGE: specifies edge transition to be used
• Flags and interrupt controlo 2 flags in TFLG2
PAOVF: set on counter overflowPAIF: set on any detected edge
o 2 corresponding interrupts: PAOVI, PAIICont..
Pulse accumulator function
• Fig 11.9 Pulse accumulator event counting mode
Cont..
Pulse accumulator function
• Event Countingo PAMOD = 0o PACNT is incremented whenever an appropriate edge is
detected (can be configured for rising or falling edges)o When PACNT overflows from $FF to $00, it sets PAIF in
TFLG2 and generates an interrupt, if enabledo Can be used to generate interrupt when a preset number of
edges have been detected• Short Counts
o Write the 2’s complement of the expected count into PACNTEx. To generate an interrupt after 24 ($18) events, write
$E8 (i.e., -$18) into PACNTo PACNT is an 8-bit counter, so this only works for counts less
than 256o See Listing 11.11
Cont..
Pulse accumulator function
• Long Countso Can count more than 256 by using software to keep track of
the number of overflowso One way to do this:
Load 16-bit count value into ACCDo ACCA (upper 8 bits) has the number of overflows that
will be needed (multiples of 256)o ACCB has the remainderWrite 2’s complement of ACCB into PACNTo If ACCB is not 0, then increment number of expected
overflowsWait for interrupt and then decrement expected overflow
countSee Listing 11.12
Cont..
Pulse accumulator function
• Fig 11.10 Pulse accumulation in the gated time mode
Cont..
Pulse accumulator function
• Gated Time Accumulationo PAMOD = 1o Counts up once every 64 E-clock cycles when PAI input is
at active levelUse PEDGE bit to specify which is active levelDoes not count edges
o Flag and interrupt bits work the same as for event countingo Can be used for pulse-width discrimination
Lets you tell wide pulses apart from narrow pulsesSet PACNT to a value halfway between the width of the
narrow and wide pulseso Narrow pulse -- edge interrupt will occur before
overflow interrupto Wide pulse -- overflow interrupt will occur before edge
interrupt
Real Time Interrupt
• The real-time interrupt subsection of the timer operations is useful for scheduling other events - make an application do something at specif-ied intervals of time
• Asserts real-time interrupt flag and interrupt at prescribed time intervals - set by values of bits RTR1 and RTR0
Cont..
Real Time Interrupt
• Interrupt rates for E = 2 MHz
Cont..
Real Time Interrupt
• Example: 24 hour clocko Note that 68HC68T1 is more accurate
;Listing 11.14
FCNT EQU 244 ;number of RTII interrupts to;make 1 second
;subroutine INITRTII;Initializes real-time interrupt foreground timer;No return registers except that CCR affected;Application program should initialize;following RAM variables:; HR = Hour count in BCD; MIN = Minute count in BCD; SEC = Second count in BCD;Calling registers
Cont..
Real Time Interrupt
; IX = register block addressINITRII
BSET TMSK2,X,$40 ;set RTII flag
CLI
CLR FSEC ;initialize FSECCLR FSEC + 1
;FSEC is function of second count for RTII routine in hex
RTS ;return
;Service routine RRTII;Handles real-time interrupt;Uses 16-bit software counter FSEC to count fractions;of seconds. Updates RAM variables SECONDS, MINUTES, and;HOURS as BCD values for use by any other routine
Cont..
Real Time Interrupt
RRTIILDX #REGBASLDAA #$40 ;clear RTIFSTAA TFLG2,XLDY FSEC ;count # of RTIIINY ;occurrencesSTY FSECCPY #FCNT ;add 1 to SEC ifBEQ SECONDS ;enough occurredRTI
SECONDSCLR FSEC ;reset function DEC COUNTCLR FSEC + 1 ;to zeroLDAA SECADDA #1 ;add 1 to seconds countDAA ;adjust for decimal arithmetic
Cont..
Real Time Interrupt
CMPA ##60 ;check for seconds --- 60BEQ MINUTES ;adjust minutes if --- 60STAA SECRTI
MINUTESCLR SEC ;reset seconds to 0LDAA MINADDA #1 ;add 1 to minutes countDAA ;adjust for decimal arithmeticCMPA #$60 ;check for minutes --- 60BEQ HOURS ;and adjust hours if – 60STAA MINRTI
HOURSCLR MIN ;reset minutes countLDAA HRADDA #1 ;add 1 to hours countDAA
Cont..
Real Time Interrupt
STAA HRCMPA #$24 ;check for hours –-- 24BNE RETURN ;and reset to 0 if – 24CLR HR
RETURNRTI
Summary
o The timer subsystem of the 68HC11 provides a wide range of flexible, timer-based functions
o Output comparePermits output pins to be manipulated at specified instances of
timePossible generation of corresponding interrupts
o Input captureUpon active edge at an input pin, read TCNT into capture
registerPermits determination of time at which edge occurs
o Pulse accumulatorPermits input transitions to be counted - track number of
transitions on an inputCan also be used for pulse width determination
o Real-time interrupt Interrupt generated at periodic times - used to schedule other
events