Ex Excepti tion ons s and Interru rrupts ts 01204322 Embedded - - PowerPoint PPT Presentation

ex excepti tion ons s and interru rrupts ts
SMART_READER_LITE
LIVE PREVIEW

Ex Excepti tion ons s and Interru rrupts ts 01204322 Embedded - - PowerPoint PPT Presentation

Ex Excepti tion ons s and Interru rrupts ts 01204322 Embedded System Chaipo Chaiporn J n Jaik aikae aeo De Department of f Computer Engineering Kasetsart Unive versity Revised 2020-01-14 Ou Outline Polling vs. interrupt


slide-1
SLIDE 1

Ex Excepti tion

  • ns

s and Interru rrupts ts

Chaipo Chaiporn J n Jaik aikae aeo De Department of f Computer Engineering Kasetsart Unive versity

01204322 Embedded System

Revised 2020-01-14

slide-2
SLIDE 2

2

Ou Outline

  • Polling vs. interrupt programming styles
  • General interrupt mechanism in microcontrollers
  • ARM Cortex-M4’s interrupt system
  • Hands-on activity
  • Standard output redirection to UART
  • Switch input probing using timer interrupt
slide-3
SLIDE 3

3

Co Common Programming Pattern rns

  • Software polling
  • Interrupt (event-driven)
  • DMA (direct memory access)
  • Good for moving large amount of data, e.g., audio
  • RTOS (Real-Time Operating System)
  • Simplifies a complex application into smaller, concurrent tasks
  • Combination of methods above
slide-4
SLIDE 4

4

Po Polling vs. Interrupt

  • Polling
  • Program keeps checking for a certain

event to happen

  • E.g., GPIO pin status changed, or timer
  • Interrupt
  • Program keeps doing regular routines
  • When an event of interest happens, the

program suspends normal execution and executes code that handles the event

http://clipart-library.com/clipart/1162315.htm

https://lastminuteengineers.com/handling

  • esp32-gpio-interrupts-tutorial/
slide-5
SLIDE 5

5

Po Polling vs. Interrupt (cont’d)

  • Considering pseudo-code for switch-toggled LED

forever: wait until switch is pressed toggle LED wait until switch is released when switch pressed is detected: toggle LED forever: do nothing (or sleep)

slide-6
SLIDE 6

6

In Inter errup upts v s vs.

  • s. Ex

Excep eptions ns

  • An exception is an event that alters normal program flow
  • Interrupts are exceptions caused by hardware events,

such as peripherals and I/O

  • Other exceptions are:
  • Faults – caused by faulting instructions, such as division by zero
  • Traps – deliberately caused by user program to trigger certain

event or service

  • Aborts – used only to signal severe problems; operation no longer

possible

slide-7
SLIDE 7

7

