0% found this document useful (0 votes)
97 views

STM32 PDF

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views

STM32 PDF

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 154

MICROCONTROLLERS AND

INTERFACING USING ARM


PROCESSOR

Lecture 1 Prof. Yasser Mostafa Kadah


Course Goals
 At the end of this course, you should be able to:
 Understand the architecture of one of the most popular microcontroller
(MCU) families
 Use an integrated development environment (IDE) to program and
debug an MCU
 Program an MCU using Assembly and C languages
 Understand and use peripherals integrated into an MCU
 Interface an MCU to simple external components
 Use timers in various modes
 Understand and use interrupts
 Understand and use analog to digital converters (ADC) and digital to
analog converters (DAC)
 Communicate using a serial interface (if time allows)
Course Prerequisites
 A course in Electric Circuits that includes understanding basic
electronic components such as resistors, capacitors, diodes and
transistors

 A course in basic digital logic design that includes logic gates


and Boolean arithmetic

 Ability to program in a high-level programming language such


as C or C++
Microprocessors and Microcontrollers

 Microprocessor: general-purpose CPU


 Emphasis is on flexibility and performance
 Generic user-interface such as keyboard, mouse, etc.
 Used in a PC, PDA, cell phone, etc.

 Microcontroller: microprocessor + memory on a single chip


 Emphasis is on size and cost reduction
 The user interface is tailored to the application, such as the buttons on a
TV remote control
 Used in a digital watch, TV remote control, car and many common day-
to-day appliances
Microcontroller Architectures
 Microcontroller architecture refers to the internal hardware
organization of a microcontroller
 Each hardware architecture has its own set of software
instructions called assembly language that allows programming
of the microcontroller
 Some of the popular microcontroller architectures
 Intel 8051
 Zilog Z80
 Atmel AVR
 Microchip PIC
 ARM
ARM Processors
 ARM: Advanced RISC Machines
 Previously “Acorn RISC Machines”
 ARM1: 1985
 Now: ARM11, ARM Cortex A, ARM Cortex R, ARM Cortex M
STM32 Platform
STM32 Product Lines
STM32 Value Line Block Diagram
STM32 Value Line Devices
STM32 Value line Discovery Kit
 The cheapest and quickest way to
discover the STM32 Value line
family
 Embedded ST-LINK or ST-LINK/V2
included to debug applications
 Works with several popular IDEs
 MDK-ARM (Keil)
 EWARM (IAR)
Kit Features
 STM32F100RBT6B microcontroller, 128 KB
Flash, 8 KB RAM in 64-pin LQFP
 On-board ST-Link (for programming and
debugging)
 Two red LEDs; LD1 for USB communication,
LD2 for 3.3 volts power on
 Designed to be powered by USB or an
external supply of 5 V or 3.3 V
 Can supply target application with 5 volts
and 3 volts
 Two user LEDs, LD3 and LD4 (green and blue)
 Two push buttons (User and Reset)
 Extension header for all QFP64 I/Os for
quick connection to prototyping board or
easy probing
Kit Hardware Block Diagram
STM32F100RBT6B Microcontroller
Assignments
 Explain the differences between MIPS and DMIPS.
 Compare the major ARM processor families available today
from the points of view of processing power, cost, applications.
(Hint: focus on ARM11 and ARM Cortex series processors)
 Install the MDK-ARM Evaluation Version and compile and link
the kit’s demo software available from ST web site.
 Revision of C programming.

 Next week: Lab demonstration of kit and development tools


STM32
MICROCONTROLLER

Lecture 2 Prof. Yasser Mostafa Kadah


Harvard and von Neumann Architectures

 Harvard Architecture—a type of computer architecture where


the instructions (program code) and data are stored in
separate memory spaces
 Example: Intel 8051 architecture

 von Neumann Architecture—another type of computer


architecture where the instructions and data are stored in the
same memory space
 Example: ARM, Intel x86 architecture (Intel Pentium, AMD Athlon, etc.)
Instruction Execution Cycle
 Fetch operation—retrieves an
instruction from the location in code
memory pointed to by the program
counter (PC)

 Execute operation—executes the


instruction that was fetched during the
fetch operation. In addition to
executing the instruction, the CPU also
adds the appropriate number to the PC
to point it to the next instruction to be
fetched.
Microcontroller Architectures
 Microcontroller architecture refers to the internal hardware
organization of a microcontroller
 Each hardware architecture has its own set of software
instructions called assembly language that allows programming
of the microcontroller
 Some of the popular microcontroller architectures
 Intel 8051
 Zilog Z80
 Atmel AVR
 Microchip PIC
 ARM
Memory and Bus Architecture
 Three masters:
 Cortex™-M3 core DCode bus (D-bus) and System bus (S-bus)
 GP-DMA1 (general-purpose DMA)
 Three slaves:
 Internal SRAM
 Internal Flash memory
 AHB to APB bridges (AHB to APBx), which connect all the APB
