0% found this document useful (0 votes)
20 views70 pages

Stm32g0 WDG Timers General Purpose Timer Gptim

Uploaded by

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

Stm32g0 WDG Timers General Purpose Timer Gptim

Uploaded by

abdularrehman139
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Hello, and welcome to this presentation on the

advanced-control, general-purpose and basic timers


embedded in STM32 microcontrollers. It covers their
main features which are useful for handling any timing-
related events, generating waveforms and measuring the
timing characteristics of input signals.

1
The STM32 embeds multiple timers providing timing
resources for software or hardware tasks. The software
tasks mainly consist of providing time bases, timeout
event generation and time-triggers. The hardware tasks
are related to I/Os: the timers can generate waveforms
on their outputs, measure incoming signal parameters
and react to external events on their inputs.
The STM32 timers are very versatile and provide
multiple operating modes to off-load the CPU from
repetitive and time-critical tasks, while minimizing
interfacing circuitry needs. All STM32 timers (with the
sole exception of the low-power timer) are based on the
same scalable architecture. Once the timer operating
principles are known, they are valid for any of the timers.
This architecture includes interconnection features and
allows several timers to be combined into larger
configurations. Lastly, some of the timers feature specific

2
functions for electrical motor control and digital power
conversion such as lighting or digital switched mode
power supplies.

2
Here are the key features of the STM32 timers. All timers
are based on the same architecture and are available in
several derivatives listed later in this presentation. The
timers mainly differ in the number of inputs and outputs
they have, from a pure time base without any I/Os to an
advanced control version with 10 I/Os. Most of the timers
feature 16-bit counters, while some have 32-bit counters.
Some features may not be present on the smallest timer
derivatives (for example, DMA, synchronization, and
up/down counting modes).
Most of the timers can be linked and synchronized to
build larger time-base timers, have a higher number of
synchronous waveforms, or handle complex timings and
waveforms.
Within a timer, each and every channel can be
configured independently as an input (typically for
capture) or as an output (typically for a PWM).

3
The timers can serve as a trigger for other peripherals, for
instance to start ADC conversions, or to monitor the
internal clocks, thanks to the interconnect matrix.

3
This slide presents the block diagram of the medium-
featured TIM15 timer.
The timer kernel consists of a 16-bit up-counter, coupled
with an auto-reload register to program the counting
period. The 2 timer channels are controlled by 2 capture-
compare registers.
The counter is fed by the Clock and Trigger controller,
also responsible for the timer chaining.
Internal trigger in and out are connected to the
Interconnect matrix, refer to the related presentation. For
instance, the STM32G0 Timer15 can trigger the ADC
and DAC and can control the Timers 1 to 3 slave
interface.
Shown on the left are the input stage and the input
conditioning circuitry while on the right we have the
output stage.
Note that TIMxCH1 and TIMxCH2 appear on both sides

4
to indicate they are both input and output capable.
The Timer 15 supports a break input that can be used to
automatically set the channel outputs in a predefined
state whenever a break event occurs.
The Timer 15 also supports a Dead Time Generator unit
(DTG) that inserts a dead time on PWM complementary
outputs.
Each part of this block diagram is described in the next
slides.

4
Timer 15 features multiple clocking options.
The Clock and Trigger controller, also responsible for
timer chaining, handles the clock for the counter.
The default clock comes from the Reset and Clock
Controller.
The timer clock TIMPCLK is derived from PCLK (used for
APB) as follows:
• If the APB prescaler is set to 1, the TIMPCLK
frequency is equal to the PCLK frequency
• Otherwise, the TIMPCLK frequency is set to twice the
PCLK frequency.
For Timers 1 and 15, the PLLQCLK clock can also be
selected. Its frequency must be set so as not to exceed
128 MHz.
External timer clocking makes it possible to count
external events or to have a counting period externally
adjusted.

5
The clock source can be provided by other on-chip
timers, using one of the 4 internal trigger inputs (ITR0 to
ITR3).
Input pins 1 and 2 can also serve as external clocks, with
the option of including digital filters to remove spurious
events.
The external trigger input (ETR) can be configured as an
external clock, with a digital filter, programmable edge
sensitivity and a first basic prescaler stage to reduce the
frequency of incoming signals if needed.
The TI1F_ED Edge Detector input can also be used as
the timer clock. A pulse is generated on both rising and
falling edges of the TI1F signal. Although it was not
intended for this, it can serve as a frequency doubler with
an external clock (count twice per incoming clock period).
Lastly, the quadrature signals from an encoder can be
processed to provide a clock and a counting direction, as
described later in this presentation.

