Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Mon Cours

Download as pdf or txt
Download as pdf or txt
You are on page 1of 213

1

EMBEDDED SYSTEMS WITH ARM


CORTEX-M MICROCONTROLLERS

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

ATTENTION : Vérifier votre accès moodle au plus vite


Règles pour le bon déroulement du module: ponctualité, investissement, autonomie
Questions d’introduction 3

C’est quoi un processeur?


De quoi est-il constitué?
Comment est-il conçu/développé?
Que permet-il?
C’est quoi un registre? A quoi servent-ils?
Comment est-il programmé?
4

INTRODUCTION TO
EMBEDDED SYSTEMS DESIGN
Introduction 5

Table Of Contents Skills

1. Our microcontroller  Low level C development


2. Programming in C  Peripheral development
3. Clocks  Datasheet
4. GPIO  Tools for debug(Logic Analyzer, Jtag)
5. Interrupts
6. Clock & Timer (Compare /
Capture)
7. ADC/DAC

ARM University
Introduction 6

• The Difference between a microcontroller and a


microprocessor?
• microprocessors don’t have RAM, ROM, and other
peripheral on the chip
• A microcontroller… controls
• It gets environment state through sensors
• It acts on system environment through actuators
• Additionally to the core, several elements enhance this
control
• Many GPIOs with interrupt capabilities
• Many timers with external I/Os Peripherals
• ADC/DAC capabilities
• Communication busses
Peripherals Importance 7

Core controller is here


8
Definition of a Microcontroller

System built around a Processor


• ALU + Registers + Memory
• Example of an IC (integrated circuit)
• Designed in VHDL/Verilog
• Constituted of combinatorial + sequencial logic
• Implemented as transistors on CMOS semiconductor
MCU (microcontroller unit)
A microcontroller contains one or more CPUs (processor cores) along with memory and
programmable input/output peripherals

Dedicated to Control (take decisions)


• Peripherals to communicate with the outside world

General public version: Arduino Uno, Intel Edison, ST Micro STM32, TI


MSP430, Microchip PIC, etc.
10
Energy Efficiency vs. Flexibility

GPP
Flexibility

GPU

DSP / MCU

FPGA

ASIC

Energy efficiency (MIPS/Watt)


Peripherals Course 13

Courses on Peripherals
• GPIOs
• interrupts
• Timers
Focusing on the integration of a microcontroller-based
system in its environment
Example 1 14

Examples of a simple application


Example 2 15

Low V

High V

~ synchronized with the Grid

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

 Functions Admission sensor


 Engine control
 System communications Exhaust sensor
 Speed detection …
 Constraints Admis
 Reliability in harsh environment System
sion
 Cost Gas pedal
 Weight

 Many Inputs and Outputs
 Discrete sensors & actuators
CAN Bus
 Network interface to rest of car
 High Performance MCU
 32-bit, 256 KB flash memory, 80 MHz

ARM University
27

CHAP 1 – OUR MICROCONTROLLER


STM32F446RE

ARM University
STM32 = Cortex + Peripherals 30
Nucleo-64 STM32F446RE
31

ARM CORTEX-M3 PROCESSOR


REGISTERS - REMINDER
Cortex-M3 Registers 32

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

Link Register (LR) R14 PSP


Program Counter (PC) R15 Process 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

R0 – R12: general purpose registers


– Low registers (R0 – R7) can be accessed by any instruction Data Data

– High registers (R8 – R12) sometimes cannot be accessed e.g. by some Thumb
PUSH POP
(16-bit) instructions
R13: Stack Pointer (SP) Low

– Records the current address of the stack


Stack Address
– Used for saving the context of a program while switching between tasks
– CORTEX-M3 has two SPs: Main SP, used in applications that require privileged SP
access e.g. OS kernel, and exception handlers, and Process SP, used in base- High
PC
level application code (when not running an exception handler)
Heap
Program Counter (PC)
– Records the address of the current instruction code
– Automatically incremented by 4 at each operation (for 32-bit instruction code),
except branching operations
Code
– A branching operation, such as function calls, will change the PC to a specific
address, meanwhile it saves the current PC to the Link Register (LR)
CORTEX-M3 Registers 35

R14: Link Register (LR)


– The LR is used to store the return address of a subroutine or a function call
– The program counter (PC) will load the value from LR after a function is finished
Current PC Current LR
PC LR

1. Save current Main Main


PC to LR Program Program
code code
Load PC with the

Code region
LR address in LR to return to

Code region
the main program

2. Load PC with the starting


address of the subroutine

subroutine subroutine
Current PC

PC

Call a subroutine Return from a subroutine to the main program


CORTEX-M3 Registers 36

xPSR, combined Program Status Register


– Provides information about program execution and ALU flags
• Application PSR (APSR)
• Interrupt PSR (IPSR)
• Execution PSR (EPSR)

APSR NZCVQ Reserved

IPSR Reserved ISR number

EPSR ICI/IT T Reserved ICI/IT

xPSR NZCVQ ICI/IT T Reserved ICI/IT ISR number

bit31 bit24 bit16 bit8 bit0


CORTEX-M3 Registers 37

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

ARM CORTEX-M3 PROCESSOR


MEMORY MAP
CORTEX-M3 Memory Map 39

The CORTEX-M3 processor has 4 GB of memory address space

The 4GB memory space is architecturally defined as a number of regions


– Each region is given for recommended usage
– Easy for software programmer to port between different devices

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

Memory is arranged as a series of “locations” 0xFFFFFFFF


– Each location has a unique “address”
– Each location holds a byte (byte-addressable)
– e.g. the memory location at address 0x080001B0 contains the byte value
0x70, i.e., 112

The number of locations in memory is limited


