STM32F103xx ACIM IFOC Software Library UM
STM32F103xx ACIM IFOC Software Library UM
User manual
STM32F103xx
AC induction motor IFOC software library V2.0
Introduction
This user manual describes the AC induction motor IFOC software library, an indirect field
oriented control (IFOC) firmware library for 3-phase induction motors developed for the
STM32F103xx microcontrollers.
These 32-bit, ARM Cortex™-M3 cored ST microcontrollers (STM32F103xx) come with a set
of peripherals which makes it suitable for performing both permanent magnet and AC
induction motors FOC. In particular, this manual describes the STM32F103xx software
library developed to control AC induction motors equipped with an encoder or
tachogenerator, in both open and closed loop. The control of a permanent magnet (PM)
motor in sinewave mode with encoder/hall sensors or sensorless is described in the
UM0492 user manual.
The AC IM IFOC software 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 an AC
induction motor, a motor can be made to run in a very short time. It also eliminates the need
for time-consuming development of IFOC and speed regulation algorithms by providing
ready-to-use functions that let the user concentrate on the application layer.
A prerequisite for using this library is basic knowledge of C programming, AC 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
ai14767
Contents
4 Library functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2/112
UM0483 Contents
3/112
Contents UM0483
4/112
UM0483 List of tables
List of tables
5/112
List of figures UM0483
List of figures
6/112
UM0483 List of figures
7/112
UM0483
Related documents
Available on www.st.com:
● STM32F103xx datasheet
● ‘ARM®-based 32-bit MCU STM32F101xx and STM32F103xx, firmware library’ user
manual
● ‘STM32F103xx Flash programming’ manual
Available on www.arm.com:
● Cortex-M3 Technical Reference Manual
8/112
UM0483 Getting started with tools
To develop an application for an AC induction motor using the AC IM IFOC 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.
9/112
Getting started with tools UM0483
1.3.1 Updates
The complete source files are available free of charge from STMicroelectronics on request.
Please, contact your nearest ST sales office or support team.
Note: 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 web sites to automatically obtain updates.
The STM32 FOC Firmware Libraries v2.0 folder contains the firmware libraries for running
3-phase AC induction motors (with sensors) and 3-phase PMSM motors (with sensors or
sensorless).
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, the EWARM, RVMDK, MULTI folders contain the configuration files for the
respective toolchains.
10/112
UM0483 Getting started with tools
11/112
Getting started with the library UM0483
ωr* + iqs*
Torque controller
3-phase
3-phase
FOC induction
– inverter
motor
ai14787
Basic information on field oriented structure and library functions is represented in Figure 5.
● The θλr calculation block estimates rotor flux angle, which is essential to transformation
blocks (park, reverse park) to perform field orientation, so that the currents supplied to
the machine can be oriented in phase and in quadrature to the rotor flux vector. More
detailed information about the reference frame theory and FOC structure is available in
Section 4.5.3 on page 68.
● The space vector PWM block (SVPWM) implements an advanced modulation method
that reduces current harmonics, thus optimizing DC bus exploitation.
● The current reading block allows the system to measure stator currents correctly, using
either cheap shunt resistors or market-available isolated current hall sensors (ICS).
● The speed-reading block handles tachogenerator or incremental encoder signals in
order to acquire properly rotor angular velocity or position.
12/112
UM0483 Getting started with the library
Iqs
Park T. iα, iβ Clarke ia, ib Current
Ids reading
θλr Speed
calculation reading
ai14787
13/112
Getting started with the library UM0483
14/112
UM0483 Getting started with the library
the update repetition rate based on PWM frequency for single or three-shunt resistor
configurations on page 102 for details).
In fact, because there is no reason for either executing the IFOC algorithm without updating
the stator currents values or for performing stator current conversions without running the
IFOC algorithm, in the proposed implementation the stator current sampling frequency and
the IFOC algorithm execution rate coincide.
15/112
Getting started with the library UM0483
the hysteresis, fixed at 4 °C. When the heatsink temperature exceeds the fixed threshold, an
overheat fault event is validated and the motor is stopped.
● #define OVERVOLTAGE_THRESHOLD
● #define UNDERVOLTAGE_THRESHOLD
These two values establish the minimum and maximum limits for the input bus DC voltage
(the default ones refer to MB459 included in the STM3210B-MCKIT kit and correspond to
19 V for the lower voltage and 350 V for the maximum voltage). If the bus voltage exceeds
the upper threshold an overvoltage fault event is validated. If the bus voltage is below the
lower threshold an undervoltage fault event is triggered. If either of the two faults occurs, the
motor is stopped and the display shows an error message.
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 PWM frequency for single or
three-shunt resistor configurations on page 102 for details); its value is 8-bit long;
16/112
UM0483 Getting started with the library
17/112
Getting started with the library UM0483
18/112
UM0483 Getting started with the library
● #define TIMER3_HANDLES_TACHO
To be uncommented if tachogenerator-based speed measurement is performed by
TIMER3.
● #define TIMER4_HANDLES_TACHO
To be uncommented if tachogenerator-based speed measurement is performed by
TIMER4.
● #define TACHO_INPUT_TI1
To be uncommented if sensor output signal is wired to TimerX Input Capture 1
(TIMx_CH1 pin). (Default - in conjunction with TIMER2 choice; required if using
STM3210B-MCKIT).
● #define TACHO_INPUT_TI2
To be uncommented if sensor output signal is wired to TimerX Input Capture 2.
● #define MAX_SPEED_FDBK
This parameter defines the frequency above which speed feedback is not realistic in
the application: this allows to discriminate glitches for example. The unit is 0.1Hz. By
default, it is set to 6400 (640.0Hz), which corresponds to approximately 20000 RPM for
a two pole pair motor.
● #define MAX_SPEED
This parameter is the value returned by the function TAC_GetRotorFreqInHz if
measured speed is greater than MAX_SPEED_FDBK. The default value is 640Hz, but
it can be 0 or FFFF depending on how this value is managed by the upper layer
software.
● #define MAX_PSEUDO_SPEED
This parameter is the value returned by the function TAC_GetRotorFreq if measured
speed is greater than MAX_SPEED_FDBK. The unit is rad/pwm period
(2π rad = 0xFFFF). See Section 4.8.4: Converting Hertz into pseudo frequency on
page 88 for more details.
● #define MIN_SPEED_FDBK
This parameter is the frequency below which speed feedback is not realistic in the
application: this allows to discriminate too low frequency. This value is set to 1 Hz by
default, and depends on sensor and signal conditioning stage characteristics. Typically,
the tacho signal is too weak at very low speed to trigger input capture on the MCU.
Note: The MC_tacho_prm.h file includes two formulas that allow to compute the minimum sensed
speed when speed is increasing (during startup) or decreasing (during motor stop).
● #define MAX_RATIO
Maximum possible TIMER clock prescaler ratio:
– This defines the lowest speed that can be measured (when counter = 0xFFFF).
– It also prevents the clock prescaler from decreasing excessively when the motor is
stopped. (This prescaler is automatically adjusted during each and every capture
interrupt to optimize the timing resolution).
19/112
Getting started with the library UM0483
● #define MAX_OVERFLOWS
This is the maximum number of consecutive timer overflows taken into account. It is set
by default to 10: if the timer overflows more than 10 times (meaning that the tacho
period has been increased by a factor of 10 at least), the number of overflows is not
counted anymore. This usually indicates that information is lost (tacho time-out) or that
the speed is decreasing very sharply. The corresponding duration depends on the
tacho timer prescaler, which is variable; the higher the prescaler (at low speed), the
longer the timeout period.
● #define 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
data.
L L m + L lr
τ r = -----r = -------------------
-
rr rr
where Lm is the magnetizing inductance, Llr is the rotor leakage inductance, Lr is the
rotor inductance, rr is the rotor resistance.
● #define POLE_PAIR_NUM
Define here the stator winding pole pair number;
● #define RATED_FREQ
Define here (in 0.1Hz) the right-hand boundary of the constant torque region (see
Figure 6): in that region we have rated current, rated flux, rated torque, rated power.
● #define NOMINAL_FLUX
Define here the required magnetizing current im (positive, peak value), expressed in
q1.15 format (see Section A.3 on page 104).
● #define NOMINAL_TORQUE
Defines the maximum value for the motor’s rated torque expressed in q1.15 format.
20/112
UM0483 Getting started with the library
The following parameters are required only to enter the field weakening operation (constant
power region begins beyond the RATED_FREQ boundary mentioned above):
● #define FLUX_REFERENCE_TABLE: this look-up table (256 signed 16-bit values)
provides reference values of current ids (expressed in q1.15 format), according to
increasing stator frequencies (see Section 4.5.4 on page 70);
Note: The first element of the table should have the same value as the NOMINAL_FLUX
parameter.
● TORQUE_REFERENCE_TABLE: this look-up table (256 signed 16-bit values) provides
saturation values of current iqs (expressed in q1.15 format), according to increasing
stator frequencies (see Section 4.5.4 on page 70).
21/112
Running the demo program UM0483
This section assumes that you are using the STM3210B-MCKIT motor control kit.
The demo program is intended to provide examples on how to use the software library
functions; it includes both Torque control and Speed control operations, with the possibility
of varying different parameters on the fly.
The default configuration allows the use of three shunt resistor for stator current reading and
tacho generator for speed feedback. Refer to Section 3.4 on page 30 for setting up the
system in the single-shunt configuration, to Section 3.5 on page 30 for setting up the system
when using ICSs, and to Section 3.6 on page 32 if using a quadrature incremental encoder.
After the MCU initialization phase, the LCD graphical display shows the main window. Use
the joystick and the button labelled KEY to navigate between the menus.
Key assignments are shown in Figure 7.
A simple state machine handles the motor control tasks in the main loop, as well as basic
monitoring of the power stage. This state machine does not differentiate Torque control
mode from Speed control mode. It is described in Figure 8.
The power stage is monitored using the ADC peripheral and the TIM1 peripheral break input
(BKIN) to watch the following conditions:
● Heatsink overtemperature (ADC channel ADC_IN10 and BKIN input),
● DC bus over/undervoltage (on ADC channel ADC_IN3),
● Overcurrent protection (BKIN input).
Any of these three conditions causes the TIM1 motor control outputs (PWM signals) to be
stopped and the state machine to go into Fault state until the user presses the joystick key.
After the user has pressed the key, the state machine goes into Idle state (only if the cause
of the fault does not persist anymore). Depending on the source of the fault, an error
message is also displayed on the LCD during Fault state.
22/112
UM0483 Running the demo program
Button pushed
Init Idle
Fault condition
Initialization over and joystick
key pressed Motor
still
Hardware or startup fault
Start Fault
Hardware
fault Wait
Start OK
Button Run
pushed
1 s delay
elapsed
Button
pushed
Stop
ai14768
In this condition, by moving in the joystick up/down, the active Control mode is selected (in
this example, Torque control). After sending the Start motor command (by pressing the Joy
or Key keys) this parameter can no longer be accessed until the motor is stopped.
23/112
Running the demo program UM0483
From the previous screen (Figure 9), if the joystick is moved to the right, the Target Iq current
component is selected. The parameter can now be changed by moving the joystick
up/down. After sending the Start motor command, the Target Iq can be changed in runtime
while the measured Iq current component is shown in the Feedback field.
From the previous screen (Figure 10), if the joystick is moved to the right, the Target Id
current component becomes selected. The parameter can now be changed by moving the
joystick up/down. After the Start motor command, the target can be changed in runtime
while the measured Id current component is shown in the Feedback field.
Together, the Target Iq and Id currents constitute the reference inputs for two PID
controllers: one to control the current component of the motor torque and the other, to
control the magnetizing current component Id. Two additional menus allow the user to
change up to three parameters for each PID in runtime. Figure 12 shows an example
screenshot used to enter the proportional term P of the torque controller.
24/112
UM0483 Running the demo program
Figure 12. LCD screen to set the P term of the Torque PID
Finally press either the Key button or the joystick to stop the motor (main state machine
moves from Run to Stop state).
The ramp up strategy is illustrated in Figure 13. Basically, the actual torque reference
reaches the final Target Iq value (set with the joystick) in the time interval specified in the
STARTUP_RAMP_DURATION parameter (defined in MC_Control_Param.h) by following a
linear ramp.
After STARTUP_RAMP_DURATION, if valid information from the speed sensor (tachometer or
encoder) is detected, the torque reference becomes adjustable on the fly from the joystick.
On the contrary, if no valid information from the speed sensor is detected, for example
because a problem occurred with speed sensor connections or because the load torque is
higher then the value that you set, then the final torque reference is kept constant until
STARTUP_TIMEOUT.
Finally, when no valid speed information comes from the motor and STARTUP_TIMEOUT is
elapsed, the main state machine goes into FAULT state for two seconds and the error
message ‘Startup failed’ is displayed on the LCD. In this case, it is strongly advised to check
speed sensor feedback connections first and then, if necessary, to increase the final ramp
torque reference in case the load torque is too high.
Caution: In Torque control mode operation, a constant torque reference is produced. Depending on
the load torque applied, this could lead to constant acceleration of the motor, making the
speed rise up to the motor’s physical limits.
25/112
Running the demo program UM0483
From the menu screen shown in Figure 9, it is possible to switch from Torque control to
Speed control mode operations (and vice versa) by moving the joystick up (or down) when
the motor is stopped.
From the menu screen shown in Figure 14, moving the joystick to the right selects the Target
speed. The parameter can then be incremented/decremented by moving the joystick
up/down, respectively. The motor is then started by pressing the joystick. With the motor on,
it is still possible to modify the target speed while checking its actual value in the Feedback
field.
Figure 16, Figure 17 and Figure 18 show the three PID screens from which the coefficient
parameters can be entered. The screens also display the targets and feedbacks for each
value of speed, torque and flux.
From the screens shown in Figure 16, Figure 17 and Figure 18, move the joystick left or
right to alternately select the P, I or D coefficients (when present). The selected coefficient
can then be changed (incremented or decremented) by moving the joystick up/down.
26/112
UM0483 Running the demo program
Figure 17. LCD screen to set the P term of the Torque PID
Figure 18. LCD screen to set the P term of the Flux PID
Finally, although you cannot directly act on torque and flux references, both the target and
measured flux and torque stator current components can be observed. In fact, in closed
loop, both flux and torque references are the outputs of the speed PID regulator and field
weakening blocks.
As in Torque control mode, pressing the joystick or the Key button starts the motor.
The Speed control ramp-up strategy is shown in Figure 19. Basically, a linear torque ramp is
applied to the motor until it reaches speed TACHO_SPEED_VAL (if a tacho speed sensor is
27/112
Running the demo program UM0483
used) or ENCODER_CL_ENABLE (if an encoder is used). Then, the speed PID regulator is
enabled and takes control of the torque reference.
However, if the motor does not reach the above mentioned speeds before
STARTUP_RAMP_DURATION, the final torque reference value (STARTUP_FINAL_TORQUE)
is further applied until STARTUP_TIMEOUT. Finally, in the case where the speeds that
enable the Speed control are not reached before STARTUP_TIMEOUT, the state machine
goes into Fault state for a few seconds and the error message Startup failed is displayed on
the LCD. In this case, it is strongly advised to check speed sensor feedback connections first
and then, if necessary, to increase STARTUP_FINAL_TORQUE if the load torque is too high.
With reference to Figure 19, note that parameters TACHO_SPEED_VAL,
ENCODER_CL_ENABLE, STARTUP_FINAL_TORQUE, STARTUP_RAMP_DURATION, and
STARTUP_TIMEOUT are fully configurable so that you can customize the startup depending
on the motor and load conditions. Parameters definitions are done in the
MC_Control_Param.h header file.
28/112
UM0483 Running the demo program
firmware can be graphically traced in the time domain at the current control loop frequency.
Moreover, when the DAC functionality is enabled, it is possible to choose the two variables
to check by using a menu screen on the LCD display. Figure 20 shows the corresponding
menu screen.
As usual, by pushing on the joystick key (to the right/left), it is possible to navigate between
the two DAC channels PB0 and PB1, and then, to change the variables to be output by
moving the key up/down. 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 2.2.2 for details).
The list below shows all the IFOC values that can be selected for each channel:
● Measured rotor speed (measured rotor speed)
● Measured el. angle (measured electrical angle position of rotor flux)
● Vβ (Reverse Parke voltage component)
● Vα (Reverse Parke voltage component)
● Vd (flux PID controller output voltage component)
● Vq (torque PID controller output voltage component)
● Id ref (flux command)
● Iq ref (torque command)
● Id (measured flux component)
● Iq (measured torque component)
● Iβ (Clarke current component)
● Iα (Clarke current component)
● Ib (stator current component b)
● Ia (stator current component a)
For the meaning of each value, please, refer to Section 2.1 where the theory of the IFOC
algorithm is treated. 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);
29/112
Running the demo program UM0483
MCDAC_Update_Value(USER_2,variable_name2);
...
These variables are shown in output if “User 1” or “User 2” is selected on the display.
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
Figure 21. MB459B power board setup for the single-shunt topology
W4 W4
W5 W5
W10 W10
(Three shunt) (Single shunt)
ai15153
30/112
UM0483 Running the demo program
31/112
Running the demo program UM0483
In addition, rotor angular velocity can be easily calculated as a time derivative of angular
position.
To set up the AC IM IFOC 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 2.2.1 on page 14 and Section 2.2.3 on page 18 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.
32/112
UM0483 Running the demo program
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, you can apply the
following procedure:
1. Set the DC source at low voltage (50V).
2. Run the system in closed loop operation, and on the LCD, observe the target and
measured speeds.
The error occurs if the sign of the measured speed is opposite to the sign of the target
speed. (For help with the LCD menus see Section 3.2 on page 26):.
3. If the error occurs, you can correct it by simply swapping and rewiring the encoder
output signals.
If this isn’t practical, you can modify a software setting instead: in the
stm32f10x_encoder.c file, replace the code line:
TIM_EncoderInterfaceConfig(ENCODER_TIMER, TIM_EncoderMode_TI12,
TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);
by
TIM_EncoderInterfaceConfig(ENCODER_TIMER, TIM_EncoderMode_TI12,
TIM_ICPolarity_Rising, TIM_ICPolarity_Falling);
33/112
Running the demo program UM0483
34/112
UM0483 Running the demo program
permanent damage to the power stage and/or motor. A dedicated bit in the DBGMCU_SR
register, the DBG_TIM1_STOP bit, must be set to 1 (see Figure 26).
If the DBG_TIM1_STOP bit is set (Safe mode), the timer is frozen and PWM outputs are
shut down. This is a Safe state for the inverter. The timer can still be restarted from where it
stopped.
If the DBG_TIM1_STOP bit is reset (Normal mode), the timer continues to operate normally,
which may prove dangerous in some cases since a constant duty cycle is applied to the
inverter (interrupts not serviced).
In the main.c module the DBGMCU_Config(DBGMCU_TIM1_STOP, ENABLE) function
performs the above described task.
Figure 26. 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
35/112
Library functions UM0483
4 Library functions
4.2.1 Overview
Two important tasks are performed in the stm32f10x_svpwm_3shunt module:
● Space vector pulse width modulation (SVPWM)
● Current reading in three shunt resistor topology
In order to reconstruct the currents flowing through a three-phase load with the required
accuracy using three shunt resistors, it is necessary to properly synchronize A/D
conversions with the generated PWM signals. This is why the two tasks are included in a
single software module.
36/112
UM0483 Library functions
SVPWM_3ShuntInit
37/112
Library functions UM0483
SVPWM_3ShuntCurrentReadingCalibration
SVPWM_3ShuntGetPhaseCurrentValues
38/112
UM0483 Library functions
SVPWM_3ShuntCalcDutyCycles
SVPWM_3ShuntAdvCurrentReading
SVPWMEOCEvent
39/112
Library functions UM0483
SVPWMUpdateEvent
40/112
UM0483 Library functions
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
41/112
Library functions UM0483
4.2.4 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 STM32F10xxx 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 A/D conversions for current-
reading purposes have completed, bus voltage and temperature sensing conversions are
simultaneously performed by the dual A/D.
Figure 29 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.
42/112
UM0483 Library functions
Counter overflow
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, before 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 sensor. 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).
43/112
Library functions UM0483
4.2.5 Tuning delay parameters and sampling stator currents in three shunt
resistor topology
Figure 30 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 4.2.4,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 4.2.4. 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 28, 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.
44/112
UM0483 Library functions
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 STM32F10xxx A/D converter (the following consideration
is made under the hypothesis that TS < DT + TN). Refer to the STM32F10xxx reference
manual for more detailed information.
This case typically occurs when SVPWM with low (<60%) modulation index is generated
(see Figure 31). 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 32 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
STM32F10xxx 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 32 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 32.
45/112
Library functions UM0483
TS
Current feedback
phase B Sampling start
Case 2: DT+(TN+TS)/2 < ΔDutyA < DT+TN and ΔDutyAB < DT+TR+TS
With the increase in modulation index, ΔDutyA can assume values smaller than DT+TN.
Sampling synchronized with the counter overflow could be impossible.
In this case, the two currents can be sampled between the two Phase A low side
commutations, 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 33.
Figure 33. DT+(TN+TS)/2 < ΔDutyA < DT+TN and ΔDutyAB < DT+TR+TS
ΔDutyA-B ΔDutyA
46/112
UM0483 Library functions
ΔDutyA-B
Low side phase A DT
Δ Duty A-B
Low side phase A DT
< TS
ai14839
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
47/112
Library functions UM0483
The maximum applicable duty cycles are listed in Table 2 as a function of the PWM
frequency.
Table 2. PWM frequency vs. maximum duty cycle relationship for three-shunt
topology
PWM frequency Max duty cycle Max modulation Index
Note: The values above were 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.
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.
48/112
UM0483 Library functions
SVPWM_1ShuntInit
49/112
Library functions UM0483
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
50/112
UM0483 Library functions
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 37. Refer to Section 4.3.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
51/112
Library functions UM0483
SVPWM_1ShuntAdvCurrentReading
SVPWMEOCEvent
SVPWMUpdateEvent
52/112
UM0483 Library functions
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 39). 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.
53/112
Library functions UM0483
For the conditions showed in Figure 39, 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
I II III IV V VI VII
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 40.
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
54/112
UM0483 Library functions
to sense any current when the imposed voltage vector falls in the gray area of the space-
vector diagram represented in Figure 41.
T2
V4 V1
α
T3
iShunt
V5 V6
ai15138
55/112
Library functions UM0483
T1
T2
Dead T3
time iA iA
iShunt
–iC
–iC
Sampling time
TRise
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 43.
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 44.
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 45.
56/112
UM0483 Library functions
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 46.
ai15143
4.3.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 = 2.55 µs
● TS = 0.7 µs
The maximum applicable duty cycles are listed in Table 4 as a function of the PWM
frequency.
57/112
Library functions UM0483
Table 4. PWM frequency vs. maximum duty cycle relationship for single-shunt
topology
PWM frequency Max duty cycle Max modulation index Min REP_RATE
4.4.1 Overview
Two important tasks are performed in the stm32f10x_svpwm_ics module.
● Space vector pulse width modulation (SVPWM),
● Three-phase current reading when two isolated current sensors (ICS) are used.
In order to reconstruct the currents flowing through a three phase load with the required
accuracy using two ICSs’, it is necessary to properly synchronize A/D conversions with the
generated PWM signals. This is why the two tasks are included in a single software module.
SVPWM_IcsInit
58/112
UM0483 Library functions
59/112
Library functions UM0483
SVPWM_IcsCurrentReadingCalibration
SVPWM_IcsGetPhaseCurrentValues
60/112
UM0483 Library functions
SVPWM_IcsCalcDutyCycles
SVPWMEOCEvent
SVPWMUpdateEvent
61/112
Library functions UM0483
PWM Counter
Compare A
Compare B
Low side A
Low side B
Phase current
Average current
ai14854
62/112
UM0483 Library functions
4.5.1 Overview
The MC_IFOC_Drive module, designed for AC induction machines, provides, at the core,
decoupled torque and flux regulation, relying on indirect field oriented control algorithm.
In addition, it makes available other important features:
● speed regulation by PID feedback control,
● flux weakening for extended speed range.
It works, requiring no adjustment, with all of the selectable current or speed sensing
configurations (in accordance with the settings in the stm32f10x_MCconf.h file):
● isolated current sensing (ICS)
● DC link single-shunt resistor current sensing
● three shunt resistors current sensing
● encoder position and speed sensing
● tachometer speed sensing
It handles several functions of other modules, and has no direct access on the
microcontroller peripheral registers.
IFOC_Init
63/112
Library functions UM0483
IFOC_Model
64/112
UM0483 Library functions
ids λ i im
im = dr = ds
Lm τrs + l
ai14790
65/112
Library functions UM0483
ids λ i im
im = dr = ds
Lm τrs + l
iqs l i ωsλr
ωsλr = × qs
τr im
ai14791
IFOC_CalcFluxTorqueRef
66/112
UM0483 Library functions
IFOC drive
Torque & flux optimization
Speed
reference ωr* + iqs** iqs*
ωr (profile PID
generator) IFOC model
– iqs
Flux max
ids*
optimization
ωr
3-phase
actual rotor speed ωr induction
Speed reading motor
ai14787
CalcIm
67/112
Library functions UM0483
CalcRotFlxSlipFreq
λr
λr λr dλqs λr
vqs = rs iqs + + ωλr λds
dt
λr
λ λ dλds λr
vds r = rs ids r + − ωλr λqs
dt
λr
dλqr
0 = rr iqr +
λr
dt
(
+ ωλr − ωr λdr ) λr
λr
dλ
0 = rr idr
λr
+ dr
dt
(
− ωλr − ωr λqr ) λr
where:
r r
(
λqs λ = Lls iqs λ + Lm iqs λ + iqr λ r r
)
λds λ = Lls ids λ + L (i )
λr λr
r r
m ds + idr
λqr λ = Llr iqr λ + L (i )
λr λr
r r
m qs + iqr
λdr λ = Llr idr λ + L (i )
λr λr
r r
m ds + idr
By choosing the phase of the reference system in such a way to arrange the rotor flux
exactly on the d-axis, we will have λqrλr = 0, λdrλr = λr..
With this choice, the electromagnetic torque can be written as:
3 p Lm λr λr
T e = --- × --- × ------- × ( λ dr ⋅ i qs )
2 2 Lr
68/112
UM0483 Library functions
i.e. as a product of a flux and a current component (P= number of stator poles).
Let us investigate further on the rotor flux λdrλr.
λr λr λr λr
Considering the d-axis rotor flux equation: λ dr = L lr i dr + L m ⋅ ( i ds + i dr )
λr λr
λr λ –L i
then, the equation for idrλr is: i dr = ----------------------------
dr m ds
Lr
Combining the latter with the d-axis rotor voltage equation, leads to:
λr
dλ dr rr λr λr
- + ----- × ( λ dr – L m i ds )
---------------
dt Lr
λr λr
d- λ dr 1 λ dr 1 λr
---- × -------- + ----- × -------- = ----- × i ds
dt L m τ r L m τr
On the other hand, under the same conditions, the q-axis rotor flux equation becomes:
λr λr λr λr
λ qr = L lr i qr + L m × ( i qs + i qr ) = 0
λr L λr
So, the equation for iqrλr is: i qr = – ------
m
- i qs
Lr
Combining the last with the q-axis rotor voltage equation, leads to:
λr
r r ⋅ i qr r r L m
ωsλ = ωλ r – ωr = – ---------------- - × i λqsr
- = ----- × -------
λr L λr
λ dr r λ dr
69/112
Library functions UM0483
70/112
UM0483 Library functions
In order to help you select the most suitable values of flux reference and torque saturation
(as needed by the CalcRotFlxSlipFreq function), a spreadsheet is available, to be filled out
with the following system parameters:
● Mains AC voltage, rms, Volt (cell B1, Volt);
● motor rated current, peak amplitude, (cell B2, Ampere); as said before, this data is to
be matched with inverter current rating;
● motor rated magnetizing current, peak amplitude, (cell B3, Ampere);
● magnetizing inductance Lm, (cell B4, Henry);
● leakage inductance Lls (Llr), (cell B5, Henry);
● stator resistance rs, (cell B6, Ohm)
● rotor resistance rr, (cell B7, Ohm);
● maximum measurable current Imax, peak amplitude, (cell B8, Ampere).
As a result of data processing, the following information can be obtained:
● highest frequency of constant torque region, i.e. the maximum allowable frequency
before entering field weakening; content of cell B13 should be inserted (as parameter
RATED_FREQ) in MC_ACMotor_Prm.h (see Section 2.2.5);.
● reference values of ids, in q1.15 format, according to increasing stator frequency;
column P should be copied (as FLUX_REFERENCE_TABLE) in MC_ACMotor_Prm.h.
● saturation values of current component iqs, in q1.15 format, according to increasing
stator frequency; column Q should be copied (as TORQUE_REFERENCE_TABLE) in
MC_ACMotor_Prm.h.
71/112
Library functions UM0483
4.6.1 Overview
This module, intended for AC machines (induction, synchronous and PMSM), is designed to
perform transformations of electric quantities between frames of reference that rotate at
different speeds.
Based on the arbitrary reference frame theory, the module provides three functions, named
after two pioneers of electric machine analysis, E. Clarke and R.H. Park.
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
(q,d), see Figure 52);
● then, from that arrangement, Park transforms currents to a frame that rotates at an
arbitrary speed (which, in IFOC drive, is synchronous with the rotor flux);
● Reverse Park transformation brings back stator voltages from a rotating frame (q,d) to a
stationary one.
● The module also includes a function to correct the voltage vector command (the so-
called “circle limitation”)
ibs
q
Clarke Park ω
a iq
ias iα α
ics
iβ id
c
d
β
Vq q Reverse Park
ω
iα α
Vd iβ
d
β ai14794
72/112
UM0483 Library functions
Clarke
Park
73/112
Library functions UM0483
Rev_Park
Rev_Park_Circle_Limitation
74/112
UM0483 Library functions
cos θ cos ⎛⎝ θ – 2π
------⎞⎠ cos ⎛⎝ θ – 2π
------⎞⎠
f qx 3 3 f ax
2
sin θ sin ⎛ θ – 2π
------⎞ sin ⎛ θ – ------
f qdox = f dx = --- × 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 53).
Figure 53. Transformation from an abc stationary frame to a rotating frame (q, d)
ω
fbx
θ0
fax a
fcx
d
c
ai14793
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.
Appropriate substitution into the general equations (given above) yields:
i α = i as
i as + 2i bs
i β = – ----------------------
-
3
In Park’s change of variables, stator currents iα and iβ, which belong to a stationary (α, β)
reference frame, are resolved to a rotor flux synchronous reference frame (properly
oriented), so as to obtain iqs and ids.
Consequently, with this choice of reference, ω = ωλr; thus:
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 rotor flux synchronous rotating frame, to a stationary reference frame, so as
to obtain vα and vβ:
v α = v qs cos θ r + v ds sin θ r
v β = – v qs sin θ r + v ds cos θ r
75/112
Library functions UM0483
and torque components of the stator current, have been independently computed by*flux
and torque PIDs, it is necessary to saturate the magnitude of the resulting vector ( V )
before passing them to the Reverse Park transformation and, finally, to the SVPWM block.
The saturation boundary is normally given by the value (S16_MAX=32767) which produces
the maximum output voltage magnitude (corresponding to a duty cycle going from 0% to
100%).
Nevertheless, when using a single- or three-shunt resistor configuration and depending on
PWM frequency, it might be necessary to limit the maximum PWM duty cycle to guarantee
the proper functioning of the stator currents reading block.
For this reason, the saturation boundary could be a value slightly lower than S16_MAX
depending on PWM switching frequency when using a single- or three-shunt resistor
configuration.
Table 2 on page 48 and Table 4 on page 58 show the maximum applicable modulation index
as a function of the PWM switching frequency when using the STM3210B-MCKIT in three-
and single-shunt topology, respectively. Appendix A.6: MMI (maximum modulation index):
automatic calculation explains how to calculate the MMI (maximum modulation index) for
given PWM frequency and noise parameters.
The RevPark_Circle_Limitation function performs the discussed stator voltage
components saturation, as illustrated in Figure 54.
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 component 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:
76/112
UM0483 Library functions
*
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 definitions 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
//#define MAX_MODULATION_98_PER_CENT // up to 12.2 kHz
//#define MAX_MODULATION_97_PER_CENT // up to 12.9 kHz
#define MAX_MODULATION_96_PER_CENT // up to 14.4 kHz
//#define MAX_MODULATION_95_PER_CENT // up to 14.8 kHz
//#define MAX_MODULATION_94_PER_CENT // up to 15.2 kHz
//#define MAX_MODULATION_93_PER_CENT // up to 16.7 kHz
//#define MAX_MODULATION_92_PER_CENT // up to 17.1 kHz
//#define MAX_MODULATION_91_PER_CENT // up to 17.5 kHz
For information on selecting the PWM switching frequency, you will find advice in
Section A.2 on page 102. To determine the max modulation index corresponding to the
PWM switching frequency, refer to Table 2 on page 48 and Table 4 on page 58. Appendix
A.6: MMI (maximum modulation index): automatic calculation explains how to calculate the
MMI (maximum modulation index) for given PWM frequency and noise parameters. As said
before, if ICSs are used, it is allowed to select a 100% MMI, regardless of the chosen PWM
frequency.
77/112
Library functions UM0483
78/112
UM0483 Library functions
ENC_Init
ENC_Get_Electrical_Angle
ENC_Get_Mechanical_Angle
79/112
Library functions UM0483
ENC_Clear_Speed_Buffer
ENC_Get_Mechanical_Speed
ENC_Calc_Average_Speed
ENC_ErrorOnFeedback
80/112
UM0483 Library functions
81/112
Library functions UM0483
TAC_TachoTimerInit
TAC_InitTachoMeasure
TAC_GetRotorFreqInHz
82/112
UM0483 Library functions
TAC_GetRotorFreq
GetLastTachoPeriod
GetAvrgTachoPeriod
83/112
Library functions UM0483
TAC_IsTimedOut
TAC_ClrTimeOut
TAC_GetCaptCounter
TAC_ClrCaptCounter
84/112
UM0483 Library functions
TAC_StartTachoFiltering
TAC_ValidSpeedInfo
85/112
Library functions UM0483
TIMx_IRQHandler
86/112
UM0483 Library functions
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 flowcharts in Section A.4 on page 105.
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
Figure 56 shows that the prescaler is not decreased although the captured value is below
0x5500, due to an overflow interrupt.
87/112
Library functions UM0483
0xFFFF
F pseudo = F [ 0.1Hz ] × -------------------------------------
10 × F pwm ( Hz )
4.9.1 Overview
The MC_PID_regulators module contains all the functions required to implement as
many instances of a PID regulator as required by the application, to control flux, torque and
motor speed (in case of Speed control mode)
Note: The differential terms are calculated as an option by uncommenting
DIFFERENTIAL_TERM_ENABLED in the library configuration file (Section 2.2.1).
An instance of a PID regulator is created by declaring and initializing a static variable that is
a structure of the PID_Struct_t type (see MC_type.h for structure declaration).
PID_Init
88/112
UM0483 Library functions
PID_Regulator
PID_Speed_Coefficients_update
89/112
Library functions UM0483
f ( X T ) = K p × Error sys + K i ×
T ∑Errorsys + Kd × ( Errorsys
t T
– Error sys
T–1
) (1)
0
90/112
UM0483 Library functions
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 a tacho-generator sensor is used while driving the motor
at low to medium speed.
As discussed in Section 2.2.2 on page 15, 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 102); its value is 8-bit long.
4.9.5 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.
91/112
Library functions UM0483
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 59). 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).
Ki_Fmax, Kp_Fmax
Kd_Fmax
Rotor mechanical
F_min F_1 F_2 F_max frequency
92/112
UM0483 Library functions
4.10.1 Overview
The stm32f10x_it module can be used to describe all the exception subroutines that might
occur within your application. When an interrupt happens, the software will automatically
branch to the corresponding routine accordingly with the interrupt vector table.
With the exception of the ADC, TIM1 update and TIM1 Break Input interrupt requests, all the
routines are empty, so that you can write your own code for exception handlers and
peripheral interrupt requests.
93/112
Library functions UM0483
TIM1_BRK_IRQHandler
TIM1_UP_IRQHandler
ADC1_2_IRQHandler
94/112
UM0483 Library functions
4.11.1 Overview
The purpose of the stm32f10x_Timebase module is to generate a time base that can be
used by the other modules of the applications.
TB_Init
TB_Wait
95/112
Library functions UM0483
TB_Set_Delay_500us, TB_Set_DisplayDelay_500us,
TB_Set_StartUp_Timeout, TB_Set_DebounceDelay_500µs
TB_StartUp_Timeout_IsElapsed, TB_Delay_IsElapsed,
TB_DisplayDelay_IsElapsed, TB_DebounceDelay_IsElapsed
96/112
UM0483 Library functions
SysTickHandler
4.12.1 Overview
This module brings together additional functions that take into account various tasks related
to preliminary motor operations like software initializations, ADC calibrations, parameter
monitoring, and critical fault checks and managements.
97/112
Library functions UM0483
MCL_Init
Note: When in Speed control mode, the Torque profile in this function is initialized for motor startup
settings.
See also Section 3.2: Speed control mode on page 26.
MCL_Init_Arrays
MCL_Chk_OverTemp
98/112
UM0483 Library functions
MCL_Chk_BusVolt
MCL_SetFault
MCL_ChkPowerStage
MCL_ClearFault
Note: This function checks for all the sources of fault handled by the Motor Control software, that is
is overcurrent (break event), Startup failure, speed feedback timeout, power stage
overtemperature and over/undervoltage on the DC bus.
99/112
Library functions UM0483
MCL_Compute_BusVolt
MCL_Compute_Temp
Synopsis u8 MCL_Compute_Temp(void)
Description This function computes the power stage heatsink temperature in Celsius
degrees.
Returns An integer representing a temperature value expressed in Celsius degrees.
100/112
UM0483 Additional information
Figure 60. AD conversions for three shunt topology stator currents reading and
IFOC algorithm execution when REP_RATE=3
PWM Period
U U U U
REP_RATE = 1
PWM Period
U U
REP_RATE = 3
101/112
Additional information UM0483
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 IFOC algorithm execution time is about 21 µs when in three shunt
resistor stator current reading configuration, the related contribution to CPU load can be
computed as follows:
F PWM –6 F PWM –6
CPU Load % = ------------------------------------- ⋅ 21 ⋅ 10 ⋅ 100 = -------------------------------------------------------- ⋅ 21 ⋅ 10 ⋅ 100
Refresh_Rate ( REP_RATE + 1 ) ⁄ 2
102/112
UM0483 Additional information
Figure 61. AD conversion intervals for three shunt topology stator currents reading
and IFOC algorithm execution
PWM Period
PWM Period
PWM Period
ADC triggering interval FOC algorithm execution New duty cycle values ready
ai14848
In the three-shunt resistor configuration, considered that as seen in Section 4.2.5, ADC
conversions are triggered latest (DT + TN – TS)/2 after the TIM1 counter overflow and,
considered the time required for the A/D converter to perform injected conversions, it can
been stated that the IFOC algorithm is started about 5 µs after the TIM1 counter overflow
(worst case). Furthermore, given that the raw execution time of the IFOC algorithm is
around 21 µs (three-shunt/tacho 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 + 21) × 2] µs. That means a maximum achievable IFOC execution rate of about 19
kHz. This allows to set the repetition counter (REP_RATE) equal to 1.
For a PWM frequency above 19 kHz, a repetition counter of 3 must be used (REP_RATE
= 3). In any case, if PWM frequencies higher than 17.5 kHz have to be used, please see
Section Section 4.2.5 to calculate a suitable MMI for MC_Control_Param.h.
For single-shunt current reading, see Table 4: PWM frequency vs. maximum duty cycle
relationship for single-shunt topology on page 58 for the minimum repetition rate selectable.
Appendix A.6: MMI (maximum modulation index): automatic calculation explains how to
calculate the MMI (maximum modulation index) for given PWM frequency and noise
parameters.
103/112
Additional information UM0483
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
104/112
UM0483 Additional information
Yes
No Yes
Index++ End of array? Index = 0
Figure 63. Processing captured value when timer did not overflow
Store capture value
No
No
Capture < 0x5500? Store current prescaler value
Yes
No
Store current prescaler value
Decrease prescaler register
Set flag indicating decrement for next
capture interrupt
105/112
Additional information UM0483
Does Capture
exceeds 16-bit Make it fit 16-bit by increasing PrscBuf
format?
Prescaler will
overflow?
106/112
UM0483 Additional information
Target Voltage
+ e + command
current
KP
- +
1
KI
Measured
current
s
ai14850
For this analysis, it is assumed that the driving strategy is isotropic with respect to the q and
d axis, so it can be assumed that the starting values of KP are the same for the torque
regulator and the flux regulator. The same assumption is done for KI coefficients.
Figure 66 shows the closed loop system in which the motor phase is modeled using the
“resistance-inductance” equivalent circuit in locked-rotor condition.
Block “A” converts the “Voltage command” software digital value into the applied stator
voltage V and block “B” converts the real motor current into the “Measured current” software
digital value.
Target Voltage 1
+ e + command
V I
current
KP A Rs (1 + s
Ls
)
- + Rs
1
KI
Measured
current
s
B
Microcontroller Motor
ai14851
The transfer functions of the two blocks “A” and “B” are expressed by the following formulas:
107/112
Additional information UM0483
16
V Bus DC R shunt A op 2
- and B = -----------------------------------
A = --------------------- - , 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 68.
Figure 68. 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_PID_regulators.c (like TF_KPDIV, TF_KIDIV, TF_KDDIV) so the computed values of KP
and KI must be multiplied by these factors.
Moreover, in the computation of the integral part, the PI algorithm does not include the PI
sampling time (T). 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 the sum of successive errors, it is
required to include T in computation of the KI.
C ω
So the final formula can be expressed as: KP = 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
108/112
UM0483 Additional information
For example it is possible to set ωC (the bandwidth of the closed loop system) equal to
1500 rad/s, so that the time constant of the current control system is 0.66 ms.
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.
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 69), 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 70 will appear.
109/112
Additional information UM0483
The generated values can be copied and pasted into the MC_Control_Param.h file. The
selected PWM frequency must then be uncommented.
A.7 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.
110/112
UM0483 Revision history
Revision history
111/112
UM0483
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.
112/112