Mon Cours
Mon Cours
Mon Cours
Anne Layec
3A EUROMED 2021/2022
2
Déroulement du module
Tous les documents sont disponibles sous Moodle : inscription au plus vite
https://moodle.insa-rennes.fr/course/view.php?id=800
- Tableau des activités et d’avancement
- À consulter et compléter au fur et à mesure du module pour évaluer votre avancement
- En fonction de l’avancement, des rendus supplémentaires seront demandés
- Evaluations
• Un TD en autonomie
• Un CR de TP
• Un examen de 2H
• Des quizz de cours
• Un examen de TP pourra être mis en place
- Module : total 44h , 9h CM, 9h TD, 24h TP, 2h DS
- La répartition pourra évoluer suivant le déroulement
INTRODUCTION TO
EMBEDDED SYSTEMS DESIGN
Introduction 5
ARM University
Introduction 6
GPP
Flexibility
GPU
DSP / MCU
FPGA
ASIC
Courses on Peripherals
• GPIOs
• interrupts
• Timers
Focusing on the integration of a microcontroller-based
system in its environment
Example 1 14
Low V
High V
source: TI
Example System 3: Bike Computer 16
Functions
Speed and distance measurement
Constraints
Size Wheel encoder
Cost
Power and Energy System LCD
Weight User Keys
Inputs
Wheel rotation indicator
Mode key
Output
Liquid Crystal Display
Low performance MCU
8-bit, 10 MIPS
ARM University
Example System 4: Car engine controller 17
ARM University
27
ARM University
STM32 = Cortex + Peripherals 30
Nucleo-64 STM32F446RE
31
Processor registers
– The internal registers are used to store and process temporary data within the processor
core
– All registers are inside the processor core, hence they can be accessed quickly
– Load-store architecture
• To process memory data, they have to be first loaded from memory to registers,
processed inside the processor core using register data only, and then written
back to memory if needed
CORTEX-M3 registers
– Register bank
• Sixteen 32-bit registers (thirteen are used for general-purpose);
– Special registers
Cortex-M3 Registers 33
Register bank R0
R1 Fastest way to read and write
R2 Registers are within the
R3
Low processor chip
R4 Registers
R5
A register stores 32-bit value
General purpose
R6
register
R7
R8
R9
R10 High
Registers
R11
R12 MSP
Stack Pointer (SP) R13(banked) Main Stack Pointer
Special registers Program Status Registers (PSR) x PSR APSR EPSR IPSR
PRIMASK Application Execution Interrupt
PSR PSR PSR
Interrupt mask register FAULTMASK
BASEPRI
Stack definition CONTROL
Cortex-M3 Registers 34
– High registers (R8 – R12) sometimes cannot be accessed e.g. by some Thumb
PUSH POP
(16-bit) instructions
R13: Stack Pointer (SP) Low
Code region
LR address in LR to return to
Code region
the main program
subroutine subroutine
Current PC
PC
APSR
– N: negative flag – set to one if the result from ALU is negative
– Z: zero flag – set to one if the result from ALU is zero
– C: carry flag – set to one if an unsigned overflow occurs
– V: overflow flag – set to one if a signed overflow occurs
– Q: sticky saturation flag – set to one if saturation has occurred in saturating arithmetic instructions, or
overflow has occurred in certain multiply instructions
IPSR
– ISR number – current executing interrupt service routine number
EPSR
– T: Thumb state – always one since CORTEX-M3 only supports the Thumb state (more on processor states
in the next module)
– IC/IT: Interrupt-Continuable Instruction (ICI) bit, IF-THEN instruction status bit
38
Nevertheless, despite of the default memory map, the actual usage of the memory map
can also be flexibly defined by the user, except some fixed memory addresses, such as
internal private peripheral bus
Memory 40
Data Address
8 bits 32 bits
0x00000000
40 Memory
CORTEX-M3 Endianness 41
e.g. SD card
0xA0000000
0x9FFFFFFF
Code Region
– Primarily used to store program code
– Can also be used for data memory
– On-chip memory, such as on-chip FLASH (Flash memory is an non-volatile memory that can
be electrically erased and reprogrammed. )
SRAM Region
– Primarily used to store data, such as heaps and stacks
– Can also be used for program code
– On-chip memory; despite its name “SRAM”, the actual device could be SRAM, SDRAM or
other types
Peripheral Region
– Primarily used for peripherals, such as Advanced High-performance Bus (AHB) or Advanced
Peripheral Bus (APB) peripherals
– On-chip peripherals
– For more details on peripheral memory area, refer to the datasheet
CORTEX-M3 Memory Map Example 45
Chip
Silicon
PPB NVIC
CORTEX-M3 SCS
Debug Ctrl
AHB/APB bus
External SRAM,
External LCD SD card
FLASH
48
Pour comprendre et réviser MOOC
https://openclassrooms.com/fr/courses/4117396-developpez-en-c-pour-
lembarque/4604781-introduction
1. Introduction
2. Découvrez les grandes lignes de l’architecture programmable ARM
3. Explorez la mémoire dans les architectures ARM
49
CHAPTER 2
PROGRAMMING IN C
ARM University
Typical Program-Generation Flow 50
Off-line Compilation
C Code
Compile Processor
Assembly Code Fetch
Assemble Instruction
Fetch Decode
Object Code Libraries
Link Execute
Program Image
Download Data Input Data Output
Processing
Program Memory
C, C++
C/C++
C/
C/ C++
C++ C/C++
C/ C++
Assembly ASM files
Compile/ assemble
armcc armasm
.O Files
C/C++
C/ C++
Object C/C++
C/ C++
Libraries .S Files
armmar
.AXF File
Image .LIB file
executable
.BIN File
binary .HEX File
Disassembly File
52
The program image is stored in the code region in the global memory
– Up to 512 MB memory space range from 0x00000000 to 0x1FFFFFFF
– Usually implemented on non-volatile memory, such as on-chip FLASH memory
– Normally separated from program data, which is allocated in the SRAM region (or
data region)
External RAM
Peripherals
Mainly used for data memory 0x3FFFFFFF
Code region
External Interrupts
SysTick
PendSV
Reserved
Start-up routine & Debug monitor
Program code & SVCall
C library code Reserved
Program
Image Usage fault
Bus fault
MemManage fault
Hard fault vector
NMI vector
Vector table Reset vector
0x00000000 Initial MSP value
C Language vs. Assembly Language 66
Easy handling of complex data structures No direct control over stack usage
Allow direct control to each instruction step and Take longer time to learn
all memory
Assembly Allows direct access to instructions that cannot Difficult to manage data structure
be generated with C
Less portable
Overview 67
A disassembler is a computer program that translates machine language into assembly language
86
Pour comprendre et réviser MOOC
https://openclassrooms.com/fr/courses/4117396-developpez-en-c-pour-
lembarque/4636751-faites-le-lien-entre-la-compilation-c-et-lassembleur
CHAP 3 – CLOCKS
ARM University
88
Microcontrollers’ Structure
Clk
Flash RAM TIM1 TIM2 UART …
Core
Bus clocks
• 3 main busses
• Advanced High-Performance Bus AHB1 (Max 180MHz): HCLK
• Advanced Peripheral Bus APB1 (Max 45MHz): PCLK1
• Advanced Peripheral Bus APB2 (Max 90MHz): PCLK2
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOCEN;
98
RCC registers Memory mapping STM32F446xx
99
RCC registers addresses STM32F446xx
Ex:
In stm32f446xx.h
__IO uint32_t AHB1ENR; /*!< RCC AHB1 peripheral clock register, Address offset: 0x30 */
#define RCC_BASE (AHB1PERIPH_BASE + 0x3800UL)
#define AHB1PERIPH_BASE (PERIPH_BASE + 0x00020000UL)
#define PERIPH_BASE 0x40000000UL /*!< Peripheral base address in the alias region */
100
Prescalers
Prescalers
• Most of the time, a clock needs to be divided before entering a
peripheral
• This is the function of the PRESCALER
16MHz 1MHz
Prescaler
/16
101
Pour comprendre et réviser
https://openclassrooms.com/fr/courses/4117396-developpez-en-c-pour-
lembarque/4633171-comprenez-les-specificites-d-une-architecture-microcontroleur
102
Mettre un bit à 1
Pour mettre un seul bit à 1 dans un registre, nous utilisons l’opérateur bit-
à-bit OU avec un masque dont tous les bits sont à 0, sauf celui que l’on
veut initialiser
Exemple:
pour une valeur de l’octet init décrite en binaire par b7 b6 b5 b4 b3 b2 b1 b0, si vous voulez
passer le bit b4 à 1, vous allez composer un masque, mask, ayant la valeur binaire b0001 0000
et appliquer l’opérateur bit-à-bit OU.
Ces écritures sont équivalentes:
init = init | 0x10;
mask = 0x10;
init = init | mask; init | = 0x10;
init = init | (1 << 4);
Exemple concret:
RCC->AHB2ENR |= RCC_AHB2ENR_GPIOBEN; // Enable clock of Port B
Mettre des bits à 1 105
Vous pouvez aussi utiliser cette méthode pour mettre à 1 plusieurs bits en même temps.
Reprenons l’exemple précédent avec init une variable décrite par 8 bits b7 b6 b5 b4 b3 b2 b1
b0 pour laquelle nous voulons passer les bits b4, b1 et b0 à 1. Une première solution est de
faire une opération pour chaque bit
Ou encore
init | = ( (1<<0) | (1<<1) | (1<<4) );
Mettre des bits à 0 106
Pour mettre des bits à 0, nous utilisons l’opérateur bit-à-bit ET avec un masque ayant
des bits à 0 uniquement devant les bits que nous voulons initialiser.
Ainsi, si vous souhaitez passer à 0 les bits b4, b1 et b0 d’un octet init dont la valeur en binaire
est décrite par b7 b6 b5 b4 b3 b2 b1 b0, vous utiliserez un masque binaire b1110 1100 avec
l’opérateur ET
init = init & 0xEC;
Une manière beaucoup plus simple, et surtout plus fiable, est de construire le masque avec des
1 pour les bits à annuler et ensuite d’inverser la valeur avec l’opérateur bit-à-bit NON. Ainsi
l’écriture du masque de l’exemple précédent devient
Exemple concret
GPIOB->OTYPE &= ~(1<<2); // Select push-pull output
Mettre des bits à 0 ou à 1 107
Il est impossible de mettre à 0 et à 1 des bits en une seule opération. Il faut toujours
passer par deux opérations ; l'une pour mettre les bits à 0 et une pour ceux à 1.
Pour inverser un bit, nous utilisons l’opérateur bit-à-bit XOR avec un masque ayant des
bits à 1 uniquement devant les bits que nous voulons inverser.
Une solution est de construire le masque avec des 1 pour les bits à inverser.
Exemple concret
GPIOB->ODR ^= GPIO_ODR_OD6; // set bit 6 of ODR reg to 0 if at 1 before, to 1 if at 0 before
Tester une valeur 109
Les opérateurs bit-à-bit peuvent aussi servir pour tester la valeur d’un bit dans un
registre. Pour cela, il faut créer un masque en mettant à 0 tous les bits qui n’ont pas
d’intérêt pour le test à faire, puis l’utiliser avec l’opérateur bit-à-bit ET.
Prenons un exemple : supposons que vous avez une valeur value égale à b7 b6 b5 b4 b3 b2 b1
b0 et que vous voulez tester si le bit 5 est à 1.
mask = (1 << 5);
et appliquez le à la valeur value avec l’opérateur bit-à-bit ET :
value = value & mask;
Vous obtenez comme résultat 0 0 b5 0 0 0 0 0, ce qui représente une valeur équivalente à vraie
si b5 vaut 1 et faux si b5 vaut 0.
110
MOOC
https://openclassrooms.com/fr/courses/4117396-developpez-en-c-pour-
lembarque/4633446-manipulez-les-registres-et-les-masques
Je souhaite éteindre l’horloge du périphérique Timer 10, comment est-ce que je procède?
Bit 17 du registre RCC_APB2ENR, on force ce bit à 0
MICROCONTROLLER PERIPHERALS
CHAPTER 4
GPIOS
117
Microcontrollers’ Structure
Clk
Flash RAM TIM1 TIM2 UART …
Core
Advantages of IO multiplexing:
– Saves space on the package
– Improves flexibility
120
Nucleo Board
121
GPIOs: Connecting with Digital I/Os
Memory-mapped I/O
A simpler and more convenient way to interface I/O devices
Each device registers is assigned to a memory address in the address
space of the microprocessor
Use native CPU load/store instructions: LDR/STR Reg, [Reg, #imm]
0x40020024
0x40020020
0x4002001C
Core Pin output
STR 0x40020018
0x40020014 GPIO Data Output Register GPIO
Output
0x40020010
Memory Space
125
Basic Example
D Bus
ARM Cortex- FLASH
AHB Bus
I Bus
Matrix
M4 SRAM
S Bus
FPU
GPIO A
GPIO B APB Bus
GPIO C Matrix
GPIO D
GPIO E UART
GPIO F
SPI
x16 GPIO x
Timer
…
STM32F4
Structure of an I/O Port 129
Input
Schmitt
trigger
Output
GPIO Mode Register (MODER) 130
Schmitt Trigger
Pull-up vs
Pull-down
Push/Pull
vs Open
Drain
Basic Structure of an I/O Port Bit: Input 132
Schmitt Trigger
133
Schmitt Trigger: From Analog to Digital
Before
After
134
Pull-Up Pull-Down
If external input is HiZ, the If external input is HiZ,
input is read as a valid the input is read as a valid
HIGH. LOW.
Basic Structure of an I/O Port Bit: Input 135
Schmitt
trigger
GPIO port pull-up/pull-down register (PUPDR) 136
Schmitt
GPIO ODR trigger
Register GPIO Output Type Register (OTYPER)
0 = Output push-pull (default)
1 = Output open-drain
+ Vcc
D
G
PMOS
GPIO S GPIO
Output Bit Output Pin
0/1 Controller
D
G
NMOS
S
+ Vcc + Vcc
Source
D current
G
PMOS PMOS
GPIO Output = 1
Source current to external circuit
GPIO Output: Push-Pull 140
+ Vcc + Vcc
D
G
PMOS
PMOS
GPIO S GPIO
Output Bit GPIO GPIO
Output Pin Output Bit Output Pin
0/1 Controller 1
0 Controller
Output is
D Grounded
G
NMOS
NMOS
S Drain
current
GPIO Output = 0
Drain current from external circuit
GPIO Output: Open-Drain 141
GPIO
Output Pin GPIO
Output Pin
Output is
GPIO GPIO Grounded
Output Bit Output Bit
D
G 1
0/1 Controller NMOS 0 Controller NMOS
S
Current
GPIO Output = 0
Drain current from external circuit
GPIO Output: Open-Drain 142
GPIO
Output Pin GPIO
Output Pin
Output is
GPIO GPIO Floating
Output Bit Output Bit
D
G 0
0/1 Controller NMOS 1 Controller NMOS
S
Output = 1
GPIO Pin has high-impedance to external circuit
One can connect several outputs together
GPIO Output: Open-Drain and bus 143
VCC
Current
Pin 2
Pin 4
READ ONLY
if( GPIOB->IDR & (1UL << 4)) == 0; // test if pin 4 input value is 0
152
0xFFFFFFFF
0.5 GB System
0xE0000000 For addressing GPIO registers
10 registers = 40 Bytes
1 GB External Device
0x60000000
0xA0000000
…
1 GB External RAM
0x40021000
GPIO D (1 KB)
0x60000000 0x40020C00
0.5 GB Peripheral GPIO C (1 KB)
0x40000000 0x40020800
GPIO B (1 KB)
0.5 GB SRAM 0x40020400
0x20000000 GPIO A (1 KB)
0.5 GB Code 0x40020000
0x40000000
…
0x00000000
0x40020400
0x40020028
0x40020024
AFR[1]
Selected alternate function
0x40020020
AFR[0]
0x40020400 LCKR
40 0x4002001C
GPIO A (1 KB) BSRR
0x40020000 bytes 0x40020018
per 0x40020014
ODR Write output data
port IDR Read input data
0x40020010
PUPDR Input Pull-up or pull-down
0x4002000C
OSPEEDR Output speed
0x40020008
0x40020004
OTYPER Output Push/pull or open drai
0x40020000
MODER 00 if input, 01 if output,
10 alternate, 11 analog
Each register is 4 bytes wide
Example of ODR Access 155
0x40020017
ODR 1 word (i.e. 32 bits)
0x40020014
0x40020017
0x40020016
4 bytes
0x40020015
0x40020014
Little Endian
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
ODR Pointer Dereferencing 156
0x40020017
ODR 1 word (i.e. 32 bits)
0x40020014
0x40020017
0x40020016
4 bytes
0x40020015
0x40020014
Little Endian
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1
typedef struct {
volatile uint32_t MODER; // Mode register
volatile uint32_t OTYPER; // Output type register
volatile uint32_t OSPEEDR; // Output speed register
GPIOA +0x24 AFR[1] volatile uint32_t PUPDR; // Pull-up/pull-down register
GPIOA +0x20 volatile uint32_t IDR; // Input data register
AFR[0] volatile uint32_t ODR; // Output data register
GPIOA +0x1C LCKR volatile uint32_t BSRR; // Bit set/reset register
volatile uint32_t LCKR; // Configuration lock register
GPIOA +0x18 BSRR volatile uint32_t AFR[2]; // Alternate function registers
GPIOA +0x14 } GPIO_TypeDef;
ODR
GPIOA +0x10 IDR /* Peripheral_memory_map */
#define PERIPH_BASE ((uint32_t)0x40000000)
GPIOA +0xC PUPDR /*!< Peripheral memory map */
#define AHB1PERIPH_BASE (PERIPH_BASE + 0x00020000)
GPIOA +0x8 OSPEEDR /*!< AHB1 peripherals */
GPIOA +0x4 OTYPER #define GPIOA_BASE (AHB1PERIPH_BASE + 0x0000)
// Casting memory address to a pointer
GPIOA MODER #define GPIOA ((GPIO_TypeDef *) GPIOA_BASE)
GPIOA->ODR |= 1UL<<14;
or (*GPIOA).ODR |= 1UL<<14;
158
How to light up a LED on PB2?
Enable Clock Reset and Control Clock 159
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOBEN;
GPIO Mode Register (MODER) 160
How do we write
MODER in C?
+ Vcc
D
G
PMOS
GPIO S GPIO
Output Bit Output Pin
OTYPE in C? G
D
NMOS
S
Main configuration
1. Enable peripheral GPIO via RCC module 0x40020028
0x40020024
AFR[1]
2. Configure the GPIO pin in MODER (input, output, AF or analog)
0x40020020
AFR[0]
3. If Input: pull up, pull down? (PUPDR)
LCKR
4. If Output: Push-pull or open-drain (OTYPE) and speed ( OSPEEDR) 0x4002001C
BSRR
5. If Alternate function: choice in AFRx reg 0x40020018
0x40020014
ODR
IDR
0x40020010
PUPDR
Signal input read in IDR 0x4002000C
OSPEEDR
Signal output driven in ODR 0x40020008
0x40020004
OTYPER
MODER
0x40020000
169
Pour comprendre et réviser
https://openclassrooms.com/fr/courses/4117396-developpez-en-c-pour-
lembarque/4633881-configurez-les-ports-d-entree-sortie
MICROCONTROLLER PERIPHERALS
CHAPTER 5
EXCEPTIONS AND INTERRUPTS
Microcontrollers’ Structure 171
Clk
Flash RAM TIM1 TIM2 UART …
Core
Polling:
You pick up the phone every three seconds to
check whether you are getting a call.
while(nobody){
pickeup();
Wait(3s);
}
answer();
Interrupt:
Do whatever you should do and pick up the phone
when it rings.
An exception, in programming, is an
Exception unplanned event, such as invalid input or a
loss of connectivity, that occurs while a
program is executing and disrupts the flow
of its instructions.
HW = Interrupt SW
Peripherals
NVIC (GPIO, Timers,
ADC, DAC, etc)
Trigger exceptions
Interrupt/Exception Processing Sequence 176
time
Some code is running
Interrupt trigger occurs
Processor does some hard-wired processing
Processor executes ISR (interrupt subroutine)
Processor resumes other code
Interrupt mechanism 177
handler for each exception type is 0x0000_0004 -3 fixed Reset Reset Vector
processor loads PC with this fixed, 0x0000_0014 1 settable BusFault_Handler Pre-fetch fault, memory access fault
ARM University
179
Table predefined in startup code for STM32F446xx
Interrupt
Exit
Interrupt Handler
Stack
Interrupt
occupancy Unstacking
Signal
NVIC
Treats interrupts
Manage enable and priorities for all interrupts sources
Interrupt Number (in ISR table) 185
16 + 96 really implemented
Example: if TIM7_IRQn = 44
NVIC->ISER[1] = 1 << 12; // Enable Timer 7 interrupt: 44 = 32*1 + 12
Disabling Peripheral Interrupts: ICER 1-8 188
TIM7_IRQn = 44
NVIC->ICER[1] = 1 << 12; // Disable Timer 7 interrupt
Disable/Enable Interrupts 189
Method 2 low-level:
– Enable: MSB to choose ISER, LSB to choose bit to set
• NVIC->ISER[ IRQn / 32] = 1 << (IRQn % 32);
• Better solution:
• NVIC->ISER[ IRQn >> 5] = 1 << (IRQn & 0x1F);
– Disable: MSB to choose ICER, LSB to choose bit to set
• NVIC->ICER[ IRQn >> 5] = 1 << (IRQn & 0x1F);
Interrupt Number in CMSIS vs in PSR 190
Thumb state flag GE[3:0]: Greater or equal flags (only available on Cortex-M4 and M7)
Overflow flag
Carry/Borrow flag
Zero flag
Example:
Need to enable EXTI0_IRQn interrupt
line
NVIC_EnableIRQ (6);
In code initialization
192
Clear a pending interrupt
NVIC_ClearingPending (6);
// clear pending status
Interrupt management: Peripheral level 195
NVIC GPIO
Up to 96 lines
Nouveau
UART message
void EXTI1_IRQHandler(void) {
https://openclassrooms.com/fr/courses/4117396-developpez-en-c-pour-
lembarque/4636746-maitrisez-les-exceptions-et-les-interruptions
Et
https://openclassrooms.com/fr/courses/4117396-developpez-en-c-pour-
lembarque/4635136-gerez-vos-interruptions
100Ω
Pull down
resistor
205
// Pull PA.3 down internally; Trigger on rising edge
int main(void) {
// Enable GPIO Clock //stm32f446ree.h
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN; #define RCC_AHB1ENR_GPIOAEN ((uint32_t)0x00000001U)
// GPIO Mode: Input(00), Output (01),
// AF(10), Analog (11)
GPIOA->MODER &= ~3U << 6;
// GPIO Push-Pull: No pull-up, pull-down (00), AHB1 peripheral clock enable register (AHB2ENR)
// Pull-up (01), Pull-down (10), Reserved (11)
GPIOA->PUPDR &= ~3U << 6;
GPIOA->PUPDR |= 2U << 6; // Pull down
while(1);
}
206
// Pull PA.3 down internally; Trigger on rising edge
int main(void) {
// Enable GPIO Clock
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
// GPIO Mode: Input(00), Output (01),
// AF(10), Analog (11, default)
GPIOA->MODER &= ~3U << 6;
// GPIO Push-Pull: No pull-up, pull-down (00), Digital Input
// Pull-up (01), Pull-down (10), Reserved (11) Mode bits = 00
GPIOA->PUPDR &= ~3U << 6;
GPIOA->PUPDR |= 2U << 6; // Pull down
01 Digital Output
NVIC_EnableIRQ(EXTI3_IRQn); // Enable Interrupt
10
// Connect External Line to the GPI
RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN; GPIO Pin Alternative Function
11
SYSCFG->EXTICR[0] &= ~SYSCFG_EXTICR1_EXTI3;
SYSCFG->EXTICR[0] |= SYSCFG_EXTICR1_EXTI3_PA;
Analog
// Interrupt Mask Register
// 0 = marked, 1 = not masked (enabled)
EXTI->IMR1 |= EXTI_IMR1_IM3;
while(1);
}
207
// Pull PA.3 down internally; Trigger on rising edge
int main(void) {
// Enable GPIO Clock
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
// GPIO Mode: Input(00), Output (01),
// AF(10), Analog (11)
GPIOA->MODER &= ~3U << 6;
// GPIO Push-Pull: No pull-up, pull-down (00), +3.3V
// Pull-up (01), Pull-down (10), Reserved (11)
GPIOA->PUPDR &= ~3U << 6;
GPIOA->PUPDR |= 2U << 6; // Pull down 100Ω
while(1);
}
Interrupt Vector Table sharing vectors 208
Cortex-
EXTI3
NVIC
EXTI2_IRQn = 8 EXTI2_IRQHandler
M4
EXTI3_IRQn = 9 EXTI3_IRQHandler
EXTI4_IRQn = 10 EXTI4_IRQHandler
EXTI3_IRQHandler
... ...
Interrupt EXTI9_5_IRQn = 23 EXTI9_5_IRQHandler
Vector
... ...
Table
EXTI15_10_IRQn = 40 EXTI15_10_IRQHandler
... ...
Interrupt Vector Table sharing vectors 209
Cortex-
EXTI3
NVIC
NVIC_EnableIRQ(EXTI3_IRQn); // Enable Interrupt
M4
// Connect External Line to the GPI
RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN;
SYSCFG->EXTICR[0] &= ~SYSCFG_EXTICR1_EXTI3;
SYSCFG->EXTICR[0] |= SYSCFG_EXTICR1_EXTI3_PA; EXTI3_IRQHandler
// Interrupt Mask Register Interrupt
// 0 = marked, 1 = not masked (enabled) Vector
EXTI->IMR1 |= EXTI_IMR1_IM3;
Table
// Rising trigger selection
// 0 = trigger disabled, 1 = trigger enabled
EXTI->RTSR1 |= EXTI_RTSR1_RT3;
210
while(1);
}
External Interrupt (EXTI) Sources 211
Cortex-
Pin.x
EXTIx
NVIC
010
M4
PC.x
011
PD.x
100 EXTIx
Nested-Vectored
PE.x x = 0, 1, 2, …, 15 Interrupt Controller
101
PF.x
110
PG.x STM32F4
111
PH.x
One mux for each of EXTI0, EXTI1, ..., EXTI15
Example External Interrupt (EXTI) Source 212
SYSCFG external
interrupt configuration
register (doc Chapter 8)
(SYSCFG_EXTICR#)
000
PA.3 source
001 selection
PB.3
Cortex-
PA.3
EXTI3
NVIC
010
M4
PC.3
011
PD.3
100 EXTI.3
Nested-Vectored
PE.3
Interrupt Controller
101
PF.3
110
PG.3 STM32F4
111
PH.3
Select pin x from Port y as EXTIx
213
// Pull PA.3 down internally; Trigger on rising edge
int main(void) {
// Enable GPIO Clock SYSCFG external
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN; interrupt configuration
// GPIO Mode: Input(00), Output (01), register
// AF(10), Analog (11)
GPIOA->MODER &= ~3U << 6;
(SYSCFG_EXTICR)
// GPIO Push-Pull: No pull-up, pull-down (00), 000
// Pull-up (01), Pull-down (10), Reserved (11)
PA.3 source selection
GPIOA->PUPDR &= ~3U << 6; 001
GPIOA->PUPDR |= 2U << 6; // Pull down PB.3
010
NVIC_EnableIRQ(EXTI3_IRQn); // Enable Interrupt PC.3
011
// Connect External Line to the GPI PD.3
RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN; // EXT IT WKUP 100 EXTI.3
SYSCFG->EXTICR[0] &= ~SYSCFG_EXTICR1_EXTI3; PE.3
SYSCFG->EXTICR[0] |= SYSCFG_EXTICR1_EXTI3_PA; 101
PF.3
// Interrupt Mask Register
110
// 0 = marked, 1 = not masked (enabled)
PG.3
EXTI->IMR1 |= EXTI_IMR1_IM3;
111
// Rising trigger selection PH.3
// 0 = trigger disabled, 1 = trigger enabled
EXTI->RTSR1 |= EXTI_RTSR1_RT3;
while(1);
}
214
SYSCFG EXTI Configuration
External Interrupt (EXTI) Controller 215
Configurable
External
Interrupts
interrupts
events
216
217
218
// Pull PA.3 down internally; Trigger on rising edge
int main(void) {
+3V
// Enable GPIO Clock
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
// GPIO Mode: Input(00), Output (01), 100Ω
// AF(10), Analog (11)
GPIOA->MODER &= ~3U << 6; Processor Chip
// GPIO Push-Pull: No pull-up, pull-down (00), Input Pin Joy_up
// Pull-up (01), Pull-down (10), Reserved (11) PA.3
GPIOA->PUPDR &= ~3U << 6; Input
GPIOA->PUPDR |= 2U << 6; // Pull down
Pull down
NVIC_EnableIRQ(EXTI3_IRQn); // Enable Interrupt resistor
while(1);
}
External Interrupt (EXTI) Controller 219
Configurable
External
Interrupts
interrupts
events
220
221
// Pull PA.3 down internally; Trigger on rising edge
int main(void) {
// Enable GPIO Clock
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
// GPIO Mode: Input(00), Output (01),
// AF(10), Analog (11)
GPIOA->MODER &= ~3U << 6;
// GPIO Push-Pull: No pull-up, pull-down (00),
// Pull-up (01), Pull-down (10), Reserved (11)
GPIOA->PUPDR &= ~3U << 6;
GPIOA->PUPDR |= 2U << 6; // Pull down
while(1);
}
222
// Pull PA.3 down internally; Trigger on rising edge
int main(void) {
// Enable GPIO Clock
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
// GPIO Mode: Input(00), Output (01),
// AF(10), Analog (11)
GPIOA->MODER &= ~3U << 6;
// GPIO Push-Pull: No pull-up, pull-down (00),
// Pull-up (01), Pull-down (10), Reserved (11)
GPIOA->PUPDR &= ~3U << 6;
GPIOA->PUPDR |= 2U << 6; // Pull down
while(1);
}
223
Interrupt Request (IRQ)
EXTI3_IRQHandle
r unstacking
stacking
while(1); while(1);
time
void EXTI3_IRQHandler(void) {
if ((EXTI->PR1 & EXTI_PR1_PIF3) != 0) { EXTI3_IRQHandle
r unstacking
// Toggle LED stacking
...
while(1); while(1);
// Cleared flag by writing 1
EXTI->PR1 |= EXTI_PR1_PIF3;
} time
}
MICROCONTROLLER PERIPHERALS
CHAPTER 6
TIMERS
227
Microcontrollers’ Structure
Clk
Flash RAM TIM1 TIM2 UART …
Core
• Several Functions
• Input capture measure time between 2 events
• Output compare generate events after a given time, generate waveforms
• Pulse-width modulation (PWM) generation application of output compare
• One-pulse mode output application of output compare
• Input Capture
• Measure pulse duration
• Output Compare
• Generate pulse
Counter
STM32F446 TIM2-5 Timers 234
Master/Slave
Controller
Time Base
Unit
Output compare
waveforms
Input capture
4 channels
only, inputs
OR outputs
STM32F446 TIM2-5 Timers 235
Reload
fCL_PSC fCL_CNT
Timer
PSC ISR
Counter
clock Prescaler Interrupt
Timer Output
= (OCxREF)
Update
OCx update
Compare &
Capture
Register (CCR)
OUTPUT COMPARE MODE 239
Output
signal
240
Practical Use of Timers
3.3V
0V
Low t
Pass
50% 50% 50% 20% 20%
Filter
3.3V
50%
20%
0V
t
Reload
fCL_PSC fCL_CNT
Timer
PSC ISR
Counter
clock Prescaler Interrupt
Channel
event
Compare &
Capture
Register (CCR)
INPUT CAPTURE MODE 242
CNT VALUE
CNT VALUE
CNT VALUE
COPIED INTO
COPIED INTO
CCRx REGISTER
CCRx REGISTER
0 0 0 0 0 0 0 0 1 1 1 1 0 1 1 1 0 1 0 1 0 0 0 0 1 0 1 0 1 1 1 1
L H
244
TIM2 to TIM5 register map and reset values
Main Configuration Registers 245
CRx
ARR
CCMRx
CCRx
Edge-aligned Mode (Up-counting) 247
clock
6 6 6 6
5 Counter
5 Counter
5 Counter
5
4 overflow 4 overflow 4 overflow 4
3 3 3 3
counter 2 2 2 2
1 1 1 1
0 0 0 0
Counter overflow
Update event (UEV)
Master/Slave
Controller
Time Base
Unit
Output compare
Input capture
251
TIMERS
DETAILS ON OUTPUT COMPARE MODE
Output Compare Modes 252
CCRx
Clock
6 6 6 6
5 5 5 5
4 4 4 4
CCR = 3 3 3 3 3
Counter 2 2 2 2
1 1 1 1
0 0 0 0
OCREF
Clock
6 6 6 6
5 5 5 5
4 4 4 4
CCR = 3 3 3 3 3
Counter 2 2 2 2
1 1 1 1
0 0 0 0
OCREF
OC1xREF
266
273
Removing transitions
If less than N cycles long
286
TIMER CONFIGURATION
ARM University
RCC Clock Settings STM32F446xx 287
RCC_APB1ENR
RCC_APB2ENR
Prescaler PSC and auto-reload ARR registers 288
X
Control Register 1(CR1) 289
URS: Update request source Select UEV event sources (UIE needs to be enabled)
0: Any of the following events generate an update interrupt or DMA request if enabled.
These events can be:
– Counter overflow/underflow
– Setting the UG bit by software (Re-initialize the counter and generates an update of the registers)
– Update generation through the slave mode controller (Trigger event)
1: Only counter overflow/underflow generates an update interrupt or DMA request if
enabled.
CEN: Counter enable Enable timer
DMA / Interrupt Enable Register (DIER) 290
UIE: Update interrupt enable Enable interrupt on update event or CNT reset
StatusRegister (SR) 291
Bit 12..9 CCxOF: Capture/Compare overcapture flag Set by hardware when CCxIF is already set on
corresponding channel (Capture not acknowledged)
Cleared by software
Bit 4..1 CCxIF: Capture/Compare interrupt flag Compare: Set by hardware when the counter matches
the compare value
Capture: Set by hardware on a capture.
Cleared by software or by reading the
TIMx_CCR1 register.
Channel 1
Compare :
CCxNP: Compare complementary output polarity 0: OCxN active high. (Only TIM1/TIM8)
1: OCxN active low.
CCxNE: Compare complementary output 1 : Enable / 0 : Disable (Only TIM1/TIM8)
CCxP: Compare output polarity 0: OC1 active high
1: OC1 active low
CCxE: Compare output 1 : Enable / 0 : Disable
Capture :
CCxNP/CCxP : Capture input polarity bits select for trigger or channel
00: noninverted/rising edge
01: inverted/falling edge
10: reserved, do not use this configuration.
11: noninverted/both edges
CCxNE: Capture complementary input 1 : Enable / 0 : Disable (Only TIM1/TIM8)
CCxE: : Capture input 1 : Enable / 0 : Disable
Capture/Compare Register channel x (CCRx) 295
CCRx: Compare value Contains the value to be compared to the counter TIMx_CNT
Capture value Counter value transferred by the last input capture 1 event
Timer configuration (for any timer type) to set the timer base time
1. Enable peripheral Clocks for TIMx and GPIO via RCC module
2. Set the prescaler value in register TIMx_PSC to define the counter clock CK_CNT frequency
3. Set the auto-reload value in register TIMx_ARR to define the timer period
4. Configure the counter (mode CMS, direction DIR) in register TIMx_CR1
5. Enable the timer CEN in register TIMx_CR1