– e.g. 4 GB of RAM 70 0x080001B0
– 1 Gigabyte (GB) = 230 bytes BC 0x080001AF
– 232 locations  4,294,967,296 locations! 18 0x080001AE
01 0x080001AD
Values stored at each location can represent either A0 0x080001AC
program data or program instructions
– e.g. the value 0x70 might be the code used to tell the processor to add
two values together

0x00000000
40 Memory
CORTEX-M3 Endianness 41

Endian refers to the order of bytes stored in memory


– Little endian: lowest byte of a word-size data is stored in bit 0 to bit 7
– Big endian: lowest byte of a word-size data is stored in bit 24 to bit 31
CORTEX-M3 supports both little endian and big endian
However, Endianness only exists in the hardware level

Address [31:24] [23:16] [15:8] [7:0] [31:24] [23:16] [15:8] [7:0]

0x00000008 Byte3 Byte2 Byte1 Byte0 Byte0 Byte1 Byte2 Byte3


Word 3 Word 3

0x00000004 Byte3 Byte2 Byte1 Byte0 Byte0 Byte1 Byte2 Byte3


Word 2 Word 2

0x00000000 Byte3 Byte2 Byte1 Byte0 Byte0 Byte1 Byte2 Byte3


Word 1 Word 1

Little endian 32-bit memory Big endian 32-bit memory


CORTEX-M3 Memory Map 42

Vendor specific 0xFFFFFFFF


Reserved for other purposes
Memory 0xE0100000
512MB
Private peripherals Private Peripheral Bus 0xE00FFFFF
e.g. NVIC, SCS (PPB) 0xE0000000
0xDFFFFFFF

Mainly used for external


peripherals External device 1GB

e.g. SD card
0xA0000000
0x9FFFFFFF

Mainly used for external


memories External RAM 1GB

e.g. external DDR, FLASH, LCD


0x60000000
Mainly used for on-chip 0x5FFFFFFF
peripherals Peripherals 512MB
e.g. AHB, APB peripherals 0x40000000
0x3FFFFFFF
Mainly used for data memory
e.g. on-chip SRAM, SDRAM SRAM 512MB
0x20000000
0x1FFFFFFF
Mainly used for program code
Code 512MB
e.g. on-chip FLASH 0x00000000
43
ARM CORTEX M3 code area
CORTEX-M3 Memory Map 44

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

On-chip FLASH On-chip SRAM Timer UART GPIO


(Code Region) (SRAM Region) Peripheral Region

External memory interface External device interface


(External RAM Region) (External Device Region)

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

The generation of program follows a typical development flow


– Compile  Assemble  Link  Download
– The generated executable file (or program image) is stored in the program memory (normally an on-
chip flash memory), to be fetched by the processor

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

Typical program-generation flow


Compilation using ARM-based Tools 51

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

armlink & Link

armmar

.AXF File
Image .LIB file

executable

.BIN File
binary .HEX File
Disassembly File
52

Levels of Program Code


C Program Assembly Program Machine Program
0010000100000000
int main(void){ 0010000000000000
int i; 1110000000000001
int total = 0; Compile Assemble 0100010000000001
for (i = 0; i < 10; i++) {
0001110001000000
total += i;
} 0010100000001010
while(1); // Dead loop 1101110011111011
} 1011111100000000
1110011111111110

 High-level language  Assembly language  Hardware


 Level of abstraction  Textual representation
closer to problem representation of  Binary digits
domain instructions (bits)
 Provides for  Encoded
productivity and instructions
portability and data
Program Image in Global Memory 53

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

e.g. on-chip SRAM, SDRAM SRAM Region 512MB


0x20000000
0x1FFFFFFF
Mainly used for program image Code Region 512MB
0x00000000
e.g. on-chip FLASH
Global memory space
CORTEX-M3 Program Image 54

What is a program image


– The program image (or sometimes referred as executable file) usually refers to a piece of fully
integrated code that is ready to execute
The program image contains
– Vector table -- includes the starting addresses of exceptions (vectors) and the value of the main
stack pointer (MSP);
– start-up routine;
– Program code – application code and data;
– C library code – program codes for C library functions.

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

Language Advantages Disadvantage


Easy to learn Limited or no direct access to core registers
and stack

Portable No direct control over instruction sequence


C generation

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

 We program in C for convenience


 There are no MCUs which execute C, only machine code
 So we compile the C to assembly code, a human-readable
representation of machine code
 We need to know what the assembly code implementing the C looks
like
 To use the processor efficiently
 To analyze the code with precision
 To find performance and other problems
69

Examining Assembly Code before Debugger


 Compiler can generate assembly code listing for reference (under licensing)
 Select in project options
70

Examining Disassembled Program in Debugger

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

Faites le lien entre la compilation C et l'assembleur


87

CHAP 3 – CLOCKS

ARM University
88
Microcontrollers’ Structure

Clk
Flash RAM TIM1 TIM2 UART …
Core

IC GPIO ADC DAC SPI I2C


89
Clocks in STM32F446
90
Clocks in STM32F446
91
Clock Sources

Many different clocks


• Low speed (LS) clocks for low energy
• High-speed (HS) clocks for strong processing

• Precise clocks for demanding I/Os


• Internally generated clocks when synchronization is not needed

• Clocks are disabled when not needed to save power


92
Clock Sources
HSE: External
• Necessitates external quartz or external clock source
• Precise clock
HSI: Internal (default SYSCLK source)
• Low cost, internally generated
• Few % of frequency errors 16MHz for ex. 180MHz for ex.
Optional PLL
• Multiplies frequency Ref Phase Loop Voltage
Oscillator Comparator Filter Controlled
Oscillator
Frequency
Divider
LSE: External
• Necessitates external quartz
• Precise 32kHz clock
LSI: Internal
• Low cost, internally generated
• ~32kHz clock
93
Clock Propagation

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