peripherals
System Architecture
Definitions
 ICode bus
 Connects the instruction bus of the Cortex™-M3 core to the Flash
memory instruction interface. Instruction fetches are performed on this
bus.
 DCode bus
 Connects the DCode bus (literal load and debug access) of the
Cortex™-M3 core to the Flash memory data interface
 System bus
 Connects the system bus of the Cortex™-M3 core (peripherals bus) to a
bus matrix which manages the arbitration between the core and the
DMA
Definitions
 DMA bus
 Connects the AHB master interface of the DMA to the bus matrix which
manages the access of CPU DCode and DMA to the SRAM, Flash
memory and peripherals
 Bus matrix
 Manages the access arbitration between the core system bus and the
DMA master bus. The arbitration uses a round robin algorithm
 AHB/APB bridges (APB)
 The two AHB/APB bridges provide full synchronous connections between
the AHB and the two APB buses
 APB buses operate at full speed (up to 24 MHz)
Memory Organization
 Program memory, data memory, registers and I/O ports are
organized within the same linear 4-Gbyte address space
 Bytes are coded in memory in little endian format
 The lowest numbered byte in a word is considered the word’s least
significant byte and the highest numbered byte, the most significant
 Addressable memory space is divided into 8 main blocks, each
of 512 MB
Memory Map
Memory Organization
 Embedded SRAM
 The STM32F100xx features up to 32 Kbytes of static SRAM. It can be
accessed as bytes, half-words (16 bits) or full words (32 bits). The SRAM
start address is 0x2000 0000
 Bit banding
 The Cortex™-M3 memory map includes two bit-band regions. These
regions map each word in an alias region of memory to a bit in a bit-
band region of memory. Writing to a word in the alias region has the
same effect as a read-modify-write operation on the targeted bit in the
bit-band region.
 In the STM32F100xx, both peripheral registers and SRAM are mapped
in a bit-band region. This allows single bit-band write and read
operations to be performed.
Memory Organization
 Bit-Banding Mapping formula:

bit_word_addr = bit_band_base + (byte_offset x 32) + (bit_number × 4)

 bit_word_addr is the address of the word in the alias memory region


that maps to the targeted bit
 bit_band_base is the starting address of the alias region
 byte_offset is the number of the byte in the bit-band region that contains
the targeted bit
 bit_number is the bit position (0-7) of the targeted bit
Memory Organization
 Bit Banding Example
 Mapping bit 2 of the byte located at SRAM address 0x2000 0300 in
the alias region is done as follows:
0x2200 6008 = 0x2200 0000 + (0x300*32) + (2*4).
 Writing to address 0x2200 6008 has the same effect as a read-
modify-write operation on bit 2 of the byte at SRAM address 0x2000
0300
 Reading address 0x2200 6008 returns the value (0x01 or 0x00) of bit
2 of the byte at SRAM address 0x2000 0300 (0x01: bit set; 0x00: bit
cleared)
Memory Organization
 Embedded Flash memory organization
Boot Configuration
 Values on the BOOT pins are latched on the 4th rising edge of
SYSCLK after a reset
 It is up to the application to set the BOOT1 and BOOT0 pins after reset
to select the required boot mode.
 BOOT pins also resampled when exiting the Standby mode and hence
must be kept in the required boot mode in the Standby mode
 After this startup delay has elapsed, the CPU fetches the top-of-stack
value from address 0x0000 0000, then starts code execution from the
boot memory starting from 0x0000 0004.
General-Purpose I/Os (GPIOs)
 Each of the general-purpose I/O ports has:
 Two 32-bit configuration registers (GPIOx_CRL, GPIOx_CRH)
 Two 32-bit data registers (GPIOx_IDR, GPIOx_ODR)
 32-bit set/reset register (GPIOx_BSRR)
 16-bit reset register (GPIOx_BRR)
 32-bit locking register (GPIOx_LCKR)
 Each port bit of GPIOs can be individually configured by software
in several modes:
 Input floating
 Input pull-up
 Input-pull-down
 Analog
 Output open-drain
 Output push-pull
 Alternate function push-pull
 Alternate function open-drain
Basic Structure of GPIO Bit
GPIO Bit Configuration Table

See Table on
following page

 Note: During and just after reset, the alternate functions are not active
and the I/O ports are configured in Input Floating mode
(CNFx[1:0]=01b, MODEx[1:0]=00b)
GPIO Configuration: Output MODE Bits
GPIO Operation
 During and just after reset, the alternate functions are not
active and the I/O ports are configured in Input Floating mode
(CNFx[1:0]=01b, MODEx[1:0]=00b)
 When configured as output, the value written to the Output
