Week #5 General Interfacing Techniques ENG3640 Microcomputer Interfacing Week #5 General Interfacing Techniques
Topics Classification of Interfacing Techniques Performance Measures Blind Cycle Gadfly (Polling) Interrupts Periodic Polling ENG3640 Fall 2012
Resources Huang, Chapter 6, Sections 6.2 Fundamental Concepts of Interrupts 6.3 Resets 6.4 HCS12 Exceptions 6.7 Real Time Interrupts ENG3640 Fall 2012
Classification of Interfacing Techniques Any MCU would communicate with peripherals through I/O ports. Types of data Numeric/Alphanumeric Control/Status Information Basic I/O Transfer alternatives can be classified as MCU Initiated I/O Device Initiated MCU Initiated Device Initiated Unconditional Transfer Polling (Gadfly) Interrupts Direct Memory Access ENG3640 Fall 2012
Classification: NO Interrupts Interrupt Based I/O to Memory Transfer Through Processor Programmed I/O (Polling) Interrupt Driven I/O Direct I/O to Memory Transfer Direct Memory Access (DMA) ENG3640 Fall 2012
Performance Measures What are some quantitative performance parameters we can measure using different interfacing techniques? Latency: is the time between when the I/O device needs service and when service is initiated. Delay sources? (a) Hardware (digital gates, computer hardware delays), (b) Software delays due to input or output device. Throughput or Bandwidth: is the maximum data flow (i.e. bytes per second) that can be processed by the system. Limitations? (a) I/O device could be slow, (b) computer software. Priority: determines the order of service when two or more requests are made simultaneously. Issues? (a) Identifying the device with highest priority, (b) If a high priority request is allowed to suspend a low priority request currently being processed (c) Monopoly. ENG3640 Fall 2012
Software & I/O Synchronization Hardware & I/O devices can be in one of three states IDLE (disabled/inactive) No I/O occurs ACTIVE usually toggles between (Busy, Done) Concerns? I/O Devices are usually slower than software execution. Solution? Synchronization; process of hardware and software waiting for each other in a manner such that data are properly transmitted. ENG3640 Fall 2012
Synchronization: Reading Waiting for new input Process Data Waiting Arrows represent synchronization events Time to process data (do useful activities) < Time for I/O This is called I/O Bound. If I/O processing is faster CPU Bound. This configuration is also called unbuffered. Any advantage of using a buffered system? Yes, (throughput) allows input device to run continuously. ENG3640 Fall 2012
Synchronization: Mechanisms Blind Cycle: Software simply waits for a fixed amount of time and assumes the I/O will complete after that fixed delay. Blind? No status info reported back Usage? Where I/O speed is short and predictable Gadfly (busy waiting, polling): is a software loop that checks the I/O status waiting for done status. When real time response is not important (CPU can wait) Interrupts: uses hardware to cause special software execution i.e. input device will cause interrupt when it has new data! When real time response is crucial Periodic Polling: Uses a clock interrupt to periodically check the I/O Status (i.e. The MCU or CPU will check the status) In situations that require interrupts but the I/O device does not support requests DMA: Transfer data directly to/from memory or I/O without CPU intervention. In situations where Bandwidth and latency are important. ENG3640 Fall 2012
Blind Cycle Synchronization: Example Printer can put 10 characters per second With Blind Cycle there is no printer status signal from printer! A simple software interface would be to output a character then wait 100 ms for it to finish. Advantage? Simple Disadvantage? If output rate is variable, then time delay is wasted. MCU Pulse Out Go Printer 8-bit DATA Data Out Port ENG3640 Fall 2012
Gadfly (Busy Waiting): Input Software checks a status bit in the I/O device and loops back until device is ready. The Gadfly loop must precede the data transfer for an input device. ENG3640 Fall 2012
Gadfly (Busy Waiting): Output Two steps are involved when the software interfaces with hardware to perform an output function. Software outputs the new data to an output port (fast!) Gadfly loop that executes until the output device is ready (long) Order of 1 and 2? Gadfly Before Gadfly After ENG3640 Fall 2012
Gadfly (Busy Waiting): Output Assumptions: Assuming that three printers are ready. Assuming that a printer will be ready 1ms after write data operation. Assuming software execution time is negligible. In Gadfly before output, all outputs will be started together and will operate concurrently. In Gadfly after output, the outputs are performed sequentially (3 times slower!) ENG3640 Fall 2012
Exceptions (Interrupts) Exceptions are asynchronous events that require processing outside the normal flow of instruction execution CPU12 exceptions include Resets (RESET Pin, COP RESET, CLK MONITOR) An unimplemented opcode trap, A software interrupt instruction (SWI), IRQ, XIRQ, ENG3640 Fall 2012
Resets vs. Interrupts What are the similarities and differences? Both are extraordinary events that cause the MPU to deviate from fetch & decode (i.e., asynchronous) Both cause the MPU to copy a special address to its Program Counter and execute a different program (ISR). Differences: Resets cause MPU to abort its normal fetch and execute then prepares it to start from scratch Interrupts cause MPU to abort its normal fetch and execute but returns the MPU to the instruction following the one that was interrupted. ENG3640 Fall 2012
Interrupts: Sources An interrupt is the automatic transfer of software execution in response to hardware that is asynchronous with the current software execution. An interrupt can be due to: An External I/O device (i.e. Printer, A/D Converter) through the IRQ line. An External signal (pulse) through the Input Capture Module. Generating a signal to an I/O device via the Output Compare Module. A Software Interrupt SWI instruction An internal event (i.e. periodic timer) Wakeup keys on port H or port J ENG3640 Fall 2012
Interrupts: Classification Interrupts from on-chip resources: Serial Interface Module: SPI, SCI Timer Module: Input Capture, Output Compare, Pulse Accumulator Analog to Digital Converter: ADC I/O ports H/J External Interrupts: IRQ line XIRQ line Software Interrupts: SWI instruction Exceptions: Opcode Trap COP failure Clock Monitor Failure ENG3640 Fall 2012
Event Triggers interrupt signal Main Program Several steps have to be completed by the processor to return to the instruction following the instruction that was interrupted. What are these steps? Example: Complete current instruction and clear the instruction queue. Handle Interrupt ISR RTI ENG3640 Fall 2012
Interrupt Processing (Details) Return address is pushed onto the stack. Registers are stacked (X, Y, D) After the CCR is stacked, the I bit (and the X bit, if an XIRQ interrupt service request caused the interrupt) is set to prevent other interrupts from disrupting the interrupt service routine (ISR). Execution continues at the address pointed to by the vector (ISR Routine) for the highest priority interrupt that was pending at the beginning of the interrupt sequence. At the end of the interrupt service routine, an RTI instruction restores context from the stacked registers, and normal program execution resumes. ENG3640 Fall 2012
(1).a Saving the Context Why do we save all the registers? Once a pending interrupt is detected, the CPU12 saves the context by pushing all the CPU registers onto the stack. This is similar to a subroutine call except that it saves ALL the registers instead of only the program counter! Why do we save all the registers? Because the interrupt is asynchronous to the program flow (main program was not responsible to issue interrupt!) and we cannot predict when it will occur! How do we recover from an interrupt? At the end of the interrupt routine, the rti instruction pulls the interrupt stack frame from the stack, which is known as restoring the context or switch the CPU context back to the interrupted program. ENG3640 Fall 2012
(1).b Stack Order of Registers Return stack is pushed down All locations are even to keep stack aligned for 16 bit memory models CCR only needs a byte not two bytes ENG3640 Fall 2012
(2) Set Interrupt Masks After the context is saved on the stack, the CPU sets the appropriate interrupt masks (recall, the I bit and X bit in the CCR!) If the interrupt source is one controlled by the I mask, then the `I’ bit in CCR will be set automatically. If the interrupt source is the XIRQ, then both X and I masks are set. Why does CPU set the interrupt masks? This is done to prevent nested interrupts before the system is ready. If you want to implement nested interrupts, you can clear the mask bit after entering the ISR. ENG3640 Fall 2012
(3) Vectors What is an interrupt Vector? It is a two byte fixed memory location that contains the address of the interrupt service routine for a given interrupt. The CPU12 interrupt vectors are stored at $FF80 - $FFFF. ENG3640 Fall 2012
CPU12 Exception Vector Map The six highest vector addresses are used for resets and un-maskable interrupt sources. The remaining vectors are used for maskable interrupts. All vectors must be programmed to point to the address of the appropriate service routine. ENG3640 Fall 2012
Vectors/Pseudo-Vectors How do we load the interrupt vector for an ISR? The first approach would be to write the address of the interrupt service routine in the vector address specifically intended for the source of the interrupt. Assume your handler is located in memory location $00EE then all you have to do is write that location in ROM location. Simple approach: ORG FFF2 FDB 00EE Written by the user Fixed by Systems ENG3640 Fall 2012
Using Interrupts with D-Bug12 IMPORTANT: The vectors for interrupts are stored in ROM with D-bug12 and some vectors are used by D-Bug12! When we are writing programs that use interrupts under the D-Bug12 monitor, it is impractical to change the actual interrupt vectors. To accommodate interrupts, D-Bug12 includes a utility routine “SetUserVec( )” that will load the ISR address into a jump table located in monitor RAM. ENG3640 Fall 2012
SetUserVec() Vector Numbers Interrupt Number PORTH Key Wake-up 7 PORTJ Key Wake-up 8 A-to-D 9 SCI #1 10 SCI #0 11 SPI #0 12 Pulse Accum. Edge 13 Pulse Accum. Overflow 14 Timer Overflow 15 Timer Channel 7 16 Timer Channel 6 17 Timer Channel 5 18 Timer Channel 4 19 Timer Channel 3 20 Timer Channel 2 21 Timer Channel 1 22 Timer Channel 0 23 RTI 24 IRQ 25 XIRQ 26 SWI 27 Unimplemented Opcode Trap 28 Jump Table Address -1 To use “ SetUserVec( ) “ we pass the ISR address and a vector number that corresponds to the interrupt source. For example if we need to use the Timer Channel 1 interrupt , the vector number would be 22. To call SetUserVec() in an assembly program, the ISR address is passed on top of the stack and the vector number is passed in ACC D.
SetUserVec() Vector Numbers **************************************************************************** * Equates USER_TC1 EQU 22 ; Vector Number of Timer #1 SETUSERVEC EQU $FE1A ; Address of SetUserVec() IC1HAN EQU $0438 ; Address of ISR written by user Init ldd #IC1HAN ; Initialize D-Bug 12 pushd ; push IC1Han (ISR) on stack ldd #USER_TC1 ; load vector number of TC1 ldx SETUSERVEC ; setup D-bug12 for ISR jsr 0,x puld ; clean up the stack …. ENG3640 Fall 2012
(4) Interrupting Software System There are four major components to interrupting software system: Ritual (Initialization) Main Program Interrupt Service Routine (ISR) Interrupt vectors. ENG3640 Fall 2012
(4).a Ritual The Ritual is a program executed during start-up that initializes hardware and software. It is executed once on start-up It is a good idea to disable interrupts at the beginning of the ritual using the sei instruction (which sets the I mask bit) Before exiting you have to enable interrupts using the cli instruction. ENG3640 Fall 2012
(4).b Main Program The main program will usually be run in the foreground. It usually calls the Ritual for initialization Generally performs tasks that are not time critical. ENG3640 Fall 2012
(4).c Interrupt Handler (ISR) The Interrupt Service Routine (ISR) must acknowledge an interrupt (i.e. clear flag associated with the interrupt source). For polled interrupt has to determine the source of the interrupt (priority) Information is exchanged with main program via global memory Executes an “RTI” to return control back. ENG3640 Fall 2012
(5) External Interrupts There are two external pins on the 68HC12 microcontrollers, IRQ XIRQ. These two pins are typical of those found on many microcontrollers and microprocessors. By default the CPU uses active low level detection for these two interrupt sources (i.e recall open collector/drain configuration). ENG3640 Fall 2012
(5).a IRQ The IRQ interrupt can be edge triggered or level-triggered. The triggering method is selected by programming the IRQE bit of the INTCR register. If set to ‘0’ the IRQ pin responds to low level If set to ‘1’ the IRQ pin responds to falling edge. The IRQEN bit in INTCR is used to enable the IRQ Default at startup? IRQE IRQEN ENG3640 Fall 2012
(5).a IRQ .. Cont The IRQ is a general purpose interrupt source that can be used by any peripheral circuits to interrupt the CPU. The advantage of using level detection is that we can use a wired-or circuit to connect several external sources to the same pin (open collector/drain!) What is the problem with this connection? CPU cannot determine the actual source of the interrupt! How do we determine the source? The ISR first polls the interrupt sources (requires a bus interface or an input port connected to signals that contain the interrupt status) ENG3640 Fall 2012
(5).a IRQ Source/Priority (Daisy Chain) INTA INTA INTA MCU Device #1 Device #2 Device #3 Data Address Control ENG3640 Fall 2012
(5).a IRQ .. Cont Any other problems associated with level detection? Yes, it may require additional circuitry to make sure an interrupt event is serviced one time and only one time! Without additional circuitry the level detection results in an ``as-long-as” response. We have to make sure that the interrupt signal is not too long and not too short. Why not too short? The CPU samples the interrupt signals between each instruction so the signal must be low when the CPU samples it. Therefore, to guarantee it will be detected, the interrupt signal must be low longer than the longest instruction. For applications in which level detection is not appropriate, the IRQ interrupt can be set to detect falling edges on the IRQ pin by setting the IRQE bit in the interrupt control register. ENG3640 Fall 2012
Interrupts (Priorities) On the 68HC812A4, the IRQ pin is assigned the highest I-bit interrupt priority, and the internal periodic real-time interrupt generator has the next highest priority. The other maskable sources have default priorities that follow the address order of the interrupt vectors. Using the HPRIO register, one interrupt can be made to have the highest priority. Writing $F0 to HPRIO assigns highest maskable interrupt priority to the Real Time Interrupt (to be covered later). ENG3640 Fall 2012
(5).b XIRQ (NMI) XIRQ interrupt is pseudo non-maskable!! After reset, the ‘X’ bit in the CCR is set, which inhibits all interrupt service requests from the XIRQ pin until the ‘X’ bit is cleared. The ‘X’ bit can be cleared by a program instruction, but program instructions cannot set ‘X’ to one. Once the ‘X’ bit is cleared, interrupt service requests made via the XIRQ pin become non-maskable. ENG3640 Fall 2012
XIRQ Interrupt: An Example ENG3640 Fall 2012
Real-Time Interrupt (RTI) An RTI is one that is requested on a fixed time basis. One application of an RTI is ``Periodic Polling” or ``intermittent Polling”. For example an I/O device is polled on a regular basis. We have to enable an RTI using some registers. How? ENG3640 Fall 2012
Real-Time Interrupt Registers The first step is to set the rate (how often) an RTI should happen via the RTR0, RTR1, RTR2 bits in the RTICTL register. The RTIE has to be set to enable Real Time Interrupts If an RTI occurs then bit RTIF in RTIFLG register is set. (LAB #5 Real Time Clock),Check Handout (more details) RTIE RTR2 RTR1 RTR0 RTIF ENG3640 Fall 2012
Interrupt Usage Guidelines Make sure the Interrupt Source is Enabled and Configured: The most common reason an interrupt-based system does not work is that all the appropriate enables, masks, and control registers have not been configured! Clear the Flag: Another common error is to forget to clear the source’s flag bit before exiting the ISR. Remember that the interrupt is pending as long as its flag is set. Stack Space and Pointer: Interrupts use the stack. Make sure the stack pointer is initialized before any interrupts are enabled. Be Careful When Nesting: It is best to avoid nesting at all! Keep it short: As a general rule of thumb, always keep your ISRs as short as possible (affects latency of other ISRs) Critical Regions: Make sure all critical regions are protected by masking interrupts. External Interrupt Signals: When using simple level detection, make sure the interrupt is active long enough to be detected and short enough not to be detected more than one time! ENG3640 Fall 2012
Extra Slides ENG3640 Fall 2012
Synchronization: Writing For an output device, a status flag is set when the output is idle and ready to accept more data. Software must clear the flag each time new output is started. ENG3640 Fall 2012
Output to a Printer ; MC68HC812A4 ; PortJ is DATA, PH0 = Go init ldaa #$FF staa DDRJ ; set PORTJ as OUTPUT ldaa #$01 staa DDRH ; set bit `0’ of PORTH as OUTPUT staa PORTH ; GO = 1 rts Out staa PORTJ ; set data ldaa #0 staa PORTH ; GO = 0 ldaa #1 ldd #16000 OLoop subd #1 bne OLoop ; ENG3640 Fall 2012
Strobed I/O (Asynchronous) Is a technique to coordinate transfer of data in a simple way. When the MCU sends data to a peripheral, it tells the peripheral that data is available. When the MCU reads data from the peripheral, it has to know when the next data is sent So peripheral can send a strobe signal that tells the MCU when new data is available. The strobe signal is sent to latch the data in the I/O port. ENG3640 Fall 2012
Strobed I/O: 68HC11 Status Interrupt Enable PortC Output Handshaking Input or Output Level or Pulse Edge Select ENG3640 Fall 2012
Strobed I/O: 68HC11 ENG3640 Fall 2012
Input handshake Peripheral MCU I received Data I have sent Data ENG3640 Fall 2012
Latched Input: 68HC12 MCU Keyboard PJ7 Strobe PJ6-0 DATA When the user types a key on the keyboard, the 7-bit ASCII code becomes available on the DATA, followed by a rise in the signal STROBE. The data remain available until the next key is typed. On the 6812 we can use the key wakeup feature. ENG3640 Fall 2012
Typical Program Execution Main program is either continuously running in a loop or is executing several tasks (processes) ENG3640 Fall 2012
Resets Sources: RESET pin Clock Monitor Reset COP Watchdog Reset ENG3640 Fall 2012
Exception Processing Flow Diagram ENG3640 Fall 2012
Exception Classification Exceptions can be classified by the effect of the X and I interrupt mask bits on recognition of a pending request Resets, the (i) unimplemented opcode trap, and (ii) the SWI instruction are not affected by the X and I mask bits. Interrupt service requests from the XIRQ pin are inhibited when X =1,but are not affected by the I bit. All other interrupts are inhibited when I = 1. ENG3640 Fall 2012