In Inter errup upt S Ser ervice R e Rout utine (IS ne (ISR)

  • A special block of code that gets executed automatically by

the CPU when a corresponding interrupt occurs

  • Also known as Interrupt Handler
  • or Exception Handler in general

normal program flow à ISR normal program flow à interrupt saves program state restores program state

slide-8
SLIDE 8

8

Ma Maskable v

  • vs. N

Non-mask maskab able le Interrupts ts

  • Maskable interrupts can be disabled by the program
  • To perform critical operations that must not be interrupted
  • Most interrupts are maskable
  • Non-maskable interrupts cannot be disabled
  • Used to indicate critical events, e.g., reset, power failure

http://clipart-library.com/clipart/618555.htm

slide-9
SLIDE 9

9

Lo Locatio ions o

  • f I

f ISR SRs

  • Should be at fixed locations so CPU can find them easily
  • Problem: different ISRs have different lengths
  • Possible solutions
  • A table of ISR locations is maintained at a fixed memory location
  • This table is called Interrupt Vector Table
  • ISRs may be changed dynamically by the application
  • AVR’s vector table is filled with JMP instructions, while Cortex-M’s

vector table stores ISR addresses

slide-10
SLIDE 10

10

In Inter errup upt P Priorities es

  • Many MCUs support different interrupt priorities
  • An interrupt with a higher priority can preempt the

execution of a lower-priority interrupt

  • Priorities may be fixed or programmable
  • Program can also choose to disable interrupts whose

priorities are below a threshold

Priority: IRQ2 > IRQ1 (IRQ = Interrupt ReQuest)

ST’s training slides on Moving from 8 to 32 bits hands-on workshop

slide-11
SLIDE 11

11

In Inter errup upt L Latenc ency

  • Interrupt latency à amount of time to respond to an

interrupt

  • Depends on:
  • 1. How long the interrupt is disabled
  • 2. Time to execute ISRs of higher priority interrupts
  • 3. Time for processor to stop current execution, do necessary

save state, and start executing the ISR

  • 4. Time taken for the ISR to save context and start executing

instructions that count as a ‘response’

  • Factor 3 depends on HW, not under software control
  • Other factors are controlled by writing efficient code that

are not too long

  • Make ISRs short

Taken from lecture slides by Prof. Chung-Ta King

slide-12
SLIDE 12

12

Wr Writing an ISR

  • ISR should finish as quickly as possible
  • ISR does not accept parameters, nor returns a value
  • To communicate with the main program, use global variables or

shared data structures

  • These variables must be declared volatile
  • For events that need complicated handling, set a flag to

notify the main code

  • Accessing variables shared with ISR must be atomic
  • Especially read-modify-write memory update sequence
  • An interrupt can happen in the middle of variable access
  • Wrap these statements inside a critical section (disable interrupt,

etc.)

slide-13
SLIDE 13

13

ST STM32L4’s Interrupt System

  • Controlled by Nested Vectored Interrupt Controller (NVIC)
  • 67 maskable interrupt channels
  • 16 programmable priority levels
  • 4 bits of interrupt priority are used
  • Low-latency exception and interrupt handling
  • Power management control

Source: ST’s UM1956: STM32 Nucleo-32 Boards

slide-14
SLIDE 14

14

Co Cort rtex-M4 M4’s s Me Memory y Ma Map

0xFFFFFFFF 0x00000000 0x20000000

Code SRAM

0x40000000

On-chip flash, storing application code On-chip SRAM, for heap, stack, and code Peripherals

0x60000000

E.g., timers, GPIO External Device External RAM

0xA0000000 0xE0000000

System

0.5 GB 0.5 GB 0.5 GB 1 GB 1 GB 0.5 GB

E.g., SD card Off-chip memory for data NVIC, system timer, system control block, vendor-specific memory (e.g., boot loader) 4GB address space

Based on lecture slides and video clips by Dr. Yifeng Zhu

slide-15
SLIDE 15

15

Da Data Memor

  • ry

0xFFFFFFFF 0x00000000 0x20000000

Code SRAM

0x40000000

Peripherals

0x60000000

External Device External RAM

0xA0000000 0xE0000000

System

0.5 GB 0.5 GB 0.5 GB 1 GB 1 GB 0.5 GB 0x3FFFFFFF 0x20000000 0x2000FFFF

Actual RAM for STM32L432KC (64KB) Stack Global Variables Heap

Based on lecture slides and video clips by Dr. Yifeng Zhu

slide-16
SLIDE 16

16

Ins Instruc uction M n Memo emory

0xFFFFFFFF 0x00000000 0x20000000

Code SRAM

0x40000000

Peripherals

0x60000000

External Device External RAM

0xA0000000 0xE0000000

System

0.5 GB 0.5 GB 0.5 GB 1 GB 1 GB 0.5 GB 0x1FFFFFFF 0x00000000 0x08000000

Reserved Reserved Actual flash for STM32L432KC (256KB)

0x0803FFFF Interrupt Vector Table

Text Section RO Data Section RW Data Section

Initial Stack Pointer Interrupt Vector Table Initial Stack Pointer

default mapping

Based on lecture slides and video clips by Dr. Yifeng Zhu

slide-17
SLIDE 17

17

NV NVIC Op Operation ion

  • When an interrupt signal is detected, NVIC looks up the ISR address

from the interrupt vector table

  • The address is then passed to the CPU

Based on lecture slides and video clips by Dr. Yifeng Zhu Interrupt Position (8 bits) Memory Address of ISR (32 bits) 1 Address of ISR for interrupt 1 2 Address of ISR for interrupt 2 3 Address of ISR for interrupt 3 : :

Interrupt Vector Table

slide-18
SLIDE 18

18

In Inter errup upt V Vec ector T Tabl ble

: : : :

Taken from RM0394: Reference Manual for STM32L41xx/2xx/3xx/4xx/5xx/6xx

Address for nth interrupt = 64 + 4n Stack :

Reserved for initial MSP

Reset_Handler()

Code executed after reset :

SysTick_Handler()

Code executed every system tick

WWDG_IRQHandler()

ISR for WWDG interrupt

slide-19
SLIDE 19

19

Ex Example: ample: IS ISR A Addre ddress ss

Find the interrupt vector table entry that contains the address of EXTI Line3 interrupt handler

  • EXTI Line3 interrupt’s position is 9
  • Entry address = 64 + 4*9 = 100 = 0x64
  • Notes: ISR address found in the table entry always has LSB

set to 1 to indicate THUMB instruction set

slide-20
SLIDE 20

20

Sin Single gle I Interrupt O Operation ion

EXTI3

Based on lecture slides and video clips by Dr. Yifeng Zhu

slide-21
SLIDE 21

21

Co Cort rtex-M4 M4’s s Interru rrupt Pri riori rities

  • Four bits à 16 different priorities
  • The four bits can be divided into
  • Preemption priorities (0-4 bits)
  • Sub priorities (0-4 bits)
  • An interrupt with smaller preemption priority number

(higher priority) preempts the execution of an interrupt with larger preemption priority number

  • For pending interrupts of the same preemption priority,
  • ne with the smaller sub priority number will be serviced

first

slide-22
SLIDE 22

22

Ne Nested Interrupts: : Preemption ion

Suppose: * DMA1_Channel2’s priority = 3 * EXTI3’s priority = 5 (The smaller the number, the higher the priority)

Based on lecture slides and video clips by Dr. Yifeng Zhu

slide-23
SLIDE 23

23

Ne Nested Interrupts: : Tail ail Chain ainin ing

  • Suppose EXTI4 is of lower priority than EXTI3
  • Cortex-M4 optimizes the unnecessary unstacking/stacking operations, saving clock

cycles

Based on lecture slides and video clips by Dr. Yifeng Zhu

slide-24
SLIDE 24

Ha Hands nds-On On: : Sw Switch Input and Serial Output

slide-25
SLIDE 25

25

Fe Feature res

  • Communicates with host computer via VCP
  • Utilizes C’s printf() function
  • Debounces switch and filter EMI in pure software
  • No additional components (resisters, capacitors) required
  • Utilizes timer for signal sampling
slide-26
SLIDE 26

26

Wi Wiring

  • Connect a switch to pin D4 and GND
  • D3 is connected to STM32L432KC’s pin PB0
slide-27
SLIDE 27

27

Cl Clock k Settings

  • Configure for 80 MHz system clock generated from 4 MHz MSI,

with 32.768 kHz LSE enabled for clock trimming

slide-28
SLIDE 28

28

Pi Pin Assign gnments

  • On-board debugger’s USART is connected to

STM32L432KC’s pins PA2 (TX) and PA15 (RX)

Pin Assignment Label PA2 USART2_TX USART2_TX PA15 USART2_RX USART2_RX PB0 GPIO_Input SW PB3 GPIO_Output LD3

slide-29
SLIDE 29

29

US USART2 Con

  • nfigu

gurati tion

  • n
slide-30
SLIDE 30

30

PB PB3 (LED) D) Con

  • nfigu