Data register (GPIOx_ODR) is output on the I/O pin.
 It is possible to use the output driver in Push-Pull mode or Open-Drain
mode (only the N-MOS is activated when outputting 0).
 The Input Data register (GPIOx_IDR) captures the data present
on the I/O pin at every APB2 clock cycle
 All GPIO pins have an internal weak pull-up and weak pull-
down which can be activated or not when configured as input
GPIO Atomic Bit Set or Reset
 Atomic Read/Modify access
 No interruption in the middle to cause errors
 Atomic operations ensure that the desired change is not
interrupted resulting in partial set/reset of GPIOs
 There is no need for the software to disable interrupts when
programming the GPIOx_ODR at bit level: it is possible to
modify only one or several bits in a single atomic APB2 write
access
 This is achieved by programming to ‘1’ the Bit Set/Reset
Register (GPIOx_BSRR, or for reset only GPIOx_BRR) to select
the bits you want to modify.
 Unselected bits will not be modified
Input Configuration
 When the I/O Port is programmed as Input:
 The Output Buffer is disabled
 The Schmitt Trigger Input is activated
 The weak pull-up and pull-down resistors are activated or not
depending on input configuration (pull-up, pull-down or floating)
 The data present on the I/O pin is sampled into the Input Data Register
every APB2 clock cycle
 A read access to the Input Data Register obtains the I/O State
Input Configuration
Output Configuration
 When the I/O Port is programmed as Output:
 The Output Buffer is enabled:
 Open Drain Mode: A “0” in the Output register activates the N-MOS while a
“1” in the Output register leaves the port in Hi-Z. (the P-MOS is never
activated)
 Push-Pull Mode: A “0” in the Output register activates the N-MOS while a “1” in
the Output register activates the P-MOS
 The Schmitt Trigger Input is activated.
 The weak pull-up and pull-down resistors are disabled.
 The data present on the I/O pin is sampled into the Input Data Register
every APB2 clock cycle
 Read access to Input Data Register gets the I/O state in open drain mode
 Read access to Output Data register gets last written value in Push-Pull
mode
Output Configuration

Compare to input
configuration
Alternate Function Configuration
 When the I/O Port is programmed as Alternate Function:
 The Output Buffer is turned on in Open Drain or Push-Pull configuration
 The Output Buffer is driven by the signal coming from the peripheral
(alternate function out)
 The Schmitt Trigger Input is activated
 The weak pull-up and pull-down resistors are disabled
 The data present on the I/O pin is sampled into the Input Data Register
every APB2 clock cycle
 A read access to the Input Data Register gets the I/O state in open
drain mode
 A read access to the Output Data register gets the last written value in
Push-Pull mode
Alternate Function Configuration
Analog Configuration
 When the I/O Port is programmed as Analog configuration:
 The Output Buffer is disabled.
 The Schmitt Trigger Input is de-activated providing zero consumption for
every analog value of the I/O pin. The output of the Schmitt Trigger is
forced to a constant value (0).
 The weak pull-up and pull-down resistors are disabled.
 Read access to the Input Data Register gets the value “0”.
Analog Configuration
GPIO Registers
GPIO Registers
GPIO Registers
Assignments
 ARM Project #1 (To start this week)
STM32
MICROCONTROLLER

Lecture 3 Prof. Yasser Mostafa Kadah


Power Supplies
 Device requires a 2.0:3.6
V operating voltage
supply (VDD)
 Embedded regulator is
used to supply the
internal 1.8 V digital
power
 Real-time clock (RTC) and
backup registers can be
powered from VBAT
voltage when main VDD
supply is powered off
Battery Backup Domain
 To retain the content of the Backup registers and supply the
RTC function when VDD is turned off, VBAT pin can be
connected to an optional standby voltage supplied by a
battery or by another source
 The VBAT pin powers the RTC unit, the LSE oscillator and the PC13 to
PC15 IOs, allowing the RTC to operate even when the main digital
supply (VDD) is turned off
 The switch to the VBAT supply is controlled by the Power Down
Reset embedded in the Reset block
Voltage Regulator
 The voltage regulator is always enabled after Reset and works
in three different modes depending on the application modes:
 Run mode: the regulator supplies full power to the 1.8 V domain (core,
memories and digital peripherals)
 Stop mode: the regulator supplies low-power to the 1.8 V domain,
preserving contents of registers and SRAM
 Standby Mode: the regulator is powered off. The contents of the registers
and SRAM are lost except for the Standby circuitry and the Backup
Domain
Power Supply Supervisor
 Power on reset (POR)/power down reset (PDR)
 Integrated POR/PDR circuitry that allows proper operation starting
from/down to 2 V
 Device remains in Reset mode when VDD/VDDA is below a specified
