0% found this document useful (0 votes)
47 views46 pages

Interrupts and Timers in Cortex-M MCUs

The document outlines the concepts of interrupts and timers in microcontrollers, specifically focusing on the Cortex-M architecture. It details types of interrupts, the Nested Vectored Interrupt Controller (NVIC), and the exception handling sequence, along with programming examples for ADC interrupts and GPIO external interrupts. Additionally, it covers timer functionalities, including the SysTick timer, and their applications in generating delays and counting events.

Uploaded by

aashitajain.ec21
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views46 pages

Interrupts and Timers in Cortex-M MCUs

The document outlines the concepts of interrupts and timers in microcontrollers, specifically focusing on the Cortex-M architecture. It details types of interrupts, the Nested Vectored Interrupt Controller (NVIC), and the exception handling sequence, along with programming examples for ADC interrupts and GPIO external interrupts. Additionally, it covers timer functionalities, including the SysTick timer, and their applications in generating delays and counting events.

Uploaded by

aashitajain.ec21
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

RV College of

Engineering

Unit 5
Interrupts and Timers
1

MGR,ECE,RVCE
Unit 5: Syllabus
Interrupts and Timers:
Types of interrupts, Nested vector interrupt controller (NVIC) in Cortex-M cores,
Interrupt vectors, Priorities, Programming interrupts.
Timers, Controlling the operation, Programming with timers, Pulse width
modulators, Programming modulators to generate PWM wave for given
specifications.

2 MGR,ECE,RVCE
Basics of Interrupts/Exceptions
 Interrupts are a common feature available in almost all microcontrollers.
 Interrupts are events typically generated by hardware (e.g., peripherals
or external input pins) that cause changes in program flow control
outside a normal programmed sequence (e.g., to provide service to a
peripheral).
 When interrupt happens, the processor suspends the current executing
task and executes a part of the program called the exception handler or
Interrupt service routine(ISR).
 In Cortex-M processors, there are a number of exception sources.

3 MGR,ECE,RVCE
•Interrupt causes main function to be suspended & the interrupt service
routine(ISR) to run
Interrupt
level execution
(Back ground function)

ISR ISR ISR

Base-level
Execution Main Main Main Main
(Fore ground function)

Interrupt/Exception (occurs asynchronously/Synchronously)

4 MGRJ,ECE,RVCE
Types of interrupts
 Hardware interrupt: These occurs by the interrupt request
signal from peripheral circuits. All hardware interrupts are
asynchronous w.r.t of code execution because arrival is not known.
 Software interrupt: These occurs by executing a dedicated
instruction. Software interrupts are synchronous as the occurrence
these are dependent on instruction execution.

5 MGR,ECE,RVCE
Nested Vectored Interrupt Interrupts…
Controller(NVIC)
 An interrupt controller called NVIC
supporting up to 240 interrupt
requests and from 8 to 256 interrupt
priority levels.
 Exceptions are processed by the
NVIC. The NVIC can handle a
number of Interrupt Requests (IRQs)
and a Non-Maskable Interrupt (NMI)
request.
• Usually IRQs are generated by on-chip peripherals or from external interrupt inputs
though I/O ports.
• Inside the processor there is also a timer called SysTick, which can generate a
periodic timer interrupt request.
6 MGR,ECE,RVCE
NVIC…
 Each exception source has an exception number. Exception numbers 1 to
15 are classified as system exceptions, and exceptions 16 and above are for
interrupts.
 The design of the NVIC in the Cortex-M4 processors can support up to 240
interrupt inputs. However, in practice the number of interrupt inputs
implemented in the design is far less, typically in the range of 16 to 100.
 The exception number is reflected in various registers, including the IPSR,
and it is used to determine the exception vector addresses. Exception
vectors are stored in a vector table.
 Reset is a special kind of exception. When the processor exits from a reset,
it executes the reset handler in Thread mode.
7 MGR,ECE,RVCE
Interrupt sources in Cortex M4 based MCUs
 Exceptions are numbered 1 to 15 for system exceptions and 16 and above for
interrupt inputs (inputs to the processor, but not necessarily accessible on the I/O
pins of the package).
 Most of the exceptions, including all interrupts, have programmable priorities, and a