5
Timers 1 and 15 are clocked by PLLQCLK, which can
have a frequency higher than 100 MHz.
It ensures fine resolution for Buck converters and lower
frequency steps for variable frequency resonant
converters, such as an LLC.
Timer 1 has 3 complementary pairs, which is appropriate
to support primary and secondary sides in LLC as well
as boundary conduction mode in Power Factor
Correction and Buck converters.
Timer 15 has a unique complementary pair, which can be
used in Buck power supplies and LLC primary-side
converters.

6
This slide explains how to adjust the timer counting
period.
Each timer embeds a linear clock prescaler which allows
you to divide the clock by any integer between 1 and
65536. This allows the counting pace to be precisely
adjusted. For instance, a division by 64 will yield a
precise 1 MHz counting rate when the APB clock is
64 MHz.
The auto-reload register defines the counting period. In
Down-counting mode, the counter is automatically
reloaded with the period value when it underflows. In Up-
counting mode, the counter rolls over and is reset when
it exceeds the auto-reload value.
An update event is issued when the counter underflows
or overflows and a new period starts. It triggers an
interrupt or DMA request that is used for adjusting timer
parameters synchronously with its period, which is useful

7
for real-time control. This update event triggers the
transfer from preload to active registers for multiple
parameters, and in particular for the clock prescaler, auto-
reload value, compare registers and PWM mode.
A 16-bit programmable repetition counter allows you to
decouple the interrupt issuing rate from the counting
period, and have, for instance, one interrupt every single,
2nd, 3rd and up to 256th PWM period. This is particularly
useful when dealing with high PWM frequencies.
Regarding the STM32G0 microcontroller, the repetition
counter is only implemented in Timer1, Timer15, 16 and
17.

7
Some of the STM32 timers feature up/down counting
modes: the advanced control timers 1 and the general-
purpose timers 2 and 3
The counting direction can be programmed by software
or automatically managed by the timer in center-aligned
PWM mode. In this mode, the counting direction
changes automatically on counter overflow and
underflow. For a given PWM switching frequency, this
mode reduces the acoustic noise by doubling the
effective current ripple frequency, thus providing the
optimum tradeoff between the power stage’s switching
losses and noise.
The counting direction can also be automatically handled
when the timer is in Encoder mode. Quadrature
encoders are typically used for high-accuracy rotor
position sensing in electrical motors, or for digital
potentiometers. From the two outputs of a quadrature

8
encoder sensor (also called an incremental encoder), the
timer extracts a clock on each and every active edge and
adjusts the counting direction depending on the relative
phase-shift between the two incomings signals. The timer
counter thus directly holds the angular position of the
motor or the potentiometer.

8
The simplest use case for a timer is to provide an
internal time base.
This is commonly used by software routines, either to
provide periodic interrupts or single-shot timeout
protection. The timer can also provide periodic triggers to
other on-chip peripherals, such as the ADC, DAC and
other timers through the interconnect matrix.
The update event from the timer (typically on counter
overflow) is the usual means to have a software time
base interrupt or to trigger a periodic event. The basic
timers TIM6 and TIM7 are best suited for such a task, as
they are the simplest timer derivatives with no
input/output channel.
It is also possible to generate internal timings using any
other timer, using compare events or using the trigger
outputs on any other timer. It is possible to generate
multiple timing events with a single timer using multiple

9
compare channels.

9
This slide describes the input capture features.
Each channel can be individually configured as input
capture with a number of signal conditioning options. An
input can be mapped on two capture channels (typically
to differentiate rising-edge from falling-edge capture).
The edge sensitivity is programmable and can be rising
edge, falling edge or both edges. An event prescaler
allows capture of one event every 2, 4 or 8 events. This
decreases the CPU burden when processing high
frequency signals and allows the measurement to be
more accurate, since it is performed over multiple input
signal periods.
Spurious transition events due to noise or bounces can
be removed using a programmable digital filter. The
figure shows how a signal is filtered when the filter
acceptance is set to 4.
In the upper case, a clean rising edge capture is