threshold, VPOR/PDR, without the need for an external reset circuit
Power Supply Supervisor
 Programmable voltage detector (PVD)
 Monitors the VDD/VDDA power supply by comparing it to a threshold
selected by the PLS[2:0] bits in the Power control register (PWR_CR)
 PVD is enabled by setting the PVDE bit
 A PVDO flag is available, in Power control/status register (PWR_CSR),
to indicate if VDD/VDDA is higher or lower than the PVD threshold
 This event is internally connected to EXTI and can generate interrupt
Low-Power Modes
 By default, microcontroller is in Run mode after a Reset
 Low power modes are available to save power when the CPU need
not to be kept running (e.g., while waiting for an external event)
 It is up to the user to select the mode that gives the best compromise
between low-power consumption, short startup time and available
wakeup sources.
 The STM32F100xx devices feature three low-power modes:
 Sleep mode (CPU clock off, all peripherals including Cortex-M3 core
peripherals like NVIC, SysTick, etc. are kept running)
 Stop mode (all clocks are stopped)
 Standby mode (1.8V domain powered-off)
 In addition, power consumption in Run mode can be reduced by:
 Slowing down the system clocks
 Gating the clocks to the APB and AHB peripherals when they are unused.
Low-Power Modes
Backup Registers (BKP)
 Backup registers are ten 16-bit registers in low and medium density devices
for storing 20 bytes of user application data
 They are implemented in the backup domain that remains powered on by
VBAT when the VDD power is switched off.
 They are not reset when the device wakes up from Standby mode or by a system
reset or power reset
 In addition, the BKP control registers are used to manage the Tamper
detection feature and RTC calibration.
 After reset, access to the Backup registers and RTC is disabled and the
Backup domain (BKP) is protected against possible parasitic write access
 To enable access to the Backup registers and the RTC, proceed as follows:
 Enable the power and backup interface clocks by setting the PWREN and BKPEN bits
in the RCC_APB1ENR register
 Set the DBP bit the Power Control Register (PWR_CR) to enable access to the Backup
registers and RTC.
Reset
 There are three types of reset:
 System Reset
 Power Reset
 Backup domain reset
System Reset
 A system reset sets all registers to their reset values except the
reset flags in the clock controller CSR register and the registers
in the Backup domain
 A system reset is generated when one of the following events
occurs:
 Low level on the NRST pin (external reset)
 Window watchdog end of count condition (WWDG reset)
 Independent watchdog end of count condition (IWDG reset)
 Software reset (SW reset)
 Low-power management reset
System Reset
 Software reset
 The SYSRESETREQ bit in Cortex™-M3 Application Interrupt and Reset
Control Register must be set to force a software reset on the device
 Low-power management reset:
 Method1: Reset generated when entering Standby mode: This type of
reset is enabled by resetting nRST_STDBY bit in User Option Bytes. In
this case, whenever a Standby mode entry sequence is successfully
executed, the device is reset instead of entering Standby mode.
 Method 2: Reset when entering Stop mode: This type of reset is enabled
by resetting NRST_STOP bit in User Option Bytes. In this case, whenever
a Stop mode entry sequence is successfully executed, the device is reset
instead of entering Stop mode.
Power Reset
 A power reset is generated when one of the following occurs:
 Power-on/power-down reset (POR/PDR reset)
 When exiting Standby mode
 A power reset sets all registers to their reset values except the
Backup domain
 These sources act on the NRST pin and it is always kept low during the
delay phase. The
 RESET vector is fixed at address 0x00000004 in the memory map
Backup Domain Reset
 Backup domain has two specific resets that affect only the
backup domain
 backup domain reset is generated when one of the following
events occurs:
 Software reset, triggered by setting the BDRST bit in the Backup domain
control register (RCC_BDCR)
 VDD or VBAT power on, if both have previously been powered off
Clocks
 Three different clock sources can be used to drive the system clock
(SYSCLK):
 HSI oscillator clock
 HSE oscillator clock
 PLL clock
 The devices have the following two secondary clock sources:
 40 kHz low speed internal RC (LSI RC) which drives the independent
watchdog and optionally the RTC used for Auto-wakeup from Stop/Standby
mode
 32.768 kHz low speed external crystal (LSE crystal) which optionally drives
the real-time clock (RTCCLK)
 Each clock source can be switched on or off independently when it is
not used, to optimize power consumption
Clock Tree
HSE Clock
 The high speed external clock signal (HSE) can be generated
from two possible clock sources:
 HSE external crystal/ceramic resonator
 HSE user external clock
HSI Clock
 The High Speed Internal (HIS) clock signal is generated from an
internal 8 MHz RC Oscillator and can be used directly as a system
clock or divided by 2 to be used as PLL input
 The HSI RC oscillator has the advantage of providing a clock source