Peripheral clock gating is controlled by the AHB1 peripheral


clock enable register (RCC_AHB1 ENR)
- APB1 peripheral clock enable register (RCC_APB1ENR)
- APB2 peripheral clock enable register (RCC_APB2ENR)
ALWAYS ENABLE THE CLOCK OF THE PERIPHERAL YOU
WANT TO USE.
94
Bus Clocks
95
RCC Clock enable Registers STM32F446xx

AHB1 peripheral clock enable register (RCC_AHB1ENR)

AHB2 peripheral clock enable register (RCC_AHB2ENR)


96
RCC Clock enable Registers STM32F446xx

APB2 peripheral clock enable register (RCC_APB2ENR)

APB1 peripheral clock enable register (RCC_APB1ENR)


Enable Clock : example for GPIOC peripheral 97

APB2 peripheral clock enable register (RCC_AHB1ENR)

SYSCLK Clock for Port A


1 GPIOCEN
AND Gate

#define RCC_AHB1ENR_GPIOCEN ((u32)0x00000004)

RCC->AHB1ENR |= RCC_AHB1ENR_GPIOCEN;
98
RCC registers Memory mapping STM32F446xx
99
RCC registers addresses STM32F446xx

Ex:

Avec RCC base address: 0x4002 3800

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

MOOC présentation des périphériques de la carte

https://openclassrooms.com/fr/courses/4117396-developpez-en-c-pour-
lembarque/4633171-comprenez-les-specificites-d-une-architecture-microcontroleur
102

ÉCRITURE DES REGISTRES DES PÉRIPHÉRIQUES


EN C
103
104

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);

init = init | 16;

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

init = init | (1 << 4);


init = init | (1 << 1);
init = init | (1 << 0);
Ceci est équivalent à
init = init | 0x13; // masque avec la valeur b0001 0011

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

init = init & ~ ( (1<<0)|(1<<1)|(1<<4) ); init & = ~ ( (1<<0)|(1<<1)|(1<<4) );

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.

Vous utiliserez le fichier


stm32f446xx.h
pour la définition des registres et des masques.
Inverser la valeur d’un bit 108

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

Manipulez les registres et les masques


111
Exemples

1- Je souhaite autoriser l’alimentation du périphérique DAC, comment est-ce que je


procède?

2- Je souhaite éteindre l’horloge du périphérique Timer 10, comment est-ce que je


procède?

3- Je souhaite vérifier l’état de l’horloge du périphérique GPIOD, comment est-ce que je


procède?
112
Exemple

Je souhaite autoriser l’alimentation du périphérique DAC, comment est-ce que je procède?

Bit 29 du registre RCC_APB1ENR, on force ce bit à 1

RCC->APB1ENR = RCC->APB1ENR | 0x1 << 29;


Equivalent à
RCC->APB1ENR |= 0x1 << 29;
Equivalent à
#define RCC_APB1ENR_DACEN ((u32)0x20000000)
RCC->APB1ENR |= RCC_APB1ENR_DACEN;
113
Exemple

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

RCC->APB2ENR = RCC->APB2ENR & 0xFFFDFFFF;


Equivalent à
RCC->APB2ENR = RCC->APB2ENR & ~( 0x1 << 17);
Equivalent à
RCC->APB2ENR |= ~(0x1 << 17);
Equivalent à
#define RCC_APB2ENR_TIM10 ((u32)0x00020000)
RCC->APB2ENR |= ~(RCC_APB2ENR_TIM10);
114

Je souhaite vérifier l’état de l’horloge du périphérique GPIOD, comment est-ce que je


procède?

Je veux vérifier l’état du bit 3 de RCC_AHB1ENR

if (RCC->APB2ENR & (1<<3) ) == 0 alors le bit est à 0


if (RCC->APB2ENR & (1<<3) ) != 0 alors le bit est à 1
116

MICROCONTROLLER PERIPHERALS
CHAPTER 4
GPIOS
117
Microcontrollers’ Structure

Clk
Flash RAM TIM1 TIM2 UART …
Core

IC GPIO ADC DAC SPI I2C


118
GPIO registers Memory mapping STM32F446xx
119
GPIO Alternative Functions

GPIOs are the main function of Pins

Pins may support different features


– Connecting to different peripherals Memory Mapped I/O
Alternate Function 1
Alternate Function 2 Pin
To enable an alternate function, one need to set …
up the appropriate register Alternate Function n

Digital path Function Select


+ analog paths for ADC / DAC

Advantages of IO multiplexing:
– Saves space on the package
– Improves flexibility
120
Nucleo Board
121
GPIOs: Connecting with Digital I/Os

I/Os organized in Ports


PA, PB, PC in our case

GPIO = primary function


Of the pins

Related Register Bit


Bit=1  Level=High
Bit=0  Level=Low
122
Interfacing Peripherals Possibilities

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

When we press Act on LEDS


GP Outputs
SW1 -> sensor -> actuators
GP Input

Goal: light either LED1 or LED2 based on switch SW1 position


GPIO = General-purpose input and output (digital)
– Input: program can determine if input signal is a 1 or a 0
– Output: program can set output to 1 or 0
Can use this to interface with external devices
– Input: switch
– Output: LEDs
126
How to light up a LED on PB2?
127
How to light up a LED on PB2?

1- We need to enable clock on necessary bus

2- We need to configure the GPIO in output mode

3- We need to set the corresponding bit to 1 to set the output


level
General Purpose Input/Output (GPIO) 128

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

32 bits (16 pins, 2 bits per pin)

Pin 2 Pin 1 Pin 0


131
Configuration of an I/O Port

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