10
triggered 4 sampling periods after the rising edge, as one
can notice looking at the internal counter value.
In the lower case, a glitch causes the filter counter to be
reset and the capture to happen after 4 successive
samples at high level have been counted.
Once the capture trigger is issued, the timer’s counter is
transferred into the capture register and an interrupt or a
DMA request can be issued. If a new capture occurs
before the previous one has been read, the capture
register is over-written and an overcapture flag is set for
the software to manage this condition if needed.

10
This slide presents some of the more advanced capture-
related functions.
The Clear-on-capture mode causes a counter reset
immediately after the capture has been triggered. This
allows a direct measurement of the period, while a
traditional free-running counter would require additional
computation to obtain the period following the trigger.
In PWM input mode, the timer is able to capture both the
period and the duty cycle of an incoming PWM signal.
The input signal is internally routed to 2 capture
channels. The signal’s rising edge is captured on input
capture 2 to provide the period value with the Clear-on-
capture mode. The falling edge is captured by the
capture 1 channel, which provides the pulse length
duration. The duty cycle then simply corresponds to the
ratio between input capture 1 and input capture 2.
Lastly, the timer includes an XOR function to combine

11
the three input channels with XOR logic. This is typically
used to handle the three 120° phase-shifted signals
coming from the Hall sensors in electrical motors. This
allows you to have a clear on capture happening on each
and every edge of the three signals and have a capture
value directly usable for speed regulation.

11
This slide presents the output compare features.
A compare event is generated when the counter matches
the value of the compare register. This event can trigger
an interrupt or a DMA request and can be reflected on
the corresponding output pin by an output set, output
reset or output toggle.
The compare register can be preloaded. The preload
must be disabled if multiple compare values must be
written during a counting period. In the timing diagram,
preload is disabled.
On the contrary, the use of preload mode must be
preferred for applications with real-time constraints, since
this gives a higher time margin for the software to update
the compare register with the next value. The transfer
from the preload to the active value is triggered by an
update event, when the counter overflows or underflows.
The output compare mode can also be preloaded, so as

12
to allow glitch-less transition from a PWM mode to a
forced On or Off state, for instance.

12
One-pulse mode is used to generate a pulse of a
programmable length in response to an external event.
The pulse can start as soon as the input trigger arrives or
after a programmable delay. The compare 1 register
(CCR1) value defines the pulse start time, while the
auto-reload register (ARR) value defines the end of
pulse. The effective pulse width is then defined as the
difference between the ARR and CCR1 register values.
See the upper timing diagram.
The waveform can be programmed to have a single
pulse generated by the trigger, or to have a continuous
pulse train started by a single trigger.
One-pulse mode also offers a retriggerable option. The
timing diagram at the bottom of this slide describes this
option.
A new trigger arriving before the end of the pulse will
cause the counter to be reset and the pulse width to be

13
extended accordingly.
Note that only timers 1, 2, 3, 15 support the retriggerable
one-pulse mode on the STM32G0 microcontroller.

13
This slide presents some of the PWM modes.
The standard edge-aligned PWM mode is programmed
with the auto-reload register defining the period and the
compare register defining the duty cycle, the counter
being in up-only or down-only counting mode. A single
timer can generate up to 6 PWM signals with
independent duty cycles and identical frequency.
When multiple PWM waveforms are generated by the
same timer, all falling edges occur at the same time,
hence the term edge-aligned.
On the contrary, the rising and falling edges of center-
aligned PWMs are not synchronized with the counter roll-
over, so that switching time varies with the duty cycle
value. This is achieved by programming the counter in
up-down mode. This mode is interesting as it spreads
the switching noise when multiple PWMs are generated
with the same timer.

14
This is a key feature for three-phase PWM generation for
electric motor drives, since it allows you to double the
frequency of the current ripple for a given switching
frequency. For instance, a 10 kHz PWM will generate
inaudible 20 kHz current ripple. This minimizes the
switching losses due to the PWM frequency while
guaranteeing silent PWM operation.
A variant of the center-aligned mode is the asymmetric
PWM mode, where two compare registers define the
turning on and off of the PWM signal. This provides
higher resolution for pulse width setting, since turn-on
and turn-off times are individually defined. It also allows
the generation of phase-shifted PWM signals, necessary
to drive DC/DC converters based on the full-bridge
phase-shifted topology.
In this case, the timer provides two PWM signals with
identical frequency, 50% duty cycle, and a phase-shift
varying from 0 to 180°.