at low cost (no external components)
 It also has a faster startup time than the HSE crystal oscillator
however, even with calibration the frequency is less accurate than an
external crystal oscillator or ceramic resonator
 RC oscillator frequencies can vary from one chip to another due to
manufacturing process variations
 Each device is factory calibrated by ST for 1% accuracy at TA=25°C.
 After reset, the factory calibration value is loaded in the HSICAL[7:0] bits in
the Clock control register (RCC_CR)
 You can trim the HSI frequency in the application using the HSITRIM[4:0] bits
in the Clock control register (RCC_CR)
PLL
 The internal PLL can be used to multiply the HSI RC output or
HSE oscillator divided by 1:16 output clock frequency
 The PLL configuration (selection of HSI oscillator divided by 2
or HSE oscillator for PLL input clock, and multiplication factor)
must be done before enabling the PLL
 Once the PLL enabled, these parameters cannot be changed
 The PLL output frequency must be in the range of 16-24 MHz
Low Speed Clocks
 The LSE crystal is a 32.768 kHz Low Speed External crystal or
ceramic resonator
 It has the advantage providing a low-power but highly accurate clock
source to the real-time clock peripheral (RTC) for clock/calendar or
other timing functions
 The LSI RC acts as an low-power clock source that can be kept
running in Stop and Standby mode for the independent
watchdog (IWDG) and Auto-wakeup unit (AWU)
 The clock frequency is around 40 kHz.
System Clock (SYSCLK) Selection
 After a system reset, the HSI oscillator is selected as system
clock
 When a clock source is used directly or through the PLL as
system clock, it is not possible to stop it
 A switch from one clock source to another occurs only if the
target clock source is ready (clock stable after startup delay
or PLL locked)
 If a clock source which is not yet ready is selected, the switch will occur
when the clock source will be ready
 Status bits in the Clock control register (RCC_CR) indicate which clock(s)
is (are) ready and which clock is currently used as system clock
Clock Security System
 Clock Security System can be activated by software. In this
case, the clock detector is enabled after the HSE oscillator
startup delay, and disabled when this oscillator is stopped.
 If a failure is detected on the HSE clock, the HSE oscillator is
automatically disabled, a clock failure event is sent to the
break input of the advanced-control timers (TIM1) and an
interrupt is generated to inform the software about the failure
(Clock Security System Interrupt CSSI), allowing the MCU to
perform rescue operations.
RTC and Watchdog Clocks
 The RTCCLK clock source can be either the HSE/128, LSE or LSI
clocks. This is selected by programming the RTCSEL[1:0] bits in
the Backup domain control register (RCC_BDCR)
 This selection cannot be modified without resetting the Backup
domain.
 If the Independent watchdog (IWDG) is started by either
hardware option or software access, the LSI oscillator is forced
ON and cannot be disabled
 After the LSI oscillator temporization, the clock is provided to the IWDG
Clock-Out Capability
 The microcontroller clock output (MCO) capability allows the
clock to be output onto the external MCO pin.
 The configuration registers of the corresponding GPIO port must be
programmed in alternate function mode
 One of 4 clock signals can be selected as the MCO clock:
 SYSCLK
 HSI
 HSE
 PLL clock divided by 2
 The selection is controlled by the MCO[2:0] bits of the Clock
configuration register (RCC_CFGR)
Assignments
 ARM Project #2
STM32
MICROCONTROLLER

Lecture 4 Prof. Yasser Mostafa Kadah


Nested Vectored Interrupt Controller

 The NVIC supports up to 56 maskable interrupt channels with


16 programmable priority levels
 Not including the sixteen Cortex™-M3 interrupt lines
 NVIC and the processor core interface are closely coupled,
which enables low latency interrupt processing and efficient
processing of late arriving interrupts.
 The NVIC maintains knowledge of the stacked (nested)
interrupts to enable tail-chaining of interrupts.
SysTick Calibration Value Register
 The SysTick calibration value is set to 9000, which gives a
reference time base of 3 ms with the SysTick clock set to 3
MHz (max HCLK/8)
Interrupt and Exception Vectors
Interrupt and Exception Vectors
External Interrupt/Event Controller (EXTI)

 Consists of up to 18 edge detectors for generating requests


 Each input line can be independently configured
 Select the type (pulse or pending)
 Select corresponding trigger event (rising or falling or both)
 Each line can also be masked independently
 Pending register maintains the status line of interrupt requests
 EXTI controller main features are the following:
 Independent trigger and mask on each interrupt/event line
 Dedicated status bit for each interrupt line
 Generation of up to 18 software event/interrupt requests
External Interrupt/Event Controller (EXTI)
NVIC Functional Description
 To generate the interrupt, the interrupt line should be
configured and enabled.
 This is done by programming the two trigger registers with the