guration

  • n
slide-31
SLIDE 31

31

PB PB0 (Switch) Con

  • nfigu

guration

  • ns
slide-32
SLIDE 32

32

Te Testing UART Communication

  • The following code in the main loop should output

messages Hello to UART every one second

/* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ HAL_UART_Transmit(&huart2, "Hello\n", 6, 0xffff); HAL_Delay(1000); } /* USER CODE END 3 */

slide-33
SLIDE 33

33

Lau Launchin ing a T a Termin minal Emu al Emula lator

  • Set baud rate to 115200 bps
  • A Hello message should appear every one second
slide-34
SLIDE 34

34

Re Redirecting St Stdou

  • ut to

to UART

  • printf() sends output characters to standard output,

which currently does nothing

  • Overwrite __io_putchar() to redirect characters to

UART instead

/* Private user code -----------------------------------------*/ /* USER CODE BEGIN 0 */ int __io_putchar(int ch) { HAL_UART_Transmit(&huart2, (uint8_t*)&ch, 1, 0xffff); return ch; } /* USER CODE END 0 */

slide-35
SLIDE 35

35

Te Testing printf()

  • Try calling printf() in the main loop
  • Results from printf() should now show up in the

terminal

/* Infinite loop */ /* USER CODE BEGIN WHILE */ int x = 0; while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ printf("x = %d\n", x); HAL_Delay(1000); x++; } /* USER CODE END 3 */

slide-36
SLIDE 36

36

Co Counting Swi witch Presse sses

  • Add a function to probe switch’s status
  • Use it to count switch presses in the

main loop

  • Observe the classic bounce problem

/* USER CODE BEGIN 0 */ : int IsSwitchPressed() { return HAL_GPIO_ReadPin(SW_GPIO_Port, SW_Pin) == 0; } /* USER CODE END 0 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ int x = 0; while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ while (!IsSwitchPressed()) ; x++; printf("x = %d\n", x); while (IsSwitchPressed()) ; } /* USER CODE END 3 */

slide-37
SLIDE 37

37

Sw Switch Debouncing Algorithm

  • Filter out spurious level changes due to
  • Bouncing contacts
  • Electromagnetic interference (EMI)
  • Idea
  • Make sure change of switch’s state is stabilized for a certain