14
This slide presents the combined PWM modes.
This mode allows a logic combination of two PWM
signals to be generated by adjacent channels (output
compare 1 and 2 or output compare 3 and 4).
The PWMs can be ORed or ANDed to create complex
waveforms. Typically, this allows you to have two
periodic pulses generated with any pulse width and any
phase relationship value.
The combined 3-phase mode specifically targets 3-
phase motor control applications. In this case, channel 5
of the timer can be combined with any of the three
channels (1, 2 and 3) to insert a low state in the middle
of a centered-pattern PWM signal. This mode greatly
simplifies the implementation of low-cost current sensing
techniques for 3-phase motor control, using a technique
usually referred to as zero vector insertion.

15
This slide presents some more specific PWM modes,
where either the frequency or the duty cycle can be
driven by external signals.
The timer can provide variable frequency signals, using
an external reset signal connected either on the ETR, or
on the channel 1 or 2 inputs. The purpose of this mode is
to provide a signal with a fixed On or Off time and a
continuously adjusted frequency controlled by the
hardware. The timer provides control for the On (or Off)
time, using the compare register, while the auto-reload
register guarantees that the PWM will not stop if the
external reset is missing, thus providing a safe control in
boundary conditions. This technique is used for a variety
of purposes, such as transition mode PFC (Power Factor
Controller) for mains-supplied applications and current-
controlled digital LED lighting.
Another mode for the timer is to have the duty cycle

16
controlled by hardware, with either an on-chip comparator
or an off-chip signal. The PWM operates at a fixed
frequency, the maximum duty cycle is set by the compare
register and the actual value controlled cycle-by-cycle.
This is used for applications requiring current-controlled
PWMs, typically for driving DC motors or solenoids. In
this case, a comparator monitors the peak current value
into the load. As soon as the current exceeds a
programmed threshold, the comparator resets the PWM
output, which is then automatically re-started at the next
PWM period, thus providing a controlled peak current
value.

16
This slide presents the timer’s synchronization features.
The trigger controller can cascade multiple timers in a
master/slave configuration. A timer can control one or
more timers as the master timer, or be controlled by
another timer as a slave. The Clock and Trigger
controller acts as a link between the timers. In Master
mode, it can redirect outside the timer, multiple internal
control signals, to an on-chip TRGO trigger output. In
Slave mode, it gathers multiple inputs on the TRGI (the
main trigger input) coming from the external trigger pin
(ETR) or from one of the four internal trigger inputs (ITR1
to ITR4), connected to the other TRGO outputs.
Additionally, the input capture 1 and 2 pins can also be
used as an internal trigger (typically to reset the counter).
Slave and Master modes can be programmed
independently. A given timer can thus simultaneously be
operating in Slave and Master modes in a cascaded

17
configuration, accepting input triggers while providing
output triggers.
Master synchronization and slave synchronization are
independently instantiated in the timer units. See the
table at the end of this presentation, summarizing the
capabilities of all STM32G0 timers.

17
This slide lists the various operating modes and the
signals exchanged between timers.
In Master mode, 16 options are given for selecting the
trigger to be sent on the TRGO output. The output can
be a single synchronization pulse issued upon counter
reset, counter enable which corresponds to the counter
start, the update event or the compare 1 match event.
Alternatively, the TRGO output can also transmit one of 6
waveforms generated, including PWM signals, to the
other timer modules (Compare on channel 1 to 6 and
compare pulses on all channels).
In Slave mode, the timer operating mode is controlled by
the TRGI input. In Triggered mode, the counter start is
externally controlled. This mode is used for
simultaneously starting multiple timers. In Reset mode,
the counter is reset by a rising edge on the TRGI input,
typically for variable frequency PWM operation. A

18
Combined mode including reset and trigger can be used
for re-triggerable one-pulse mode generation. In Gated
mode, shown in the figure, the counter is active only while
the level on the input signal is high. This signal either
comes from an input or from the Interconnect Matrix. In
this case, synchronization pulses issued on reset, enable,
update or compare match cannot be used.
Lastly, the slave mode selection includes clock-related
modes, such as quadrature encoder decoding or external
clocking modes mentioned earlier in this presentation.