desired edge detection and by enabling the interrupt request
by writing a ‘1’ to the corresponding bit in the interrupt mask
register.
 When the selected edge occurs on the external interrupt line,
an interrupt request is generated.
 The pending bit corresponding to the interrupt line is also set.
This request is reset by writing a ‘1’ in the pending register.
NVIC Functional Description
 To generate the event, the event line should be configured and
enabled
 This is done by programming the two trigger registers with the
desired edge detection and by enabling the event request by
writing a ‘1’ to the corresponding bit in the event mask register
 When the selected edge occurs on the event line, an event
pulse is generated and the pending bit corresponding to the
event line is not set
 An interrupt/event request can also be generated by software
by writing a ‘1’ in the software interrupt/event register
Hardware Interrupt/Event Selection
 To configure the 18 lines as interrupt sources, use the following
procedure:
 Configure the mask bits of the 18 Interrupt lines (EXTI_IMR)
 Configure the Trigger Selection bits of the Interrupt lines (EXTI_RTSR and
EXTI_FTSR)
 Configure the enable and mask bits that control the NVIC IRQ channel
mapped to the External Interrupt Controller (EXTI) so that an interrupt
coming from one of the 18 lines can be correctly acknowledged
 To configure the 18 lines as event sources, use the following
procedure:
 Configure the mask bits of the 18 Event lines (EXTI_EMR)
 Configure the Trigger Selection bits of the Event lines (EXTI_RTSR and
EXTI_FTSR)
Software Interrupt/Event Selection
 The 18 lines can be configured as software interrupt lines as
follows:
 Configure the mask bits of the 18 Interrupt/Event lines (EXTI_IMR,
EXTI_EMR)
 Set the required bit of the software interrupt register (EXTI_SWIER)
External Interrupt/Event GPIO Mapping

 The two other EXTI lines are connected as follows:


 EXTI line 16 is connected to the PVD output
 EXTI line 17 is connected to the RTC Alarm event
Interrupt Mask Register (EXTI_IMR)
Event Mask Register (EXTI_EMR)
Rising trigger selection register
(EXTI_RTSR)
Falling trigger selection register
(EXTI_FTSR)
Software Interrupt Event Register
(EXTI_SWIER)
Pending Register (EXTI_PR)
SysTick Control and Status Register
SysTick Reload Value Register
SysTick Current Value Register
SysTick Calibration Value Register
Assignments
 ARM Project #3
STM32 MICROCONTROLLER:
GENERAL-PURPOSE TIMERS
(TIM2-TIM5)

Lecture 5 Prof. Yasser Mostafa Kadah


TIM2-TIM5 Introduction
 The general-purpose timers consist of a 16-bit auto-reload
counter driven by a programmable prescaler.
 Measuring the pulse lengths of input signals (input capture)
 Generating output waveforms (output compare, PWM)
 Pulse lengths and waveform periods can be modulated from a
few microseconds to several milliseconds using the timer
prescaler and the RCC clock controller prescalers
 General-purpose (TIMx) timers are completely independent,
and do not share any resources
 They can still be synchronized together
TIM2-TIM5 Main Features
 16-bit up, down, up/down auto-reload counter
 16-bit programmable prescaler allowing dividing (also “on the fly”)
the counter clock frequency either by any factor between 1 and
65535.
 Up to 4 independent channels for:
 Input Capture
 Output Compare
 PWM generation (Edge and Center-aligned Mode)
 One-pulse mode output
 Synchronization circuit to control timer with external signals and to
interconnect several timers together
 Interrupt/DMA generation based on several events
TIM2-TIM5 Block Diagram
Time-Base Unit
 The main block of the programmable timer is a 16-bit counter
with its related auto-reload register
 The counter can count up, down or both up and down
 The counter clock can be divided by a prescaler.
 The counter, the auto-reload register and the prescaler
register can be written or read by software
 This is true even when the counter is running
 The time-base unit includes:
 Counter register (TIMx_CNT)
 Prescaler register (TIMx_PSC)
 Auto-reload register (TIMx_ARR)
Time-Base Unit
 Auto-reload register is preloaded
 Writing to or reading from the auto-reload register accesses the
preload register
 Contents of preload register are transferred into the shadow
register permanently or at each update event (UEV), depending on
the auto-reload preload enable bit (ARPE) in TIMx_CR1 register
 Update event is sent when counter reaches overflow or underflow
and if the UDIS bit equals 0 in TIMx_CR1 register
 Update event can also be generated by software
 Counter is clocked by prescaler output CK_CNT, which is enabled
only when counter enable bit (CEN) in TIMx_CR1 register is set
 actual counter enable signal CNT_EN is set 1 clock cycle after CEN
Prescaler
 Prescaler can divide the counter clock frequency by any factor
between 1 and 65536
 Based on a 16-bit counter controlled through a 16-bit register