GPIO Input: Pull Up and Pull Down


A digital input can have three states: High, Low, and High-Impedance (also called
floating, tri-stated, HiZ)

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

GPIO Pull-up/Pull-down Register (PUPDR)


00 = No pull-up, pull-down 01 = Pull-up
10 = Pull-down 11 = Reserved

Schmitt
trigger
GPIO port pull-up/pull-down register (PUPDR) 136

 32 data bits, 2 bits for each pin


Basic Structure of an I/O Port Bit: Output 137

Schmitt
GPIO ODR trigger
Register GPIO Output Type Register (OTYPER)
0 = Output push-pull (default)
1 = Output open-drain

GPIO MODE Register


00 = Input, 01 = Output,
10 = AF, 11 = Analog (default)
GPIO Output Type Register (OTYPE) 138

 16 bits reserved, 16 data bits, 1 bit for each pin

+ Vcc

D
G
PMOS
GPIO S GPIO
Output Bit Output Pin
0/1 Controller

D
G
NMOS
S

GPIOB->OTYPE &= ~(1UL<<2); // Clear bit 2


GPIO Output: Push-Pull 139

+ Vcc + Vcc

Source
D current
G
PMOS PMOS

GPIO S GPIO GPIO GPIO


Output Bit Output Pin Output Bit Output Pin
0
0/1 Controller 1 Controller
Output is
+Vcc
D
G
NMOS
NMOS
S

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

GPIO GPIO GPIO


Output Pin Output Pin Output Pin

Output is Output is Output is


GPIO Floating GPIO Floating GPIO Grounded
Output Bit Output Bit Output Bit
0 0 1
1 Controller NMOS 1 Controller NMOS 0 Controller NMOS

Current

In order to connect several outputs together


Pull-up set to 1
Only 1 open-drain output can force 0 at a time
146
GPIO port output speed register (GPIOx_OSPEEDR)
GPIO Output Speed 147

Output Speed: Speed of Rising


– Slew rate: speed of rising and falling
– Four speeds: Low, Medium, Fast, High
Tradeoff Low
– Higher GPIO speed increases EMI noise and power
consumption
– Configure based on peripheral speed
• Low speed for toggling LEDs Medium
• High speed for SPI
On STM32F446
• Complex speed info, cf. electrical datasheet
Fast
• OSPEEDR=00  fI/O < 8MHz
• OSPEEDR=01  fI/O < 50MHz
• OSPEEDR=10  fI/O < 100MHz
• OSPEEDR=11  fI/O < 180MHz High
At high frequency, need for using a
“compensation cell”
GPIO Output Data Register (ODR) 148

16 bits reserved, 16 data bits, 1 bit for each pin


Allow to set the output value

Pin 2

GPIOB->ODR |= 1UL << 2; // Set bit 2


GPIO Input Data Register (IDR) 149

16 bits reserved, 16 data bits, 1 bit for each pin


Allow to read the input value

Pin 4
READ ONLY

if( GPIOB->IDR & (1UL << 4)) == 0; // test if pin 4 input value is 0
152

GPIO REGISTERS CONFIGURATION


SUMMARY
Memory Map of STM32F4 153

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

153 One Byte (8 bits)


GPIO Memory Map 154

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

How do we write *((uint32_t *) 0x40020014) |= 1UL<<14;


ODR in C?
Dereferencing a pointer Bitwise OR
Dereferencing a Memory Address 157

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

AHB1 peripheral clock enable register (RCC_AHB1ENR)

SYSCLK Clock for Port B


1 GPIOEN
AND Gate

#define RCC_AHB1ENR_GPIOBEN ((uint32_t)0x00000002U)

RCC->AHB1ENR |= RCC_AHB1ENR_GPIOBEN;
GPIO Mode Register (MODER) 160

32 bits (16 pins, 2 bits per pin)


Select GPIO mode

Pin 2 Pin 1 Pin 0

How do we write
MODER in C?

GPIOB->MODER &= ~(3UL<<4); // Clear bits 4 and 5 for Pin 2


GPIOB->MODER |= 1UL<<4; // Set bit 4, set Pin 2 as output
GPIO Output Type Register (OTYPE) 161

16 bits reserved, 16 data bits, 1 bit for each pin


FOR OUTPUT

+ Vcc

D
G
PMOS
GPIO S GPIO
Output Bit Output Pin

How do we write 0/1 Controller

OTYPE in C? G
D
NMOS
S

GPIOB->OTYPE &= ~(1UL<<2); // Clear bit 2


Light up a Red LED on PB2 162

RCC->AHB1ENR |= RCC_AHB1ENR_GPIOBEN; // Enable clock of Port B

GPIOB->MODER &= ~(3UL<<4); // Clear mode bits


GPIOB->MODER |= 1UL<<4; // Set mode to output

GPIOB->OTYPE &= ~(1UL<<2); // Select push-pull output

GPIOB->ODR |= 1UL << 2; // Output 1 to turn on red LED


165
GPIO alternate function low register (GPIOx_AFRL)
166
167
GPIO configuration summary 168

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

Configurez les ports d’entrée/sortie

Mise en œuvre de tous ces périphériques dans le TD1


170

MICROCONTROLLER PERIPHERALS
CHAPTER 5
EXCEPTIONS AND INTERRUPTS
Microcontrollers’ Structure 171

Clk
Flash RAM TIM1 TIM2 UART …
Core

IC GPIO ADC DAC SPI I2C


Polling vs Interrupt 172

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.

// interrupt routine to be called upon request


void isRinging(void){
answer();
}
Exceptions/Interrupts ARM Terminology 173

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

Non-Maskable Maskable Fault System Debug