few system exceptions have fixed priority.
 The Cortex-M4 NVIC supports up to 240 IRQs (Interrupt Requests), a Non-
Maskable Interrupt (NMI), a SysTick (System Tick) timer interrupt, and a number of
system exceptions. Most of the IRQs are generated by peripherals such as timers,
I/O ports, and communication interfaces (e.g., UART, I2C).
 The NMI is usually generated from peripherals like a watchdog timer or Brown-Out
Detector (BOD). The rest of the exceptions are from the processor core. Interrupts
can also be generated using software.
8 MGR,ECE,RVCE
Interrupt sources in Cortex M4 based MCUs…

IRQs,NMI: These
interrupt requests.

Exceptions: These are


similar to interrupts but
generated because of
execution of an
instruction or fault
occurring while
program execution.

9 MGR,ECE,RVCE
Interrupt sources in Cortex M4 based MCUs…
Exception Priority Exception Descriptions
type number
 Exception Reset -3(Highest) 1 Reset
NMI -2 2 Non-Maskable Interrupt (NMI), can be generated from on chip
types 1 to 15 peripherals or from external sources.
are system Hard Fault -1 3 All fault conditions, if the corresponding fault handler is not enabled
exceptions MemManage Fault Programmable 4 Memory management fault

(there is no Bus Fault Programmable 5 Bus error; usually occurs when AHB interface receives an error
response from a bus slave (also called prefetch abort if it is an
exception type instruction fetch
or data abort.
0).
Usage Fault Programmable 6 Exceptions due to program error or trying to access co-processor
Reserved --- 7-10
SVC Programmable 11 SuperVisor Call
Debug Monitor Programmable 12 Debug monitor
Reserved -- 13
PensSV Programmable 14 Pendable service call;
SYSTICK Programmable 15 System Tick Timer
10 MGR,ECE,RVCE
Interrupt sources in Cortex M4 based MCUs…
 Exceptions of Exception Priority Exception Descriptions
type number
type 16 or above
Interrupt #0 Programmable 16 It can be generated from on chip peripherals or from
are external external sources.
Interrupt #1 Programmable 17
interrupt inputs.
---- --- --
Interrupt #239 Programmable 255

11 MGR,ECE,RVCE
Vector Table
 When the Cortex-M processor
accepts an exception request, the
processor needs to determine the
starting address of the exception
handler (or ISR if the exception is
an interrupt).
 By default, the vector table starts at
memory address 0, and the vector
address is arranged ac- cording to
the exception number times four.

12 MGR,ECE,RVCE
Vector Table of STM32F407VG
 The vector table is normally defined in the start up codes provided by the
microcontroller vendors.

13 MGR,ECE,RVCE
Vector Table of STM32F407VG…

Vector table is defined in


startup_stm32f407xx.s file

14 MGR,ECE,RVCE
Exception Sequence
 When an exception occurs and is accepted by the processor, the core
performs sequence of operations before passing control to ISR. The process is
called exception sequence and is as follows:
- Finishes current instructions (except for lengthy instructions).
- Push 8 32 bit words(xPSR, Return address, LR, R12,R3,R2,R1,R0) on to stack.
- Switch to handler privileged mode and use MSP.
- Load LR with EXC_RETRUN code.
- Load IPSR with exception number.
- Start execution of interrupt service routine.
EXC_RETURN: The value of this code is used to trigger the exception return
mechanism when it is loaded into the Program Counter (PC) using BX, POP,
or memory load instructions (LDR or LDM).
15 MGR,ECE,RVCE
Exception Sequence…

 EXC_RETURN Example:
Value 0xFFFFFFF9 indicate Return to Thread mode and use the Main Stack for return.

 The figure below shows storing of context on stack.

16 MGR,ECE,RVCE
Interrupt management
 The Cortex-M processors have a number of programmable registers for managing
interrupts and exceptions.
 Most of these registers are inside the NVIC and System Control Block (SCB).
 There are also special registers inside the processor core for interrupt masking (e.g.,
PRIMASK, FAULTMASK, and BASEPRI).
 To make it easier to manage interrupts and exceptions, the CMSIS-Core provides a
number of access functions.
 For general application programming, the best practice is to use the CMSIS-Core access
functions.

17 MGRJ,ECE,RVCE
Interrupt management…
 Interrupt Making registers:
-The PRIMASK register is used to disable all exceptions except NMI
and HardFault.
- The FAULTMASK register is used to disable all exceptions except
NMI.
- The PRIMASK register is used to disable all exceptions of priority
equal to or less than certain value.

18 MGR,ECE,RVCE
Interrupt management…

 In C programming, we can use the functions provided in CMSIS-Core for accessing masking
registers.
void __enable_irq(); // Clear PRIMASK
void __disable_irq(); // Set PRIMASK
void __enable_fault_irq(void); // Clear FAULTMASK
void __disable_fault_irq(void); // Set FAULTMASK to disable interrupts
__set_BASEPRI(0x60); // Disable interrupts with priority
// 0x60-0xFF using CMSIS-Core function

19 MGR,ECE,RVCE
Priorities
 In microcontrollers, whether and when an exception can be accepted by the processor and
get its handler executed can be dependent on the priority of the exception.
 A higher-priority (smaller number in priority level) exception can pre-empt a lower-priority
(larger number in priority level) exception; this is the nested exception/interrupt scenario.
 Reset, NMI, and HardFault have fixed priority levels and their priority levels are
represented with negative numbers to indicate that they are of higher priority than other
exceptions.
 Other exceptions have programmable priority levels, which range from 0 to 255.
 In C programming, we can use function provided in CMSIS-Core for accessing masking
registers:
void NVIC_SetPriority(IRQn_Type IRQn, unit32_t Priority);

20 MGRJ,ECE,RVCE
 IRQn can specify any device specific interrupt, or processor exception number. Priorities…
 The number assignment in different interrupts in STM32F4xx is as follows(available in
stm32f407xx.h file):

21 MGR,ECE,RVCE
Programming example in STM32CubeMX for using ADC interrupt

 Use STM32CubeMX to configure ADC1 of STM32F407VG MCU to following


parameters:
 Channel: IN1(PA1), PCLK2:60 MHz, ADCCLK:30MHz, Sampling time:3 ADCCLKs,
Resolution:12 bits, Triggering: S/W controlled, Analog input range(dynamic range):0 V to
3.3 V(DC)
Write application code in Keil IDE to use ADC to analog to digital conversion and display
equivalent digital value in debug window and configure ADC in interrupt mode.

Note: This is 6(a) experiment of ADC configured to read digital value in polling
mode. Now, with a few modifications, code can be made to read value in
interrupt mode.

22 MGR,ECE,RVCE
Programming example…
 HAL APIs of ADC used in experiment 6(a)
HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef* hadc)
This Enables ADC and starts conversion of the regular channels in polling mode.
Parameters: hadc pointer to a ADC_HandleTypeDef structure that contains the configuration information for the
specified ADC.
Return type: HAL status

HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout)


Poll for regular conversion complete. ADC conversion flags EOS (end of sequence) and EOC (end of conversion) are
cleared by this function.
Parameters: hadc pointer to a ADC_HandleTypeDef structure that contains the configuration information for the
specified ADC.
Timeout Timeout value in millisecond.
Return type: HAL status

uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef* hadc)


Gets the converted value from data register of regular channel.

23 MGR,ECE,RVCE
Programming example…
 In STM32CubeMX, enable ADC1,ADC2 and ADC3 global interrupts under NVIC
settings in ADC 1 configuration. Retain all the settings of experiment 6(a).

24 MGR,ECE,RVCE
Program:
#include "main.h"
APIs generated:
ADC_HandleTypeDef hadc1; // handler for ADC
HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef* hadc)
void SystemClock_Config(void);
static void MX_GPIO_Init(void); Enables the interrupt and starts ADC conversion of regular channels.
static void MX_ADC1_Init(void);
uint32_t analogValue; // 32- bit variable for ADC value
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
This function is called from HAL_ADC_IRQHandler( ) upon analog to digital
{
conversion.
analogValue=HAL_ADC_GetValue(&hadc1);
}
int main(void)
{
HAL_Init(); Note that, after initialization main function executes endless
SystemClock_Config(); loop and statement in to read ADC value is executed upon
MX_GPIO_Init();
MX_ADC1_Init();
interrupt generation.
HAL_ADC_Start_IT(&hadc1);
while (1)
{
}
}

