CSE211s Introduction To Embedded Systems: Interrupts
CSE211s Introduction To Embedded Systems: Interrupts
CSE211s Introduction To Embedded Systems: Interrupts
Topic Outlines:
➢ Simple Embedded Software Structures (Most embedded systems are simple) A super-loop is an infinite loop, with all the tasks of the system
contained in the loop.
1. Super Loop Benefit:
After system initialization, the program executes an infinite loop, • Simple
2. Event-driven program in which all tasks are executed sequentially in order.
Drawbacks:
main() { Each task in the loop does the • Wasting CPU time and system power
➢ Complex Embedded Software Structure
system_initialization(); following: checking the status of all devices, even if
• Application is decomposed into tasks: // super loop Check_Status(); not ready.
while(1){ if condition then • Accurate timing not guaranteed.
Run-to-Completion, Endless-Loop, System, and Application Tasks Task_1(); Do_Calculations();
Task_2(); • Sequential task execution results in bad
A task scheduling policy ensures task concurrency and system responsiveness. Output_Response();
…; system responsiveness as it is unable to
else
wait(35); //optional respond to an input e.g., from keyboard
} return until it reaches the keyboard task.
} end
For this reason, event-driven systems are also called reactive systems. When an interrupt occurs, it invokes a routine to handle the event.
When the CPU has nothing to do, a special instruction can put it into a power-saving state,
waiting for events.
Interrupts Basic Questions when Considering Interrupts
➢ Which peripherals are allowed to cause interrupts?
➢ Interrupts provide efficient event-based processing.
▪ The startup code configures the peripheral (and an interrupt controller) to let it cause an interrupt on a specific event. ➢ Should we have control on when to allow or disallow interrupts?
▪ A code (background) starts executing main function and other background tasks.
➢ In case we have multiple sources of interrupts, how does the interrupting source is identified?
▪ When the specified event occurs, an interrupt occurs triggering the following sequence:
11) CPU does some hard-wired processing to ➢ Which code (function) should the CPU execute to service the identified interrupt?
save its current context, to be able to come
1 ➢ How the interrupted code status is saved so that the CPU can resume it after the interrupt is serviced.
back. Also, it identifies what to execute to Main Code Hardwired CPU ISR
(Background) response activities (Foreground)
service the interrupt.
➢ What does the CPU do if multiple interrupts are requested simultaneously?
2
22) CPU executes the identified interrupt
service routine (ISR) which includes a ➢ What does the CPU do if an interrupt is requested while servicing another interrupt?
return instruction at its end. time
➢ How to share data safely between different pieces of code?
33) CPU resumes the interrupted code.
3 17
CORTEX-M Exceptions
In the ARM programmer’s model, interrupts are a type of exception. The term “exception” in ARM definition means
any deviation of program flow which may be caused by an external event (an interrupt) or any internal CPU condition.
1) External events (interrupts): Caused by an event in a peripheral which is asynchronous to the CPU.
It can be caused by:
• A condition in an on-chip peripheral module such as GPIO, ADC, Timer, UART …
• A signal on a pin of the MCU.
2) Internal CPU events:
• Requested by the program executing specific instruction such as:
▸ SVC (supervisor call) and SWI (software interrupt) by ARM
▸ INT (interrupt) by Intel (x86)
▸ TRAP by Motorola (HC12)
Cortex-M0+ Interrupts • Automatically generated trap (coerced rather than requested) caused by an exceptional condition such as:
▸ Undefined instruction
▸ Bus fault
▸ Division by zero
18
Cortex-M0+ Exception Sources CORTEX-M Interrupts
➢ The ARM Cortex-M has room for the total of 255 interrupts and exceptions.
➢ The ARM core uses vectored interrupts which means that each interrupt source is assigned:
➢ The Cortex-M0+ CPU supports up to 32 non-core interrupt sources and 16 core sources.
• An interrupt request number (IRQn) identifying itself
▪ Core exception examples:
• An interrupt vector (an address) to tell the CPU where to go to execute the service to the interrupt
• when the CPU starts up (Power-up reset or RESET pin signal)
• when errors occur e.g., the code tries to access a peripheral that is not enabled yet through clock gating.
➢ The lowest 1024 bytes (256 × 4 = 1024) of memory space are set aside for the interrupt vector table that maps
• when system services are requested. (Supervisor call; SVC instruction)
the interrupt request number IRQn to the interrupt vector and must not be used for any other function.
▪ Non-Core 32 interrupt sources (numbered IRQ0-IRQ31):
• These interrupts are caused by peripheral modules, so they are MCU-manufacturer dependent. ➢ The ARM core uses prioritized interrupts: it uses priority numbers to assign precedence to different sources.
Priority means:
➢ All Cortex-M has an on-chip interrupt controller called Nested Vector Interrupt Controller (NVIC) to interface the
• which interrupt is serviced first when simultaneous requests are made, or
CPU to different interrupt sources. It allows some degree of standardization among the ARM Cortex-Mx (M0, M1,
M3, and M4) family members. • can a new interrupt preempt a running interrupt service routine.
➢ The Nested Vector Interrupt Controller (NVIC), part of the ARM core, is configured to control the peripheral’s
20 interrupt generation behavior. It employs a priority resolution that can be customized by software.
Selected Cortex-M0+ Core Exception Sources Selected Cortex-M0+ Core Exception Sources
Vector Address Vector # Source Description Priority
2. NMI: The non-maskable interrupt request to the NVIC is controlled by the external NMI signal.
0x0000_0004 1 Reset CPU reset −3 Priority:
The lower the number, the The pin which the NMI signal is multiplexed on, must be configured for the NMI function to generate the non-
0x0000_0008 2 NMI Nonmaskable interrupt −2 higher the priority maskable interrupt request.
0x0000_000C 3 HardFault Hard fault error −1
Programmable:
0x0000_002C 11 SVCall Call to supervisor with SVC instruction Programmable Means can be changed by 3. HardFault: The catchall for assorted system failures that can take place such as accesses to bad memory,
program.
0x0000_0038 14 PendSV System-level service request Programmable divide-by-zero errors and illegal unaligned accesses.
0x0000_003C 15 SysTick System timer tick Programmable
11. SVCall: Exception handler invoked when a Supervisor Call (svc) instruction is executed.
1. Reset: is caused by
• Asserting RESET pin which wakes the device from any mode. 14, 15. PendSV & SysTick: System level interrupts triggered by software. They are typically used when
• Power-on reset beginning with the on-chip regulator in full regulation and system clocking generation from an internal reference. running areal-time operating system (RTOS) to manage when the scheduler runs and when context switches
Reset provides a way to start processing from a known set of initial conditions: take place.
1. The CPU performs the following:
• Reads the start SP (SP_main) from vector-table offset 0
• Reads the start PC from vector-table offset 4 The interrupts that are external to the core are usually routed to vendor-specific peripherals on the MCU such
• LR is set to 0xFFFF_FFFF
as GPIOs. All these interrupts are configured via the Nested Vectored Interrupt Controller (NVIC).
2. The on-chip peripheral modules are disabled.
3. The non-analog I/O pins are initially configured as disabled.
4. The pins with analog functions assigned to them default to their analog function.
22 23
KL25Z Interrupt Sources
ARM Cortex-M NVIC
Vector address Vector # IRQ Description
0x0000_0040, 44, 48, 4C 16–19 0–3 Direct memory access controller
Mapping IRQ number to interrupt vector: ➢ If any enabled interrupts are requested, the NVIC selects the one with the highest priority and directs the CPU
0x0000_0058 22 6 Power management controller
For example, if PORTD requests an interrupt: to start executing its ISR.
0x0000_005C 23 7 Low leakage wake up
2
0x0000_0060, 64 24–25 8–9 I C communications 1. The port control module signals the NVIC. ➢ The supported 32 interrupt sources IRQ0 through IRQ31 can be configured individually:
0x0000_0068, 6C 26–27 10–11 SPI communications
– Enabled or disabled
0x0000_0070, 74, 78 28–30 12–14 UART communications
2. The NVIC will issue interrupt request #31 – Prioritized
0x0000_007C 31 15 Analog to digital converter
0x0000_0080 32 16 Comparator to the CPU. – Set as pending (requested but not yet serviced)
0x0000_0084, 88, 8C 33–35 17–19 Timers and pulse-width modulation
0x0000_0090, 94 36–37 20–21 Real-time clock alarm and seconds
➢ Interrupt processing status can be read and modified
3. The CPU will read the vector table to find
0x0000_0098 38 22 Programmable interval timer
the location of the ISR for IRQ #31
0x0000_00A0 40 24 USB on-the-go
0x0000_00A4 41 25 Digital to analog converter (vector #47). It will read the word starting
0x0000_00A8 42 26 Touch sense interface
0x0000_00AC 43 27 Main clock generator at address 0x0000_00BC and load it into
0x0000_00B0 44 28 Low power timer
the PC so the ISR starts. ➢ The Wakeup Interrupt Controller WIC duplicates the interrupt masking of NVIC which enables NVIC to be
0x0000_00B8 46 30 Port control module, Port A pin detect
0x0000_00BC 47 31 Port control module, Port D pin detect turned off when the system is idle or sleeping to reduce power.
The WIC will wake up the NVIC if new interrupts are requested, ensuring they are processed and not lost.
24
IRQ number = interrupt vector number ̶ 16:
• To disable an interrupt source n, write a 1 to bit n in ICER. • NVIC_SetPendingIRQ(IRQnum) Sets interrupt pending flag for IRQnum
• NVIC_ClearPendingIRQ(IRQnum) Clears interrupt pending flag for IRQnum
CMSIS Interface:
– NVIC_EnableIRQ(IRQn) to enable interrupt of type IRQn
– NVIC_DisableIRQ(IRQn) to disable interrupt of type IRQn
➢ Reading ISER or ICER will return the enabled/disabled state for all 32 IRQ sources.
2. New exception has priority lower than or equal to current priority, then
» Hold new exception pending state.
» Current handler continues and completes execution.
» Previous priority level restored.
» Start new exception handler if its priority level allows.
Initializing the Interrupt Vector Table Initializing the Interrupt Vector Table
➢ CMSIS-CORE specifies standard names for system exception handlers.
➢ Different microcontrollers have different peripherals, so the interrupt handler’s names and vectors are
defined in the MCU-specific startup code.
➢ The Define Constant Data DCD symbol tells the assembler to define a constant data word with the value
specified. In this case it is the address of the specified handler (the interrupt vector).
The definition of the Interrupt Vector Table IVT in the KL25Z4 MCUs assembly language file startup_MKL25Z4.s (16 exceptions) The rest of the IVT in the KL25Z4 MCUs assembly language file startup_MKL25Z4.s (IRQ0-22 out of 32)
Initializing the Interrupt Vector Table Interrupt Configuration
➢ In order to use hardware interrupts from a peripheral module we must go through three steps to configure the
interrupt from that module :
22. The NVIC to selectively enable and give priority to that IRQ
The rest of the IVT in the KL25Z4 MCUs assembly language file startup_MKL25Z4.s (IRQ23-31 out of 32) 1 2 3
Interrupt 1. Entering
occurs Exception Sequence
time
3. Exiting Exception
Sequence
Code operations
Hardware operations (Done transparently)
42 43
[1] Entering an Exception Handler (Done Transparently) 1. Finish Current Instruction
1. Finish current instruction (except for lengthy instructions) ➢ Most instructions are short and finish quickly in one cycle
The hardware itself implements the ARM ➢ Some instructions may take many cycles to execute:
2. Push context (832-bit words) onto current stack (MSP or PSP)
Architecture Procedure Calling Standard (AAPCS).
Load Multiple (LDM), Store Multiple (STM), Push, Pop, MULS (32 cycles for some CPU core implementations)
3. Switch to handler/privileged mode, use main stack pointer MSP
Waiting for such instructions to complete will delay interrupt response significantly.
4. Load PC with address of exception handler from Interrupt Vector Table.
➢ If one of these instructions is executing when the interrupt is requested, the processor does the following:
5. Load LR with EXC_RETURN code. (Note LR does not hold the Return Address which is saved on the stack) ▪ abandons the instruction
Reset
Thread
Mode.
MSP or PSP.
Port D ISR
▪ Which SP to restore registers from? MSP (0) or PSP (1)
PORTD_IRQHandler
◦ Previous value of SPSEL
Port A ISR PORTA_IRQHandler
▪ Which mode to return to? Handler (0) or Thread (1)
◦ Another exception handler may have been running when this exception was requested
Non-maskable Interrupt
Service Routine NMI_IRQHandler
EXC_RETURN Return Mode Return Stack Description
Contains Port D Interrupt Vector 0x0000_00BC PORTD_IRQHandler 0xFFFF_FFF1 0 (Handler) 0 (MSP) Return to exception handler
Contains Port A Interrupt Vector 0x0000_00B8 PORTA_IRQHandler
0xFFFF_FFF9 1 (Thread) 0 (MSP) Return to thread with MSP
Contains Non-Maskable Interrupt Vector 0x0000_0008 NMI_IRQHandler
0x0000_0004 start
Contains Reset Interrupt Vector 0xFFFF_FFFD 1 (Thread) 1 (PSP) Return to thread with PSP
48 50
▪ IPSR is loaded with exception number and exception handler starts running, unless
preempted by a higher-priority exception
51 52
[3] Exiting an Exception Handler 1. Execute Instruction for Exception Return
1. Execute instruction triggering exception return processing
There is no “RETURN FROM INTERRUPT” instruction. Instead use regular instruction: ➢ The processor saves an EXC_RETURN value to the LR on
i. BX LR - Branch to address in LR by loading PC with LR contents. exception entry. The exception mechanism relies on this value to
ii. POP …, PC - Pop address from stack into PC.
detect when the processor has completed an exception handler:
… with a special value EXC_RETURN loaded into the PC to trigger exception handling processing
i. BX LR used if EXC_RETURN is still in LR ▪Bits[31:4] of an EXC_RETURN value are 0xFFFFFFF.
ii. POP used if EXC_RETURN has been saved on stack EXC_RETURN Description
➢ When the processor loads a value matching this pattern to the PC it Return to Handler mode.
Exception return gets state from the
2. Select return stack, restore context from that stack detects that the operation is not a normal branch operation and, 0xFFFFFFF1
main stack MSP.
i. Check EXC_RETURN (bit 2) to determine from which SP to pop the context Execution uses MSP after return.
instead, that the exception is complete. As a result, it starts the
ii. Pop the registers from that stack Return to Thread mode.
SP points here after handler exception return sequence. 0xFFFFFFF9 Exception return gets state from MSP.
Execution uses MSP after return.
Return to Thread mode.
➢ Bits[3:0] of the EXC_RETURN value indicate the required return 0xFFFFFFFD Exception return gets state from PSP.
stack and processor mode, as in the table: Execution uses PSP after return.
All other values Reserved.
• Bit0 indicates thumb mode
SP points here during handler
• Bit2 indicates PSP
3. Resume execution of code at restored address • Bit3 indicates MSP
53 54
55 56
[2] Executing The Exception Handler Differences Between Interrupt and Subroutine Call (BL)
Rules to write an exception handler:
➢ A BL instruction is used by the programmer in the sequence of instructions
▪ No arguments or return values – void is only valid type ➢ The interrupt is caused by a hardware event; it comes at any time.
▪ Name the ISR according to CMSIS-CORE system exception names, to ensure that the software toolchain places
ISR addresses in the IVT correctly. ➢ A BL instruction automatically saves only PC of the next instruction on the stack.
The linker will load the vector table with this handler rather than the default handler.
➢ Before servicing an interrupt, the LP, R12, R3–R0, xPSR (flag register) in addition to PC
Examples: are automatically saved on stack.
▪ void PORTA_IRQHandler(void); PORTA_IRQHandler,
▪ void RTC_IRQHandler(void); RTC_IRQHandler, etc.
➢ The BL instruction does not change the CPU execution mode.
▪ Keep it short and simple: Much easier to debug and improves system response time. ➢ An interrupt puts the CPU in the Handler Mode.
▪ Make sure to clear interrupting flag at the end of the ISR before the “Return” instruction.
57 This step is essential to avoid recurrent interrupts from the same source. 58