Interrupts, Phototransistors, Opto-isolators, Triacs, and Thermistors Alex Buchanan Aaron May Peter Ngo Reason for Interrupts • You might want a certain subroutine executed immediately after a request from an external device or from an internal program, providing certain conditions are met. • Interrupts do just this by suspending the execution of the current program in order to execute the subroutine Request Checking Implementation • There are 2 ways of implementing Request Checking • Polling • Interrupts Polling • Polling iteratively checks a device or registers for data. • This method of implementing request checking is cumbersome as it requires the MC to frequently suspend operations to check for new data from devices or registers. Interrupts • Nothing is done until a Request is issued • Once issued, the CPU suspends execution of the main program until instructions in the Interrupt Service Routine (ISR) are executed • More efficient than constantly scanning devices or registers for new Data Hardware Interrupt Complete Current Instruction Software Interrupt (SWI) YES 1 Maskable Mask Set NO 0 Complete Current Instruction Wait For Interrupt (WAI) Store MPU Registers to SP YES Hardware Interrupt Wait For Interrupt (WAI) Maskable NO Is the Mask Set? SP -6 Condition Code Register SP -5 Accumulator B SP -4 Accumulator A SP -3 Index Register (MS) SP -2 Index Register (LS) SP -1 Program Counter (MS) SP Program Counter (LS) NO YES 1 Stack Pointer Set Mask (CCR4) (set to 1) 0 Load Interrupt Vector into PC Condition Code Register X Begin Interrupt Program (ISR) Clear Mask (CCR4) (set to 0) Back to Main Program Interrupts: Flow Interrupt Vector I Stacking Order when an Interrupt Occurs Memory Location CPU Registers SP PCL SP-1 PCH SP-2 IYL SP-3 IYH SP-4 IXL SP-5 IXH SP-6 ACCA SP-7 ACCB SP-8 CCR Last value to be pulled from stack Hardware Interrupt Software Interrupt (SWI) Wait For Interrupt (WAI) Complete Current Instruction YES 1 Maskable Mask Set NO 0 Complete Current Instruction Store MPU Registers to SP YES Hardware Interrupt Wait For Interrupt (WAI) 1. 2. 3. 4. 5. 6. NO Maskable YES 1 Mask Set 7. NO Set Mask (CCR4) (set to 1) 0 Load Interrupt Vector into PC Begin Interrupt Program (ISR) Clear Mask (CCR4) (set to 0) Back to Main Program Interrupts: Flow: IRQ Example 1 8. 9. If I bit in CCR is not set (I=0) and IRQ goes low for at least 2 cycle, the IRQ sequence is entered. Internal registers stored to RAM (SP). The IRQ mask bit set (I=1). Data at FFF2 gets loaded into PCH Data at FFF3 gets loaded into PCL PC contents go out on address bus during 1. Contents of the location addressed enter instruction register and are decoded as first instruction of interrupt routine. If it is a more than 1-byte instruction, additional bytes enter MPU for execution. If not, go to next step After execution, step 7 is repeated for subsequent instructions. This is repeated until “RTI” is executed. RTI tells the MPU that service is complete and that it may reload the registers and continue the main program from where it left off. Interrupt Types 2 Types : • Maskable • • • • 27 Maskable Interrupts Split into Local and Global Types Lower Priority than Non-Maskable Priority between Maskable Interrupts can be adjusted via the HPRIO • Non-Maskable • 6 Non-Maskable Interrupts • Default Priority between Non-Maskable Interrupts that cannot be adjusted Maskable Interrupts • Global • I-bit in the CCR • Local • Interrupt enable bit • Follows a default priority arrangement • Any one interrupt can be promoted to higher priority using HPRIO register Any can be assigned the highest maskable interrupt priority... 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. IRQ Real-Time Interrupt Standard Timer Channel 0 Standard Timer Channel 1 Standard Timer Channel 2 Standard Timer Channel 3 Standard Timer Channel 4 Standard Timer Channel 5 Standard Timer Channel 6 Standard Timer Channel 7 Standard Timer Overflow Pulse Accumulator A Overflow Pulse Accumulator Input Edge SPI transfer Complete SCI system ATD Port J CRG PLL Lock CRG Self Clock Mode Flash CAN Wakeup CAN Errors CAN Receive CAN Transmit Port P PWM Emergency Shutdown VREG LVI Maskable Interrupts: IRQ Input • IRQ pin provides additional external interrupting source • IRQE bit in Options Register used to configure IRQ for Edge-Sensitive-Only Operation • IRQE = 0 IRQ is configured for low level sensitive operation • IRQE = 1 IRQ is configured for falling edge-sensitive operation HPRIO Register for Maskable Interrupts • Used to elevate priority of any one maskable interrupt • Default is IRQ • Set by changing contents of HPRIO (Highest Priority Interrupt Register) • Can only be written when I-bit is set HPRIO Register for Maskable Interrupts Address: $001F Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 PSEL7 PSEL6 PSEL5 PSEL4 PSEL3 PSEL2 PSEL1 Bit 0 PSEL[7:1] – Priority Select Bits • Selects one interrupts source to be elevated • Can only be written while I-bit in the CCR is set • Write the low byte of the maskable interrupt vector to HPRIO to elevate that maskable interrupt to the highest priority • Ex: writing $DE to HPRIO elevates the Standard Timer Overflow to highest priority (Standard Timer Overflow vector = $FFDE) Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 1 1 0 1 1 1 1 PSEL7 PSEL6 PSEL5 PSEL4 PSEL3 PSEL2 PSEL1 Bit 0 - Non-Maskable Interrupts • 6 Non-Maskable Interrupts • Follows a default priority arrangement • Interrupts are not subject to global masking • Except XIRQ • Global mask is X in CCR 1. 2. 3. 4. POR of RESET pin Clock monitor reset COP watchdog reset Unimplemented instruction trap 5. Software interrupt (SWI) 6. XIRQ interrupt Non-Maskable Interrupts: Unimplemented instruction trap • Generates interrupt request to Unimplemented instruction trap vector • Reinitializes stack pointer once interrupt service is completed • Left un-initialized, illegal opcode vector can cause infinite loop causing stack underflow Non-Maskable Interrupts: Software Interrupt-SWI • Software instruction, thus cannot be interrupted until completed • Uninhibited by global mask bits in the CCR • Similar to other interrupts, sets I-bit upon servicing Non-Maskable Interrupts: XIRQ • Enabled by TAP (Transfer accumulator A to CCR) which, while being unable to transfer the X-bit from 0->1 will convert the X-bit from 1->0 • After it is cleared, software cannot set X-bit (only set by the XIRQ or during Reset), thus XIRQ is nonmaskable • Higher priority than any source maskable by I-bit • Both X and I bits are both automatically set by Reset or recognition of XIRQ interrupt • RTI restores X and I bit to pre-interrupt states Interrupt Vectors • Points to the memory address where the Interrupt Subroutine is stored • Vector addresses can change depending on whether MON12 is in use or not MON12 calls ISR’s specified by the user in the $0Fxx range The microcontroller calls ISR’s specified in the $FFxx range. Interrupt Vector Table (MON12 in Use) … Interrupt Vector Table (MON12 Not in Use) Resets • Forces MCU to: • • Assume set of initial conditions Begin executing instructions at predetermined starting address • Initiated similarly to interrupts by using a vector to define the starting address of code to be run • Resets completely stop execution of set of instructions Sources of Resets • Power on Reset (POR) • • • Used only for power-up conditions Applying Vdd to MCU triggers POR circuit, initiates reset sequence, and starts internal timing circuit 4064 clock cycle delay after oscillator becomes active, allows clock generator to stabilize • External Reset (RESET) • • System reset can also be forced by applying low level to RESET pin External source must hold reset pin low for a total of 6 cycles Sources of Resets • Computer Operating Properly (COP) Reset • • • Protects against software failures, such as infinite loops Enabled by setting NOCOP bit in CONFIG register Timer rate controlled in OPTION Register. System E-clock is divided by 215 and further scaled by 1, 2, and 4 • Clock Monitor Reset • • • Protects against clock failure Set by CME control bit If enabled, the system resets if no MCU clock edges are detected Process Flow out of Resets When Reset is triggered: • Program counter loaded with contents of specified address from the vector • S, X, and I bits are set in CCR • MCU hardware is reset • Checks for interrupts that have occurred Standby Modes • Suspends CPU operation until reset or interrupt occurs • Used to reduce power consumption • Two standby modes: • • WAIT STOP Standby Modes: WAIT • • • • Opcode (WAI) Suspends CPU processing CPU registers are stacked On-chip crystal oscillator remains active • Peripherals keep running • Exit WAIT mode through external IRQ, XIRQ, or any internally generated interrupts Standby Modes: STOP • • • • • If S-bit in the CCR is 0, CPU goes into Stop mode If S-bit in the CCR is set, opcode is treated as NOP All clocks and internal peripherals are stopped Retains data in Internal RAM if Vdd is maintained CPU state and I/O pins are static Standby Modes: STOP • Exit STOP mode through external interrupts, pending edge-triggered IRQ, or RESET pin • Recovering through XIRQ: • • X-bit is clear Returns to stacking sequence leading to normal XIRQ request X-bit is set Returns to instruction immediately following STOP instruction INTERRUPT PROGRAM EXAMPLE Example Problem: 1ms interrupt • Write a routine to interrupt the MC9S12C32 after 1ms of elapsed time. Assume: • E = 8 Mhz, Prescaler = 1, MON12 in use • Use IOC3 channel to generate interrupt request • IOC3 will be used in output compare mode (OC3) • Standard timer channel 3 interrupt will be sent Timer Module and Port T IOC3 will be used in output compare mode Write a routine to interrupt the MC9S12C32 after 1msec of elapsed time. 1: Assign values to labels 2: Delay unwanted interrupts 3: Set timer registers 4: Store ISR 5: Set delay & unmask TC3HI TIOS TIE TFLG1 TCTL2 TCNT IOC3ISR IOC3VEC BIT3HI DLYIOMS EQU EQU EQU EQU EQU EQU EQU EQU EQU ORG SEI LDAA STAA STAA STAA LDAB STAB LDX STX LDD ADDD STD CLI $0056 $0040 EQU $004E $0049 $0044 $2000 $0FE8 %00001000 8000 $1000 Example Problem: 1ms interrupt /* IOC3 output compare register */ /* Input capture or output compare mode select */ $004C /* Timer interrupt enable register */ /* Timer interrupt flag register 2 */ /* Timer control register 2 */ /* Timer count register */ /* Location of IOC3 interrupt service routine */ /* Location of IOC3 interrupt vector */ /* Bit 3 set HIGH, all others LOW */ /* Number of delay cycles. 8000 cycles = 1ms */ /* Set I bit in CCR to mask interrupts during this routine*/ /* BIT3HI = %00001000 */ /* Configure IOC3 as output compare */ /* Enable IOC3 interrupt generation */ /* Clear IOC3 interrupt flag*/ #BIT3HI TIOS TIE TFLG1 #%11000000 TCTL2 /* Successful compare will set PT3 high */ #IOC3ISR /* IOC3ISR = $2000, starting address of ISR */ IOC3VEC /* IOC3VEC = $0FE8, high byte ($20) stored in $0FE8, low byte ($00) stored in $0FE9 */ TCNT /* Read current count from timer count register */ #DLYIOMS /* Add delay of 8000 cycles (=1ms) */ TC3HI /* Clear I bit in CCR to allow maskable interrupts */ Step 1: Assign values to labels TC3HI TIOS TIE TFLG1 TCTL2 TCNT IOC3ISR IOC3VEC BIT3HI DLYIOMS EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU $0056 $0040 $004C $004E $0049 $0044 $2000 $0FE8 %00001000 8000 Example Problem: 1ms interrupt /* IOC3 output compare register*/ /* Input capture/output compare select*/ /* Timer interrupt enable register*/ /* Timer interrupt flag register 2 */ /* Timer control register 2*/ /* Timer count register*/ /* Location of IOC3 ISR*/ /* Location of IOC3 interrupt vector*/ /* Bit 3 set HIGH, all others LOW*/ /* 8000 cycles = 1ms*/ • Treat these as named constants • EQU is an assembler directive (not a CPU instruction!) • Register addresses found in MC9S12C32 Device User Guide • Register details found in TIM_16B8C Block User Guide Step 2: Delay unwanted interrupts ORG SEI Example Problem: 1ms interrupt $1000 /* Set I bit in CCR to mask interrupts */ /* Clear I bit at the end of our routine */ Alternatively, ORG LDD STD $1000 #$FFFF TC3HI /* Set output compare reference to maximum */ /* Store output compare reference */ • Understand why both work. What are the differences? Example Problem: 1ms interrupt Step 3: Write to timer registers LDAA STAA STAA STAA LDAB STAB #BIT3HI TIOS TIE TFLG1 #$C0 TCTL2 /* BIT3HI = %00001000 */ /* Configure IOC3 as output compare (IOS3)*/ /* Enable IOC3 Interrupt bit (C3I)*/ /* Clear IOC3 Interrupt Flag bit (C3F) */ /* #$C0 = #%11000000 */ /* Successful compare will set PT3 high */ • Configure desired settings using the timer registers 7 TIOS 6 5 4 3 2 1 0 IOS7 IOS6 IOS5 IOS4 IOS3 IOS2 IOS1 IOS0 7 6 5 4 3 2 1 0 $0040 TIE C7I 7 C6I 6 C5I 5 C4I 4 C3I 3 C2I 2 C1I 1 C0I 0 $004C TFLG1 C7F 7 C6F 6 C5F 5 C4F 4 C3F 3 C2F 2 C1F 1 C0F 0 $004E TCTL2 OM3 OL3 OM2 OL2 OM1 OL1 OM0 OL0 $0049 Step 4: Store ISR LDX STX #IOC3ISR IOC3VEC Example Problem: 1ms interrupt /* IOC3ISR = $2000, starting address of ISR*/ /* IOC3VEC = $0FE8, high byte ($20) stored in $0FE8 and low byte ($00) stored in $0FE9 */ • In this example, ISR is located in $2000 • Standard timer channel 3 interrupt vector is $0FE8 (hi) : $08FE9 (lo) when MON12 is in use Step 5: Set delay and interrupt LDD ADDD STD CLI Example Problem: 1ms interrupt TCNT /* Read current count from timer count register*/ #DLYIOMS /* DLYIOMS = 8000. 8000 cycles = 1ms delay*/ TC3HI /* Clear I bit */ • TCNT is a 16-bit up-counter based on the bus clock • Read in count from TCNT and add 8000, store contents in IOC3 output compare register • Clear I bit in CCR to enable maskable interrupts • Approximately 1ms after this section, a Standard timer channel 3 interrupt request will be sent to the CPU PHOTOTRANSISTORS*, OPTO-ISOLATORS*, TRIACS, AND THERMISTORS * = USED IN ME 4447/6405 Phototransistors • Behave like regular transistors, but: • Use light-sensitive collector-base junction to control collectoremitter current (ICE) • Base often unconnected, otherwise biased to adjust sensitivity to light • Small collector-emitter leakage current when no light is incident, called dark current Phototransistor Structure and Packaging http://www.radioelectronics.com/info/data/semicond/ phototransistor/photo_transistor.php Phototransistor Application: Obstacle Detection • Adjust baffle length to vary detection range • Use IR LED and Photodiode to avoid visible light interference • Use multiple sensors in a row to detect narrow obstacles Phototransistors: Additional Notes • Must be properly biased (as with regular transistors) • Used in linear and saturation/cut-off regions • Sensitive to temperature changes • Must be protected against moisture • Hermetic packaging more expensive, but more tolerant of severe environments than plastic packaging Optoisolators • • • • Combines IR LED with IR photodiode Operates similar to relays Used to control high voltage devices Excellent noise isolation because switching circuits are electrically isolated • Eliminates need for common ground between circuits Optoisolators are like relays Optoisolator Relay Optoisolator Structure • Glass dielectric separates input from output Planar Silicon dome Optoisolator Application • Transmitting analog or digital signals between circuits, esp. with mismatched voltages, noise issues, inductive loads • Arduino isolated from relay drivers: To Arduino To Arduino http://arduinoinfo.wikispaces.com/RelayIsolation Optoisolators: Additional Notes • Non-transistor optoisolators exist • • • • • Resistive optoisolator Diode optoisolator Optoisolated SCR Optoisolated TRIAC Solid-state relay (photoresistor output) (photodiode output) (thyristor output) (TRIAC output) • Relevant parameters for comparison: • • • • • Current Transfer Ratio (output current/input current) Maximum output voltage Input current, required for activating input transmitter Bandwidth Speed Triacs (Triode for Alternating Current) • Conducts current in either direction when triggered, until current drops below holding current threshold • Bidirectionality makes TRIACs excellent AC switches • Can handle large power flows (hundreds of amps / thousands of watts) • Effectively based on thyristors Triacs and Thyristors • Triacs are effectively 2 thyristors back-to-back Thyristor Triac Triac Structure Triac Applications • High Power TRIACS • Switching for AC circuits, allowing the control of very large power flows with milliampere-scale control currents • Can eliminate mechanical wear in a relay • Low Power TRIACS • • • • Light bulb dimmers (switching AC wave) Motor speed controls for electric fans and other AC motors Heater control Modern computerized control circuits in household appliances Triac Application: Light dimmer • Switching of waveform varies power transmission Triacs: Additional Notes • Pros: • Better than a transistor in current surge rating – it can handle more current, as it simply turns on more • Cheaper than relays • Cons: • Cannot open switch with gate; must reduce current through the device below its holding current to turn off • Relevant parameters: • • • • Gate signal requirements Voltage drop Steady-state/holding current Peak current (maximum amount to handle surge) Thermistors V or R • Temperature sensitive resistors • Change in resistance is very large and precise in relation to change in temperature • Exhibit larger resistance change with temperature than thermocouples and RTD’s Thermistor resistance (sensitive in small T range) RTD resistance (stable over large T range) T Thermocouple voltage (versatile) Thermistor Characteristics • Extremely non-linear (high process dependency) • An individual thermistor curve can be very closely approximated by using the Steinhart-Hart equation: 1 T T = Degrees Kelvin = A B ln( R) 3 C ln( R) R = Resistance of the thermistor A,B,C = Curve-fitting constants Thermistor Characteristics • Wheatstone bridge with selector switch to measure temperature at several locations Thermistors: Additional Notes • Generally composed of semiconductor materials • Very fragile and prone to permanent decalibration • Most have a negative temperature coefficient (NTC); resistance decreases with increasing temperature • Positive temperature coefficient (PTC) thermistors also exist with directly proportional R vs. T. • Common ranges are -100°F (-75°C) to +300°F (150°C); Some can reach up to 600°F References • Interrupt program example: 1ms interrupt • Timer module register details from TIM_16B8C Block User Guide • Phototransistors • http://www.radio-electronics.com/info/data/semicond/phototransistor/photo_transistor.php • Optoisolators • http://arduino-info.wikispaces.com/RelayIsolation • http://yourduino.com/sunshop2/index.php?l=product_detail&p=218 • Triacs • http://www.radio-electronics.com/info/data/semicond/triac/what-is-a-triac-basics-tutorial.php • http://www.digikey.com/us/en/techzone/lighting/resources/articles/Dimming-LEDs-withTraditional-TRIAC-Dimmers.html • http://www.circuitstoday.com/diac-applications • Thermistors • http://www.radio-electronics.com/info/data/resistor/thermistor/thermistor.php • Previous student lectures • Interrupts, Thermistors, Opto-isolators and Phototransistors – Fall 2009 – Kipp Schoenwald, Stephen Hunte, Joseph Storey • DACs and Triacs – Fall 2009 – Wye-Chi Chok Questions?