18
This slide gives two examples of synchronized operation.
The first example shows how four timers can be
simultaneously started. A mechanism allows the master
timer to start slightly delayed to compensate for the
master/slave link delay, and have all timers synchronized
with cycle accuracy. By combining the channels of
Timers 2, 1, 3 and 15 as shown, it is possible to have up
to 16 synchronized PWM channels.
The second example shows how to create a 48-bit timer
by cascading three timers. Here the update event
generated on counter roll-over is used as the input clock
for the following slave timer, so that Timer 3’s counter
holds the least significant 16-bits, Timer 15’s counter
holds the medium bits (bits 16 to 31) and Timer 1’s
counter holds the upper bits from bit 32 to bit 47.

19
This slide summarizes the timer’s 4 main electrical motor
control features:
The timer includes specific PWM modes for controlling
power switches. In addition to center-aligned and
combined 3-phase PWMs previously described, the
timer features dead time insertion for complementary
PWM generation and 6-step mode for driving brushless
DC motors.
It includes power stage protection circuitry with a dual-
level emergency stop mechanism to disable the PWM
outputs by hardware in case of a fault.
It is able to handle the most common sensors found in
motor control systems. Quadrature encoders and Hall
sensors are used for fine and coarse position
feedback, while tachometer generators are used for
cost-effective speed feedback and just require a Clear-
on-capture mode.

20
Lastly, the timer includes synchronized ADC triggering
options, necessary to properly manage voltage and
current sensing and avoid any acquisition issues due to
switching noise in power stages.

20
This slide presents the dead time insertion function.
A hardware dead time generator provides two non-
overlapping complementary PWMs from a reference
PWM signal. The STM32 timers includes up to three
dead time generators for OC1, OC2 and OC3 channels.
The dead time duration is programmed with an 8-bit
value. This value can be locked by the user to prevent
this critical value from being corrupted during run-time.
This is done by setting a write-once lock bit which
switches the dead time register into read-only mode until
the next MCU reset.
Dead time insertion is necessary when driving half-
bridges, where a pair of transistors are connected in
series between two power rails. In this case, it is
necessary to insert some time before the switch on of
one side to allow the other side to switch off, taking into
account physical switching characteristics.

21
Half-bridges are usually found in DC/DC converters, for
DC or stepper motor drive, using the full-bridge topology
shown here or for 3-phase inverters, with three PWM
pairs.

21
This slide shows how the 6-step drive (also called block
commutation) is managed with the STM32 timer.
It consists of chaining two timers, one handling the three
Hall sensor signals while the other manages the PWM
generation synchronized with the rotor angular position,
generating six successive steps.
The first timer operates in clear-on-capture mode,
triggered by the three inputs. A compare register (here
compare 2), is responsible for adding a programmable
delay between the raw angular position and the
commutation time. The capture register 1 holds the
timing interval between successive Hall sensor edges
and is necessary for the speed regulation loop.
The compare 2 match event is propagated to the slave
timer through the TRGO output. These events serve as
commutation events and trigger changes for PWM
generation. For each of the six steps of the sequence,

22
the states of the six outputs are defined to be either
forced active or inactive, or generating a PWM signal.
The transition from one step to the other is preloaded by
software, in the commutation interrupt routine, and
automatically transferred by hardware to re-program the
output operating mode when the next commutation
arrives.
The figure at right shows the six PWM signals for two
consecutive, complete 6-step sequences, together with
the current in one of the motor phases.

22
This slide presents the break function.
A break event triggers a hardware protection mechanism
that automatically disables the PWM outputs, and forces
them to a user-configurable state, either low impedance
with high or low level, or high impedance.
The logic circuitry works asynchronously, without any
clock.
This guarantees the functionality even in case of a
system clock failure, and avoids any clock-related
propagation time that would tend to delay the protection.
This feature is available on all timers having
complementary PWM outputs, which are capable of
performing power conversion tasks: Timers 1 and 15.
Timers 1 has two separated break channels, while
Timer15 supports a unique break channel.
Supporting two break channels provides a dual-level
protection scheme, where for instance a low priority

23
protection with all switches off can be overridden by a
higher priority protection with low-side switches active.
Furthermore, a dead time delay can be inserted
immediately before entering the fault mode for safely
disabling the power stage. This prevents potential shoot-
through conditions. Let’s consider for instance that the
fault occurs when the high-side PWM is ON, while the
safe state is programmed to have high-side switched
OFF and low-side switched ON. At the time the fault
occurs the system will first disable the high-side PWM,
and insert a dead time before switching ON the low side.