25 MGR,ECE,RVCE
Interrupts on GPIO pins(external interrupts)
 Up to 140 GPIOs of STM32F407xx are connected to the 16 external interrupt/event lines
in the following manner:

 Similarly, interrupts on other GPIOs are used to generate EXTI2,EXTI3,…EXTI15..


 The external interrupt/event controller(EXTI) module in MCU is used to control these
interrupts.
 The system configuration controller(SYSCFG) is used to manage the external interrupt line
connection to the GPIOs
26 MGR,ECE,RVCE
Interrupts on GPIO pins(external interrupts)….
Registers for external interrupt control
SYSCFG external interrupt configuration register 1 (SYSCFG_EXTICR1)

27 MGR,ECE,RVCE
Registers for external interrupt control…

Interrupt mask register (EXTI_IMR)

28 MGR,ECE,RVCE
Registers for external interrupt control…

Rising trigger selection register (EXTI_RTSR)

29 MGR,ECE,RVCE
Registers for external interrupt control…

Falling trigger selection register (EXTI_FTSR)

30 MGR,ECE,RVCE
 For programming example, refer experiment 9 in lab

31 MGR,ECE,RVCE
Timers
 Timer/counter are part of micro-controller internal hardware. Timer/
counter are same as per hardware point of view. Timer is used to
generate delay and counter is for counting external events.
 When we want to count events, we connect external event (e.g. event :
rising edge or falling edge) source to input pin of timer/counter
module. When external event occurs the value of counter increments.
Value of counter represents no. of external events.
 During timer operation, timers runs on clock signal applied to CPU
where as counter run on external clock signal applied.

32 MGR,ECE,RVCE
Timers…
SysTick Timer
 The Cortex-M processors have a integrated timer called the SysTick (System Tick)
timer. It is integrated as a part of the NVIC and can generate the SysTick exception
(exception type #15).
 The SysTick timer is a simple decrement 24-bit timer, and can run on processor
clock frequency or from a reference clock frequency (normally an on-chip clock
source).
 It counts from an initial value down to 0. When it reaches 0, in the next clock, it
underflows and it raises a flag called COUNT and reloads the initial value and starts
over [Link] can set the initial value to a value between 0x000000 to 0xFFFFFF.

33 MGR,ECE,RVCE
SysTick Timer Registers
 When the counter is enabled by setting bit 0 of the Control and Status
register, the current value register decrements at every processor
clock cycle or every rising edge of the reference clock. If it reaches zero, it
will then load the value from the reload value register and continue.
 An additional register called SysTick Calibration Register is available to
allow the on-chip hardware to provide calibration information for the
software.

34 MGR,ECE,RVCE
SysTick Timer Registers …
 If we only want to generate a periodic SysTick interrupt, the easiest way is to use a
CMSIS-Core function called “SysTick_Config”:
uint32_t SysTick_Config(uint32_t ticks);
 This function sets the SysTick interrupt interval to “ticks,” enables the counter using the
processor clock, and enables the SysTick exception with the lowest exception priority.
 For example, if we have a clock frequency of 30MHz and we want to trigger a SysTick
exception of 1KHz, we can use:
SysTick_Config(30000);
Time to reach count 0=30000x 1/30 MHZ = 1 ms
so, exception rate= 1KHz

35 MGR,ECE,RVCE
Timers in MCU
 In addition to SysTick timers, STM32Fxx Arm
comes with a large number of timers. The timers
are called TIMx where x=0, 1, 2, 3, 4,5,..,14.
 They fall into three categories:
a) Advanced Control Timer
b) General PurposeTimer
c) BasicTimer
 Capture mode – retrieves/store a timer value
based on a signal event.
 Compare mode - constantly monitors a timer