(in the TIMx_PSC register)
 It can be changed on the fly as this control register is buffered
 New prescaler ratio is taken into account at the next update event
Prescaler
 Counter timing diagram with prescaler division change from 1 to 2
Prescaler
 Counter timing diagram with prescaler division change from 1 to 4
Counter Modes: Upcounting Mode
 Counter counts from 0 to the auto-reload value (content of the
TIMx_ARR register), then restarts from 0 and generates a
counter overflow event
 An Update event can be generated at each counter overflow
or by setting the UG bit in the TIMx_EGR register
 When an update event occurs, all the registers are updated
and the update flag (UIF bit in TIMx_SR register) is set
(depending on the URS bit):
 The buffer of the prescaler is reloaded with the preload value (content
of the TIMx_PSC register)
 The auto-reload shadow register is updated with the preload value
(TIMx_ARR)
Upcounting Mode Example
 TIMx_ARR=0x36 , internal clock divided by 1
Upcounting Mode Example
 TIMx_ARR=0x36 , internal clock divided by 2
Upcounting Mode Example
 TIMx_ARR=0x36 , internal clock divided by 4
Upcounting Mode Example
 TIMx_ARR=0x36 , Update event when ARPE=0 (TIMx_ARR not preloaded)
Upcounting Mode Example
 TIMx_ARR=0x36 , Update event when ARPE=1 (TIMx_ARR preloaded)
Counter Modes: Downcounting Mode
 Counter counts from the auto-reload value (content of the
 TIMx_ARR register) down to 0, then restarts from the auto-
reload value and generates a counter underflow event
 An Update event can be generate at each counter underflow
or by setting the UG bit in the TIMx_EGR register
 When an update event occurs, all the registers are updated
and the update flag (UIF bit in TIMx_SR register) is set
(depending on the URS bit):
 The buffer of the prescaler is reloaded with the preload value (content
of the TIMx_PSC register)
 The auto-reload shadow register is updated with the preload value
(TIMx_ARR)
Downcounting Mode Example
 TIMx_ARR=0x36 , internal clock divided by 1
Downcounting Mode Example
 TIMx_ARR=0x36 , internal clock divided by 2
Downcounting Mode Example
 TIMx_ARR=0x36 , internal clock divided by 4
Counter Modes: Center-Aligned Mode
(Up/Down Counting)
 Counter counts from 0 to the auto-reload value (content of the
TIMx_ARR register) – 1, generates a counter overflow event, then
counts from the autoreload value down to 1 and generates a counter
underflow event. Then it restarts counting from 0
 Center-aligned mode is active when CMS bits in TIMx_CR1 register
are not equal to '00'. The Output compare interrupt flag of channels
configured in output is set when: the counter counts down (Center
aligned mode 1, CMS = "01"), the counter counts up (Center aligned
mode 2, CMS = "10") the counter counts up and down (Center
aligned mode 3, CMS = "11")
 In this mode, the direction bit (DIR from TIMx_CR1 register) cannot
be written
 Updated by hardware and gives the current direction of the counter
Up/Down Counting Example
 Internal clock divided by 1, TIMx_ARR=0x6
Up/Down Counting Example
 Internal clock divided by 2, TIMx_ARR=0x6
Up/Down Counting Example
 Counter timing diagram, Update event with ARPE=1 (counter underflow)
Up/Down Counting Example
 Counter timing diagram, Update event with ARPE=1 (counter overflow)
Clock Selection
 The counter clock can be provided by the following clock
sources:
 Internal clock (CK_INT) (Our focus in this part)
 External clock mode1: external input pin (TIx)
 External clock mode2: external trigger input (ETR)
 Internal trigger inputs (ITRx): using one timer as prescaler for another
timer, for example, you can configure Timer 1 to act as a prescaler for
Timer 2
Internal Clock Source (CK_INT)
 If the slave mode controller is disabled (SMS=000 in the TIMx_SMCR
register), then the CEN, DIR (in the TIMx_CR1 register) and UG bits (in the
TIMx_EGR register) are actual control bits and can be changed only by
software (except UG which remains cleared automatically)
 As soon as the CEN bit is written to 1, the prescaler is clocked by the
internal clock CK_INT.
TIMx Control Register 1 (TIMx_CR1)
TIMx Slave Mode Control Register
(TIMx_SMCR)
TIMx Event Generation Register
(TIMx_EGR)
TIMx Counter (TIMx_CNT)
TIMx Prescaler (TIMx_PSC)
TIMx Auto-Reload Register (TIMx_ARR)
TIMx DMA/Interrupt Enable Register
(TIMx_DIER)
TIMx Status Register (TIMx_SR)
Vector Table for STM32F100xx Devices
Timer Standard Driver
 Standard interface to all STM32 timers

 TIM_CounterModeConfig
 TIM_SetCounter
 TIM_SetAutoreload
 TIM_PrescalerConfig
 TIM_ITConfig
 TIM_Cmd
 TIM_ClearITPendingBit