23
This slide describes the break function, BRK2 is not
represented.
Multiple break sources can be combined for triggering a
break event.
A system break request results from serious errors
detected in the MCU: CPU lockup, Power Voltage Drop,
RAM parity error, flash ECC error and loss of clock.
The Lock signals are write-once enable bits located in
the SYSCFG peripheral. They are reset by default (fault
error is masked). Once set (fault detection is enabled),
they cannot be reset unless the whole MCU is reset, for
functional safety.
An application break request results from a board failure.
Break inputs can also be selected with the alternate
function controller, on the MCU pinout.
External sources can be conditioned before entering the
break detection unit in order to select the proper polarity

24
and discarding of spurious glitches by means of a digital
filter.
Software is also capable of requesting a break, typically
when diagnosing an unrecoverable error condition.
When one of these break requests occurs, an interrupt or
DMA request is asserted.

24
The STM32G0 implements a new feature, called
bidirectional break.
The break IO pad is used to report board-level failure,
but can also be used as an output to signal an MCU
internal failure.
The bidirectional mode is available for both the Break
and Break 2 inputs, and require the I/O to be configured
in open-drain mode with active low polarity.
A global break information detected inside the STM32G0
can therefore be output to other CPUs or gate drivers.
Internal break sources and multiple external open drain
comparator outputs are ORed together to trigger a
unique break event, when multiple internal and external
break sources must be merged.

25
This slide explains how to arm and disarm the break
circuitry.
The bidirectional mode is active when the BKxBID bit is
set. x means BK or BK2 break signal.
Since the break IO pad is bidirectional, a low level on the
break input triggers a break which enforces a low level
on the same pad. Therefore a disarming mechanism is
required to exit the break condition.
The Main Output Enable (MOE) bit is relevant when a
channel is configured as an output. It is cleared
asynchronously by hardware as soon as one of the
break inputs is active to disable OC and OCN outputs.
The following sequence should be used to re-arm the
protection after a break event:
• The BKDSRM (BK2DSRM) bit must be set to release
the output control
• The software must wait until the system break

26
condition disappears (if any) and clear the SBIF status
flag (or clear it systematically before re-arming)
• The software must poll the BKDSRM (BK2DSRM) bit
until it is cleared by hardware (when the application
break condition disappears)
From this point, the break circuitry is armed and active,
and the MOE bit can be set to re-enable the PWM
outputs.

26
This slide presents the ADC triggering options related to
the timers.
The ADCs can be triggered with most of the STM32
timers, as indicated in the table.
This can be done using compare events: the ADC
conversion will start on a given compare match. This
applies to Timer 1 channel 4.
The TRGO event can also be used on certain timers.
This gives extra flexibility since the TRGO can be any of
the compare events or timer internal control signals,
such as register update, counter reset or trigger input.
On the other hand, this prevents the TRGO from being
used for synchronization purposes.
For this reason, Timer 1 also has an additional TRGO2
output, fully devoted to ADC triggering.
TRGO2 offers 16 possibilities, including the six compare
events and the possibility to have a dual trigger per PWM

27
period, by combining the compare 4 and 6 events, as
shown in the figure, or compare 5 and 6 events.
This also leaves the TRGO free for multiple timer
synchronization schemes.

27
This slide presents an example of PWM-synchronized
ADC trigger.
For 3-phase motor control, it is mandatory to have ADC
readings synchronized with the PWM generated for
controlling the power stage. This allows extraction of the
average value out of the current waveform ripple, and
makes sure the ADC reading is done at an adequate
distance from the ringing due to the power switches.
Shown here on the left is a 3-phase motor inverter. The
six switches are controlled by three complementary
PWM pairs with dead time inserted, while the current in
the motor windings is measured using shunt resistors
placed in the three half-bridges’ bottom side. The right
side shows the timer’s counter, compare 1 and compare
2 values and corresponding PWM outputs for the low-
side switches controlled by CH1N and CH2N. The two
bottom waveforms represent the current in the motor

28
phase and the image of this current obtained on the shunt
resistors. With this low-cost topology, the voltage can only
be measured when the low-side switches are ON, which
explains the square-wave-shaped signal obtained on the
ADC input. In this case, the ADC trigger is generated on
the counter roll-over. This allows the reading to be done
precisely in the middle of the period and get the average
value of a signal with significant ripple. Additionally, using
a PWM-synchronized ADC trigger also guarantees that
the ADC conversion will be done away from the ringing
noise present on the shunt voltages.

