ELN5622 Embedded Systems Class 5 Spring, 2003 Aaron Itskovich itskovich@rogers.com Interrupts Introduction to interrupts – What are they – How are they used 68HC11 interrupt mechanisms – Types of interrupts – Interrupt priorities Resets and their operation/use Introduction to interrupts Mechanism for responding to external events – CPU suspends execution of current routine – Jumps to a special interrupt service routine (ISR) – After executing the ISR, it returns to what it was executing before Why use interrupts? ... Efficiency! – Interrupts increase processor system efficiency by letting an I/O device request CPU time only when that device needs immediate attention. – “Main” programs can perform routine tasks without continually checking I/O device status. Interrupt usage Interrupts allow the processor to interact with slow devices in an efficient manner Loop: Loop: update counter delay check for digital input goto Loop • What about inputs that occur during delay? check for input goto Loop Timer_ISR: update counter reset timer return Interrupt Vector Table – Interrupt Vector Table located at $FFC0-$FFFF in memory (ROM area) – Each type of interrupt has an entry in the table • Entry contains address of interrupt service routine – 16-bit value What happens when an interrupt occurs? – CPU finishes processing current instruction – CPU automatically stacks registers to save the current state of the processor • Pushed onto stack in following order: PC, IY, IX, ACCA, ACCB, CCR – Fetches address of ISR from vector table – Jumps to ISR address – ISR should end with RTI instruction (Return from Interrupt) • Automatically pulls registers off stack • Returns to original program (using value of PC that was pulled) Sources of interrupt – I/O • SCI, SPI • Parallel I/O (STRBA) – Timer, pulse accumulator, real-time interrupt – External pins • XIRQ*, IRQ* – Software interrupt • SWI instruction – – – – Illegal opcode trap COP failure Clock monitor RESET* pin Masks and Enables Some interrupts are maskable – If interrupt is masked (or disabled), it will be ignored by the CPU – Can be enabled/disabled by setting bits in control registers Non-maskable interrupts – Can be used for interrupts that should never be ignored I bit in CCR is the interrupt request mask – If set, all maskable interrupts are disabled • Use CLI and SEI instructions to clear/set • I bit is initially set after system reset – To only mask some interrupts, clear I and set the individual masks in the control registers X bit in CCR is the XIRQ mask – Masks the XIRQ* pin (non-maskable interrupt) – Initially set after system reset – Software can clear it, but cannot set it 68HC11 Interrupts Non-maskable -- 3 types – XIRQ* • On reset, this interrupt is masked • During initialization, XIRQ can be enabled using a TAP instruction (clear the X bit in the CCR) • Once enabled during initiation, its state will not change • Used for high priority interrupt sources -- safety – Illegal opcode fetch • When an opcode is decoded, if it is invalid, this interrupt will occur • User should write trap routine to deal with the error – Software generated interrupt (SWI) • Instruction SWI behaves like an interrupt • Enables development tools such as breakpoints in Buffalo monitor 68HC11 Interrupts Maskable -- 15 types – These interrupts are masked as a group by the I bit in the CCR – IRQ* • External pin • Primary off-chip maskable interrupt • Can be set to either low-level or falling-edge sensitive – Default is level sensitive (IRQE=0 in OPTION register) – Edge sensitive can be set within first 64 cycles after reset (IRQE=1 in OPTION register) – Other interrupts based on operation of internal support hardware -- timers, serial I/O, parallel I/O, etc. Interrupt Priority Interrupt Priority – What if two interrupts occur at the same time? • Interrupts have assigned priority levels – PSEL3-0 in HPRIO register can be used to designate highest priority interrupt • Default is IRQ* • Higher priority interrupt is serviced first – When CPU recognizes an interrupt, it sets the I bit • Prevents additional interrupts – I bit is restored by RTI • It is possible to clear the I bit in the ISR (CLI instruction) to allow the ISR to be interrupted (nested interrupts) – Usually a bad idea Reset Resetting the processor brings the system up into a known point from which normal operations can be initiated – Primarily concerned with the initialization of operating conditions and key register values Similar to interrupt except that registers are not stacked 68HC11 supports 3 types of resets – Power on or RESET* • Occurs when a rising edge is detected on input power Vdd (i.e., at power up) or when user asserts the input RESET* line • Power up reset delays reset actions for 4096 clock cycles to allow clock to stabilize • RESET* must be held low for 6 clock cycles in order to be recognized (vs. it being used as an output signal) Watchdog – Computer Operating Properly (COP) watchdog timer failure reset • When activated, causes the processor to reset if no activity is detected for a long period of time • Processor must periodically execute code segment to reset the watchdog timer to avoid the reset – Write $55 to COPRST ($103A) followed by writing $AA • Examples of use: – System is waiting for sensor input but sensor has failed and will never provide input – EMI may cause interference in fetching instructions/data – software error - (while(1)) • Enable the watchdog during initialization operations (NOCOP bit in CONFIG register) Atomic operation 68HC11 instructions and interrupts – – – – RTI -- Return from Interrupt CLI -- Clear I bit in CCR SEI -- Set I bit in CCR WAI -- Wait for Interrupt • Stacks registers and waits for an unmasked interrupt • Reduces power consumption – STOP • If S bit in CCR is set, this acts like a NOP • Else – – – – Causes all system clocks to halt Minimum power standby mode Registers and I/O pins are unaffected Can recover with RESET*, XIRQ*, or unmasked IRQ* signal Vector table Vector table and EVBU – In evaluation units such as the EVBU, we can not change the contents of the ROM jump table (the table had to be completed during manufacture) • In the table, the ISR starting addresses are specified to be in the RAM area of the memory system • This RAM area is, in effect, a second “pseudo-jump table” for user to specify the real ISR starting addresses -- sort of like indirect addressing – Each entry is 3 bytes -- allows for unconditional jump statement to the ISR address • Thus, to use interrupts in your programs, you must – Determine the ISR starting address specified in the jump table at FFC0 – At that specified address in RAM, store the opcode for a JMP instruction followed by the address of the ISR Reentrant subroutines – Any subroutines called by an ISR should be reentrant, especially if used elsewhere in your program • A “reentrant” subroutine can be called again before it returns from a previous call – To make subroutines reentrant, don’t use allocated memory for passing parameters or temporary storage – Use the stack or registers instead Reentrance - Example ;****************** ; Hex_To_ASCII: Assume Convert_Nibble is also reentrant. ; Input: Hex value in ACCA ; Output: ASCII digits in ACCA and ACCB ;****************** Hex_To_ASCII: TAB ANDB #$0F JSR Convert_Nibble ; result in B PSHB ; save on stack TAB LSRB LSRB LSRB LSRB JSR Convert_Nibble PULA ; get first result RTS ;****************** ; Hex_To_ASCII: Calls routine Convert_Nibble to convert 4-bit ; value to ASCII ; Input: Hex value in ACCA ; Output: ASCII digits in ACCA and ACCB ;****************** Temp_Storage DS 1 ; temporary result Hex_To_ASCII: TAB ANDB #$0F JSR Convert_Nibble ; result in B STAB Temp_Storage TAB LSRB LSRB LSRB LSRB JSR Convert_Nibble LDAA Temp_Storage RTS ******************************************************************* * Subroutine to initialize(INIT) SCI for serial communications * at 8 data, no parity, 1 stop bit. Directly compatible with * TERM in PCbug11 and F7 comm in Iasm11. * * All registers returned to calling conditions. * ******************************************************************* INIT PSHX ; Save registers PSHY PSHA SEI LDAA STAA LDY STY ; disable interrupts #JMP_OPCODE ; set up interrupt vector $C4 ; pseudo vector address is $C4-$C6 #REC ; address of ISR $C5 LDY STY #BUFFER BUFF_PTR LDAA LDX LDAA STAA #$00 STAA LDAA STAA LDAA ; set up buffer pointer #REGBAS #$30 ; 9600 baud, assuming 8 MHz clock BAUD,X ; ; 8 data bits SCCR1,X ; #$2C ; Receive interrupt, poll transmit, enable TX, RX, SCCR2,X ; SCSR,X LDAA SCDR,X CLI PULA PULY PULX RTS ; Clear RDRF, Error flags ; Clear receive buffer ; enable interrupts ; Restore registers ****************************************************************** * Subroutine to receive(REC) a single character from an initialized * SCI serial device. No echo to screen takes place. The character is stored in * a receive buffer using the pointer stored in BUFF_PTR. * * CEN 9/23/93 * JMB 10/20/98 -- Modified to use interrupts ****************************************************************** REC LDX #REGBAS ; Point to register bank LDY BUFF_PTR ; get pointer to receive buffer LDAA SCSR,X ; Clear RDRF LDAA SCDR,X ; Get received character STAA 0,Y ; Store in buffer INY ; Increment buffer pointer STY BUFF_PTR ; should also check for end of buffer RTI ; Return from interrupt ********************************************* * Receive buffer ********************************************* ORG $100 BUFF_PTR RMB 2 ; pointer into buffer BUFFER RMB 32 ; Timer and Counter overview – – – – – Free running counter Output compare Input capture Pulse accumulator Real time interrupt Timers & Counters Registers – Control registers TCLT1 Timer control register 1 TCTL2 Timer control register 2 TMSK1 Main timer interrupt mask register 1 TMSK2 Miscellaneous timer interrupt mask register 2 PACTL Pulse accumulator control register – Data registers TCNT Timer counter register TIC1-3 Timer input capture registers 1-3 TOC1-5 Timer output compare registers 1-5 PACNT Pulse accumulator count register – Status registers TFLG1 Main timer interrupt flag register 1 TFLG2 Miscellaneous timer flag register 2 Timers & Counters Pins – Timer uses pins on Port A • If you’re not using a certain timer function, you can use the pin for I/O Pin Name Description PA0 IC3 Input Capture 3 PA1 IC2 Input Capture 2 PA2 IC1 Input Capture 1 PA3 IC4/OC5/OC1 Input Capture 4 or Output Compare 5 or 1 PA4 OC4/OC1 Output Compare 4 or 1 PA5 OC3/OC1 Output Compare 3 or 1 PA6 OC2/OC1 Output Compare 2 or 1 PA7 PAI/OC1 Pulse Accumulator Input or Output Compare 1 Timers and counters Why do we need it? The 68HC11 supports a wide variety of timer-based applications through the use of its on-chip timer – Using the timer frees the CPU for other processing • Don’t need to use time-delay loops – More accurate timing • Not affected by interrupts Timers & Counters usage – Generating pulses (continuous streams or oneshots) – Internal timer to start and/or stop tasks – Measure period (or frequency) – Measure pulse widths – Count events – The HC11’s “free running counter / timer” forms the basis for all timing functions and provides time information to all programs Free running timer/counter – The (2 MHz) E-clock drives a prescaler to the counter – Prescaler divides E-clock by 1, 4, 8, or 16 – The counter is a 16-bit count • Counting sequence is from $0000 to $FFFF and repeat • Counter 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 reset – 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) Free running timer counter Prescale bit selection – Bits PR1 and PR0, bits 1 and 0 in register TMSK2 determine prescaler division value – These bits are "write once" during the first 64 E-clock cycles after a reset PR1 PR0 Divide by 0 0 1 0 1 4 1 0 8 1 1 16 Resolution using 8 MHz system crystal Prescale Factor Resolution / overflow 1 500ns / 32.77ms 4 2 us / 131.1 ms 8 4 us / 262.1 ms 16 8 us / 524.3 ms Clearing overflow Clearing flag bits in TFLG1 and TFLG2 interrupt flag registers – Flag bits in these registers are cleared by writing 1s to the associated bit positions – Use LDAA / STAA or BCLR -- not BSET! – To clear timer overflow flag TOF, use LDAA #$80 STAA TFLG2 or BCLR TFLG2,X, $7F Timer output compare function Uses: – Output pulse waveforms • Square waves • Variable duty-cycle waves • Single pulses – Elapsed time indicator (to external circuitry) – Trigger execution sequence at a specified time • Can generate an interrupt with/without external output Description: – There are 5 output compare functions, OC1 -- OC5 • Each is associated with a 16-bit output compare register: – TOC1--TOC5 – At addresses $1016 -- $101F – The user or user program stores time values in these registers • Times at which the user wants something to happen • Usually, you read TCNT, add a value to it (the amount of delay), store in TOCx Timer output compare function – 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 – 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) • 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) Output compare registers Functions OC2-OC5 – These functions manipulate single output bits, bits PA6 -- PA3 Force Output Compare Writing a 1 to a bit(s) in CFORC register “forces” a compare before the timer reaches the value in TOCx Does not generate an interrupt Drives the associated output pin according to setting of OMx and OLx bits in TCTL1 – Be 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 – Doesn’t matter if you’re using “Drive Output High” or “Drive Output Low” modes – For “Toggle,” the output will toggle when you force it and then toggle back when timer reaches TOCx value OC1 function Used to control any combination of output pins PA7 -- PA3 – To use PA7 for OC1, you must write a 1 to DDRA7 in PACTL Uses 2 separate registers to control its operation – OCM1, 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 OCD1, output compare 1 data register, contains the data to be sent to the port A pins upon occurrence of a compare – 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 OCx – Data is latched when you write to Port A – Latch data is placed on pin when you disable counter OC1 Function registers Example Objective: Generate a single 10 ms high pulse – This is NOT using interrupts -- one-time use of code segment Example - II Objective: Generating square waves – Use “Toggle” mode and interrupts – Initialization Set OMx and OLx Set TOCx Enable timer interrupt – Interrupt service routine Update TOCx (add half-period) Clear OCxF flag Return – Note that you must update TOCx after every interrupt to generate a continuous signal Example-III Objective: Pulse width modulation – Generate a pulse at a fixed periodic interval – 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 – Steps to implement in EVBU: • Select desired prescale value • Determine count on TCNT that corresponds to desired period • Determine 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 • Develop the needed software to initialize timer operations and then the associated ISR Example - IV Use multiple output compares to generate a 1 E-clock period pulse at a rate of "period" on OC2 using polling Input capture function The input capture function records the time when an active transition on a pin occurs Useful for: – Measuring time between events (occurring in external hardware) • Results might be speed, frequency, period, distance traveled, fluid flow, etc. – Reacting to real-time events (do something after X occurs, or after X occurs Y times) Description: – 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) • Use 16-bit timer input capture registers at addresses $1010 -- $1015 (IC1-3) and $101E-F (IC4) – Input capture edge detectors sense when an edge occurs on the pin(s) Input capture function – If an edge detection occurs, the following will happen • The TCNT value is loaded into the timer input capture register • The associated status flag is set • An interrupt may occur (if enabled) – Initialization of IC1-3: Input capture function – 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 • Desired edge is specified by bits EDG4b, EDG4A (bits 7 and 6) in register TCTL2 • Shares interrupt service routine vector $FFE0-1 with OC5 Example I Pulse width measurement example – Measure the width of a pulse on IC1 • Won’t work if pulse is too short or too long – Pseudo code: • Wait for and record time of rising edge • Wait for and record time of falling edge • Difference between the 2 is the pulse width Example II Period calculation example – Determine the period of a periodic waveform on input IC1 – Must capture the times of consecutive rising (or falling) edges – Remember to initialize ISR vectors and to scale result (if needed) Real Time Interrupt The real-time interrupt subsection of the timer operations is useful for scheduling other events -- make an application do something at specified intervals of time Asserts real-time interrupt flag and interrupt at prescribed time intervals -- set by values of bits RTR1 and RTR0 Real Time Interrupt Real Time Interrupt Interrupt rates for E = 2 MHz RTR1 RTR2 Divide by Rate (ms) 0 0 213 4.10 0 1 214 8.19 1 0 2 15 16.38 1 1 216 32.77 Real Time Clock Example Example: 24 hour clock – Note that 68HC68T1 is more accurate Pulse accumulator/event count – Pulse accumulator is an 8-bit counter that counts edges (events) or tracks the pulse width – Description: • Input is on PA7 (conflicts with OC1) • Initialization and control is via bits in PACTL: – DDRA7: data direction set to 0 – PAEN: pulse accumulator enable – PAMOD: mode bit -- 0 for event counting, 1 for gated time accumulation – PEDGE: specifies edge transition to be used – Flags and interrupt control • 2 flags in TFLG2 – PAOVF: set on counter overflow – PAIF: set on any detected edge • 2 corresponding interrupts: PAOVI, PAII Event Counter Event Counting – PAMOD = 0 – PACNT is incremented whenever an appropriate edge is detected (can be configured for rising or falling edges) – When PACNT overflows from $FF to $00, it sets PAIF in TFLG2 and generates an interrupt, if enabled – Can be used to generate interrupt when a preset number of edges have been detected Event Counter Short counts Write the 2’s complement of the expected count into PACNT – Ex. To generate an interrupt after 24 ($18) events, write $E8 (i.e., -$18) into PACNT PACNT is an 8-bit counter, so this only works for counts less than 256 Event Counter Long Counts Can count more than 256 by using software to keep track of the number of overflows – One way to do this: • Load 16-bit count value into ACCD – ACCA (upper 8 bits) has the number of overflows that will be needed (multiples of 256) – ACCB has the remainder • Write 2’s complement of ACCB into PACNT – If ACCB is not 0, then increment number of expected overflows • Wait for interrupt and then decrement expected overflow count Pulse accumulation in the gated time mode Gated Time Accumulation – PAMOD = 1 – Counts up once every 64 E-clock cycles when PAI input is at active level • Use PEDGE bit to specify which is active level • Does not count edges – Flag and interrupt bits work the same as for event counting – Can be used for pulse-width discrimination • Lets you tell wide pulses apart from narrow pulses • Set PACNT to a value halfway between the width of the narrow and wide pulses – Narrow pulse -- edge interrupt will occur before overflow interrupt – Wide pulse -- overflow interrupt will occur before edge interrupt Debugging When it’s the right time to think about debugging? – Debugging embedded software is very complex task and software should be written in sauch way it make it easier not harder Creating debugable software – ASSERT (stop in the place you have problem) – LOGS (flight recorder) – Unit testing – white box test. No software unit should be integrated before unit test!!!!!!!! – Scripting for tests Debugging Create models and use tools to test models – Rational Rose – Rhapsody – … Decouple software debugging and hardware – Simulate anything you can – payback during integration – Obvious to you but not so much obvious to your manager ( Don’t forget to allocate time in the schedule) – Don’t try to load untested software on untested hardware with crosses fingers - it won’t help Tools for target debugging Remote debugger and debug kernel Debuggers Run control services – – – – – Breakpoints Loading program from the host Viewing and modifying memory and registers Running from an address Single stepping Resources required for debug kernel – Interrupt vector – Software interrupt Advantages and disadvantages of the debug kernel Low cost Same debugger on target and simulator Provides most of the required services Simple serial link is all what is required Can be left for field service Depends on stable memory subsystem and not suitable for initial hardware/software integration. Not real time Problems running from ROM (no breakpoints and single step ) Depends on code being well behaved ) Debugging tools ICE – Inter Circuit Emulator – – – – Special variation of the microcontroller Real time solution Hardware breakpoint Overlay memory ROM Emulator JTAG (Join test action group) BDM LOGIC ANAIZER Code maintenance How to avoid the famous “fixed one bug created two” problem –Regression testing! –Automated regression testing! Optimization Find where is the bottleneck Fix design Efficient coding – Think how it will look in Assembly Loop opening Inline assembly