Reset or NMI Deactivated by default
Generated by an Call Event
error condition.
Example: EXTI OS related
Example: writing Interrupt
Vector in unprivileged mode
Interrupts definition 174

 Hardware-triggered asynchronous software routine


 Triggered by hardware signal from peripheral or external device
 Asynchronous - can happen anywhere in the program
 Software routine - Interrupt service routine runs in response to interrupt

 Fundamental mechanism of microcontrollers


 Provides efficient event-based processing rather than polling
 Provides quick response to events regardless of program state, complexity,
location
 Allows embedded systems to be responsive without an operating system
(specifically task scheduler)
On the board 175

Nucleo-64 STM32F446RE Board


STM32F446RE
ARM cortex Memory
M3 Core

Peripherals
NVIC (GPIO, Timers,
ADC, DAC, etc)

Trigger exceptions
Interrupt/Exception Processing Sequence 176

Main Code Hardwired CPU ISR


(Background) response activities (Foreground)

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

Physical Signal + interrupt vector table+ ISR


Interrupt request
An interrupt is supported by:
• A HW signal on a given line 1
• Raising / Falling edge will launch the interrupt
0

• The interrupt vector table


• Associates the list of interrupt handlers with a list of interrupt requests
• Each entry of the interrupt vector table, is the address of an interrupt handler.
• Sometimes, several HW lines share the same vector
Interrupt vector
Bit 31 Bit 0
• The interrupt handler or ISR (interrupt Service Routine)
• The processor Program Counter (PC) jumps to the routine pointed by the
interrupt register when interrupt request (IRQ) occurs
• Code to be executed
178
Interrupt vectors Table
Type of
Address Priority Acronym Description

• Start address for the exception


priority
0x0000_0000 - - - Stack Pointer Initialization

handler for each exception type is 0x0000_0004 -3 fixed Reset Reset Vector

Non maskable interrupt. The RCC


fixed and pre-defined for a 0x0000_0008 -2 fixed NMI_Handler
Clock Security System (CSS) is
linked to the NMI vector.
processor 0x0000_000C -1 fixed HardFault_Handler All class of fault

• When interrupt occurs, the 0x0000_0010 0 settable


MemManage_Handle
r
Memory management

processor loads PC with this fixed, 0x0000_0014 1 settable BusFault_Handler Pre-fetch fault, memory access fault

0x0000_0018 2 settable UsageFault_Handler Undefined instruction or illegal state


pre-defined address 0x0000_001C-
0x0000_002B - - - Reserved
• Exception Vector Table starts at 0x0000_002C
System service call via SWI
3 settable SVC_Handler instruction
memory address 0
0x0000_0030 4 settable DebugMon_Handler Debug Monitor

• Program Counter PC is loaded from - - - Reserved


0x0000_0034
0x00000004 initially
0x0000_0038 5 settable PendSV_Handler Pendable request for system service

0x0000_003C 6 settable SysTick_Handler System tick timer

ARM University
179
Table predefined in startup code for STM32F446xx

Recognized by the linker


Under the name _Vectors

This table precise the ISR


name to be used when
writing the interrupt
subroutine code
What happens when handling an IRQ 180

• Before ISR execution, current state of registers need to be


stored
• For example flags that store results of last operations
• negative, zero, carry, etc. in xPSR
• As for any subroutine called in your software
• Only for some registers

• When ISR execution ends , previous values of registers are


restored

• This is automated when writing C code


Stacking & Unstacking 181

Interrupt
Exit
Interrupt Handler
Stack
Interrupt
occupancy Unstacking
Signal

User Program User Program


Stacking
Time
Thread Mode Handler Mode Thread Mode
NVIC = Nested Vectored Interrupt Controller 184

 Specific to ARM CORTEX PROCESSOR


 Vector table is Up to 255 entries

What if several interrupts events occur simultaneously?


What if a new interrupt event occurs during ISR?

NVIC
 Treats interrupts
 Manage enable and priorities for all interrupts sources
Interrupt Number (in ISR table) 185

 Cortex-M supports up to 256 exceptions.

System Peripheral interrupt


Exceptions Interrupts number
CMSIS
Interrupt Number -16 -1 0 239

16 + 96 really implemented

 First 16 are system exceptions … CORTEX-M3


 CMSIS defines their interrupt numbers as negative
 Defined by ARM core
 The rest 240 are peripheral interrupts
 Peripheral interrupt number starts with 0.
 Defined by chip manufacturers.
List of interruptions at processor level 186

• 96 predefined interrupts channels at processor level


ISR
Interrupt program
number address
Enabling Peripheral Interrupts: ISER 1-8 187

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

For all peripheral interrupts: IRQn ≥ 0


Method 1  high-level:
• NVIC_EnableIRQ (IRQn); // Enable interrupt
• NVIC_DisableIRQ (IRQn); // Disable interrupt

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

Interrupt number for CMSIS functions


NVIC_DisableIRQ (IRQn); // Disable interrupt
NVIC_EnableIRQ (IRQn); // Enable interrupt
NVIC_ClearingPending (IRQn); // clear pending status
NVIC_SetPriority (IRQn, priority); // set priority level

Interrupt number in Program Status Register (xPSR) when in ISR


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

N Z C V Q IT[7:6] T Reserved GE[3:0] IT[5:0] 0 or Exception Number

IT[7:0]: If-Then bits

Thumb state flag GE[3:0]: Greater or equal flags (only available on Cortex-M4 and M7)

Stick saturation flag for SSAT and USAT

Overflow flag

Carry/Borrow flag

Zero flag

Negative or less than flag

Interrupt Number can be read in xPSR status Register


= 16 + Interrupt Number for CMSIS
191
CMSIS Interrupt number defined in file stm32f446xx.h

Example:
Need to enable EXTI0_IRQn interrupt
line