28
This slide lists the interrupts and DMA requests sources.
Most of events are able to generate either an interrupt or
a DMA request, and even the two simultaneously. The
update is issued when the counter overflows or
underflows. It is mainly used to refresh the timer’s run-
time settings at the beginning of the PWM period and
maximize the interval before the next register update.
The repetition counter allows you to skip some PWM
periods and decrease the number of interrupts or DMA
requests at high PWM frequency.
Each of the six capture/compare events have their own
interrupt and DMA. A trigger event on the TRGI input
(regardless of the trigger source) can also trigger an
interrupt or DMA request.
Lastly, additional sources of interrupts and DMA requests
are the commutation and break events on Timers 1, 15,
16, 17 only.
29
The timer includes a DMA burst mode to have multiple
registers re-programmed with a single DMA stream. This
allows the modification of several run-time parameters
simultaneously (for instance duty cycle and frequency of
several channels) or dynamically change the timer
configuration by writing the configuration registers.
The example shows how a table containing three
compare values can be transferred into the compare
registers with a single DMA burst when a new PWM
period starts.
The DMA must be programmed in memory to peripheral
mode, pointing to a unique location in the timer (virtual
register TIMx_DMAR). When the update event occurs,
the timer sends a number of DMA requests
corresponding to the programmed burst length. Each
value is then automatically redirected from the virtual
register into the active register targeted.

30
On the next update event, three new compare values are
transferred again. In this example, this mechanism saves
two DMA streams that would normally be necessary for
such an update scheme.

30
This table indicates the state of the general-purpose
timers (GPT) according to the current MCU power mode.
In Run, Low-power run, Sleep and Low-power sleep
modes, the general-purpose timers are active.
In Sleep and Low-power sleep modes, GPT interrupts
cause the device to exit respectively Sleep or Low-power
sleep mode.
In Stop 0 and 1 modes, the general-purpose timers are
frozen. The peripheral register content is kept. No
reconfiguration of the GPT is needed when exiting these
modes.
In Standby and Shutdown modes, the general-purpose
timers are powered down and must therefore be
reinitialized upon exit of these modes.
Note that for low-power use cases, the LPTIMER offers
extended features, such as full operation and wake-up
capabilities in Stop 0 and 1 modes.
The timer’s state in Debug mode can be configured with
one configuration bit per timer.
If the debug bit is reset, the timer clock is maintained
during a breakpoint.
If the debug bit is set, the timer’s counter is stopped as
soon as the core is halted. Additionally, the outputs of
the timers having complementary outputs are disabled
and forced to an inactive state. This feature is
extremely useful for applications where the timers are
controlling power switches or electrical motors. It
prevents the power stages from being damaged by
excessive current, or the motors from being left in an
uncontrolled state when hitting a breakpoint.

32
This slide explains how to set the timer’s PWM
frequency.
This parameter is defined using the autoreload value
(ARR) programmed in the TIMx_ARR register and the
clock prescaler programmed in the TIMx_PSC register.
The PWM frequency is given by the timer operating
frequency (fTIM) divided by ARR+1 times the clock
prescaler+1.
Practically, finding both register values is an iterative
process, where one must start from PSC = 0, i.e. no
clock division. This guarantees that the PWM will have
the finest possible resolution.
In this case, the ARR value is simply the ratio between
the timer clock frequency and the PWM frequency, the
whole minus 1.
If this equation yields an ARR value above the timer’s
ARR range, either a 16-bit or 32-bit value depending on

33
the selected timer, the computation must be re-done with
a higher prescaler value, with the following sequence:
An ARR value equal to timer clock frequency divided by
two over the PWM frequency, the whole minus 1, then an
ARR value equal to timer clock frequency divided by
three over the PWM frequency, the whole minus 1, and
so on up to the point where the ARR value fits within the
programmable range.

33
This slide explains how to program a duty cycle for a
given PWM frequency.
This parameter is defined using the autoreload value
(ARR) programmed in the TIMx_ARR register and the
compare value programmed in the TIMx_CCRx register.
The duty cycle does not depend on the PWM frequency
and is given by the compare value +1 over the
autoreload value +1.
Another useful indication is the PWM resolution.
This gives the number of possible duty cycle values and
indicates how fine the control on the PWM signal will be.
The resolution, expressed in number of duty cycle steps,
is simply equal to the ratio between the timer clock
frequency and the PWM frequency, the whole minus 1.
Another way of expressing it is in bits, as for giving a
DAC converter output resolution. In this case, the
resolution is the base 2 logarithm of the ratio between