counter value and compares it to a value set in
the application. Compare mode will trigger an
event when the values match.
36 MGR,ECE,RVCE
Timers’ clock

 Timer clocks can be reduced further by programming TIMx_PSC register to 1,2,3,4,..65536


 If APB1 and APB2 timer clock is 16 MHz, then clock signal to timers is 1 KHz if TIMx_PSC is
set to 16000(16MHz/16000).
37 MGR,ECE,RVCE
Registers of Timer(TIM2 to TIM9)
TIMx control register 1 (TIMx_CR1)

CEN (Counter Enable, D0): enables or disables the counter. When the CEN bit is set,
the timer starts to count. It counts up or down depending on the DIR bit.
DIR (Direction, D4): This bit configures the Timer/Counter as an up or down counter.
If the DIR bit is 0, the timer counts up. If the DIR bit is 1, the counter counts down.

38 MGR,ECE,RVCE
Registers of Timer(TIM2 to TIM9)….
TIMx status register (TIMx_SR)

UIF (D0): This is like overflow flag in other microcontrollers. When the timer
counts down from a starting value and reaches 0, the UIF is set high. In the case of
up counter, the UIF goes HIGH when it reaches the top value and wraps around to
zero. The UIF flag remains high until it is cleared by software.

39 MGR,ECE,RVCE
Registers of Timer(TIM2 to TIM9)….
TIMx counter (TIMx_CNT)

In the case of a 16-bit imer, TIMx_CNT is a 16-bit counter and can take values
between 0 to 0xFFFF. For the 32-bit timers such as TIM2, the TIM2_CNT is 32 bit
wide.

40 MGR,ECE,RVCE
Registers of Timer(TIM2 to TIM9)….
TIMx auto-reload register (TIMx_ARR)

• The counter is an up counter by default. It counts up from 0 to the auto- reload value.
Notice that when the counter reaches the TIM_ARR value, the UIF flag in TIM_SR
(status) register is set HIGH, the counter value is wrapped around to zero, then
continues to count up.
• When the DIR bit of CR1 (Control 1) register is set (DIR=1), the counter counts
from the autoreload value (content of the TIMx_ARR register) down to 0, then
restarts from the auto-reload value and generates a counter underflow and the UIF
flagMGR,ECE,RVCE
is set.
41
Registers of Timer(TIM2 to TIM9)….
TIMx prescaler (TIMx_PSC)

The prescaler slows down the counting speed of the timer by dividing the input clock of the
timer.

42 MGR,ECE,RVCE
Program(Register level Programming)

 Design STM32F407VG based system to toggle LED connected to PA5 at the rate of
10 Hz. Use Timer 2 to generate suitable delay.

Assume: APB1/APB2 Timer clock=16 MHz


If timer pre scale is set to 16000,then clock frequency =16M/16000=1 KHz
Timer clock period is 1 ms.
Rate of toggle=10Hz=> Delay=100 ms
So, totally 100 states are required.

43 MGR,ECE,RVCE
#include "stm32f4xx.h“ Program…
void main( ){
RCC->AHB1ENR |= 1; //Enable GPIO clock
GPIOA->MODER |= 0x00000400; // set pin to output mode
RCC->APB1ENR |= 1; //enable TIM2 clock
TIM2->PSC = 16000; //divided by 16000
TIM2->ARR = 100;
TIM2->CNT = 0; //clear timer counter
TIM2->CR1 = 1; //enable timer 2
While(1){
while(TIM2->SR & 0x01==0) ; //wait till overflow flag is set
TIM2->SR &= ~1; // Clear overflow flag
GPIOA->ODR ^= 0x00000020; // Toggle LED
}
}
44 MGR,ECE,RVCE
Redesign of Program using Interrupts in STM32CubeMx
 Configure for timer
2 in
STM32CubeMx as
shown in figure.
 Set PA5 as GPIO
output.

45 MGR,ECE,RVCE
#include "main.h" Program…
TIM_HandleTypeDef htim2;
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_TIM2_Init(void);
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim){
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);
}

int main(void)
{
SystemClock_Config();
MX_GPIO_Init();
MX_TIM2_Init();
HAL_TIM_Base_Start_IT(&htim2);
while (1)
{
}
}

46 MGR,ECE,RVCE

You might also like