NVIC_EnableIRQ (6);

In code initialization
192
Clear a pending interrupt

Example: interrupt has been treated,


flag needs to be cleared

NVIC_ClearingPending (6);
// clear pending status
Interrupt management: Peripheral level 195

• Most interrupts are disabled by default (otherwise the


core could act violently at reset)

• Interrupt must be enabled(unmask) if you want to use it


• At NVIC (Nested Vectored Interrupt Controller) level to enabled
the interrupt line
• At peripheral level to configure the type of event
generating the interrupt on the enabled line
• Code to be executed when the interrupt occurs must be
written (ISR)
196
STM32 Peripherals
ARM cortex EVENT
M3 Core Timer

NVIC GPIO

Up to 96 lines

Nouveau
UART message

CORTEX-M3 CORE INTERRUPT LINES


CONNECTED TO THE VARIOUS PERIPHERALS
197
Enable an Interrupt at peripheral level

• Different and specific for each type of peripheral


• GPIO
• Timers
• …
• Event must be configured ( external or internal event,
rising or falling edge….) in the peripheral registers
• Interrupt flags must be cleared as well in the
peripheral registers
• Once during the initial configuration
• Each time the interrupt is treated ( at the end of the ISR)
Interrupt management : the interrupt subroutine 198

• To manage an interrupt, the following must be configured in


your system
– HW
• A HW line
• A table containing the address of the ISR, called Interrupt Vector / Exception
Handler
• Some registers configuring the interrupt (raising/falling edge, etc.)
– SW
• A function called Interrupt Service Routine (ISR) or interrupt handler.
• This function is never called from software

• The activation of an interrupt is called


– Interrupt Request (IRQ)
199
Handler re-definition

• Default ISR exists for each available interrupt


but is empty ( weak definition)
• Corresponding ISR (handler) must be redefined
(rewritten) when enabling an interrupt
• Code you want to execute when the interrupt occurs
• At the end of the routine, always clear the flag of the interrupt at
NVIC level and peripheral level
200
Handler name predefined in startup code for STM32F446xx
You must redefine the handler fonction, for
example:

void EXTI1_IRQHandler(void) {

// Cleared flag by writing 1


EXTI->PR |= EXTI_PR_PR1;
NVIC_ClearingPendingIRQn (6); // flag at processor level

THIS FUNCTION IS NEVER CALLED IN YOUR CODE


MOOC 203

https://openclassrooms.com/fr/courses/4117396-developpez-en-c-pour-
lembarque/4636746-maitrisez-les-exceptions-et-les-interruptions

Maîtrisez les exceptions et les interruptions

Et
https://openclassrooms.com/fr/courses/4117396-developpez-en-c-pour-
lembarque/4635136-gerez-vos-interruptions

Gérez vos interruptions


204
Example

Interrupt the processor when pushing on a button


+3.3V

100Ω

Processor Chip Input Pin


PA.3 Joy_up
Input

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

=XTI3_IRQn); // Enable Interrupt

// Connect External Line to the GPI


RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN;
SYSCFG->EXTICR[0] &= ~SYSCFG_EXTICR1_EXTI3;
SYSCFG->EXTICR[0] |= SYSCFG_EXTICR1_EXTI3_PA; 1
// Interrupt Mask Register
// 0 = marked, 1 = not masked (enabled)
EXTI->IMR1 |= EXTI_IMR1_IM3; SYSCLK AND
Clock for Port A
Gate
// Rising trigger selection
1 GPIOAEN
// 0 = trigger disabled, 1 = trigger enabled
EXTI->RTSR1 |= EXTI_RTSR1_RT3;

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;

// Rising trigger selection


// 0 = trigger disabled, 1 = trigger enabled
EXTI->RTSR1 |= EXTI_RTSR1_RT3;

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Ω

NVIC_EnableIRQ(EXTI3_IRQn); // Enable Interrupt Processor Chip Input Pin


PA.3 Joy_up
// Connect External Line to the GPI Input
RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN;
SYSCFG->EXTICR[0] &= ~SYSCFG_EXTICR1_EXTI3; Pull down
SYSCFG->EXTICR[0] |= SYSCFG_EXTICR1_EXTI3_PA; resistor

// Interrupt Mask Register


// 0 = marked, 1 = not masked (enabled)
EXTI->IMR1 |= EXTI_IMR1_IM3;

// Rising trigger selection


// 0 = trigger disabled, 1 = trigger enabled
EXTI->RTSR1 |= EXTI_RTSR1_RT3;

while(1);
}
Interrupt Vector Table  sharing vectors 208

Interrupt Vector Table


Interrupt Number Memory Address of ISR
(8 bits) (32 bits)
... ...
Nested-Vectored
EXTI0_IRQn = 6 EXTI0_IRQHandler
Interrupt Controller
PA.3 (NVIC) EXTI1_IRQn = 7 EXTI1_IRQHandler

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

• If 2 interrupts share the Interrupt Vector Table


same vector: Interrupt Number Memory Address of ISR
(8 bits) (32 bits)
need to test ... ...

interrupt flag available in EXTI0_IRQn = 6 EXTI0_IRQHandler


EXTI1_IRQn = 7 EXTI1_IRQHandler
EXTI_PR (Pending Register) EXTI2_IRQn = 8 EXTI2_IRQHandler
EXTI3_IRQn = 9 EXTI3_IRQHandler
EXTI4_IRQn = 10 EXTI4_IRQHandler
... ...
EXTI9_5_IRQn = 23 EXTI9_5_IRQHandler
... ...
EXTI15_10_IRQn = 40 EXTI15_10_IRQHandler
... ...
210
// 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) Nested-Vectored
GPIOA->PUPDR &= ~3U << 6;
GPIOA->PUPDR |= 2U << 6; // Pull down Interrupt Controller
PA.3 (NVIC)

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