34
the timer clock frequency and the PWM frequency, the
whole minus 1.

34
This slide shows a simple practical example of PWM
usage, for dimming a low-power LED.
This can be done directly using a PWM output, as long
as the current does not exceed the rated output current.
The 1st step is to program the frequency, to be set to
1 kHz. When doing the ARR value computation with no
prescaler and a timer operating frequency of 128 MHz,
the result is 127999, which is above the 16-bit range that
can be used with Timer 1.
The timer prescaler must be set to 1 to have the timer
operating at 64 MHz and this results in a valid value of
63999 for the ARR register.
The second step consists of computing the Compare
register value to have a 20% duty cycle. This yields a
value of 12799.
Lastly, the dimming resolution can be computed from
formulas presented in the previous slides. With a timer

35
running at 64 MHz, a 1 kHz PWM provides 640000
dimming steps, which corresponds to an equivalent
resolution of 15.9 bits.

35
This slide explains a common support case, where the
whole timer is configured, the counter is started, the
PWM mode is enabled, as well as the corresponding
outputs, but still there’s no activity on the pins.
Usually, this is because the MOE bit or the CCxE bit was
not set.
The CCxE bit in the TIMxCCER register defines the
configuration of a CCx channel as input or output. The
CC1E bit must be set to get a PWM signal on the CH1
channel.
For timers equipped with dead time generators (Timers 1
and 15), a Main Output Enable (MOE) bit in the
TIMx_BDTR registers controls all outputs and acts as a
circuit breaker in case of fault detection on the break
input (global disable of all PWM outputs).
The MOE bit must be set (armed) to have the outputs
enabled.

36
This is valid even if the timer is used without dead time
insertion, and the timer is used for general-purpose
applications.

36
This slide lists the timer instances present in STM32G0
microcontrollers.
Timer 1 is a full-featured timer, motor control capable,
including all PWM options and six compare channels for
being able to generate simultaneously 3-phase PWM
signals and have two independent ADC triggers.
Timers 15, 16, 17 are general-purpose timers. Only
Timer 15 supports a complementary channel and
advanced PWM modes.
Timers 2 and 3 are general-purpose timers, including
advanced PWM modes, up-down counting capability and
4 channels. Timer 2 additionally offers a 32-bit counting
range.
Timer 14 is a lite timer, with support for standard PWM
only, with 1 channel and up-counting mode only. They
complement the other timers whenever additional
independent time bases are necessary.

37
Lastly, Timers 6 and 7 are pure time bases with no
outputs, used principally to trigger the DAC converters or
to provide software time bases.

37
This slide indicates which features are implemented for
each timer present in STM32G0:
Input capture and output compare is not supported by
Timers 6 and 7.
Programmable dead-time makes sense when the timer
has complementary outputs, which is the case for Timer
1 (channels 1 to 3) and Timer 15 (channel 1).
Timers 1, 15, 16, and 17 support a break input.
Retriggerable one pulse mode is not supported by
Timers 14, 16, and 17.
Only Timers 1, 2, and 3 have the encoder interface.
XOR function that combines channels is only available in
Timers 1 and 15.
Timer 14 is unable to assert a DMA request.

38
The timer is linked with multiple on-chip peripherals.
It serves as a trigger source for the ADC and the DAC
converter.
The interconnect matrix enables timer to timer direct
connection, using the master and slave interfaces, and
also direct connection between timers and other
peripherals.
The Reset and Clock Control unit, called RCC, provides
the internal clock reference for all timers.
At last, the comparator units can detect abnormal
temperature or voltage conditions and cause a timer
break event.

39
Three application notes complement the timer sections in
the reference manual:
AN2592 gives a practical implementation of a 32-bit
timer made of two synchronized 16-bit timers, and is
useful for better understanding the overall timer
synchronization mechanism. It comes with a software
example.
AN4013 provides a more detailed overview of all timer
features and available firmware examples.
AN4507 presents an implementation of PWM resolution
enhancement by means of dithering techniques. It
comes with a software example.
AN4776 starts with few reminders on timer operating
principles and contains a collection of examples for
standard timer use cases. It comes with a software
example.

40

You might also like