Note: Modify only files in the “User” group of your project and never change the
standard peripheral drivers since they will affect other programs not just the one you
are working on at the time. Modification of such files will result in deducting points off
your project grade.
Assignments
 ARM Project #4
STM32 MICROCONTROLLER:
DIGITAL-TO-ANALOG
CONVERTER (DAC)

Lecture 6 Prof. Yasser Mostafa Kadah


DAC Introduction
 DAC module is a 12-bit, voltage output digital-to-analog
converter
 DAC can be configured in 8- or 12-bit mode and may be used
in conjunction with the DMA controller
 In 12-bit mode, the data could be left- or right-aligned
 DAC has two output channels, each with its own converter
 In dual DAC channel mode, conversions could be done independently or
simultaneously when both channels are grouped together for
synchronous update operations
 Input reference pin, VREF+ (shared with ADC) is available for
better resolution
DAC Main Features
 Two DAC converters: one output channel each
 Left or right data alignment in 12-bit mode
 Synchronized update capability
 Noise-wave generation
 Triangular-wave generation
 Dual DAC channel for independent or simultaneous conversions
 DMA capability for each channel
 DMA underrun error detection
 External triggers for conversion
 Input voltage reference, VREF+
DAC Channel Block Diagram
DAC Pins
 Once the DAC channelx is enabled, the corresponding GPIO
pin (PA4 or PA5) is automatically connected to the analog
converter output (DAC_OUTx)
 In order to avoid parasitic consumption, the PA4 or PA5 pin
should first be configured to analog (AIN)
DAC Functional Description
 DAC channel enable
 Setting its corresponding ENx bit in the DAC_CR register
 DAC channel is then enabled after a startup time tWAKEUP
 DAC output buffer enable
 DAC integrates two output buffers to reduce output impedance, and to
drive external loads directly without having to add an external op amp
 Enabled using the corresponding BOFFx bit in the DAC_CR register
DAC Functional Description
 DAC data format
 Single DAC channelx

 Dual DAC channels


DAC Functional Description
 DAC output voltage

 DAC trigger selection


 Rising edge for HW triggers: conversion after three APB1 clock cycles
 If the software trigger is selected, the conversion starts once the SWTRIG
bit is set. SWTRIG is reset by hardware once the DAC_DORx register
has been loaded with the DAC_DHRx register contents
DAC Conversion
 DAC_DORx cannot be written directly and any data transfer to the
DAC channelx must be performed by loading the DAC_DHRx
register
 Data stored in the DAC_DHRx register are automatically transferred
to the DAC_DORx register after one APB1 clock cycle, if no
hardware trigger is selected (TENx bit in DAC_CR register is reset)
 When hardware trigger is selected (TENx bit in DAC_CR register is
set) and a trigger occurs, transfer is performed three APB1 clock
cycles later
 When DAC_DORx is loaded with the DAC_DHRx contents, the
analog output voltage becomes available after a time tSETTLING that
depends on power supply voltage and analog output load
DAC Conversion
 Timing diagram for conversion with trigger disabled TEN = 0
Noise Generation
 In order to generate a variable-amplitude pseudonoise, an
LFSR (linear feedback shift register) is available
 Noise generation is selected by setting WAVEx[1:0] to “01”
 The preloaded value in LFSR is 0xAAA and is updated after
each trigger event, following a specific calculation algorithm
Triangle-Wave Generation
 It is possible to add a small-amplitude triangular waveform on
a DC or slowly varying signal.
 DAC triangle-wave generation is selected by setting
WAVEx[1:0] to “10”
 Amplitude is configured through MAMPx[3:0] bits in DAC_CR register
 It is possible to reset triangle wave generation by resetting the
WAVEx[1:0] bits
Triangle-Wave Generation
 DAC conversion (SW trigger enabled) with triangle wave generation
 DAC trigger must be enabled by setting the TENx bit in DAC_CR register
 The MAMPx[3:0] bits must be configured before enabling the DAC, otherwise they cannot
be changed
DAC Control Register (DAC_CR)
DAC Software Trigger Register
(DAC_SWTRIGR)
DAC Channel 1 Data Registers
 DAC channel1 12-bit right-aligned data holding register (DAC_DHR12R1)

 DAC channel1 12-bit left aligned data holding register (DAC_DHR12L1)

 DAC channel1 8-bit right aligned data holding register (DAC_DHR8R1)


DAC Channel1 Data Output Register
(DAC_DOR1)
TIMx Control Register 2 (TIMx_CR2)
Assignments
 ARM Project #5

You might also like