See System configuration controller


(SYSCFG) Chapter 8
SYSCFG external
interrupt configuration
register
(SYSCFG_EXTICR#)
000
PA.x source selection
001
PB.x

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

// Connect External Line to the GPI


RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN;
SYSCFG->EXTICR[0] &= ~SYSCFG_EXTICR1_EXTI3;
SYSCFG->EXTICR[0] |= SYSCFG_EXTICR1_EXTI3_PA;

// Rising trigger selection


// 0 = trigger disabled, 1 = trigger enabled
EXTI->RTSR1 |= EXTI_RTSR1_RT3;

// Interrupt Mask Register


// 0 = marked, 1 = not masked (enabled)
EXTI->IMR1 |= EXTI_IMR1_IM3;
Rising edge triggers EXTI interrupt.

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

NVIC_EnableIRQ(EXTI3_IRQn); // Enable Interrupt

// Connect External Line to the GPI


RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN; IMR
SYSCFG->EXTICR[0] &= ~SYSCFG_EXTICR1_EXTI3;
SYSCFG->EXTICR[0] |= SYSCFG_EXTICR1_EXTI3_PA;

// Rising trigger selection


// 0 = trigger disabled, 1 = trigger enabled
EXTI->RTSR1 |= EXTI_RTSR1_RT3;

// Interrupt Mask Register


// 0 = marked, 1 = not masked (enabled)
EXTI->IMR1 |= EXTI_IMR1_IM3;

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

NVIC_EnableIRQ(EXTI3_IRQn); // Enable Interrupt

// Connect External Line to the GPI


RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN;
SYSCFG->EXTICR[0] &= ~SYSCFG_EXTICR1_EXTI3;
SYSCFG->EXTICR[0] |= SYSCFG_EXTICR1_EXTI3_PA;

// Rising trigger selection


// 0 = trigger disabled, 1 = trigger enabled Processor runs a dead loop
EXTI->RTSR1 |= EXTI_RTSR1_RT3; forever!
// Interrupt Mask Register
// 0 = marked, 1 = not masked (enabled)
EXTI->IMR1 |= EXTI_IMR1_IM3;

while(1);
}
223
Interrupt Request (IRQ)

EXTI3_IRQHandle
r unstacking
stacking

while(1); while(1);

time

Push the user button


224
225
Interrupt Service Routine (ISR)

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
}

Push the user button


226

MICROCONTROLLER PERIPHERALS
CHAPTER 6
TIMERS
227
Microcontrollers’ Structure

Clk
Flash RAM TIM1 TIM2 UART …
Core

IC GPIO ADC DAC SPI I2C


Timer 228

• Free-run counter (independent of the 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

• STM32F446: 14 timers, 8 timer types


• TIM1 – TIM14
• These timers share common features
Classical Timer Usage 229

• Input Capture
• Measure pulse duration

• Measure periodic signal

• Output Compare
• Generate pulse

• Generate PWM signal


230

Different timers for different usage =>


differences in configuration registers
STM32F4 Timer Peripherals 231

Advanced Control Timer


– TIM1 and TIM8
– Input capture, output compare, PWM, one pulse mode
– 16-bit auto-reload register
– control for driving motor or other devices
General Purpose Timer
– TIM2 to TIM5
– Input capture, output compare, PWM, one pulse mode
– 16-bit or 32-bit auto-reload register
General Purpose Timer
– TIM9 to TIM14
– Input capture, output compare, PWM, one pulse mode
– Only 16-bit auto-reload register
Basic Timer (Simple timer)
– TIM6 and TIM7
– Can be generic counter or internally connected to DAC
– 16-bit auto reload register
– NO CHANNEL
They all share the same structure (with optional features)
232
Timers registers Memory mapping STM32F446xx
STM32F446 TIM2-5 Timers 233

Counter
STM32F446 TIM2-5 Timers 234

Master/Slave
Controller

Time Base
Unit

Input channels Output channels


Measure Generate
waveforms

Output compare
waveforms

Input capture
4 channels
only, inputs
OR outputs
STM32F446 TIM2-5 Timers 235

Capture Interrupts Compare Interrupts


Timer: Clock 237

Reload Value ARR


𝑓𝐶𝐿_𝑃𝑆𝐶
𝑓𝐶𝐿_𝐶𝑁𝑇 = Reload
𝑃𝑆𝐶 + 1
fCL_PSC fCL_CNT
Timer
PSC Gestion IT
Counter
clock Prescaler Interrupt

@180MHz: 32-bit counter overflows after 24 seconds


@180MHz: 16-bit counter overflows after…0.4ms!!!

And also, high-speed clocks cost energy!


Timer: Output Compare 238

Reload Value ARR

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

modify modify modify


modify

Output
signal
240
Practical Use of Timers

• Timer in Compare mode


• the timer generates a waveform on an output
• Used
• to generate a modulated digital signal
• As a low speed Digital to Analog Converter (DAC) via low-pass filtering
• to control a DC motor speed via Pulse Width Modulation (PWM) and power amplification (the
motor does the low pass filtering)
• …

3.3V

0V
Low t
Pass
50% 50% 50% 20% 20%
Filter
3.3V
50%
20%
0V
t

50% 50% 50% 20% 20%


Timer: Input Capture 241

Reload Value ARR

Reload

fCL_PSC fCL_CNT
Timer
PSC ISR
Counter
clock Prescaler Interrupt

Channel
event

Compare &
Capture
Register (CCR)
INPUT CAPTURE MODE 242

RISING EDGE DETECTED ON


RISING EDGE DETECTED ON
TIMER CHANNEL
TIMER CHANNEL

CNT VALUE

CNT VALUE
CNT VALUE
COPIED INTO
COPIED INTO
CCRx REGISTER
CCRx REGISTER

=> PERIOD OF INPUT SIGNAL = 61- 54 = 7 ms


243
Practical Use of Capture Mode

• Timer Capture mode


• when a signal edge appears on an input, the current value of the timer counter is stored
• Used
• to check the period of a periodic input signal
• to measure the width of a pulse in a digital code
• …

Example of an infrared remote control

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

ARR = 6, RCR = 0 (if repetition counter)

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)

