STM32F103xx PMSM FOC Software Library UM
STM32F103xx PMSM FOC Software Library UM
User manual
STM32F103xx
permanent-magnet synchronous motor FOC software library V2.0
Introduction
This user manual describes the permanent magnet synchronous motor (PMSM) FOC
software library, a field oriented control (FOC) firmware library for 3-phase permanent-
magnet motors developed for the STM32F103xx microcontrollers.
These 32-bit, ARM Cortex™-M3 cored ST microcontrollers (STM32F103xx) come with a set
of peripherals that makes it suitable for performing both permanent-magnet and AC
induction motor FOC. In particular, this manual describes the STM32F103xx software library
developed to control surface-mounted or internal, sinewave-driven permanent-magnet
motors in both torque and speed control mode. These motors may be equipped with an
encoder, with three Hall sensors or they may be sensorless. The control of an AC induction
motor equipped with encoder or tacho generator is described in the UM0483 user manual.
The PMSM FOC library is made of several C modules, and is fitted out with IAR EWARM
5.20, KEIL RealView MDK 3.22a and Green Hills MULTI 5.03 workspaces. It is used to
quickly evaluate both the MCU and the available tools. In addition, when used together with
the STM32F103xx motor control starter kit (STM3210B-MCKIT) and PM motor, a motor can
be made to run in a very short time. It also eliminates the need for time-consuming
development of FOC and speed regulation algorithms by providing ready-to-use functions
that let the user concentrate on the application layer. Moreover, it is possible to get rid of any
speed sensor thanks to the sensorless algorithm for rotor position reconstruction.
A prerequisite for using this library is basic knowledge of C programming, PM motor drives
and power inverter hardware. In-depth know-how of STM32F103xx functions is only
required for customizing existing modules and for adding new ones for a complete
application development.
Figure 1 shows the architecture of the firmware. It uses the STM32F103xx standard library
extensively but it also acts directly on hardware peripherals when optimizations in terms of
execution speed or code size are required.
Application layer
STM32F103xx peripherals
ai14812
Contents
2/148
UM0492 Contents
5 Library functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
5.1 Current reading in three shunt resistor topology and space
vector PWM generation: stm32f10x_svpwm_3shunt module . . . . . . . 61
5.1.1 List of available functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
5.1.2 Space vector PWM implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
3/148
Contents UM0492
5.1.3 Current sampling in three shunt topology and general purpose A/D
conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.1.4 Tuning delay parameters and sampling stator currents in three shunt
resistor topology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
5.2 Current reading in single shunt resistor topology and space
vector PWM generation: stm32f10x_svpwm_1shunt module . . . . . . . 73
5.2.1 List of available functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
5.2.2 Current sampling in single-shunt topology . . . . . . . . . . . . . . . . . . . . . . . 78
5.2.3 Definition of the noise parameter and boundary zone . . . . . . . . . . . . . . 80
5.2.4 Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
5.3 Isolated current sensor reading and space vector PWM
generation: stm32f10x_svpwm_ics module . . . . . . . . . . . . . . . . . . . 83
5.3.1 List of available functions and interrupt service routines . . . . . . . . . . . . 83
5.3.2 Current sampling in isolated current sensor topology and integrating
general-purpose A/D conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
5.4 PMSM (SM-PMSM / IPMSM) field-oriented control:
MC_FOC_Drive and MC_FOC_Methods modules . . . . . . . . . . . . . . . . . . 87
5.4.1 List of available C functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
5.5 Reference frame transformations: MC_Clarke_Park module . . . . . . . . 95
5.5.1 List of available C functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
5.5.2 Detailed explanation about reference frame transformations . . . . . . . 100
5.5.3 Circle limitation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
5.6 Encoder feedback processing: stm32f10x_encoder module . . . . . . . 103
5.6.1 List of available functions and interrupt service routines . . . . . . . . . . . 103
5.7 Hall sensor feedback processing: stm32f10x_hall module . . . . . . . 106
5.7.1 List of available functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
5.7.2 Speed measurement implementation . . . . . . . . . . . . . . . . . . . . . . . . . 110
5.7.3 Electrical angle extrapolation implementation . . . . . . . . . . . . . . . . . . . 112
5.8 Sensorless speed / position detection: MC_State_Observer
and MC_State_Observer_Interface modules . . . . . . . . . . . . . . . . 113
5.8.1 List of available C functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
5.9 PID regulators: MC_PID_regulators module . . . . . . . . . . . . . . . . . . . 119
5.9.1 List of available functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
5.9.2 PID regulator theoretical background . . . . . . . . . . . . . . . . . . . . . . . . . 121
5.9.3 Regulator sampling time setting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
5.9.4 Adjusting speed regulation loop Ki, Kp and Kd vs. motor frequency . . 123
5.10 General purpose time base: stm32f10x_Timebase module . . . . . . . 125
5.10.1 List of available functions and interrupt service routines . . . . . . . . . . . 125
4/148
UM0492 Contents
5/148
List of tables UM0492
List of tables
6/148
UM0492 List of figures
List of figures
7/148
List of figures UM0492
8/148
UM0492
9/148
Getting started with tools UM0492
To develop an application for a PM synchronous motor using the PMSM FOC software
library, you must set up a complete development environment, as described in the following
sections. A PC running Windows XP is necessary.
The JTAG interface can also be used for in-circuit programming of the MCU. Other
production programmers can be obtained from third-parties.
10/148
UM0492 Getting started with tools
1.3.1 Updates
It is highly recommended to check for the latest releases of the library before starting any
new development, and then to verify from time to time all release notes to be aware of any
new features that might be of interest for your project. Registration mechanisms are
available on ST websites to automatically obtain updates.
The STM32 FOC Firmware Libraries v2.0 folder contains the firmware libraries for running
3-phase (sensored or sensorless) PMSM and sensored AC induction motors.
The STM32F10xFWLIB folder contains the standard library for the STM32F103xx.
The inc folder contains the header and the src folder contains the source files of the motor
control library.
Finally, each of the EWARM, RVMDK and MULTI folders contains the configuration files for
the respective toolchain plus a lib folder that contains the compiled object files of two
modules: MC_State_Observer and MC_FOC_Methods.
The complete source files are available free of charge from ST on request. Do not hesitate
to contact your nearest ST sales office or support team.
11/148
Getting started with tools UM0492
12/148
UM0492 Introduction to the sensorless FOC of PM motors
13/148
Introduction to the sensorless FOC of PM motors UM0492
The iqs and ids current components can be selected to perform electromagnetic torque and
flux control.
On the other hand, Figure 5 shows the speed control loop as well as the whole set of
specific features offered by this motor control library. See Section 2.1.4, Section 2.3 and
Section 2.1.5. Section 2.1.4 explains the MTPA (maximum-torque-per-ampere) strategy
optimized for IPMSM. Section 2.3 explains flux-weakening control, and Section 2.1.5 shows
how to take advantage of the feed-forward current regulation.
14/148
UM0492 Introduction to the sensorless FOC of PM motors
Each of these features can be set as an option (see Section 4.1), according to the motor
being used and user needs.
SM-PMSMs inherently have an isotropic structure, that is, the direct and quadrature
inductances Ld and Lq are the same. Usually, their mechanical structure allows a wider
airgap, which in turn means lower flux weakening capability.
On the other hand, IPMSMs show an anisotropic structure (with Ld < Lq, typically), slight in
the b) construction (called inset PM motor), strong in the c) configuration (called buried or
radial PM motor); this peculiar magnetic structure can be exploited (as explained in
Section 2.1.4) to produce a greater amount of electromagnetic torque. their fine mechanical
structure usually shows a narrow airgap, thus giving good flux weakening capability.
This firmware library is optimized for use in conjunction with SM-PMSMs and IPMSMs.
machines.
15/148
Introduction to the sensorless FOC of PM motors UM0492
With reference to Figure 7, the motor voltage and flux linkage equations of a PMSM (SM-
PMSM or IPMSM) are generally expressed as:
dλ abc
ν abc = r s i abc + -----------------s
s s dt
L ms L ms
L ls + L ms – ---------
- – ---------
- sin θ r
2 2
sin ⎛⎝ θ r – ------
2π⎞
L ms L ms
λ abc =
s
– ---------
- L ls + L ms – ---------
- i abc +
s
3 ⎠ Φm , where:
2 2
L ms L ms sin ⎛⎝ θ r + 2π
------⎞⎠
– ---------
- – ---------
- L ls + L ms 3
2 2
● rs is the stator phase winding resistance
● Lls is the stator phase winding leakage inductance
● Lms is the stator phase winding magnetizing inductance; in case of an IPMSM, self and
mutual inductances have a second harmonic component L2s proportional to cos(2θ r + k
× 2π/3), with k = 0±1, in addition to the constant component Lms(neglecting higher-
order harmonics)
● θr is the rotor electrical angle
● Φm is the flux linkage due to permanent magnets
The complexity of these equations is apparent, as the three stator flux linkages are mutually
coupled and, what is more, as they are dependent on the rotor position, which is time-
varying and a function of the electromagnetic and load torques.
The reference frame theory simplifies the PM motor equations, by making a change of
variables that refers the stator quantities abc (that can be visualized as directed along axes
each 120° apart) to qd components, directed along a 90° apart axes, rotating synchronously
with the rotor, and vice versa (see Section 5.5 for more details). The d “direct” axis is aligned
with the rotor flux, while the q “quadrature” axis leads at 90 degrees in the positive rolling
direction.
16/148
UM0492 Introduction to the sensorless FOC of PM motors
⎧ dλ qs
⎪ ν qs = r s i qs + -----------
- + ωr λ ds
⎪ dt
⎨
dλ ds
⎪ ν = r i + -----------
⎪ ds s ds - – ωr λ qs
dt
⎩
⎧ λ qs = L qs i qs
⎨
⎩ λ ds = L ds i ds + Φm
For an SM-PMSM, the inductances of the d- and q- axis circuits are the same (refer to
Section 2.1.1), that is we have:
3L ms
L s = L qs = L ds = L ls + ------------
-
2
On the other hand, IPMSMs show a salient magnetic structure, so their inductances can be
written as:
3 ( L ms + L 2s )
L qs = L ls + ---------------------------------
2
3 ( L ms – L 2s )
L ds = L ls + --------------------------------
2
3 3
T e = --- p ( λ ds i qs – λ qs i ds ) = --- p ( L s i ds i qs + Φm i qs – L s i qs i d )
2 2 s
3
T e = --- p ( Φm i qs )
2
The last equation makes it clear that the quadrature current component iqs has linear control
on the torque generation, whereas the current component ids has no effect on it (as
mentioned above, these equations are valid for SM-PMSMs).
Therefore, if Is is the motor rated current, then its maximum torque is produced for iqs = Is
2 2
and ids = 0 (in fact I s = i q s + i d s ). In any case it is clear that, when using an SM-PMSM, the
torque/current ratio is optimized by letting ids = 0. This choice therefore corresponds to the
MTPA (maximum-torque-per-ampere) control for isotropic motors. See Section 4.1 to find
out how to set up the library configuration and carry out this strategy.
17/148
Introduction to the sensorless FOC of PM motors UM0492
On the other hand, the magnetic flux can be weakened by acting on the direct axis current
ids; this extends the achievable speed range, but at the cost of a decrease in maximum
quadrature current iqs, and hence in the electromagnetic torque supplied to the load (see
Section 2.3 for details about the Flux weakening strategy).
In conclusion, by regulating the motor currents through their components iqs and ids, FOC
manages to regulate the PMSM torque and flux; current regulation is achieved by means of
what is usually called a “synchronous frame CR-PWM”.
3 3
T e = --- p ( λ ds i qs – λ qs i ds ) = --- p ( L ds i ds i qs + Φm i qs – L qs i qs i ds )
2 2
3 3
T e = --- pΦm i qs + --- pL ds – L qs i qs i ds
2 2
The first term in this expression is the PM excitation torque. The second term is the so-
called reluctance torque, which represents an additional component due to the intrinsic
salient magnetic structure. Besides, since Ld < Lq typically, reluctance and excitation torques
have the same direction only if ids < 0.
Considering the torque equation, it can be pointed out that the current components iqs and
ids both have a direct influence on torque generation.
The aim of the MTPA (maximum-torque-per-ampere) control is to calculate the reference
currents (iqs, ids) which maximize the ratio between produced electromagnetic torque and
2 2
copper losses (under the condition: I s = i qs + i ds ≤I n ).
Therefore, given a set of motor parameters (pole pairs, direct and quadrature inductances
Ld and Lq, magnets flux linkage, nominal current) the MTPA trajectory is identified as the
locus of (iqs, ids) pairs that minimizes the current consumption for each required torque (see
Figure 8).
18/148
UM0492 Introduction to the sensorless FOC of PM motors
Section 4.1 explains how this feature is activated. By inputting the motor parameters into a
spreadsheet included in the firmware library package (the file location is STM32MC-
KIT\design tools\ PMSM_MTPA_FEEDFORWARD.xls), it is possible to precalculate the
MTPA trajectory and insert the result, as coefficients of an 8-interval linear interpolation, into
the proper parameter header file (see details in Section 4.6.4).
Figure 9 shows an actual implementation. The MTPA strategy is implemented inside a
speed-control loop. In that case, iq* (output of the PI regulator) is fed to the MTPA function,
id* is chosen by entering the linear interpolated trajectory.
In any case, by acting on the direct axis current ids, the magnetic flux can be weakened so
as to extend the achievable speed range. As a consequence of entering this operating
region, the MTPA path is left (see Section 2.3 for details about the flux-weakening strategy).
In conclusion, by regulating the motor currents through their iqs and ids components, FOC
manages to regulate the PMSM torque and flux. Current regulation is then achieved by
means of what is usually called a “synchronous frame CR-PWM”.
19/148
Introduction to the sensorless FOC of PM motors UM0492
Depending on some overall system parameters, such as the DC bulk capacitor size,
electrical frequency required by the application, motor parameters etc., the feed-forward
functionality could bring a major or a poor contribution to the motor drive. It is therefore
20/148
UM0492 Introduction to the sensorless FOC of PM motors
recommended that the user assess the resulting system performance and enable the
functionality only if a valuable effect is measured.
See Section 4.1 for details on activating the feed-forward feature, Section 4.6 for how to
insert the required parameters into the proper header file (by using the
PMSM_MTPA_FEEDFORWARD.xls spreadsheet provided in STM32MC-KIT\design
tools\) and, Section 5.4 for the functional description and prototypes of the available
functions.
21/148
Introduction to the sensorless FOC of PM motors UM0492
In particular, the observed states are compared for consistency with the real system via the
phase currents, and the result is used to adjust the model through a gain vector (K1, K2).
The motor back-emfs are defined as:
e α = Φm pωr cos ( pωr t )
e β = – Φm pωr sin ( pωr t )
As can be seen, they hold information about the rotor angle. Then, back-emfs are fed to a
block which, acting as a PLL, is able to reconstruct the rotor electrical angle and speed.
Figure 12 shows a scope capture taken while the motor is running in field oriented control
(positive rolling direction); the yellow and the red waveforms (C1,C2) are respectively the
observed back-emfs alpha and beta, the blue square wave (C3) is a signal coming from a
Hall sensor cell placed on the a-axis, the green sinewave is current ia (C4).
22/148
UM0492 Introduction to the sensorless FOC of PM motors
Figure 12. PMSM back-emfs detected by the sensorless state observer algorithm
More information on how to set parameters to make the firmware suit the user’s motor could
be found in Section 4.5.
23/148
Introduction to the sensorless FOC of PM motors UM0492
The current ids** output from the flux-weakening controller must be checked against ids max
to avoid the demagnetization of the motor.
See Section 4.1, Section 4.6 and Section 5.4, respectively, about the activation of the flux-
weakening feature, inserting the required parameters into the proper header file, and the
functional description and prototypes of the available functions.
24/148
UM0492 Running the demo program
From the previous screen (Figure 14), if the joystick is moved to the right, the Target Iq
current component becomes highlighted (in red). This parameter can now be modified by
moving the joystick up/down. Once the motor Start command has been issued, Target Iq
can be changed in runtime while the measured Iq current component is shown in the
Measured field.
From the previous screen (Figure 15), if the joystick is moved to the right, the Target Id
current component becomes highlighted (in red). This parameter can now be modified by
25/148
Running the demo program UM0492
moving the joystick up/down. Once the motor Start command has been issued, the Target Id
can be changed in runtime while the measured Id current component is shown in the
Measured field.
The motor is stopped (main state machine moves from Run to Stop state) by pressing either
the KEY button or the joystick.
Different motor ramp-up strategies are used in torque control mode depending on the kind of
configuration utilized for the speed / position feedback:
● ENCODER or VIEW_ENCODER_FEEDBACK uncommented in the configuration file
stm32f10x_MCconf.h. In this case a rotor pre-positioning phase (also called alignment)
is necessary in order to make absolute the otherwise relative position information fed
back by the quadrature encoder. This alignment phase is performed only at first startup
after any detected microcontroller fault event or reset. Refer to Section 4.3 for a deeper
description of this procedure.
After the rotor pre-positioning is performed, if ENCODER is uncommented, the variables
containing the target value of the Iq and Id stator current components (respectively
hTorque_Reference and hFlux_Reference) are initialized with the values
PID_TORQUE_REFERENCE and PID_FLUX_REFERENCE defined in the header file
MC_Control_Param.h; the main state machine switches from the Start to the Run state.
On the other hand, if VIEW_ENCODER_FEEDBACK is uncommented, the ramp-up
strategy related to the sensorless operation starts just after the end of the pre-
positioning.
● HALL_SENSORS is uncommented in the stm32f10x_MCconf.h configuration file. In this
case no rotor pre-positioning is performed and the hTorque_Reference software
variable is simply initialized with the PID_TORQUE_REFERENCE value defined in the
MC_Control_Param.h header file. The software variable containing the electrical rotor
angle is initialized based on the digital value of the three Hall sensor outputs, and the
main state machine switches from the Start to the Run state.
● NO_SPEED_SENSORS is uncommented in stm32f10x_MCconf.h. In case of sensorless
motor driving, a particular ramp-up is necessary in order to make the rotor move and
the sensorless algorithm converge to the actual rotor position. A deeper description of
the ramp-up procedure is described in Section 4.5.
26/148
UM0492 Running the demo program
From the menu screen shown in Figure 18, moving the joystick to the right selects the Target
speed (parameter highlighted in red). Once selected, the parameter can be
incremented/decremented by moving the joystick up/down. The motor can then be started
simply by pressing the joystick. When the motor is on, the target speed can still be modified.
Like in the torque control mode, the motor is started/stopped by pressing the joystick or the
KEY button.
Since in speed control mode, the torque and flux parameters (Target Iq and Target Id) are
the outputs of the Torque and flux controller, they cannot be set directly. The PID regulators
can however be real-time tuned as explained below.
27/148
Running the demo program UM0492
Different motor ramp-up strategies are used in speed control mode depending on the kind of
configuration utilized for the speed / position feedback:
● ENCODER or VIEW_ENCODER_FEEDBACK uncommented in the stm32f10x_MCconf.h
configuration file. As already stated in the previous paragraph, a rotor pre-positioning
phase (also called alignment) is necessary in this case. Refer to Section 4.3 for a
deeper description of this procedure.
After the rotor pre-positioning is performed, if ENCODER is uncommented the variables
containing the target values of the Iq and Id current components (hTorque_Reference
and hFlux_Reference, respectively) are driven by the torque and flux controller
block and the main state machine switches from the Start to the Run state. On the
other hand, if VIEW_ENCODER_FEEDBACK is uncommented, the ramp-up strategy
related to the sensorless operation starts just after the end of the pre-positioning.
● HALL_SENSORS is uncommented in the stm32f10x_MCconf.h configuration file. The
hTorque_Reference software variable is driven by the flux and torque controller block
from the moment the start command is given. The software variable containing the
electrical rotor angle is also initialized based on the digital value of the three Hall
sensor outputs at that moment. Finally, the main state machine switches from the Start
to the Run state.
● NO_SPEED_SENSORS is uncommented in stm32f10x_MCconf.h. In case of sensorless
motor driving, a particular ramp-up is necessary in order to make the rotor move and
the sensorless algorithm converge to the actual rotor position. A more detailed
description of the ramp-up procedure is described in Section 4.5.
Figure 19. LCD screen for setting the P term of torque PID
28/148
UM0492 Running the demo program
Figure 20. LCD screen for setting the P term of flux PID
Moreover, to achieve speed regulation in speed control mode, a PI(D) is also implemented
inside the torque and flux controller block. The tuning of its related gains can be done in real
time by means of the dedicated LCD menu:
Figure 21. LCD screen for setting the P term of the speed PID
Like for the previous menus, either of the P, I or D (when present) coefficients can be
selected (highlighted in red) by moving the joystick to the right/left. The desired values can
then be changed (incremented or decremented) by pressing the joystick up/down.
29/148
Running the demo program UM0492
Figure 22. LCD screen for setting the P term of the flux-weakening PI
2 2
The target and measured stator voltages ( V s = ν α + ν β ) are shown in the lower part of the
screen as a percentage of the maximum available phase voltage.
Figure 23. LCD screen for setting the P term of the flux PID
When the menu shown in Figure 23 is displayed, the joystick can be moved to the right/left
to navigate between the different gains. Pressing the joystick up/down will
increment/decrement the gain highlighted in red color.
This menu is used to change both the observer and the PLL gains in real time. This feature
is particularly useful when used in conjunction with the DAC functionality and with a
firmware configuration handling either Hall effect sensors or an encoder. In this way, it is
possible to modify the observer and PLL gains by looking for example at both the observed
and measured rotor electrical angle and by adjusting the gains so as to cancel any error
between the two waveforms.
30/148
UM0492 Running the demo program
Figure 24. LCD screen for setting the P term of the flux PID
When the menu shown in Figure 24 is displayed, the joystick can be moved to the right/left
to select the desired microcontroller pin. To change the software variable in output, move the
joystick up/down (the list of the available variables depends on the selected firmware
configuration). For all other menus, pressing the joystick or the Key button will cause the
motor to start/stop.
It is also possible to add two user-defined variables to the default list, by placing the
following code lines:
...
#include "stm32f10x_MClib.h"
...
MCDAC_Update_Value(USER_1,variable_name1);
MCDAC_Update_Value(USER_2,variable_name2);
...
These variables are shown in output if “User 1” or “User 2” are selected on the display.
Variable tracing is turned on if the demo program is in the START/RUN states. The variable
update frequency is fixed by the sampling rate of the FOC algorithm (see Section 4.2 for
details).
The DAC functionality was implemented in the presented firmware library by using two out
of the four TIM3 output compare channels (PB0 and PB1 pins) and by modulating the duty
cycle of the generated 30 kHz PWM signal. In order to properly filter the generated signals
without introducing important delays on the waveforms, it is suggested to use a proper first-
order low-pass filter (e.g. with a 10 kΩ resistor and a 22 nF capacitor). Furthermore, if a
High-density performance line (that is an STM32F103xC, STM32F103xD or STM32F103xE
derivative) MCU is used, the user can exploit the built-in 2-channel, 12-bit D/A converter by
suitably modifying the stm32f10x_MCdac.c file.
31/148
Running the demo program UM0492
The message “Press ‘Key’ to return to menu” is visible only if the source of the fault has
disappeared. In this case, pressing the ‘Key’ button causes the main state machine to switch
from the Fault to the Idle state.
There are six different fault sources when using the firmware library in conjunction with the
STM3210B-MCKIT:
3.8.1 Overcurrent
A low level was detected on the PWM-peripheral-dedicated pin (BKIN). If the STM3210B-
MCKIT is being used, this means that either the hardware overtemperature protection or the
32/148
UM0492 Running the demo program
hardware overcurrent protection has been triggered. Refer to the STM3210B-MCKIT user
manual for details.
3.8.2 Overheating
An overtemperature was detected on the dedicated analog channel. The intervention
threshold (NTC_THRESHOLD_C) and the related hysteresis (NTC_HYSTERESIS_C) are
specified in the MC_Control_Param.h header file. Refer to the STM3210B-MCKIT user
manual for details.
33/148
Running the demo program UM0492
usually indicates that information has been lost (Hall sensor timeout) or that speed is
decreasing very sharply.
● in case of sensorless operation, the quality of the speed measurement expressed in
terms of the distribution around the mean value is not good. This typically means that
either the observer is not properly tuned or that the speed is so low that a good
observation of the induced B-emf is not possible (e.g. rotor is locked). Refer also to
Section 4.5.3.
Figure 27. MB459B power board setup for the single-shunt topology
W4 W4
W5 W5
W10 W10
(Three shunt) (Single shunt)
ai15153
34/148
UM0492 Running the demo program
PWM2 (Phase B). In particular, the current coming out of inverter Phase A must be read by
an ICS whose output has to be sent to the analog channel specified by the
PHASE_A_ADC_CHANNEL parameter in MC_pwm_ics_prm.h. Likewise, the current
coming out of inverter Phase B must be read by the other ICS and its output has to be sent
to the analog channel specified by the PHASE_B_ADC_CHANNEL parameter in
MC_pwm_ics_prm.h.
About the positive current direction convention, a positive half-wave on
PHASE_X_ADC_CHANNEL is expected, corresponding to a positive half-wave on the
current coming out of the related inverter leg (see direction of I in Figure 28).
Note: Firmware support of ICS current measurement is enabled as explained in Section 4.1.
Using ICS allows the MMI to be set to 100% (#define
MAX_MODULATION_100_PER_CENT, see Section 4.2 and Section 5.5.3).
35/148
Running the demo program UM0492
As the name implies, incremental encoders actually read angular displacements with
respect to an initial position: if that position is known, then the rotor absolute angle is known
too. For this reason it is always necessary, when processing the encoder feedback
(ENCODER or VIEW_ENCODER_FEEDBACK definitions not commented in
stm32f10x_MCconf.h), to perform a rotor prepositioning before the first startup after any
fault event or microcontroller reset.
Quadrature encoders have two output signals (represented in Figure 29 as TI1 and TI2).
With these, and with the STM32F103xx standard timer in encoder interface mode, it is
possible to get information about the rolling direction.
In addition, the rotor angular velocity can be easily calculated as a time derivative of the
angular position.
To set up the PMSM FOC software library for use with an incremental encoder, simply
modify the stm32f10x_MCconf.h and MC_encoder_param.h header files according to
the indications given in Section 4.1 and Section 4.3, respectively.
However, some extra care should be taken, concerning what is considered to be the positive
rolling direction: this software library assumes that the positive rolling direction is the rolling
direction of a machine that is fed with a three-phase system of positive sequence.
Because of this, and because of how the encoder output signals are wired to the
microcontroller input pins, it is possible to have a sign discrepancy between the real rolling
direction and the direction that is read. To avoid this kind of reading error, apply the following
procedure:
1. Turn the rotor by hand in the direction assumed to be positive and look at the B-emf
induced on the three motor phases. For this purpose, a neutral point may need to be
reconstructed with three resistors if the real one is not available.
2. Connect the motor phases to the hardware respecting the positive sequence (for
instance when using the MB459 board, a positive sequence of the motor phases may
be connected to J5 2,1 and 3).
3. Run the firmware in encoder configuration and turn by hand the rotor in the direction
assumed to be positive. If the measured speed shown on the LCD is positive, the
36/148
UM0492 Running the demo program
Figure 30. 60° and 120° displaced Hall sensor output waveforms
H2 H3
H1
H1
H2 H2
H3 H3
ai14826
Since the rotor position information they provide is absolute, there is no need for any initial
rotor prepositioning. Particular attention must be paid, however, when connecting the
sensors to the proper microcontroller inputs.
In fact, as stated in Section 3.11, this software library assumes that the positive rolling
direction is the rolling direction of a machine that is fed with a three-phase system of positive
sequence. In that case to properly work, the software library expects the Hall sensor signal
transitions to be in the sequence shown in Figure 30 for both 60° and 120° displaced Hall
sensors.
For these reasons, it is suggested to follow the instructions given below when connecting a
Hall-sensor equipped PM motor to your board:
37/148
Running the demo program UM0492
1. Turn the rotor by hand in the direction assumed to be positive and look at the B-emf
induced on the three motor phases. For this purpose if the real neutral point is not
available, it can be reconstructed by means of three resistors for instance.
2. Connect the motor phases to the hardware respecting the positive sequence. Let
“Phase A”, “Phase B” and “Phase C” be the motor phases driven by TIM1_CH1,
TIM1_CH2 and TIM1_CH3, respectively (e.g. when using the MB459 board, a positive
sequence of the motor phases could be connected to J5 2,1 and 3).
3. Turn the rotor by hand in the direction assumed to be positive, look at the three Hall
sensor outputs (H1, H2 and H3) and connect them to the selected timer on channels 1,
2 and 3, respectively, making sure that the sequence shown in Figure 30 is respected.
4. Measure the delay in electrical degrees between the maximum of the B-emf induced on
Phase A and the first rising edge of signal H1. Enter it in the MC_hall_param.h header
file (HALL_PHASE_SHIFT). For your convenience, an example with
HALL_PHASE_SHIFT equal to –90 °C is illustrated in Figure 31.
38/148
UM0492 Running the demo program
39/148
Running the demo program UM0492
Note: Be aware that due to the different speed resolution/accuracy, a different setup for speed PID
could be necessary.
– Tune startup parameters performing different ramp-up trials and, if required,
further tune observer and PLL gains
4. Congratulations! The motor can now run in pure sensorless mode:
Depending on the requirements of the used debug feature, on the expected code size
and CPU load you could:
– Comment VIEW_HALL_FEEDBACK or VIEW_ENCODER_FEEDBACK (depending on
which was not commented) in stm32f10x_MCconf.h
– Comment OBSERVER_GAIN_TUNING in stm32f10x_MCconf.h
– Comment DAC_FUNCTIONALITY in stm32f10x_MCconf.h
3.14.1 How to configure the FOC software library for brake resistor
management
To enable the management of the brake resistor on the STM32F103xx PMSM FOC
firmware library, simply uncomment the definition of BRAKE_RESISTOR in the
stm32f10x_MCconf.h header file.
The analog watchdog feature of the STM32F103xx allows to generate an interrupt whenever
the bus voltage goes above the OVERVOLTAGE_THRESHOLD_V parameter specified in
MC_Control_Param.h and as a consequence, the BRAKE_GPIO_PIN pin of the
BRAKE_GPIO_PORT port is set to high level (both definitions are in
MC_MotorControl_Layer.c, default values are GPIOD and GPIO_Pin_13 for compatibility
with STM3210B-MCKIT). From then on, a hysteresis control of the bus voltage is performed.
Hysteresis can be entered by editing the BRAKE_HYSTERESIS parameter in stm32f10x_it.c.
40/148
UM0492 Running the demo program
3.14.2 How to modify the MB459 board for brake resistor management
In order to make the MB459 board suitable for the management of a brake resistor, it is
necessary to solder some additional components on its wrapping area.
Figure 32 gives an example of the circuit to be used for the hardware implementation of the
brake.
Note that the size of the resistor in terms of both resistance and sustainable power should
be carefully dimensioned.
When using the PMSM FOC library in conjunction with the STM3210B-MCKIT, note that the
pin 23 of the MC connector (J7) that carries the signal for brake implementation is
positioned close to the wrapping area.
41/148
Running the demo program UM0492
Figure 33. DBG_TIM1_STOP bit in TIM1 control register (extract from STM32
reference manual)
DBGMCU_CR
Address: 0xE0042004
Only 32-bit access supported
POR Reset: 0x00000000 (not reset by system reset)
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16
DBG_I2C
2_SMBU
Reserved S_TIMEO
UT
Res. rw
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
DBG_I2C
DBG_ DBG_ DBG_ DBG_ DBG_ DBG_ DBG_ TRACE_ DBG_
1_SMBU TRACE_ DBG_ DBG_
CAN_ TIM4_ TIM3_ TIM2_ TIM1_ WWDG_ IWDG MODE Reserved STANDB
S_TIME IOEN STOP SLEEP
STOP STOP STOP STOP STOP STOP STOP [1:0] Y
OUT
rw rw rw rw rw rw rw rw rw rw rw Res. rw rw rw
42/148
UM0492 Getting started with the library
It is quite easy to set up an operational evaluation platform with a drive system that includes
the STM3210B-MCKIT (featuring the STM32F103xx microcontroller, where this software
runs) and a permanent-magnet motor.
This section explains how to quickly configure your system and, if necessary, customize the
library accordingly.
Follow these steps to accomplish this task:
1. Gather all the information that is needed regarding the hardware in use (motor
parameters, power devices features, speed/position sensor parameters, current
sensors transconductance);
2. Edit, using an IDE, the stm32f10x_MCconf.h configuration header file (as explained
in more detail in Section 4.1), and the following parameter header files,
– MC_Control_Param.h (see Section 4.2),
– MC_encoder_param.h (see Section 4.3) or MC_hall_prm.h (see Section 4.4),
– MC_State_Observer_param.h (see Section 4.5)
– MC_PMSM_motor_param.h (see Section 4.6);
3. Re-build the project and download it on the STM32F103xx microcontroller.
Please be aware that this procedure should also be followed when the final target is a
sensorless drive. In fact, receiving speed/position information from any kind of sensor
makes it possible to achieve a more precise customization, and to tune the algorithm utilized
for sensorless rotor position reconstruction.
43/148
Getting started with the library UM0492
● Enable or disable the execution of a specific software dedicated to the tuning of current
PIDs
● Enable or disable the tuning of the State Observer and PLL gains
● In case of "no speed sensor" it is still possible to acquire signals coming from Hall
sensors or encoder and evaluate whether the sensorless algorithm is working properly,
using the DAC functionality. Those signal will not be used in the FOC algorithm; the
choice here is between Hall sensors, quadrature incremental encoder or none.
If this header file is not edited appropriately (no choice or undefined choice), you will receive
an error message when building the project. Note that you will not receive an error message
if the configuration described in this header file does not match the hardware that is actually
in use, or in case of wrong wiring.
More specifically:
● #define ICS_SENSORS
To be uncommented when current sampling is done using isolated current sensors.
● #define THREE_SHUNT
To be uncommented when current sampling is performed via three shunt resistors
(default).
● #define SINGLE_SHUNT
To be uncommented when current sampling is performed via a single shunt resistor (it
is also required to set up the MB459B power board as described in Section 3.9: Setting
up the system when in single-shunt topology and using the MB459B power board on
page 34)
● #define ENCODER
To be uncommented when an incremental encoder is connected to the starter kit for
position sensing; in parallel, fill out MC_encoder_param.h (as explained in Section 4.3)
● #define HALL_SENSORS
To be uncommented when three Hall sensors (60° or 120° displaced) are in use to
detect rotor speed; in parallel, fill out MC_hall_prm.h (as explained in Section 4.4)
● #define NO_SPEED_SENSORS
To be uncommented to use the rotor position information inside the FOC algorithm
(rotor position information is provided by a state observer) (default). In this case, the
user should fill MC_State_Observer_param.h and MC_PMSM_motor_param.h in
parallel (as explained in Section 4.5 and Section 4.6, respectively)
● #define VIEW_HALL_FEEDBACK
To be uncommented only in conjunction with NO_SPEED_SENSORS. It is used to
process the information that comes from three Hall sensors, to be displayed through
the DAC functionality (and compared with the information coming from the sensorless
rotor position reconstruction algorithm)
● #define VIEW_ENCODER_FEEDBACK
To be uncommented only in conjunction with NO_SPEED_SENSORS. It is used to
process the information coming from an incremental encoder, to be displayed through
the DAC functionality (and compared with the information coming from the sensorless
rotor position reconstruction algorithm) (default)
44/148
UM0492 Getting started with the library
● #define NO_SPEED_SENSORS_ALIGNMENT
To be uncommented only in conjunction with NO_SPEED_SENSORS. It sets up the driver
to perform a rotor alignment before every motor startup. In this case, the user also has
to fill a section of MC_State_Observer_param.h (as explained in Section 4.5)
● #define IPMSM_MTPA
To be uncommented to take advantage of the optimized MTPA (maximum torque per
ampere) drive designed for internal permanent magnet synchronous motors (IPMSMs).
In this case, the user also has to fill a section of MC_PMSM_Motor_param.h (see
Section 2.1.4 and Section 4.6). Leaving this #define commented (default) implies that
the demo program optimizes vector control as needed by a PMSM (as explained in
Section 2.1.3)
● #define FLUX_WEAKENING
To be uncommented if the user's application requires to operate the motor beyond its
nominal speed (default). In parallel, fill MC_PMSM_Motor_param.h (as explained in
Section 4.6); see Section 3.13 about the precautions to be taken when using the flux-
weakening feature
● #define FEED_FORWARD_CURRENT_REGULATION
To be uncommented in order to back up the standard PID current regulation with a
feed-forward calculation. In parallel, the user should fill the corresponding section in
MC_PMSM_Motor_param.h (as explained in Section 4.6)
● #define BRAKE_RESISTOR
To be uncommented to enable the software management of a resistive brake (refer to
Section 3.14.2 for more information about the hardware modifications to be applied to
the MB459 board)
Caution: In order to avoid any damage to the power stage, it is mandatory to utilize the brake resistor
feature for operation above the nominal speed.
● #define DIFFERENTIAL_TERM_ENABLED
To be uncommented to enable the differential term in the PID regulator function in the
MC_PID_regulators library module (see Section 5.9)
● #define FLUX_TORQUE_PIDs_TUNING
To be uncommented when a rotor position sensor is utilized. It generates a software
dedicated to torque and flux PID gain tuning. Fill MC_Control_Param.h in parallel
● #define OBSERVER_GAIN_TUNING
If uncommented, it enables the visualization on LCD of a menu dedicated to state
observer and PLL gain tuning
● #define DAC_FUNCTIONALITY
To be uncommented to enable the DAC functionality. Refer to Section 3.6 for more
detailed information about this feature.
Once these settings have been done, only the required blocks will be linked in the project;
this means that you do not need to exclude .c files from the build.
Caution: When using shunt resistors for current measurement, ensure that the REP_RATE parameter
(in MC_Control_Param.h) is set properly (see Section 4.2 and Section A.2: Selecting the
update repetition rate based on the PWM frequency for single- or three-shunt resistor
configuration on page 136 for details).
45/148
Getting started with the library UM0492
⋅ PWM_FREQ-
Flux and torque PID sampling rate = 2
--------------------------------------------
REP_RATE + 1
In fact, because there is no reason for either executing the FOC algorithm without updating
the stator currents values or for performing stator current conversions without running the
FOC algorithm, in the proposed implementation the stator current sampling frequency and
the FOC algorithm execution rate coincide.
Note: REP_RATE must be an odd number if currents are measured by shunt resistors (see
Section A.2: Selecting the update repetition rate based on the PWM frequency for single- or
three-shunt resistor configuration on page 136 for details); its value is 8-bit long;
46/148
UM0492 Getting started with the library
● #define OVERVOLTAGE_THRESHOLD_V
● #define UNDERVOLTAGE_THRESHOLD_V
These two values (expressed in volt) set the minimum and maximum acceptable bus
DC voltage when the software library is utilized with the MB459 board. If the bus
voltage exceeds OVERVOLTAGE_THRESHOLD_V or is below
UNDERVOLTAGE_THRESHOLD_V, a fault event is generated that is kept as long as the
bus voltage remains outside the allowed range.
● #define BUS_ADC_CONV_RATIO
Defines the ratio between the ADC input voltage and the corresponding DC bus
voltage.
47/148
Getting started with the library UM0492
48/148
UM0492 Getting started with the library
49/148
Getting started with the library UM0492
Alignment settings:
Quadrature encoder is a relative position sensor. Considering that absolute information is
required for performing field oriented control, it is necessary to somehow establish a 0°
position. This task is performed by means of an alignment phase, and is carried out at first
motor startup and after any fault event. It basically consists in imposing a null reference
torque (Iq) and a reference flux (Id) with a linearly increasing magnitude and a constant
orientation.
If properly configured, at the end of this phase, the rotor is locked in a well-known position
and the encoder timer counter is initialized accordingly.
50/148
UM0492 Getting started with the library
The following parameters are used to customize the alignment phase depending on the
motor inertia and load conditions:
● T_ALIGNMENT in milliseconds defines the desired duration of the alignment phase
● ALIGNMENT_ANGLE specifies the vector orientation (angle θ in the below diagram)
θ0
a
d
c
ai14833
● I_ALIGNMENT (in digits) defines the final value of the reference Id magnitude. With
STM3210B-MCKIT and with ALIGNMENT_ANGLE set to 90° (default), the final phase A
current value can be computed by using the formula:
Alignment final phase A current = (I_ALIGNMENT * 0.64)/(32767*Rshunt)
51/148
Getting started with the library UM0492
52/148
UM0492 Getting started with the library
● #define HALL_MAX_OVERFLOWS
This is the maximum number of consecutive timer overflows taken into account. It is set
by default to 2: if the timer overflows more than twice (meaning that the Hall sensor
period has been increased by a factor of at least two between two consecutive valid
edges), the number of overflows is not counted anymore. This usually indicates that
information has been lost (Hall sensor timeout) or that speed is decreasing very
sharply. The corresponding timeout delay depends on the selected timer prescaler,
which is variable; the higher the prescaler (low speed), the longer the timeout period
(see also Section 5.7)
● #define HALL_SPEED_FIFO_SIZE
This is the length of the software FIFO in which the latest speed measurements are
stored. This stack is necessary to compute rolling averages on several consecutive
pieces of data.
– Av is the gain of the amplifying network (Av = 2.57 on the MB459B kit board)
– Rshunt is the shunt resistance (in Ohms)
● #define K1
K1 (signed 32-bit value) is an element of the gain vector of the implemented state
observer (as described in Section 2.2). An “a priori” determination of K1 can be made
using the formulas given in Section A.5. When the motor is running, this initial value
can then be tuned using the LCD interface and evaluating the results. In that case, the
value of K1 read on the display is 10 times smaller.
● #define K2
K2 (signed 32-bit value) is an element of the gain vector of the implemented state
observer (as described in Section 2.2). An “a priori” determination of K2 can be made
using the formulas given in Section A.5. When the motor is running, this initial value
53/148
Getting started with the library UM0492
can then be tuned using the LCD interface and evaluating the results. In that case, the
value of K2 read on the display is 100 times smaller.
● #define PLL_KP_GAIN
The default formula provides an “a priori” determination of the phase detector gain of
the PLL. Nonetheless, this (signed 16-bit) value can be tuned when the motor is
running, by using the LCD interface and evaluating the results. If necessary, the default
value can be overwritten with a more suitable one.
● #define PLL_KI_GAIN
The default formula provides an “a priori” determination of the loop filter gain of the
PLL. Nonetheless, this (signed 16-bit) value can be tuned when the motor is running by
using the LCD interface and evaluating the results. If necessary, the default value can
be overwritten with a more suitable one.
● #define F1, #define F2
These coefficients (signed 16-bit values) help amplify the observer equations, so that
motor winding resistance and inductance can give a valuable contribution.
Maximum value is 215 = 32768
Note: Depending on several system parameters (motor parameters, state observer parameters,
sampling frequency, current and voltage conversion parameters), compilation errors [Pe068]
or/and [Pe069] may occur in the MC_State_Observer_Interface.c source file. In that
case, the user should follow the procedure below to solve the problem:
1 Jump to the code line where the error was reported and see which Cx factor (x=1..5) caused
the issue.
2 Go to the definition of that Cx factor (in MC_State_Observer_param.h) and assess
whether F1 or F2 is involved.
3 Decrease F1 or F2 accordingly, always choosing positive powers of two.
54/148
UM0492 Getting started with the library
● #define FREQ_START_UP_DURATION
In milliseconds, defines the overall time allowed for startup.
● #define FINAL_START_UP_SPEED
In RPM, defines the speed of the rotating stator flux, and hence of the rotor, at the end
of the overall time allowed for startup (this parameter sets the slope of the frequency
linear ramp-up).
● #define FIRST_I_STARTUP
In digits, defines the initial amplitude of the three-phase current system according to
the formula below:
I(Amps) ⋅ R shunt ⋅ A ν ⋅ 65536
I(digit) = -----------------------------------------------------------------------------------
-
3.3
● #define FINAL_I_STARTUP
In digits, defines the final amplitude of the three-phase current system according to the
above formula. This amplitude should be chosen to generate an electromagnetic
torque Te that matches the estimated load applied.
● #define I_STARTUP_DURATION
In milliseconds, defines the time allowed to increase current amplitude linearly from
initial to final amplitude.
● #define MINIMUM_SPEED_RPM
In RPM, defines the minimum speed at which the startup procedure may end (if the
rotor speed / position detection is considered reliable) to make way for normal
operations.
Depending on the user's application requirements, a rotor alignment or pre-positioning
55/148
Getting started with the library UM0492
phase can be performed before each motor startup. This additional feature is activated
as an option by properly configuring stm32f10x_MCconf.h (see Section 4.1).
In this case, the following parameters should be selected to achieve the expected
behavior:
– #define SLESS_T_ALIGNMENT
In milliseconds, defines the desired duration of the alignment phase.
– #define SLESS_ALIGNMENT_ANGLE
specifies the vector orientation (angle θ in Figure 34)
– #define SLESS_I_ALIGNMENT
Defines (in digits) the final value of the reference Id magnitude. With STM3210B-
MCKIT and with SLESS_ALIGNMENT_ANGLE set to 90° (default), the final phase A
current value can be computed by using the formula:
Alignment final phase A current = (SLESS_I_ALIGNMENT × 0.64)/(32767 × Rshunt)
56/148
UM0492 Getting started with the library
57/148
Getting started with the library UM0492
58/148
UM0492 Getting started with the library
● DC bus to ADC conversion factor; it defines the ratio between the ADC input voltage
and the corresponding DC bus voltage, cell B12
59/148
Getting started with the library UM0492
As a result of data processing, the following information can be obtained from the
spreadsheet:
● #define CONSTANT1_Q
The user can copy it from cell B25
● #define CONSTANT1_D
The user can copy it from cell B26
● #define CONSTANT2
The user can copy it from cell B27
60/148
UM0492 Library functions
5 Library functions
61/148
Library functions UM0492
SVPWM_3ShuntInit
62/148
UM0492 Library functions
SVPWM_3ShuntCurrentReadingCalibration
SVPWM_3ShuntGetPhaseCurrentValues
63/148
Library functions UM0492
SVPWMEOCEvent
SVPWMUpdateEvent
SVPWM_3ShuntCalcDutyCycles
64/148
UM0492 Library functions
SVPWM_3ShuntAdvCurrentReading
65/148
Library functions UM0492
X ≤0 X>0 X ≤0 X>0
Sector V IV III VI I II
The duration of the positive pulse widths for the PWM applied on Phase A, B and C are
respectively computed by the following relationships:
Sector I, IV: t A = T + X – Z- , t = t + Z , t = t – X
---------------------- B A C B
2
Sector II, V: t A = T + Y – Z- , t = t + Z , t = t – Y
---------------------- B A C A
2
66/148
UM0492 Library functions
5.1.3 Current sampling in three shunt topology and general purpose A/D
conversions
The three currents I1, I2, and I3 flowing through a three-phase system follow the
mathematical relation:
I1 + I2 + I3 = 0
For this reason, to reconstruct the currents flowing through a generic three-phase load, it is
sufficient to sample only two out of the three currents while the third one can be computed
by using the above relation.
The flexibility of the STM32F103xx A/D converter makes it possible to synchronously
sample the two A/D conversions needed for reconstructing the current flowing through the
motor. The ADC can also be used to synchronize the current sampling point with the PWM
output using the external triggering capability of the peripheral. Owing to this, current
conversions can be performed at any given time during the PWM period. To do this, the
control algorithm uses the fourth PWM channel of TIM1 to synchronize the start of the
conversions.
Injected conversions, as described above, are used for current-reading purposes whereas
regular conversions are reserved for the user. As soon as the injected A/D conversions for
current-reading purposes have completed, bus voltage and temperature sensing are also
simultaneously converted by the dual A/D.
Figure 38 shows the synchronization strategy between the TIM1 PWM output and the ADC.
The A/D converter peripheral is configured so that it is triggered by the rising edge of
TIM1_CH4.
67/148
Library functions UM0492
OCR 4 OCR 4
OCR 1 OCR 1
OCR 2 OCR 2
OCR 3 OCR 3
TIM1_CH1 TIM1_CH1
TIM1_CH2 TIM1_CH2
TIM1_CH4 TIM1_CH4
Sampling point before counter overflow Sampling point after counter overflow
ai14835
In this way, supposing that the sampling point must be set before the counter overflow, that
is, when the TIM1 counter value matches the OCR4 register value during the upcounting,
the A/D conversions for current sampling are started. If the sampling point must be set after
the counter overflow, the PWM 4 output has to be inverted by modifying the CC4P bit in the
TIM1_CCER register. In so doing, when the TIM1 counter matches the OCR4 register value
during the downcounting, the A/D samplings are started.
After the first two simultaneous conversions other two simultaneous conversions are started,
one for the bus voltage and the other for the temperature sensing. At the end of the second
conversion, the three-phase load current has been updated and the FOC algorithm can then
be executed in the A/D end of injected conversion interrupt service routine (JEOC ISR).
After execution of the FOC algorithm, the value to be loaded into the OCR4 register is
calculated to set the sampling point for the next PWM period, and the A/D converter is
configured to sample the correct channels.
Regular conversions are reserved for user purposes and must be configured manually (See
also firmware standard library user manual UM0427).
68/148
UM0492 Library functions
5.1.4 Tuning delay parameters and sampling stator currents in three shunt
resistor topology
Figure 39 shows one of the three inverter legs with the related shunt resistor:
To indirectly measure the phase current I, it is possible to read the voltage V providing that
the current flows through the shunt resistor R.
It is possible to demonstrate that, whatever the direction of current I, it always flows through
the resistor R if transistor T2 is switched on and T1 is switched off. This implies that in order
to properly reconstruct the current flowing through one of the inverter legs, it is necessary to
properly synchronize the conversion start with the generated PWM signals. This also means
that current reading cannot be performed on a phase where the duty cycle applied to the low
side transistor is either null or very short.
Fortunately, as discussed in Section 5.1.3,to reconstruct the currents flowing through a
generic three-phase load, it is sufficient to simultaneously sample only two out of three
currents, the third one being computed from the relation given in Section 5.1.3. Thus,
depending on the space vector sector, the A/D conversion of voltage V will be performed
only on the two phases where the duty cycles applied to the low side switches are the
highest. In particular, by looking at Figure 37, you can deduct that in sectors 1 and 6, the
voltage on the Phase A shunt resistor can be discarded; likewise, in sectors 2 and 3 for
Phase B, and finally in sectors 4 and 5 for Phase C.
Moreover, in order to properly synchronize the two stator current reading A/D conversions, it
is necessary to distinguish between the different situations that can occur depending on
PWM frequency and applied duty cycles.
Note: The explanations below refer to space vector sector 4. They can be applied in the same
manner to the other sectors.
69/148
Library functions UM0492
Case 1: Duty cycle applied to Phase A low side switch is larger than
DT+TN
Where:
● DT is dead time.
● TN is the duration of the noise induced on the shunt resistor voltage of a phase by the
commutation of a switch belonging to another phase.
● TS is the sampling time of the STM32F103xx A/D converter (the following consideration
is made under the hypothesis that TS < DT + TN). Refer to the STM32F103xx reference
manual for more detailed information.
This case typically occurs when SVPWM with low (<60%) modulation index is generated
(see Figure 40). The modulation index is the applied phase voltage magnitude expressed as
a percentage of the maximum applicable phase voltage (the duty cycle ranges from 0% to
100%).
Figure 41 offers a reconstruction of the PWM signals applied to low side switches of Phase
A and B in these conditions plus a view of the analog voltages measured on the
STM32F103xx A/D converter pins for both Phase B and C (the time base is lower than the
PWM period).
Note that these current feedbacks are constant in the view in Figure 41 because it is
assumed that commutations on Phase B and C have occurred out of the visualized time
window.
Moreover, it can be observed that in this case the two stator current sampling conversions
can be performed synchronized with the counter overflow, as shown in Figure 41.
70/148
UM0492 Library functions
ai14836b
Case 2: (DT+TN+TS)/2 < ΔDutyA < DT+TN and ΔDutyAB < DT+TR+TS
With the increase in modulation index, ΔDutyA can have values smaller than DT+TN.
Sampling synchronized with the counter overflow could be impossible.
In this case, the two currents can still be sampled between the two Phase A low side
commutations, but only after the counter overflow.
Consider that in order to avoid the acquisition of the noise induced on the phase B current
feedback by phase A switch commutations, it is required to wait for the noise to be over (TN).
See Figure 42.
Figure 42. (DT+TN+TS)/2 < ΔDutyA < DT+TN and ΔDutyAB < DT+TR+TS
ai14837b
71/148
Library functions UM0492
Phase A high-side switch-off. The choice was therefore made to sample the currents TS µs
before of phase A high-side switch-off (see Figure 43).
ai14838b
ai14839b
72/148
UM0492 Library functions
The following parameters have been set as default in the firmware. They are related to the
MB459 board:
● DT = 0.8 µs
● TN = 2.55 µs
● TS = 0.7 µs
● TR = 2.55 µs
The maximum applicable duty cycles are listed in Table 2 as a function of the PWM
frequency.
The values in Table 2 are measured using the MB459 board. This evaluation platform is
designed to support several motor driving topologies (PMSM and AC induction) and current
reading strategies (single- and three-shunt resistor). Therefore, the figures provided in
Table 2 should be understood as a starting point and not as a best case.
Table 2. PWM frequency vs. maximum duty cycle relationship for three-shunt
topology
PWM frequency Max duty cycle Max modulation Index
It is possible to adjust the noise parameters based on customized hardware by editing the
following definitions in the MC_pwm_3shunt_prm.h header file:
#define SAMPLING_TIME_NS 700 //0.7usec
#define TNOISE_NS 2550 //2.55usec
#define TRISE_NS 2550 //2.55usec
Changing the noise parameters, sampling time and dead time affects the values provided in
Table 2.
73/148
Library functions UM0492
SVPWM_1ShuntInit
74/148
UM0492 Library functions
SVPWM_1ShuntCurrentReadingCalibration
SVPWM_1ShuntGetPhaseCurrentValues
ADC sample 1 IA
Get current Stator current AB
IB
values
ADC sample 2 IC
Sampling current 1
Sampling current 2
ai15133
75/148
Library functions UM0492
SVPWM_1ShuntCalcDutyCycles
Synopsis void SVPWM_1ShuntCalcDutyCycles (Volt_Components
Stat_Volt_Input);
Description After executing the FOC algorithm, the new stator voltage
components, Vα and Vβ, are computed. The purpose of this function is
to calculate the three exact duty cycles to be applied to the inverter
legs, starting from the values of these voltage components.
Moreover, once the three duty cycles to be applied during the next
PWM period are known, this function performs the following tasks:
● Gets stator flux position (regular or boundary zone 1, 2 or 3)
● Computes the PWM channel that must be distorted and updates
the value of duty cycle registers
● Computes the sampling point and the related sampled phase
● Sets the preload variables for PWM mode Ch 1,2,3,4.
See Figure 46. Refer to Section 5.2.2 for information on the theoretical
approach to single-shunt current reading.
Input Vα and Vβ.
Returns None.
Note None.
Functions called None.
Duty A Regular
Stator SVM Calc Duty B GetStator
Boundary 1
voltage aβ Duty FluxPos
Duty C Boundary 2
Boundary 3
Duty A*
PWMDuty Duty B* SetSampling Sampling point 1
adj points Sampling point 2
Duty C*
ai15134
76/148
UM0492 Library functions
SVPWM_1ShuntAdvCurrentReading
SVPWMEOCEvent
SVPWMUpdateEvent
77/148
Library functions UM0492
T4 T5 T6
iA iB iC
VBUS T1 T2 T3
Three PWM
TIM1 output channels
ADC1
OC4Ref used
as external trigger
ADC2
ai15135
It is possible to demonstrate that for each configuration of the low-side switches, the current
through the shunt resistor is given in Table 3. T4, T5 and T6 assume the complementary
values of T1, T2 and T3, respectively.
In Table 3, the value “0” means that the switch is open whereas the value “1” means that the
switch is closed.
0 0 0 0
0 1 1 iA
0 0 1 -iC
1 0 1 iB
1 0 0 -iA
1 1 0 iC
0 1 0 -iB
1 1 1 0
Using the centered-aligned pattern, each PWM period is subdivided into 7 subperiods (see
Figure 48). During three subperiods (I, IV, VII) the current through the shunt resistor is zero.
During the other subperiods, the current through the shunt resistor is symmetrical with
respect to the center of the PWM.
78/148
UM0492 Library functions
For the conditions showed in Figure 48, there are two pairs:
● subperiods II and VI, during which iShunt is equal to –iC
● subperiods III and V, during which iShunt is equal to iA
So under these conditions, it is possible to reconstruct the three-phase current through the
motor from the sampled values:
● iA is iShunt measured during subperiod III or V
● iC is -iShunt measured during subperiod II or VI
● iB = –iA – iC
T1
T2
T3
iA iA
iShunt
–iC –iC
ai15136
But if the stator-voltage demand vector lies in the boundary space between two space
vector sectors, two out of the three duty cycles will assume approximately the same value.
In this case, the seven subperiods are reduced to five subperiods.
Under these conditions, only one current can be sampled, the other two cannot be
reconstructed. This means that it is not possible to sense both currents during the same
PWM period, when the imposed voltage demand vector falls in the gray area of the space
vector diagram represented in Figure 49.
I II III IV V I II III IV V β
V3 V2
T1 T1
T2 T2
V4 V1
α
T3 T3
iA iA
ai15137
Similarly, for a low modulation index, the three duty cycles assume approximately the same
value. In this case, the seven subperiods are reduced to three subperiods. During all three
subperiods, the current through the shunt resistor is zero. This means that it is not possible
to sense any current when the imposed voltage vector falls in the gray area of the space-
vector diagram represented in Figure 50.
79/148
Library functions UM0492
T2
V4 V1
α
T3
iShunt
V5 V6
ai15138
T1
T2
Dead T3
time iA iA
iShunt
–iC
–iC
Sampling time
TRise
80/148
UM0492 Library functions
The voltage-demand vector lies in a region called the Regular region when the three duty
cycles (calculated by space vector modulation) inside a PWM pattern differ from each other
by more than DMIN. This is represented in Figure 52.
ai15140
The voltage-demand vector lies in a region called Boundary 1 when two of the duty cycles
differ from each other by less than DMIN, and the third is greater than the other two and
differs from them by more than DMIN. This is represented in Figure 53.
ai15141
The voltage-demand vector lies in a region called Boundary 2 when two duty cycles differ
from each other by less than DMIN, and the third is smaller than the other two and differs
from them by more than DMIN. This is represented in Figure 54.
ai15142
The voltage-demand vector lies in a region called Boundary 3 when the three PWM signals
differ from each other by less than DMIN. This is represented in Figure 55.
81/148
Library functions UM0492
ai15143
5.2.4 Performance
The following parameters have been set as default in the firmware. They are related to the
MB459 board:
● DT = 0.8 µs
● TR = 1.5 µs
● TS = 0.7 µs
The maximum applicable duty cycles are listed in Table 4 as a function of the PWM
frequency.
Table 4. PWM frequency vs. maximum duty cycle relationship for single-shunt
topology
PWM frequency Max duty cycle Max modulation index Min REP_RATE
82/148
UM0492 Library functions
83/148
Library functions UM0492
SVPWM_IcsInit
SVPWM_IcsCurrentReadingCalibration
84/148
UM0492 Library functions
SVPWM_IcsGetPhaseCurrentValues
SVPWM_IcsCalcDutyCycles
85/148
Library functions UM0492
SVPWMEOCEvent
SVPWMUpdateEvent
86/148
UM0492 Library functions
PWM Counter
Compare A
Compare B
Low side A
Low side B
Phase current
Average current
87/148
Library functions UM0492
FOC_Init
88/148
UM0492 Library functions
FOC_Model
89/148
Library functions UM0492
FOC_CalcFluxTorqueRef
90/148
UM0492 Library functions
Functions PID_Regulator;
called
if working with encoder:
ENC_Get_Mechanical_Speed;
if working with Hall sensors:
HALL_GetSpeed;
if working in sensorless mode:
STO_Get_Speed_Hz;
If FLUX_WEAKENING is enabled (library configuration file):
FOC_FluxRegulator;
FOC_FluxRegulator_Update;
If IPMSM_MTPA is enabled:
FOC_MTPA;
if FEED_FORWARD_CURRENT_REGULATION is enabled:
FOC_FF_CurrReg.
FOC_TorqueCtrl
91/148
Library functions UM0492
FOC_MTPA
FOC_FluxRegulator
92/148
UM0492 Library functions
FOC_FF_CurrReg
FOC_MTPAInterface_Init
93/148
Library functions UM0492
FOC_MTPA_Init
FOC_FluxRegulatorInterface_Init
FOC_FluxRegulator_Init
94/148
UM0492 Library functions
FOC_FluxRegulator_Update
FOC_FF_CurrReg_Init
95/148
Library functions UM0492
These functions implement three variable changes that are required to carry out field-
oriented control (FOC):
● Clarke transforms stator currents to a stationary orthogonal reference frame (named αβ
frame, see Figure 57);
● then, from that arrangement, Park transforms currents to a frame that rotates at an
arbitrary speed (which, in PMSM field-oriented control, is synchronous with the rotor);
● Reverse Park transformation brings back stator voltages from a rotating frame (q, d) to
a stationary one.
The module also includes a function to calculate trigonometric functions (sine and cosine),
and a function to correct the voltage vector command (the so-called “Circle limitation”).
ω
i bs Clarke Park q
iq
a iα α
i as
i cs iβ
id
c
β d
ω
vq q Reverse Park
vα α
v
vd β
d β
ai14841
96/148
UM0492 Library functions
Clarke
Park
Rev_Park
97/148
Library functions UM0492
Rev_Park_Circle_Limitation
Trig_Functions
98/148
UM0492 Library functions
angle (s16)
32767
0 π 2π angle (radians)
-32768
ai14842
32767
cosine sine
-32768
0 32767 angle (s16)
-32767
ai14843
99/148
Library functions UM0492
cos θ cos ⎛⎝ θ – 2π
------⎞⎠ cos ⎛⎝ θ + ------
2π⎞
f qx 3 3⎠ f ax
2
f qdox = f dx = --- × sin θ sin ⎛ θ – 2π
------⎞ sin ⎛ θ + 2π
------⎞ f bx
3 ⎝ 3⎠ ⎝ 3⎠
f 0x f cx
1 1 1
--- --- ---
2 2 2
where θ is the angular displacement of the (q, d) reference frame at the time of observation,
and θ 0 that displacement at t=0 (see Figure 60).
Figure 60. Transformation from an abc stationary frame to a rotating frame (q, d)
ω
f bx
θ0
f ax a
f cx
ai14844
With Clark’s transformation, stator currents ias and ibs (which are directed along axes each
displaced by 120 degrees) are resolved into currents iα and iβ on a stationary reference
frame (α β).
100/148
UM0492 Library functions
In Park’s change of variables, stator currents iα and iβ, which belong to a stationary
reference frame (α β), are resolved to a reference frame synchronous with the rotor and
oriented so that the d-axis is aligned with the permanent magnets flux, so as to obtain iqs
and ids.
Consequently, with this choice of reference, we have:
i qs = i α cos θ r – i β sin θ r
i ds = i α sin θ r + i β cos θ r
On the other hand, reverse Park transformation takes back stator voltage vq and vd,
belonging to a rotating frame synchronous and properly oriented with the rotor, to a
stationary reference frame, so as to obtain vα and vβ:
ν α = ν qs cos θ r + ν ds sin θ r
ν β = – ν qs sin θ r + ν ds cos θ r
101/148
Library functions UM0492
r *
V
r
V Vq*
Vq
Vd Vd*
r2
r1
r1 S16_MAX
r2 MMI S16_MAX
ai14845
Vd and Vq represent the saturated stator voltage components to be passed to the Reverse
Park transformation function, while Vd* and Vq*are the outputs of the PID current controllers.
From geometrical considerations, it is possible to draw the following relationship:
*
v d ⋅ MMI ⋅ S16_MAX
v d = -----------------------------------------------------------
*
v
*
v q ⋅ MMI ⋅ S16_MAX
v q = -----------------------------------------------------------
*
v
In order to speed up the computation of the above equations while keeping an adequate
resolution, the value
2
MMI ⋅ S16_MAX -
------------------------------------------------
*
v
*
is computed and stored in a look-up table for different values of v . Furthermore,
considering that MMI depends on the selected PWM frequency, a number of look-up tables
are stored in MC_Clarke_Park.c (with MMI ranging from 91 to 100).
Once you have selected the required PWM switching frequency, you should uncomment the
Max Modulation Index definition corresponding to the selected PWM frequency in the
MC_Control_Param.h definition list shown below.
//#define MAX_MODULATION_100_PER_CENT // up to 11.4 kHz PWM frequency
//#define MAX_MODULATION_99_PER_CENT // up to 11.8 kHz PWM frequency
//#define MAX_MODULATION_98_PER_CENT // up to 12.2 kHz PWM frequency
//#define MAX_MODULATION_97_PER_CENT // up to 12.9 kHz PWM frequency
//#define MAX_MODULATION_96_PER_CENT // up to 14.4 kHz PWM frequency
//#define MAX_MODULATION_95_PER_CENT // up to 14.8 kHz PWM frequency
//#define MAX_MODULATION_94_PER_CENT // up to 15.2 kHz PWM frequency
//#define MAX_MODULATION_93_PER_CENT // up to 16.7 kHz PWM frequency
//#define MAX_MODULATION_92_PER_CENT // up to 17.1 kHz PWM frequency
//#define MAX_MODULATION_91_PER_CENT // up to 17.5 kHz PWM frequency
For information on selecting the PWM switching frequency, you will find advice in
Section A.2 on page 136. To determine the max modulation index corresponding to the
PWM switching frequency, refer to Table 2 on page 73 and Table 4 on page 82. As said
102/148
UM0492 Library functions
before, if ICSs are used, it is allowed to select a 100% MMI, regardless of the chosen PWM
frequency.
ENC_Init
ENC_Get_Electrical_Angle
103/148
Library functions UM0492
ENC_Get_Mechanical_Angle
ENC_ResetEncoder
ENC_Clear_Speed_Buffer
ENC_Get_Mechanical_Speed
104/148
UM0492 Library functions
ENC_Calc_Average_Speed
ENC_ErrorOnFeedback
ENC_Start_Up
105/148
Library functions UM0492
HALL_HallTimerInit
106/148
UM0492 Library functions
HALL_GetRotorFreq
HALL_GetSpeed
107/148
Library functions UM0492
HALL_InitHallMeasure
HALL_IsTimedOut
HALL_GetElectricalAngle
108/148
UM0492 Library functions
HALL_IncElectricalAngle
HALL_Init_Electrical_Angle
HALL_ClrTimeOut
Synopsis HALL_ClrTimeOut
Description This function sets to FALSE the boolean variable containing the
timeout error flag indicating that information was lost, or speed is
decreasing sharply.
Functions called None
Input None
Returns None
109/148
Library functions UM0492
H2 H3
H1
H1
H2 H2
H3 H3
State5 –> State1 –> State 3 –> State1 –> State3 –> State 7 –>
State2 –> State6 –> State 4 –>... State6 –> State4 –> State 0 –>... ai14846
Consequently, it is possible to reconstruct the rolling direction of the rotor by comparing the
present state with the previous one, and considering that in presence of a positive speed,
the sequence must be the one illustrated in Figure 62.
Period measurement
Although the principle for measuring a period with a timer is quite simple, it is important to
keep the best resolution, in particular for signals, such as the one under consideration, that
can vary with a ratio that can easily reach 1:1000.
In order to always have the best resolution, the timer clock prescaler is constantly adjusted
in the current implementation.
The basic principle is to speed up the timer if the captured values are too low (for an
example of short periods, see Figure 63), and to slow it down when the timer overflows
between two consecutive captures (see example of large periods in Figure 64).
110/148
UM0492 Library functions
0xFFFF
0x5500
0x0000
Prescaler (preload) 30 29 29 29
Prescaler (active) 30 30 29 29
Transfer from preload to active on
next capture (= update) event
0xFFFF
ovf ovf
Timer overflowed, the
prescaler is increased
0x5500
0x0000
Prescaler (preload) 30 31 31 31
Prescaler (active) 30 30 31 31
The prescaler modification is done in the capture interrupt, taking advantage of the buffered
registers: the new prescaler value is taken into account only on the next capture event, by
the hardware, without disturbing the measurement.
Further details are provided in the flowchart shown in Figure 65, which summarizes the
actions taken into the TIMx_IRQHandler.
111/148
Library functions UM0492
112/148
UM0492 Library functions
3 sensors 120˚
H1
120˚
N S
H2 H3
H1
H2
H3
ai14847
For this reason, in the proposed solution, the electrical angle is synchronized every time an
IC occurs with an angle depending on the present state on the Hall sensor output, spinning
direction and PHASE_SHIFT (see also Section 3.12 for indications on how to measure it).
Furthermore, the utilization of the FOC algorithm implies the need for a good and constant
rotor position accuracy, including between two consecutive falling edges of the XORed
signal (which occurs each 120 electrical degrees). For this reason it is clearly necessary to
somehow interpolate rotor electrical angle information. For this purpose, the latest available
speed measurement in dpp format is added to the present electrical angle software variable
value any time the FOC algorithm is executed.
113/148
Library functions UM0492
STO_Init
114/148
UM0492 Library functions
STO_StateObserverInterface_Init
STO_Obs_Gains_Update
STO_Calc_Rotor_Angle
115/148
Library functions UM0492
STO_Calc_Speed
STO_InitSpeedBuffer
STO_Get_Electrical_Angle
STO_Get_Mechanical_Angle
116/148
UM0492 Library functions
STO_Get_Speed
STO_Get_Speed_Hz
STO_IsSpeed_Reliable
STO_Check_Speed_Reliability
117/148
Library functions UM0492
STO_Start_Up
STO_Get_wIalfa_est
STO_Get_wIbeta_est
STO_Get_wBemf_alfa_est
118/148
UM0492 Library functions
STO_Get_wBemf_beta_est
STO_Gains_Init
STO_Gains_Update
119/148
Library functions UM0492
PID_Init
PID_Regulator
120/148
UM0492 Library functions
PID_Speed_Coefficients_update
f ( X T ) = K p × Error sys + K i ×
T ∑Errorsys + Kd × ( Errorsys
t T
– Error sys
T–1
) (1)
0
121/148
Library functions UM0492
t d Error
Time domain f ( t ) = K p × Error sys ( t ) + K i × ∫ 0
Error sys ( t )dt + K d ×
dt
( sys ( t ) )
In theory, the higher the sampling rate, the better the regulation. In practice, you must keep
in mind that:
● The related CPU load will grow accordingly.
● For speed regulation, there is absolutely no need to have a sampling time lower than
the refresh rate of the speed information fed back by the external sensors; this
becomes especially true when Hall sensors are used while driving the motor at low
speed.
As discussed in Section 4.2 on page 46, the speed regulation loop sampling time can be
customized by editing the PID_SPEED_SAMPLING_TIME parameter in the
MC_Control_Param.h header file. The flux and torque PID regulator sampling rates are
given by the relationship
⋅ PWM_FREQ-
Flux and torque PID sampling rate = 2
--------------------------------------------
REP_RATE + 1
Note: REP_RATE must be an odd number if currents are measured by shunt resistors (see also
Section A.2 on page 136); its value is 8-bit long.
122/148
UM0492 Library functions
5.9.4 Adjusting speed regulation loop Ki, Kp and Kd vs. motor frequency
Depending on the motor frequency, it might be necessary to use different values of Kp, Ki
and Kd.
These values have to be input in the code to feed the regulation loop algorithm. A function
performing linear interpolation between four set-points
(PID_Speed_Coefficient_update) is provided as an example in the software library
(see MC_PID_regulators.c) and can be used in most cases, as long as the coefficient
values can be linearized. If that is not possible, a function with a larger number of set-points
or a look-up table may be necessary.
To enter the four set-points, once the data are collected, edit the MC_Control_param.h
file and fill in the field dedicated to the Ki, Kp and Kd coefficient calculation as shown below.
//Settings for min frequency
#define Freq_Min 10 // 1 Hz mechanical
#define Ki_Fmin 1000 // Frequency min coefficient settings
#define Kp_Fmin 2000
#define Kd_Fmin 3000
Once the motor is running, integer, proportional and derivative coefficients are computed
following a linear curve between F_min and F_1, F_1 and F_2, F_2 and F_max (see
Figure 69). Note that F_min, F_1, F_2, F_max are mechanical frequencies, with 0.1 Hz
resolution (for example F_1 = 1234 means F_1 = 123.4Hz).
123/148
Library functions UM0492
Ki_Fmax, Kp_Fmax
Kd_Fmax
Rotor mechanical
F_min F_1 F_2 F_max frequency
124/148
UM0492 Library functions
125/148
Library functions UM0492
TB_Init
TB_Wait
TB_Set_Delay_500us, TB_Set_DisplayDelay_500us,
TB_Set_StartUp_Timeout, TB_Set_DebounceDelay_500us
126/148
UM0492 Library functions
TB_StartUp_Timeout_IsElapsed, TB_Delay_IsElapsed,
TB_DisplayDelay_IsElapsed, TB_DebounceDelay_IsElapsed
SysTickHandler
127/148
Library functions UM0492
MCL_Init
128/148
UM0492 Library functions
MCL_ChkPowerStage
MCL_ClearFault
MCL_SetFault
129/148
Library functions UM0492
MCL_Chk_OverTemp
MCL_Chk_BusVolt
MCL_Compute_BusVolt
MCL_Compute_Temp
Synopsis u8 MCL_Compute_Temp(void)
Description This function computes the power stage heat-sink temperature in Celsius
degrees (only for MB459 board). In the proposed firmware library this
function is utilized for user interfacing.
Input None
Returns An integer representing a temperature value expressed in Celsius degrees.
130/148
UM0492 Library functions
MCL_Calc_BusVolt
MCL_Calc_BusVolt
MCL_Init_Arrays
MCL_Brake_Init
131/148
Library functions UM0492
MCL_Set_Brake_On
MCL_Set_Brake_Off
132/148
UM0492 Library functions
TIM1_BRK_IRQHandler
TIM1_UP_IRQHandler
133/148
Library functions UM0492
ADC1_2_IRQHandler
134/148
UM0492 Additional information
Figure 70. AD conversions for three shunt topology stator currents reading and
FOC algorithm execution when REP_RATE=3 and PWM frequency>18 kHz
PWM Period
Note: Because three shunt resistor topology requires low side switches to be on when performing
current reading A/D conversions, the REP_RATE parameter must be an odd number in this
case.
Considering that the raw FOC algorithm execution time is about 20 µs in sensorless and
three shunt resistor current reading configuration, the related contribution to CPU load
can be computed as follows:
F PWM –6 F PWM –6
CPU Load % = ------------------------------------- ⋅ 20 ⋅ 10 ⋅ 100 = -------------------------------------------------------- ⋅ 20 ⋅ 10 ⋅ 100
Refresh_Rate ( REP_RATE + 1 ) ⁄ 2
135/148
Additional information UM0492
Figure 71. AD conversions for three shunt topology stator currents reading and
FOC algorithm execution
New duty cycles ready before next U event, OK New duty cycles not ready before next U
event, necessary to increase REP_RATE
PWM Period
U U U U U U
REP_RATE = 1 REP_RATE = 1
ADC triggering interval FOC algorithm execution New duty cycle values ready
ai14848
In the three-shunt resistor configuration, considering that as seen in Section 5.1.4, the ADC
conversions are triggered latest (DT+TN-TS)/2 after the TIM1 counter overflow, and
considering the time required for the A/D converter to perform injected conversions, it can
been stated that the FOC algorithm is started about 5 µs after the TIM1 counter overflow
(worst case). Furthermore, given that the execution time of the FOC algorithm is around
20 µs, in sensorless configuration, to compute the new duty cycle values before the next
update event, it is necessary to guarantee a minimum duty cycle period of about
(5 + 20) × 2 µs, that is, a maximum achievable FOC execution rate of about 20 kHz. The
repetition counter (REP_RATE) can therefore be set to 1.
For PWM frequencies higher than 20 kHz, the repetition counter must be set to 3
(REP_RATE= 3). If PWM frequencies higher than 17.5 kHz are used, please see
Section 5.5.3 to calculate a suitable MMI for MC_Control_Param.h.
136/148
UM0492 Additional information
For single-shunt current reading, see Table 4: PWM frequency vs. maximum duty cycle
relationship for single-shunt topology on page 82 for the minimum repetition rate (A.8: MMI
(maximum modulation index): automatic calculation explains how to calculate the MMI
(maximum modulation index) for given PWM frequency and noise parameters.).
bit n. 7 6 5 4 3 2 1 0
value -4 2 1 1/2 1/4 1/8 1/16 1/32
This software library uses the PU (“Per Unit”) system to express current values. They are
always referred to a base quantity that is the maximum measurable current Imax (which, for
the proposed hardware, can be estimated approximately at Imax = 0.6 / Rshunt); so, the “per
unit” current value is obtained by dividing the physical value by that base:
iS .I .
i PU =
I max
In this way, ipu is always in the range from -1 to +1. Therefore, the q1.15 format, which
ranges from -1 to 0.999969482421875, with a resolution of 0.000030517578125, is perfectly
suitable (taking care of the overflow value (-1)·(-1)=1) and thus extensively used.
Thus, the complete transformation equation from SI units is:
i S.I.
i q1.15 = floor ⎛⎝ ----------- ⋅ 2 ⎞⎠
QF
I max
137/148
Additional information UM0492
Target Voltage
+ e + command
current
KP
- +
1
KI
Measured
current
s
ai14850
For this analysis, the motor electrical characteristics are assumed to be isotropic with
respect to the q and d axes. So, it is assumed that the torque and flux regulators have the
same starting value of KP, and that they also have the same KI value.
Figure 73 shows the closed loop system in which the motor phase is modelled using the
resistor-inductance equivalent circuit in the “locked-rotor” condition.
Block “A” is the proportionality constant between the software variable storing the voltage
command (expressed in digit) and the real voltage applied to the motor phase (expressed in
Volt). Likewise, block “B” is the is the proportionality constant between the real current
(expressed in Ampere) and the software variable storing the phase current (expressed in
digit).
Target Voltage 1
+ e + command
V I
current
KP A Rs (1 + s
Ls
)
- + Rs
1
KI
Measured
current
s
B
Microcontroller Motor
ai14851
138/148
UM0492 Additional information
The transfer functions of the two blocks “A” and “B” are expressed by the following formulas:
16
V Bus DC R shunt A op 2
A = ---------------------
- and B = -----------------------------------
- , respectively.
16 3.3
2
Target Voltage
+ e V 1 I
current KI KP command
s
(1 + s
KI
)
A Rs (1 + s
Ls
)
- Rs
Measured
current
B
ai14852
In this condition, the closed loop system is brought back to a first-order system and the
dynamics of the system can be assigned using a proper value of KI. See Figure 75.
Figure 75. Block diagram of closed loop system after pole-zero cancellation
Target V I
+
current KII
K 1
1
ss A Rs
Rs
- Target
current
1
1
. 1
1
current I
B
B Rs
R s
1+
1 s s
K IAB
K
I
AB
B ai14853
It is important to note that the KI and KP parameters used inside the PI algorithms will be
scaled using the proper divider. The KPDIV and KiDIV dividers are defined in
MC_Control_Param.h (like TF_KPDIV, TF_KIDIV, TF_KDDIV) so the computed values of KP
and KI must be multiplied by these factors.
Moreover the PI algorithm does not include the PI sampling time (T) in the computation of
the integral part. See the following formula:
t n n
k i ∫ e ( τ ) dτ = k i T ∑ e ( kT ) = Ki ∑ e ( kT )
0 k=1 k=1
Since the integral part of the controller is computed as a sum of successive errors, it is
required to include T in the KI computation.
C ω
So the final formula can be expressed as: K P = L S -------
- K P DIV
AB
R S ⋅ ωC ⋅ K i DIV
K i = --------------------------------------------- ⋅ T
AB
V Bus DC ⋅ R shunt ⋅ A op
AB = ----------------------------------------------------------------
3.3
139/148
Additional information UM0492
Usually, it is possible to set ωC (the bandwidth of the closed loop system) to 1500 rad/s, to
obtain a good trade-off between dynamic response and sensitivity to the measurement
noise.
The Aop measured for the MB459 is 2.57. It is then possible to compute the values of the
parameters knowing the motor parameters (RS, LS), VBUSDC and RShunt.
140/148
UM0492 Additional information
141/148
Additional information UM0492
e2 = 1
142/148
UM0492 Additional information
143/148
Additional information UM0492
It is then possible to generate the new MMI vs. PWM frequency table.
To do so, in the Maximum modulation index configuration tool window (Figure 78), set the
minimum PWM frequency of the table in the Fpwm lower limit field, set the maximum PWM
frequency of the table in the Fpwm upper limit field and set the frequency step used to
calculate the table in the Step field. Then press the MMI vs. PWM freq button and the
dialog box shown in Figure 79 will appear.
The generated values can be copied and pasted into the MC_Control_Param.h file. The
selected PWM frequency must then be uncommented.
144/148
UM0492 Additional information
A.9 References
● [1] P. C. Krause, O. Wasynczuk, S. D. Sudhoff, Analysis of Electric Machinery and Drive
Systems, Wiley-IEEE Press, 2002.
● [2] T. A. Lipo and D. W. Novotny, Vector Control and Dynamics of AC Drives, Oxford
University Press, 1996.
● [3] S. Morimoto, Y. Takeda, T. Hirasa, K. Taniguchi, “Expansion of Operating Limits for
Permanent Magnet Motor by Optimum Flux-Weakening”, Conference Record of the
1989 IEEE, pp. 51-56 (1989).
● [4] J. Kim, S. Sul, “Speed control of Interior PM Synchronous Motor Drive for the Flux-
Weakening Operation”, IEEE Trans. on Industry Applications, 33, pp. 43-48 (1997).
● [5] M. Tursini, A. Scafati, A. Guerriero, R. Petrella, “Extended torque-speed region
sensor-less control of interior permanent magnet synchronous motors”, ACEMP'07, pp.
647 - 652 (2007).
● [6] M. Cacciato, G. Scarcella, G. Scelba, S.M. Billè, D. Costanzo, A. Cucuccio,
“Comparison of Low-Cost-Implementation Sensorless Schemes in Vector Controlled
Adjustable Speed Drives”, SPEEDAM '08, Applied Power Electronics Conference and
Exposition (2008).
145/148
Revision history UM0492
Revision history
146/148
UM0492 Revision history
147/148
UM0492
Information in this document is provided solely in connection with ST products. STMicroelectronics NV and its subsidiaries (“ST”) reserve the
right to make changes, corrections, modifications or improvements, to this document, and the products and services described herein at any
time, without notice.
All ST products are sold pursuant to ST’s terms and conditions of sale.
Purchasers are solely responsible for the choice, selection and use of the ST products and services described herein, and ST assumes no
liability whatsoever relating to the choice, selection or use of the ST products and services described herein.
No license, express or implied, by estoppel or otherwise, to any intellectual property rights is granted under this document. If any part of this
document refers to any third party products or services it shall not be deemed a license grant by ST for the use of such third party products
or services, or any intellectual property contained therein or considered as a warranty covering the use in any manner whatsoever of such
third party products or services or any intellectual property contained therein.
UNLESS OTHERWISE SET FORTH IN ST’S TERMS AND CONDITIONS OF SALE ST DISCLAIMS ANY EXPRESS OR IMPLIED
WARRANTY WITH RESPECT TO THE USE AND/OR SALE OF ST PRODUCTS INCLUDING WITHOUT LIMITATION IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE (AND THEIR EQUIVALENTS UNDER THE LAWS
OF ANY JURISDICTION), OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT.
UNLESS EXPRESSLY APPROVED IN WRITING BY AN AUTHORIZED ST REPRESENTATIVE, ST PRODUCTS ARE NOT
RECOMMENDED, AUTHORIZED OR WARRANTED FOR USE IN MILITARY, AIR CRAFT, SPACE, LIFE SAVING, OR LIFE SUSTAINING
APPLICATIONS, NOR IN PRODUCTS OR SYSTEMS WHERE FAILURE OR MALFUNCTION MAY RESULT IN PERSONAL INJURY,
DEATH, OR SEVERE PROPERTY OR ENVIRONMENTAL DAMAGE. ST PRODUCTS WHICH ARE NOT SPECIFIED AS "AUTOMOTIVE
GRADE" MAY ONLY BE USED IN AUTOMOTIVE APPLICATIONS AT USER’S OWN RISK.
Resale of ST products with provisions different from the statements and/or technical features set forth in this document shall immediately void
any warranty granted by ST for the ST product or service described herein and shall not create or extend in any manner whatsoever, any
liability of ST.
Information in this document supersedes and replaces all information previously supplied.
The ST logo is a registered trademark of STMicroelectronics. All other names are the property of their respective owners.
148/148