amount of time (e.g., 10 ms)

  • Start a counter when a change is detected
  • Decrease the counter when the next sampling remains the same;
  • r restart the counter if different
  • Once the counter reaches zero, accept the change (set a global)
slide-38
SLIDE 38

38

Se Settin ing U g Up a T a Tim imer

  • A timer is needed to generate

periodic interrupts for sampling switch’s signal levels

  • We will use TIM6 in this example
  • TIM6 is a basic timer with no

connectivity to external I/O pins

  • Timer period is set to 1 ms

(for 80MHz system clock)

  • PSC = 8000-1
  • ARR = 10-1
slide-39
SLIDE 39

39

Enabling Enabling T TIM IM6 In 6 Inter errup upt

slide-40
SLIDE 40

40

Mo Modifyi ying IsSwitchPressed()

  • Declare a global to keep track of filtered switch’s state
  • This global will be updated by the timer interrupts

/* USER CODE BEGIN PV */ volatile int g_sw_pressed; /* USER CODE END PV */ : /* USER CODE BEGIN 0 */ : int IsSwitchPressed() { return g_sw_pressed; } /* USER CODE END 0 */

slide-41
SLIDE 41

41

TI TIM6 M6’s s ISR

  • Every TIM6’s timeout, the switch debouncing algorithm is

executed as the ISR

/* USER CODE BEGIN 4 */ void CheckSW() { static uint16_t count = 0; int raw_sw_pressed = !HAL_GPIO_ReadPin(SW_GPIO_Port, SW_Pin); if (g_sw_pressed == raw_sw_pressed) { // switch returned to previous state; reset counter count = 10; } else { if (--count == 0) { // switch state has stabilized g_sw_pressed = raw_sw_pressed; } } } void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { if (htim->Instance == htim6.Instance) { CheckSW(); } } /* USER CODE END 4 */

This function is called by TIM6_DAC_IRQHandler(), which is the actual ISR

slide-42
SLIDE 42

42

St Star artin ing T g TIM6 I Interrupt

  • Activate TIM6 interrupt before entering the main loop

/* USER CODE BEGIN 2 */ HAL_TIM_Base_Start_IT(&htim6); /* USER CODE END 2 */

slide-43
SLIDE 43

43

Te Testing New Algorithm

  • Run the code and observe counting behavior
  • Try adjusting the initial counter value in CheckSW()
  • Make the value smaller
  • Does bouncing reappear?
  • Make the value larger
  • Does switch press event latency become noticeable?
slide-44
SLIDE 44

44

Ma Maki king Co Code Event-Dr Driven St Style

  • When switch changes its state, call a registered application

callback function with the updated switch state

/* Private typedef -------------------------------------------------*/ /* USER CODE BEGIN PTD */ typedef void (*SwitchChangedCallbackFn)(int state); /* USER CODE END PTD */ : /* USER CODE BEGIN PV */ volatile int g_sw_pressed; SwitchChangedCallbackFn g_sw_cb = NULL; /* USER CODE END PV */ : /* USER CODE BEGIN 0 */ void SetSwitchChangedCallback(SwitchChangedCallbackFn fn) { g_sw_cb = fn; } /* USER CODE END 0 */

slide-45
SLIDE 45

45

In Invoking ng C Callba back fr from IS m ISR

  • Call the registered callback, if not NULL

/* USER CODE BEGIN 4 */ void CheckSW() { static uint16_t count = 0; int raw_sw_pressed = !HAL_GPIO_ReadPin(SW_GPIO_Port, SW_Pin); if (g_sw_pressed == raw_sw_pressed) { // switch returned to previous state; reset counter count = 10; } else { if (--count == 0) { // switch state has stabilized g_sw_pressed = raw_sw_pressed; if (g_sw_cb) // invoke the callback, if registered (*g_sw_cb)(g_sw_pressed); } } } : /* USER CODE END 4 */

slide-46
SLIDE 46

46

Te Testing Callback

  • Define a custom callback
  • Register before entering the main loop and leave the main

loop empty

/* USER CODE BEGIN 0 */ : void MySwitchCb(int state) { printf("Switch state is %d\n", state); } /* USER CODE END 0 */ /* USER CODE BEGIN WHILE */ SetSwitchChangedCallback(MySwitchCb); while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */

slide-47
SLIDE 47

47

Co Conclusi sion

  • Interrupts are hardware events generated at unpredictable

time

  • When an interrupt is generated, an interrupt service

routine (ISR) is automatically called to handle the event

  • Interrupts may have different priorities, where a higher-

priority interrupt may preempt execution of a lower- priority interrupt