Period = (1 + ARR) * Clock Period


= 7 * Clock Period
STM32F446 TIM2-5 Timers 250

Master/Slave
Controller

Time Base
Unit

Input channels Output channels


 Measure waveforms  Generate waveforms

Output compare
Input capture
251

TIMERS
DETAILS ON OUTPUT COMPARE MODE
Output Compare Modes 252

CCRx

Output Compare Mode (OCM) Timer Output (OCREF)


000 Frozen  no effect
001 High if CNT == CCR
010 Low if CNT == CCR
011 Toggle if CNT == CCR
100 Forced low (always low)
101 Forced high (always high)
110 PWM mode 1
111 PWM mode 2
253
Output Compare: PWM Modes 1 & 2 254

Counter < Counter ≥


OCM Mode
Reference Reference
PWM mode 1
110 1 0
(Low True)
PWM mode 2
111 0 1
(High True)
Mode 1
PWM Mode 1 Timer Output =
High if counter < CCR 255

Low if counter ≥ CCR


(Low-True)
Upcounting mode, ARR = 6, CCR = 3, RCR = 0 (if repetition counter)

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

What is the CCR


Duty Cycle = Period = (1 + ARR) * Clock Period
duty Cycle? ARR + 1
= 7 * Clock Period
3
=
7
Mode 2
PWM Mode 2 Timer Output =
Low if counter < CCR 256

High if counter ≥ CCR


(High-True)
Upcounting mode, ARR = 6, CCR = 3, RCR = 0 (if repetition counter)

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

What is the CCR


Duty Cycle = 1 - Period = (1 + ARR) * Clock Period
duty Cycle? ARR + 1
= 7 * Clock Period
4
=
7
Multi-Channel Outputs 265

generate different waveforms/events from 1 counter

OC1xREF
266
273

DETAILS ON INPUT CAPTURE MODE


Input Capture 274
Input Capture 275

Monitor both rising and falling edges  measuring pulse


Input Capture 276

Monitor only rising edges or only falling edge  measuring period


Input Capture Diagram 277

Is there 1 or are there several


Interrupt lines per timer?

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

CMS[1:0]: Center-aligned mode selection Counter Mode


00: Edge-aligned mode.
01: Center-aligned mode 1
10: Center-aligned mode 2
11: Center-aligned mode 3
DIR: Direction
0: Counter used as upcounter
1: Counter used as downcounter

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

Bit 4..1 CCxIE: Capture/Compare x interrupt enable Enable interrupt on capture/compare on


corresponding channel

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.

UIF: Update interrupt flag Set by hardware on an update event.


Cleared by software.
–At overflow or underflow if the UDIS=0 in the TIMx_CR1 register.
–When CNT is reinitialized by a trigger event, if URS=0 and UDIS=0 in the TIMx_CR1 register.
Capture/Compare Mode Register (CCMR1) 292

OCxM: Output Compare mode 110: PWM mode 1


111: PWM mode 2

CCxS: Capture/Compare selection Defines the direction of the channel :


-Output Compare
-Input Capture + used input.
00: CCx channel is configured as output
01: CCx channel is configured as input, ICx is mapped on TIx
10: CCx channel is configured as input, ICx is mapped on TIy
11: CCx channel is configured as input, ICx is mapped on TRC. This mode is working only if an
internal trigger input is selected through TS bit (TIMx_SMCR register)

CCMR1 for channels 1 and 2, CCMR2 for channels 3 and 4


Capture/Compare Mode Register 2 (CCMR2) 293

OCxM: Output Compare mode 110: PWM mode 1 Channel 3


111: PWM mode 2

CCxS: Capture/Compare selection Defines the direction of the channel :


-Output Compare
-Input Capture + used input.
00: CCx channel is configured as output
01: CCx channel is configured as input, ICx is mapped on TIx
10: CCx channel is configured as input, ICx is mapped on TIy
11: CCx channel is configured as input, ICx is mapped on TRC. This mode is working only if an
internal trigger input is selected through TS bit (TIMx_SMCR register)

Permet de configurer les channels 3 et 4


Capture/Compare Enable Register (CCER) 294

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

For others channels


Use CCR2 for channel 2
Use CCR3 for channel 3
Use CCR4 for channel 4
Timer configuration 297

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

Complex configuration if using timer IOs (compare or capture modes)


1. Configure the GPIO pins (alternative function mode)
2. Configure the timer channels (see output compare or input capture )
Compare / Capture configuration 298

Configuration of output compare (OC) mode for channel i


1. Set the channel i as output: CCiS[1:0] in TIMx_CCMRy
2. Select the output compare mode: OCiM[2:0] in TIMx_CCMRy
3. Enable output compare: CCiE in register TIMx_CCER
4. Set the output compare value in register TIMx_CCRi (define OC duty-cycle)
5. Enable interrupt (if required): CCiIE in register TIMx_DIER

Configuration of input capture mode for channel i


1. Select the active input: CCiS[1:0] in register TIMx_CCMRy
2. Set the active edge: CCiP-CCiNP in register TIMx_CCER
3. Enable input capture: CCiE in register TIMx_CCER
4. Enable interrupt (if required): CCiIE in register TIMx_DIER

You might also like