0% found this document useful (0 votes)
52 views112 pages

STM32F103xx ACIM IFOC Software Library UM

Uploaded by

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

STM32F103xx ACIM IFOC Software Library UM

Uploaded by

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

UM0483

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.

Figure 1. Firmware architecture

Application layer

Speed, flux and IFOC drive


STM32F103xx torque PIDs User
standard interface
library Speed Current
feedback feedback SVPWM
STM32F103xx motor control library

STM32F103xx peripherals
ai14767

August 2008 Rev 2 1/112


www.st.com
Contents UM0483

Contents

1 Getting started with tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9


1.1 Working environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.2 Software tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.3 Library source code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3.1 Updates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3.2 File structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.4 Customizing the workspace for your STM32F103xx derivative . . . . . . . . 11

2 Getting started with the library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12


2.1 Introduction to AC induction motor FOC drive . . . . . . . . . . . . . . . . . . . . . 12
2.2 How to customize hardware and software parameters . . . . . . . . . . . . . . 13
2.2.1 Library configuration file: stm32f10x_MCconf.h . . . . . . . . . . . . . . . . 14
2.2.2 Drive control parameters: MC_Control_Param.h . . . . . . . . . . . . . . . . 15
2.2.3 Incremental encoder parameters: MC_encoder_param.h . . . . . . . . . 18
2.2.4 Tachogenerator parameters: MC_tacho_prm.h . . . . . . . . . . . . . . . . . . 18
2.2.5 AC induction motor parameters: MC_ACmotor_param.h . . . . . . . . . . 20

3 Running the demo program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22


3.1 Torque control mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.2 Speed control mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.3 Output IFOC variables using a 2-channel DAC . . . . . . . . . . . . . . . . . . . . 28
3.4 Setting up the system when in single-shunt topology and using the
MB459B power board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.5 Setting up the system when using ICSs . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.5.1 Connecting the two ICSs to the motor and to STM32F103xx . . . . . . . . 31
3.5.2 Selecting PHASE_A_ADC_CHANNEL and
PHASE_B_ADC_CHANNEL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.6 How to build the system when using an incremental encoder . . . . . . . . . 32
3.7 Fault messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.8 Actual values of DC bus voltage and IGBT heatsink temperature . . . . . . 34
3.9 Note on debugging tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

4 Library functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

2/112
UM0483 Contents

4.1 Function description conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36


4.2 Current reading in three shunt resistor topology and space
vector PWM generation: stm32f10x_svpwm_3shunt module . . . . . . . 36
4.2.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
4.2.2 List of available functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.2.3 Space vector PWM implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4.2.4 Current sampling in three shunt topology and general purpose A/D
conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.2.5 Tuning delay parameters and sampling stator currents in three shunt
resistor topology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.3 Current reading in single shunt resistor topology and space
vector PWM generation: stm32f10x_svpwm_1shunt module . . . . . . . 48
4.3.1 List of available functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.3.2 Current sampling in single-shunt topology . . . . . . . . . . . . . . . . . . . . . . . 53
4.3.3 Definition of the noise parameter and boundary zone . . . . . . . . . . . . . . 55
4.3.4 Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
4.4 Isolated current sensor reading and space vector PWM
generation: stm32f10x_svpwm_ics module . . . . . . . . . . . . . . . . . . . 58
4.4.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
4.4.2 List of available functions and interrupt service routines . . . . . . . . . . . . 58
4.4.3 Current sampling in isolated current sensor topology and integrating
general-purpose A/D conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
4.5 Induction motor IFOC vector control: MC_IFOC_Drive module . . . . . . . 63
4.5.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
4.5.2 List of available C functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
4.5.3 Detailed explanation about indirect field oriented control (IFOC) . . . . . 68
4.5.4 Detailed explanation about field weakening operation . . . . . . . . . . . . . . 70
4.6 Reference frame transformations: MC_Clarke_Park module . . . . . . . . 72
4.6.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
4.6.2 List of available C functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
4.6.3 Detailed explanation about reference frame transformations . . . . . . . . 74
4.6.4 Circle limitation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
4.7 Encoder feedback processing: stm32f10x_encoder module . . . . . . 78
4.7.1 List of available functions and interrupt service routines . . . . . . . . . . . . 78
4.8 Tachogenerator feedback processing: stm32f10x_tacho module . . . . 81
4.8.1 List of available functions and interrupt service routines . . . . . . . . . . . . 81
4.8.2 Integration tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
4.8.3 Operating principle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

3/112
Contents UM0483

4.8.4 Converting Hertz into pseudo frequency . . . . . . . . . . . . . . . . . . . . . . . . 88


4.9 PID regulators: MC_PID_regulators module . . . . . . . . . . . . . . . . . . . 88
4.9.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
4.9.2 List of available functions and interrupt service routines . . . . . . . . . . . . 88
4.9.3 PID regulator theoretical background . . . . . . . . . . . . . . . . . . . . . . . . . . 90
4.9.4 Regulator sampling time setting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
4.9.5 Adjusting speed regulation loop Ki, Kp and Kd vs. motor frequency . . . 91
4.10 Main interrupt service routines: stm32f10x_it module . . . . . . . . . . . . 93
4.10.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
4.10.2 List of non-empty interrupt service routines . . . . . . . . . . . . . . . . . . . . . . 93
4.11 General purpose time base: stm32f10x_Timebase module . . . . . . . . 95
4.11.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
4.11.2 List of available functions and interrupt service routines . . . . . . . . . . . . 95
4.12 Routines for monitoring and handling the system critical
parameters: MC_MotorControl_Layer module . . . . . . . . . . . . . . . . . . 97
4.12.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
4.12.2 List of available functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
4.13 Application layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100

Appendix A Additional information. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101


A.1 Adjusting CPU load related to IFOC algorithm execution . . . . . . . . . . . . 101
A.2 Selecting the update repetition rate based on PWM
frequency for single or three-shunt resistor configurations . . . . . . . . . . . 102
A.3 Fixed-point numerical representation . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
A.4 Tacho-based speed measurement flow charts . . . . . . . . . . . . . . . . . . . . 105
A.5 A priori determination of flux and torque currents PI gains . . . . . . . . . . . 107
A.6 MMI (maximum modulation index): automatic calculation. . . . . . . . . . . . 109
A.7 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

Revision history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

4/112
UM0483 List of tables

List of tables

Table 1. Sector identification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41


Table 2. PWM frequency vs. maximum duty cycle relationship for three-shunt
topology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Table 3. Current through the shunt resistor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Table 4. PWM frequency vs. maximum duty cycle relationship for single-shunt
topology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Table 5. Document revision history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

5/112
List of figures UM0483

List of figures

Figure 1. Firmware architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1


Figure 2. JTAG interface for debugging and programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Figure 3. File structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Figure 4. FOC drive placed in a speed loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Figure 5. FOC structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Figure 6. Torque vs. speed characteristic curve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Figure 7. Key function assignments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Figure 8. Main.c state machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Figure 9. LCD screen for Torque control mode settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Figure 10. LCD screen for Target Iq settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Figure 11. LCD screen for Target Id settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Figure 12. LCD screen to set the P term of the Torque PID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Figure 13. Torque control startup strategy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Figure 14. LCD screen for Speed control settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Figure 15. LCD screen to set the Target speed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Figure 16. LCD screen for setting P term of Speed PID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Figure 17. LCD screen to set the P term of the Torque PID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Figure 18. LCD screen to set the P term of the Flux PID. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Figure 19. Speed control startup strategy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Figure 20. LCD screen to select and view IFOC variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Figure 21. MB459B power board setup for the single-shunt topology . . . . . . . . . . . . . . . . . . . . . . . . . 30
Figure 22. ICS hardware connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Figure 23. Encoder output signals: counter operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Figure 24. Error message shown in case of an undervoltage fault . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Figure 25. LCD screen to monitor power stage status. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Figure 26. DBG_TIM1_STOP bit in TIM1 control register (extract from STM32 reference manual) . . 35
Figure 27. Vα and Vβ stator voltage components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Figure 28. SVPWM phase voltages waveforms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Figure 29. PWM and ADC synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Figure 30. Inverter leg and shunt resistor position . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Figure 31. Low-side switch gate signals (low modulation indexes) . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Figure 32. Low side Phase A duty cycle > DT+TN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Figure 33. DT+(TN+TS)/2 < ΔDutyA < DT+TN and ΔDutyAB < DT+TR+TS . . . . . . . . . . . . . . . . . . . . . . 46
Figure 34. ΔDutyA < DT+(TN+TS)/2 and ΔDutyA-B>DT+TR+TS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Figure 35. ΔDutyA<DT+(TN+TS)/2 and ΔDutyA-B<DT+TR+TS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Figure 36. Block diagram of GetPhaseCurrentValues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Figure 37. Block diagram of CalcDutyCycles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Figure 38. Single-shunt hardware architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Figure 39. Single-shunt current reading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Figure 40. Boundary between two space-vector sectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Figure 41. Low modulation index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Figure 42. Definition of noise parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Figure 43. Regular region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Figure 44. Boundary 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Figure 45. Boundary 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Figure 46. Boundary 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Figure 47. Stator currents sampling in ICS configuration (REP_RATE=1) . . . . . . . . . . . . . . . . . . . . . . 62
Figure 48. Rotor flux angle calculation (quadrature encoder) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

6/112
UM0483 List of figures

Figure 49. Rotor flux angle calculation (tachogenerator) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66


Figure 50. Torque and flux optimization block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Figure 51. Torque vs. speed characteristic curve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Figure 52. Clarke, Park, and reverse Park transformations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Figure 53. Transformation from an abc stationary frame to a rotating frame (q, d) . . . . . . . . . . . . . . . 75
Figure 54. Circle limitation working principle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Figure 55. Automatic tacho timer prescaler decrease . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Figure 56. Automatic tacho timer prescaler increase. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Figure 57. PID general equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Figure 58. Time domain to discrete PID equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Figure 59. Linear curve for coefficient computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Figure 60. AD conversions for three shunt topology stator currents reading and
IFOC algorithm execution when REP_RATE=3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Figure 61. AD conversion intervals for three shunt topology stator currents reading
and IFOC algorithm execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Figure 62. Tacho capture overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Figure 63. Processing captured value when timer did not overflow. . . . . . . . . . . . . . . . . . . . . . . . . . 105
Figure 64. Processing captured value when timer did overflow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Figure 65. Block diagram of PI Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Figure 66. Closed loop block diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Figure 67. Pole-zero cancellation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Figure 68. Block diagram of closed loop system after pole-zero cancellation . . . . . . . . . . . . . . . . . . 108
Figure 69. Maximum modulation index configuration tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Figure 70. MMI vs. PWM freq. define table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

7/112
UM0483

AC IM IFOC software library V2.0 features (CPU running at


72 MHz)
● Supported speed feedback:
– Tachogenerator
– Quadrature incremental encoder
● Current sampling method:
– 2 isolated current sensors (ICS)
– 3 shunt resistors placed on the bottom of the three inverter legs
– single, common DC link shunt resistor
● DAC functionality for tracing the most important software variables
● Current regulation for torque and flux control:
– PID sampling frequency adjustable up to the PWM frequency
● Speed control mode for speed regulation
● Torque control mode for torque regulation
● Field weakening
● 16-bit space vector PWM generation frequencies:
– PWM frequency can be easily adjusted
– Centered PWM pattern type
– 11 bits resolution at 17.6 kHz
● Free C source code and spreadsheet for look-up table generation
● CPU load below 21% (IFOC algorithm refresh frequency 10 kHz)
● Code size 11.5 KB (three shunt resistors for current reading, tachogenerator for speed
feedback) + 12.6 KB for LCD/joystick management
Note: These figures are for information only; this software library may be subject to changes
depending on the final application and peripheral resources. Note that it was built using
robustness-oriented structures, thus preventing the speed or code size from being fully
optimized.

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

1 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.

1.1 Working environment


The AC IM IFOC software library was fully validated using the main hardware boards
included in STM3210B-MCKIT starter kit (a complete inverter and control board). The
STM3210B-MCKIT starter kit provides an ideal toolset for starting a project and using the
library. Therefore, for rapid implementation and evaluation of the software described in this
user manual, it is recommended to acquire this starter kit.
This library is provided with IAR EWARM v. 5.20, KEIL RVMDK v. 3.22 and Green Hills
MULTI v. 5.0.3 workspaces. Exhaustive validation was performed using IAR, while simple
functional validation was done with the other toolchains. You can set up your workspace
manually for any other toolchain.

1.2 Software tools


A complete software package consists of:
● A third-party integrated development environment (IDE)
● A third-party C-compiler
● JTAG interface for debugging and programming
Using the JTAG interface of the MCU you can enter in-circuit debugging session with
most of toolchains. Each toolchain can be provided with an interface connected
between the PC and the target application.

Figure 2. JTAG interface for debugging and programming

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 Library source code

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.

1.3.2 File structure


The AC IM IFOC software library contains the workspace for the previously mentioned
toolchains. Once the files are unzipped, the following library structure appears, as shown in
Figure 3.

Figure 3. File structure

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

1.4 Customizing the workspace for your STM32F103xx derivative


The AC IM IFOC software library was written for the STM32F103VB. However, it works
equally successfully with all the products in the STM32F103xx performance line family.
Using a different sales type may require some modifications to the library, according to the
available features (some of the I/O ports are not present on low-pin count packages). Refer
to the MCU datasheet for further details.
Also, depending on the memory size, the workspace may have to be configured to fit your
STM32F103xx MCU derivative.

11/112
Getting started with the library UM0483

2 Getting started with the library

2.1 Introduction to AC induction motor FOC drive


The AC IM IFOC software library is designed to achieve the high dynamic performance in
AC motor control offered by the field oriented control (FOC) strategy.
Through complex machine electrical quantity transformations, this well-established drive
system optimizes the control of the motor, to the extent that it is able to offer decoupled
torque (Te) and magnetic flux (λ) regulation. That is, it offers the same optimum and
favorable conditions as DC motors but, in this case, carried out with rugged and powerful AC
induction motors.
With this approach, it can be stated that the two currents iqsλr and idsλr, derived from stator
currents, have in AC induction motor (IM) the same role that armature and field currents
have in DC motors: the first is proportional to mechanical torque the second to the rotor flux.
In more detail, in the context of FOC, rotor flux position is indirectly calculated, starting from
transformed equations of the machine, by means of known motor parameters and stator
current measurements: this is why the controller is an indirect controller and, hence the
phrase IFOC drive.
In other words, it can be stated that IFOC drive is halfway between dynamic controllers (like
speed and position) and machine core. So, the system may well be depicted as in Figure 4,
if introduced in a loop for speed control.

Figure 4. FOC drive placed in a speed loop

ωr* + iqs*
Torque controller
3-phase
3-phase
FOC induction
– inverter
motor

Flux controller ids*

actual rotor speed

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

● The PID-controller block implements a proportional, integral and derivative feedback


controller, to achieve speed, torque and flux regulation.

Figure 5. FOC structure


rotor flux stator stator
d.q frame d.q frame a,b,c frame IFOC model
Torque
command
(iqs*) + Vqs
PID Reverse, pwm signal
Flux Park T. vα, vβ CALC va, vb, vc

command SVPWM
(ods*) + & circle
Vds limitation
PID

Iqs
Park T. iα, iβ Clarke ia, ib Current
Ids reading

θλr Speed
calculation reading

ai14787

2.2 How to customize hardware and software parameters


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 an AC induction 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 2.2.1), and the following parameter header files,
– MC_Control_Param.h (see Section 2.2.2),
– MC_encoder_param.h (see Section 2.2.3) or MC_tacho_prm.h (see
Section 2.2.4),
– MC_ACmotor_prm.h (see Section 2.2.5);
3. Re-build the project and download it on the STM32F103xx microcontroller.

13/112
Getting started with the library UM0483

2.2.1 Library configuration file: stm32f10x_MCconf.h


The purpose of this file is to declare the compiler conditional compilation keys that are used
throughout the entire library compilation process to:
● Select which current measurement technique is actually in use (the choice is between
single-shunt, three-shunt or ICS sensors, according to availability).
● Select which speed/position sensor is actually performed (here the choice is between
tachometer and quadrature incremental encoder, according to availability).
● Enable or disable the derivative action in the PID controllers in accordance with
expected performance and code size.
● Enable or disable a virtual 2-channel DAC used to output in real time all the variables
involved in the IFOC algorithm.
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 setup the MB459B power board as described in Section 3.4: Setting
up the system when in single-shunt topology and using the MB459B power board on
page 30.
● #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 2.2.3);.
● #define TACHO
To be uncommented when a tachogenerator is in use to detect rotor speed (default); in
parallel, fill out MC_tacho_prm.h (as explained in Section 2.2.4);.
● #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 4.9)
● #define DAC_FUNCTIONALITY
If uncommented, the TIM3 timer outputs (channels 3 and 4) are configured in PWM
mode to show two variables among the ones involved in the IFOC algorithm. Once this
feature in enabled, an additional menu in LCD is shown for selecting the two variables
to be output on the PWM channels.
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 2.2.2 and Section A.2: Selecting

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

2.2.2 Drive control parameters: MC_Control_Param.h


The MC_Control_Param.h header file gathers parameters related to:
● Power device control parameters on page 15
● Flux and torque PID regulators sampling rate on page 15
● Power board protection thresholds on page 15
● Speed regulation loop frequency on page 16
● Speed controller setpoint and PID constants (initial values) on page 16
● Torque and flux controller setpoints and PID constants on page 17
● Startup torque ramp parameters on page 17
● Linear variation of PID constants according to mechanical speed. on page 17

Power device control parameters


● #define PWM_FREQ
Define here, in Hz, the switching frequency; in parallel, uncomment the maximum
allowed modulation index definition (MAX_MODULATION_XX_PER_CENT)
corresponding to the PWM frequency selection.
Note that if ICSs are used, the 100% modulation index is allowed regardless of the
selected PWM frequency.
● #define DEADTIME_NS
Define here, in ns, the dead time, in order to avoid shoot-through conditions.

Flux and torque PID regulators sampling rate


● #define REP_RATE
Stator currents sampling frequency and consequently flux and torque PID regulators
sampling rate, are defined according to the following equation:

Flux and torque PID sampling rate = 2 ⋅ PWM_FREQ-


--------------------------------------------
REP_RATE + 1

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.

Power board protection thresholds


● #define NTC_THRESHOLD
● #define NTC_HYSTERIS
These two values are used to set the maximum operating temperature rating for the power
board in use (the default values refer to MB459 included in the STM3210B-MCKIT kit and
correspond to a maximum temperature of about 60 °C). The second parameter is related to

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;

Speed regulation loop frequency


#define PID_SPEED_SAMPLING_TIME
The speed regulation loop frequency is selected by assigning one of the defines below:
#define PID_SPEED_SAMPLING_500µs 0 //min 500µs
#define PID_SPEED_SAMPLING_1ms 1
#define PID_SPEED_SAMPLING_2ms 3 //(4-1)*500µs=2ms
#define PID_SPEED_SAMPLING_5ms 9
#define PID_SPEED_SAMPLING_10ms 19
#define PID_SPEED_SAMPLING_127ms 255 //max(255-1)*500µs=127ms

Speed controller setpoint and PID constants (initial values)


● #define PID_SPEED_REFERENCE
Define here, in 0.1Hz, the mechanical rotor speed setpoint at startup in closed loop
mode;
● #define PID_SPEED_KP_DEFAULT
The proportional constant of the speed loop regulation (signed 16-bit value, adjustable
from 0 to 32767);
● #define PID_SPEED_KI_DEFAULT
The integral constant of the speed loop regulation (signed 16-bit value, adjustable from
0 to 32767);
● #define PID_SPEED_KD_DEFAULT
The derivative constant of the speed loop regulation (signed 16-bit value, adjustable
from 0 to 32767);

16/112
UM0483 Getting started with the library

Torque and flux controller setpoints and PID constants


● #define PID_TORQUE_REFERENCE
The torque reference value, in open loop, at startup (signed 16-bit value);
● #define PID_TORQUE_KP_DEFAULT
The proportional constant of the torque loop regulation (signed 16-bit value, adjustable
from 0 to 32767);
● #define PID_TORQUE_KI_DEFAULT
The integral constant of the torque loop regulation (signed 16-bit value, adjustable from
0 to 32767);
● #define PID_TORQUE_KD_DEFAULT
The derivative constant of the torque loop regulation (signed 16-bit value, adjustable
from 0 to 32767);
● #define PID_FLUX_REFERENCE
Flux reference: its default value is equal to NOMINAL_FLUX defined in the
MC_ACmotor_prm.h header file (see Section 2.2.5);
● #define PID_FLUX_KP_DEFAULT
The proportional constant of the flux loop regulation (signed 16-bit value, adjustable
from 0 to 32767);
● #define PID_FLUX_KI_DEFAULT
The integral constant of the flux loop regulation (signed 16-bit value, adjustable from 0
to 32767);
● #define PID_FLUX_KD_DEFAULT
The derivative constant of the flux loop regulation (signed 16-bit value, adjustable from
0 to 32767);

Startup torque ramp parameters


See Section 3.1: Torque control mode and Section 3.2: Speed control mode on page 26 for
details.
● #define STARTUP_TIMEOUT
Define here, in ms, the overall time allowed for startup;
● #define STARTUP_RAMP_DURATION
Define here, in ms, the duration of the torque ramp up;
● #define STARTUP_FINAL_TORQUE
Define here, in q1.15 format, the final reference value for torque ramp up (Speed
control mode only);
● #define TACHO_SPEED_VAL
Define here, in 0.1Hz, the lowest speed for tachogenerator reading validation.

Linear variation of PID constants according to mechanical speed.


Refer to Section 4.9.5: Adjusting speed regulation loop Ki, Kp and Kd vs. motor frequency
on page 91.

17/112
Getting started with the library UM0483

2.2.3 Incremental encoder parameters: MC_encoder_param.h


The MC_encoder_parameter.h header file is to be filled out if position/speed sensing is
performed by means of a quadrature, square wave, relative rotary encoder (ENCODER
defined in stm32f10x_MCconf.h).
● #define ENCODER_PPR
Define here the number of pulses, generated by a single channel, for one shaft
revolution (actual resolution will be 4x);
● #define TIMER2_HANDLES_ENCODER
To be uncommented if the two sensor output signals are wired to TIMER2 input pins
(default: required if using STM3210B-MCKIT);
● #define TIMER3_HANDLES_ENCODER
to be uncommented if the two sensor output signals are wired to TIMER3 input pins;
● #define TIMER4_HANDLES_ENCODER
To be uncommented if the two sensor output signals are wired to TIMER4 input pins.
● #define MINIMUM_MECHANICAL_SPEED_RPM
Defines in rpm, the minimum speed below which the speed measurement is either not
realistic or not safe in the application; an error counter is increased every time the
measured speed is below the specified value.
● #define MAXIMUM_MECHANICAL_SPEED_RPM
Defines in rpm, the maximum speed above which the speed measurement is either not
realistic or not safe in the application; an error counter is increased every time the
measured speed is above the specified value.
● #define MAXIMUM_ERROR_NUMBER
Defines the number of consecutive errors on speed measurements to be detected
before a fault event is generated (check rate is specified by SPEED_MEAS_TIMEBASE
in stm32f10x_Timebase.c).
● #define SPEED_BUFFER_SIZE
Defines the buffer size utilized for averaging speed measurement. Power of two is
desirable for ease of computation.

2.2.4 Tachogenerator parameters: MC_tacho_prm.h


The MC_tacho_prm.h header file is to be filled out if speed sensing is performed using an
AC tachogenerator. Extra details and more explanations on tacho-based speed
measurement can be found in Section 4.8 on page 81 and Section A.4 on page 105.
● #define TACHO_PULSE_PER_REV
Define here the number of pulses per revolution given by the tachogenerator; in order
to verify the correct operation of the tacho module, this parameter can be set to 1, so
that the frequency measurement can be directly compared with the one of a signal
generator.
● #define TIMER2_HANDLES_TACHO
To be uncommented if tachogenerator-based speed measurement is performed by
TIMER2. (Default: required if using STM3210B-MCKIT in conjunction with Input
Capture 1 choice - see #define TACHO_INPUT_TI1 below).

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.

2.2.5 AC induction motor parameters: MC_ACmotor_param.h


The MC_ACmotor_param.h header file holds motor parameters which are essential to
properly operate the IFOC vector drive.
The following parameters must be defined in all cases:
● #define ROTOR_TIME_CONSTANT
Define here (in µs), the rotor open circuit time constant of the motor τ r:

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

Figure 6. Torque vs. speed characteristic curve

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

3 Running the demo program

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.

Figure 7. Key function assignments

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

Figure 8. Main.c state machine

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

3.1 Torque control mode


Figure 9, Figure 10 and Figure 11 show a list of some LCD menus used to set motor control
parameters in the Torque control mode. The parameter in red is the one that is being
selected and whose value can be modified by acting on the joystick key.

Figure 9. LCD screen for Torque control mode settings

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

Figure 10. LCD screen for Target Iq settings

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.

Figure 11. LCD screen for Target Id settings

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.

Figure 13. Torque control startup strategy

25/112
Running the demo program UM0483

3.2 Speed control mode


Figure 14, Figure 15, Figure 16 show a list of some LCD menus used to set motor control
parameters in the Speed control mode. The parameter in red is the one that is being
selected and whose value can be modified by acting on the joystick key.

Figure 14. LCD screen for Speed control settings

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 15. LCD screen to set the Target speed

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 16. LCD screen for setting P term of Speed PID

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.

Figure 19. Speed control startup strategy

3.3 Output IFOC variables using a 2-channel DAC


In the stm32f10x_MCconf.h configuration file, if the DAC_FUNCTIONALITY option is
uncommented, two variables can be output by using the PWM outputs of the TIM3 timer
(channels 3 and 4 on the PB0 and PB1 microcontroller pins). The PWM duty cycles are then
mapped to the actual value of the variable the user would like to see. By using an external
RC low-pass filter, the averaged value of the PWM signal will represent the digital value of
the software variable, reproduced by a scope in real time. This advanced feature makes it
easier to debug the IFOC algorithm efficiently, as the actual values processed by the

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.

Figure 20. LCD screen to select and view IFOC variables

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

3.4 Setting up the system when in single-shunt topology and


using the
MB459B power board
To set up the MB459B power board for the single-shunt topology, the only required operation
is to move the wires present in the W4, W5 and W10 place holders as shown in Figure 21:
● W4 open
● W5 closed
● W10 between 1-2 (unlike in the silkscreen)

Figure 21. MB459B power board setup for the single-shunt topology

W4 W4

W5 W5

W10 W10
(Three shunt) (Single shunt)
ai15153

3.5 Setting up the system when using ICSs


The default configuration provides for the use of three shunt resistors and tacho-generator.
Section 3.5.1 describes how to change the firmware configuration from three shunt resistor
to two ICS stator current reading. This section gives you information about how to provide
the STM32F103xx with ICS feedback signals and to properly customize the firmware.
Note: Firmware support of ICS current measurement is enabled as explained in Section 2.2.1.
Using ICSs allows the MMI to be set to 100% (#define
MAX_MODULATION_100_PER_CENT, see Section 2.2.2, Section 4.6.4).
Caution: When using two ICSs for stator current reading, you must ensure that the conditioned
sensors output signal range is compatible with the STM32F103xx supply voltage.

30/112
UM0483 Running the demo program

3.5.1 Connecting the two ICSs to the motor and to STM32F103xx


In order for the implemented IFOC algorithm to work properly, it is necessary to ensure that
the software implementation of the stm32f10x_svpwm_ics module and the hardware
connections of the two ICSs are consistent.
As illustrated in Figure 22, the two ICSs must act as transducers on motor phase currents
coming out of the inverter legs driven by STM32F103xx TIM1 signals PWM1 (Phase A) and
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 22).

Figure 22. ICS hardware connections

3.5.2 Selecting PHASE_A_ADC_CHANNEL and


PHASE_B_ADC_CHANNEL
Default settings for PHASE_A_ADC_ CHANNEL and PHASE_B_ADC_CHANNEL are
respectively ADC_CHANNEL11 and ADC_CHANNEL12. You can change the default settings if
the hardware requires it by editing the MC_pwm_ics_prm.h file.
///////////////////////////// Current reading parameters
//////////////////////

#define PHASE_A_ADC_CHANNEL ADC_Channel_11


#define PHASE_A_GPIO_PORT GPIOC
#define PHASE_A_GPIO_PIN GPIO_Pin_1

31/112
Running the demo program UM0483

#define PHASE_B_ADC_CHANNEL ADC_Channel_12


#define PHASE_B_GPIO_PORT GPIOC
#define PHASE_B_GPIO_PIN GPIO_Pin_2
Caution: The proper GPIOs must be initialized as analog inputs.
An example for ADC channel 8 is given below:
/* ADC Channel 8 pin configuration */
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_Init(GPIOC, &GPIO_InitStructure);

3.6 How to build the system when using an incremental encoder


Quadrature incremental encoders are widely used to read the rotor position of electric
machines.
As the name implies, incremental encoders actually read angular displacements with
respect to an initial position: if that position is known, then rotor absolute angle is known too.
Quadrature encoders have two output signals (represented in Figure 23 as TI1 and TI2).
With these, and with the STM32F103xx standard timer in encoder interface mode, it is
possible to get information about rolling direction.

Figure 23. Encoder output signals: counter operation

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

3.7 Fault messages


This section provides a list of possible fault message that can be displayed on the LCD
when using the software library together with the STM3210B-MCKIT:
● Overcurrent
A Break Input was detected on the TIM1 peripheral dedicated pin. If using STM3210B-
MCKIT it could mean that either the hardware overtemperature protection or the
hardware overcurrent protection were triggered. Refer to the STM3210B-MCKIT user
manual for details
● Overheating
An overtemperature was detected on the dedicated analog channel; the digital
threshold NTC_THRESHOLD and the relative hysteresis (NTC_HYSTERESIS) are
specified in the MC_Control_Param.h header file. Refer to the STM3210B-MCKIT
user manual for details
● Error on speed feedback
The speed feedback timed out. Verify speed sensor connections
● Startup failed
The motor ramp-up failed. Refer to Section 3.1 and Section 3.2 for in-depth information,
● Bus overvoltage
An overvoltage was detected on the dedicated analog channel. The digital threshold
(OVERVOLTAGE_THRESHOLD) is specified in the MC_Control_Param.h header file.
Refer to the STM3210B-MCKIT user manual for details.
● Bus undervoltage
The bus voltage is below 20 V DC. This threshold is specified in the
UNDERVOLTAGE_THRESHOLD parameter in the MC_Control_Param.h header file.
Figure 24 shows the example of the error message screen that appears when the applied
DC bus voltage level is too low.

33/112
Running the demo program UM0483

Figure 24. Error message shown in case of an undervoltage fault

3.8 Actual values of DC bus voltage and IGBT heatsink


temperature
In case of overtemperature and bus overvoltage/undervoltage, the system is autoprotected,
it warns the user about the fault event while blocking motor operations. The user may
however be interested in seeing how these values change during the motor control run
phase. For this purpose, an LCD screen was added that continuously shows the DC bus
voltage level (in volts) and the power switch heat sink temperature, in Celsius degrees.

Figure 25. LCD screen to monitor power stage status

3.9 Note on debugging tools


The third party JTAG interface should always be isolated from the application using the
MB535 JTAG opto-isolation board; it provides protection for both the JTAG interface and the
PC connected to it.
Caution: During a breakpoint, when using the JTAG interface for the firmware development, the motor
control cell clock circuitry should always be enabled; if disabled, a permanent DC current
may flow in the motor because the PWM outputs are enabled, which could cause

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.1 Function description conventions


Functions are described in the format given below:

Synopsis Lists the prototype declarations.


Description Describes the functions specifically with a brief explanation of how they
are executed.
Input Gives the format and units.
Returns Gives the value returned by the function, including when an input value
is out of range or an error code is returned.
Note Indicates the limits of the function or specific requirements that must be
taken into account before implementation.
Caution Indicates important points that must be taken into account to prevent
hardware failures.
Functions called Lists called functions. Useful to prevent conflicts due to the
simultaneous use of resources.
Code example Indicates the proper way to use the function, and if there are certain
prerequisites (interrupt enabled, etc.).
Some of these sections may not be included if not applicable (for example, no parameters or
obvious use).

4.2 Current reading in three shunt resistor topology and space


vector PWM generation: stm32f10x_svpwm_3shunt module

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

4.2.2 List of available functions


The following is a list of available functions as listed in the stm32f10x_svpwm_3shunt.h
header file:
● SVPWM_3ShuntInit on page 37
● SVPWM_3ShuntCurrentReadingCalibration on page 38
● SVPWM_3ShuntGetPhaseCurrentValues on page 38
● SVPWM_3ShuntCalcDutyCycles on page 39
● SVPWM_3ShuntAdvCurrentReading on page 39
● SVPWMEOCEvent on page 39
● SVPWMUpdateEvent on page 40

SVPWM_3ShuntInit

Synopsis void SVPWM_3ShuntInit(void);


Description The purpose of this function is to set-up microcontroller peripherals for
performing 3 shunt resistor topology current reading and center aligned
PWM generation.
The function initializes NVIC, ADC, GPIO, TIM1 peripherals.
In particular, the ADC and TIM1 peripherals are configured to perform
two synchronized A/D conversions per PWM switching period.
Refer to Section 4.2.3 for further information.
Input None.
Returns None.
Note It must be called at main level.
Functions called Standard library:
RCC_ADCCLKConfig, RCC_AHBPeriphClockCmd,
RCC_APB2PeriphClockCmd, GPIO_StructInit, GPIO_Init,
GPIO_PinRemapConfig, TIM1_DeInit, TIM1_TimeBaseStructInit,
TIM1_TimeBaseInit, TIM1_OCStructInit, TIM1_OC1Init, TIM1_OC2Init,
TIM1_OC3Init, TIM1_OC1PreloadConfig, TIM1_OC2PreloadConfig,
TIM1_OC3PreloadConfig, TIM1_BDTRConfig,
TIM1_SelectOutputTrigger, TIM1_ClearITPendingBit, TIM1_ITConfig,
TIM1_Cmd, ADC_DeInit, ADC_Cmd, ADC_StructInit, ADC_Init,
ADC_StartCalibration, ADC_GetCalibrationStatus,
ADC_RegularChannelConfig, ADC_InjectedSequencerLengthConfig,
ADC_InjectedChannelConfig, ADC_ExternalTrigInjectedConvCmd,
NVIC_PriorityGroupConfig, NVIC_StructInit, NVIC_Init.
Motor control library:
SVPWM_3ShuntCurrentReadingCalibration

37/112
Library functions UM0483

SVPWM_3ShuntCurrentReadingCalibration

Synopsis void SVPWM_3ShuntCurrentReadingCalibration(void);


Description The purpose of this function is to store the three analog voltages
corresponding to zero current values for compensating the offset
introduced by the amplification network.
Input None.
Returns None.
Note This function is called by MCL_Init which is executed at every motor
startup. The function reads the analog voltage on A/D channels
utilized for current reading before TIM1 outputs are enabled so that
the current flowing through the inverter is zero. Those values are then
stored into Phase_x_Offset variables.
Functions called Standard library:
ADC_ITConfig, ADC_ExternalTrigInjectedConvConfig,
ADC_ExternalTrigInjectedConvCmd,
ADC_InjectedSequencerLengthConfig,
ADC_InjectedChannelConfig, ADC_SoftwareStartInjectedConvCmd,
ADC_GetFlagStatus, ADC_GetInjectedConversionValue,
ADC_SoftwareStartInjectedConvCmd
Motor control library:
SVPWM_InjectedConvConfig

SVPWM_3ShuntGetPhaseCurrentValues

Synopsis Curr_Components SVPWM_3ShuntGetPhaseCurrentValues(void);


Description This function computes current values of Phase A and Phase B in
q1.15 format starting from values acquired from the A/D Converter
peripheral.
Input None.
Returns Curr_Components type variable.
Note In order to have a q1.15 format for the current values, the digital value
corresponding to the offset must be subtracted when reading phase
current A/D converted values. Therefore, the function must be called
after SVPWM_3ShuntCurrentReadingCalibration.
Functions called None.

38/112
UM0483 Library functions

SVPWM_3ShuntCalcDutyCycles

Synopsis void SVPWM_3ShuntCalcDutyCycles (Volt_Components


Stat_Volt_Input);
Description After execution of the IFOC algorithm, new stator voltage components
Vα and Vβ are computed. The purpose of this function is to calculate
exactly the three duty cycles to be applied to motor phases from the
values of these voltage components.
Moreover, once the three duty cycles to be applied in the next PWM
period are known, this function sets the TIM1 Channel 4
capture/compare register (TIM1_CCR4) to set the sampling point for
the next current reading. In particular, depending on the duty cycle
values, the sampling point is computed (see Section 4.2.5 on page
44).
Refer to Section 4.2.3 for information on the theoretical approach of
SVPWM.
Input Vα and Vβ
Returns None.
Note None.
Functions called None.

SVPWM_3ShuntAdvCurrentReading

Synopsis void SVPWM_3ShuntAdvCurrentReading(FunctionalState cmd);


Description It is used to enable or disable advanced current reading. If advanced
current reading is disabled, current reading is performed in conjunction
with the update event.
Input cmd (ENABLE or DISABLE)
Returns None.
Note None.
Functions called TIM1_ClearFlag, TIM1_ITConfig

SVPWMEOCEvent

Synopsis void SVPWMEOCEvent();


Description Routine to be performed inside the end-of-conversion ISR. It
computes the bus voltage and temperature sensor sampling and
disables external ADC triggering.
Input None.
Returns Always true.
Note None.
Functions called ADC_GetInjectedConversionValue

39/112
Library functions UM0483

SVPWMUpdateEvent

Synopsis void SVPWMUpdateEvent(void);


Description Routine to be performed inside the update event ISR. It re-enables
external ADC triggering.
Input None
Returns None.
Note None.
Functions called ADC_ClearFlag

4.2.3 Space vector PWM implementation


Figure 27 shows the Stator Voltage components Vα and Vβ while Figure 28 illustrates the
corresponding PWM for each of the six space vector sectors:

Figure 27. Vα and Vβ stator voltage components

40/112
UM0483 Library functions

Figure 28. SVPWM phase voltages waveforms

With the following definitions for: U α = 3 × T × V alfa , U θ = – T × V beta and X = U β ,


Uα + Uθ Uθ – Uα
- and Z = -------------------
Y = ------------------- -.
2 2
literature demonstrates that the space vector sector is identified by the conditions shown in
Table 1.

Table 1. Sector identification


Y<0 Y≥0

Z<0 Z≥0 Z<0 Z≥0

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

Sector III, VI: t A = T – X + Y- t = t + X t = t – Y


----------------------- , B C , C A , where T is the PWM period.
2
Now, considering that the PWM pattern is center aligned and that the phase voltages must
be centered at 50% of duty cycle, it follows that the values to be loaded into the PWM output
compare registers are given respectively by:

41/112
Library functions UM0483

T ⁄ 2 + X – Z- , TimePhB = TimePhA + Z , TimePhC = TimePhB – X


Sector I, IV: TimePhA = T
--- + ---------------------------------
4 2

T ⁄ 2 + Y – Z- TimePhB = TimePhA + Z TimePhC = TimePhA – Y


Sector II, V: TimePhA = T
--- + --------------------------------- , ,
4 2

T ⁄ 2 + Y – X- TimePhB = TimePhC + X TimePhC = TimePhA – Y


Sector III,VI: TimePhA = T
--- + --------------------------------- , ,
4 2

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

Figure 29. PWM and ADC synchronization

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

ADC Start ADC Start


TIM1_CH3 TIM1_CH3

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:

Figure 30. Inverter leg and shunt resistor position

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

Figure 31. Low-side switch gate signals (low modulation indexes)

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

Figure 32. Low side Phase A duty cycle > DT+TN

Δ Duty A Counter overflow


HP: TS << DT+TN
Low side phase A DT

High side phase A DT

Low side phase B DT

High side phase B TN DT

TS

Current feedback
phase B Sampling start

Current feedback TS Sampling end


phase C
Space available for sampling
ai14836

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

Low side phase A DT

High side phase A DT

Low side phase B DT

High side phase B TN TS DT

Current feedback phase B


TS Sampling start

Current feedback phase C Sampling end


Space available for sampling
< TS
ai14837

Case 3: ΔDutyA < DT+(TN+TS)/2 and ΔDutyA-B>DT+TR+TS


In this case, the two currents can be sampled between Phase B low-side switch-on and
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 34).

46/112
UM0483 Library functions

Figure 34. ΔDutyA < DT+(TN+TS)/2 and ΔDutyA-B>DT+TR+TS

ΔDutyA-B
Low side phase A DT

High side phase A DT

Low side phase B DT


TR
High side phase B DT

Current feedback phase B TS


Sampling start

Current feedback phase C Sampling end


TS
Space available for sampling
< TS ai14838

Case 4: ΔDutyA<DT+(TN+TS)/2 and ΔDutyA-B<DT+TR+TS


In this case, the duty cycle applied to Phase A is so short that no current sampling can be
performed between the two low-side commutations.
Furthermore if the difference in duty cycles between Phases B and A is not long enough to
allow the A/D conversions to be performed between Phase B low-side switch-on and Phase
A high-side switch-off, it is impossible to sample the currents (See Figure 35).
To avoid this condition, it is necessary to reduce the maximum modulation index or decrease
the PWM frequency.

Figure 35. ΔDutyA<DT+(TN+TS)/2 and ΔDutyA-B<DT+TR+TS

Δ Duty A-B
Low side phase A DT

High side phase A DT

Low side phase B DT

High side phase B TR DT

Current feedback phase B

Current feedback phase C

No space available for sampling

< 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

Up to 11.4 kHz 100% 100%


12.2 kHz 99% 98%
12.9 kHz 98.5% 97%
13.7 kHz 98% 96%
14.4 kHz 98% 96%
15.2 kHz 97% 94%
16 kHz 96.5% 93%
16.7 kHz 96.5% 93%
17.5 kHz 95.5% 91%

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.

4.3 Current reading in single shunt resistor topology and space


vector PWM generation: stm32f10x_svpwm_1shunt module
Two major tasks are performed in the stm32f10x_svpwm_1shunt module:
● space-vector pulse-width modulation (SVPWM)
● current reading in single-shunt-resistor topology
In order to reconstruct the currents flowing through a three-phase load with the required
accuracy using a single shunt resistor, 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.

48/112
UM0483 Library functions

4.3.1 List of available functions


The following is the list of available functions as listed in the stm32f10x_svpwm_shunt.h
header file:
● SVPWM_1ShuntInit on page 49
● SVPWM_1ShuntCurrentReadingCalibration on page 50
● SVPWM_1ShuntGetPhaseCurrentValues on page 50
● SVPWM_1ShuntCalcDutyCycles on page 51
● SVPWM_1ShuntAdvCurrentReading on page 52
● SVPWMEOCEvent on page 52
● SVPWMUpdateEvent on page 52

SVPWM_1ShuntInit

Synopsis void SVPWM_1ShuntInit(void);


Description The purpose of this function is to set up the microcontroller peripherals
so as to perform single-shunt-resistor topology current reading and
center aligned PWM generation.
The function initializes the NVIC, ADC, GPIO, TIM1 and DMA
peripherals. More particularly, the ADC and TIM1 peripherals are
configured to perform two A/D conversions per PWM switching period.
Refer to Section 4.3.3 for further information.
Input None.
Returns None.
Note It must be called at main level.
Functions called Standard library: RCC_ADCCLKConfig, RCC_AHBPeriphClockCmd,
RCC_APB2PeriphClockCmd, GPIO_StructInit, GPIO_Init,
GPIO_PinLockConfig,GPIO_PinRemapConfig, TIM1_DeInit,
TIM1_TimeBaseStructInit, TIM1_TimeBaseInit, TIM1_OCStructInit,
TIM1_OC1Init, TIM1_OC2Init, TIM1_OC3Init, TIM1_OC4Init,
TIM1_OC1PreloadConfig, TIM1_OC2PreloadConfig,
TIM1_OC3PreloadConfig, TIM1_OC4PreloadConfig,
TIM1_BDTRConfig, TIM1_SelectOutputTrigger,
TIM1_ClearITPendingBit, TIM1_ITConfig,
TIM1_Cmd,TIM1_GenerateEvent, TIM1_ClearFlag, TIM1_DMACmd,
TIM1_DMAConfig, ADC_DeInit, ADC_Cmd, ADC_StructInit, ADC_Init,
ADC_StartCalibration, ADC_GetCalibrationStatus,
ADC_RegularChannelConfig, ADC_InjectedSequencerLengthConfig,
ADC_InjectedChannelConfig, NVIC_PriorityGroupConfig,
NVIC_StructInit, NVIC_Init. DMA_DeInit, DMA_Init, DMA_Cmd
Motor control library: SVPWM_1ShuntCurrentReadingCalibration

49/112
Library functions UM0483

SVPWM_1ShuntCurrentReadingCalibration

Synopsis void SVPWM_1ShuntCurrentReadingCalibration(void);


Description The purpose of this function is to store the analog voltages
corresponding to zero-current values in order to compensate for the
offset introduced by the amplification circuit.
Input None.
Returns None.
Note This function reads the analog voltage on the ADC channels used for
current reading. For this reason it must be called before the PWM
outputs are enabled so that the current flowing through the inverter is
zero. Those values are then stored into the hPhaseOffset variable.
Functions called Standard library: ADC_ITConfig,
ADC_ExternalTrigInjectedConvConfig,
ADC_ExternalTrigInjectedConvCmd,
ADC_InjectedSequencerLengthConfig, ADC_InjectedChannelConfig,
ADC_ClearFlag, ADC_SoftwareStartInjectedConvCmd,
ADC_GetFlagStatus, ADC_GetInjectedConversionValue,
ADC_SoftwareStartInjectedConvCmd
Motor control library: SVPWM_InjectedConvConfig

SVPWM_1ShuntGetPhaseCurrentValues

Synopsis Curr_Components SVPWM_1ShuntGetPhaseCurrentValues(void);


Description This function computes current values of Phase A and Phase B in
q1.15 format starting from values acquired from the A/D converter
peripheral. See Figure 36.
Input None.
Returns Curr_Components type variable.
Note In order to have a q1.15 format for the current values, the digital value
corresponding to the offset must be subtracted when reading phase
current A/D converted values. Therefore, the function must be called
after SVPWM_1ShuntCurrentReadingCalibration.
Functions called None.

Figure 36. Block diagram of GetPhaseCurrentValues

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.

Figure 37. Block diagram of CalcDutyCycles

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*

Sampling IA, NIA


Sector current 1
IB, NIB
Sampling IC, NIC
current 2

ai15134

51/112
Library functions UM0483

SVPWM_1ShuntAdvCurrentReading

Synopsis void SVPWM_1ShuntAdvCurrentReading(FunctionalState cmd);


Description It is used to enable or disable current reading. If current reading is
disabled, the bus voltage and temperature sensor are still sampled in
conjunction with the update event.
Input cmd (ENABLE or DISABLE)
Returns None.
Note None.
Functions called TIM1_ClearFlag, TIM1_ITConfig

SVPWMEOCEvent

Synopsis void SVPWMEOCEvent();


Description Routine to be performed inside the end-of-conversion ISR. For single-
shunt current reading, it is called twice. The first time, to store the first
sampled value. It returns a “false”. The second time, it returns a “true”
to indicate the execution of the FOC cycle. It computes the bus voltage
and temperature sensor sampling, and disables external ADC
triggering.
Input None.
Returns False the first time it is entered, True the second time.
Note None.
Functions called ADC_GetInjectedConversionValue, ADC_ITConfig.

SVPWMUpdateEvent

Synopsis void SVPWMUpdateEvent(void);


Description Routine to be performed inside the update event ISR. It sets the PWM
output mode of the four channels (Toggle or PWM), enables or
disables the DMA event for each channel, updates the DMA buffers
and DMA length and, finally, it re-enables external ADC triggering.
Input None.
Returns None.
Note None.
Functions called ADC_ClearFlag,ADC_ITConfig.

52/112
UM0483 Library functions

4.3.2 Current sampling in single-shunt topology


Figure 38 illustrated the single-shunt hardware architecture.

Figure 38. Single-shunt hardware architecture

T4 T5 T6

iA iB iC
VBUS T1 T2 T3

Temperature sensor Bus voltage


iShunt RShunt
+

ADC_IN12 ADC_IN10 ADC_IN3

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.

Table 3. Current through the shunt resistor


T1 T2 T3 IShunt

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

Figure 39. Single-shunt current reading

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.

Figure 40. Boundary between two space-vector sectors

I II III IV V I II III IV V β
V3 V2
T1 T1

T2 T2
V4 V1
α
T3 T3
iA iA

iShunt iShunt –iC –iC


V5 V6

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.

Figure 41. Low modulation index


I II III β
V3 V2
T1

T2
V4 V1
α
T3

iShunt

V5 V6

ai15138

4.3.3 Definition of the noise parameter and boundary zone


TRise is the time required for the data to become stable in the ADC channel after the power
device has been switched on or off.
The duration of the ADC sampling is called the sampling time.
TMIN is the minimum time required to perform the sampling, and
TMIN = TRise + sampling time + dead time
DMIN is the value of TMIN expressed in duty cycle percent. It is related to the PWM frequency
as follows:
DMIN = (TMIN × FPWM) × 100
It is possible to adjust the noise parameters based on customized hardware by editing the
following definitions in the MC_pwm_1shunt_prm.h header file:
● #define SAMPLING_TIME_NS 700 //0.7usec
● #define TRISE_NS 2550 //2.55usec
Changing the noise parameters, sampling time and dead time affects the values provided in
Table 4.

55/112
Library functions UM0483

Figure 42. Definition of noise parameters

T5 switched off T2 switched on


I II III IV V VI VII

T1

T2

Dead T3
time iA iA

iShunt
–iC
–iC
Sampling time
TRise

End of noise, start of sampling


End of sampling, start of conversion ai15139

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.

Figure 43. Regular region

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.

Figure 44. Boundary 1

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

Figure 45. Boundary 2

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.

Figure 46. Boundary 3

ai15143

If the voltage-demand vector lies in Boundary 1 or Boundary 2 region, a distortion must be


introduced in the related PWM signal phases to sample the motor phase current.
An ST patented technique for current sampling in the “Boundary” regions has been
implemented in the firmware. Please contact your nearest ST sales office or support team
for further information about this technique.
Note: The current-compensation technique implemented by default can lead to bad current
sampling if a motor with a high stator inductance is driven at a high electrical speed. In this
case, it may be useful to exclude the current compensation technique by commenting the
following define inside the MC_pwm_1shunt_prm.h header file:
#define CURRENT_COMPENSATION.

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

Up to 11.4 kHz 100% 100%


12.2 kHz 99.5% 99%
12.9 kHz 99% 98% 1
13.7 kHz 98.5% 97%
14.4 kHz 98% 96%
15.2 kHz 97.5% 95%
1
16 kHz 97% 94%
16.7 kHz 96.5% 93%
3
17.5 kHz 96% 92%

4.4 Isolated current sensor reading and space vector PWM


generation: stm32f10x_svpwm_ics module

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.

4.4.2 List of available functions and interrupt service routines


The following is a list of available functions as listed in the stm32f10x_svpwm_ics.h
header file:
● SVPWM_IcsInit on page 58
● SVPWM_IcsCurrentReadingCalibration on page 60
● SVPWM_IcsGetPhaseCurrentValues on page 60
● SVPWM_IcsCalcDutyCycles on page 61
● SVPWMUpdateEvent on page 61
● SVPWMEOCEvent on page 61

SVPWM_IcsInit

Synopsis void SVPWM_IcsInit(void);

58/112
UM0483 Library functions

Description The purpose of this function is to set-up microcontroller peripherals for


performing ICS reading and center aligned PWM generation.
The function initializes NVIC, ADC, GPIO, and TIM1 peripherals.
In particular ADC and TIM1 peripherals are configured to perform two
pairs of simultaneous injected A/D conversions every time PWM
registers are updated (event called U event). The first pair of
conversions reads the current values while the second one acquires
the bus voltage and the voltage on the temperature sensor.
Refer to Section 4.4.3 for further information on A/D conversion
triggering in ICS configuration.
Input None.
Returns None.
Note It must be called at main level.
Functions called Standard library:
RCC_ADCCLKConfig, RCC_AHBPeriphClockCmd,
RCC_APB2PeriphClockCmd, GPIO_StructInit, GPIO_Init,
GPIO_PinRemapConfig, TIM1_DeInit, TIM1_TimeBaseStructInit,
TIM1_TimeBaseInit, TIM1_OCStructInit, TIM1_OC1Init,
TIM1_OC2Init, TIM1_OC3Init, TIM1_BDTRConfig,
TIM1_SelectOutputTrigger, TIM1_ClearITPendingBit, TIM1_ITConfig,
TIM1_Cmd, ADC_DeInit, ADC_Cmd, ADC_StructInit, ADC_Init,
ADC_StartCalibration, ADC_GetCalibrationStatus,
ADC_InjectedSequencerLengthConfig, ADC_InjectedChannelConfig,
ADC_ExternalTrigInjectedConvCmd, NVIC_PriorityGroupConfig,
NVIC_StructInit, NVIC_Init.
Motor control library:
SVPWM_IcsCurrentReadingCalibration

59/112
Library functions UM0483

SVPWM_IcsCurrentReadingCalibration

Synopsis void SVPWM_IcsCurrentReadingCalibration(void);


Description The purpose of this function is to store the two analog voltages
corresponding to zero current values for compensating the offset
introduced by both ICSs and amplification network.
Input None.
Returns None.
Note This function is called by MCL_Init which is executed at every motor
startup. It reads the analog voltage on the A/D channels used for
current reading before the PWM outputs are enabled so that the
current flowing through the inverter is zero.
Functions called Standard Library:
ADC_ITConfig, ADC_ExternalTrigInjectedConvConfig,
ADC_ExternalTrigInjectedConvCmd,
ADC_InjectedSequencerLengthConfig, ADC_InjectedChannelConfig,
ADC_SoftwareStartInjectedConvCmd, ADC_GetFlagStatus,
ADC_GetInjectedConversionValue
Motor Control library:
SVPWM_IcsInjectedConvConfig

SVPWM_IcsGetPhaseCurrentValues

Synopsis Curr_Components SVPWM_IcsGetPhaseCurrentValues(void);


Description This function computes current values of Phase A and Phase B in
q1.15 format from the values acquired from the A/D converter.
Input None.
Returns Curr_Components type variable
Note In order to have a q1.15 format for the current values, the digital value
corresponding to the offset must be subtracted when reading phase
current A/D converted values. Thus, the function must be called after
SVPWM_IcsCurrentReadingCalibration.
Functions called None.

60/112
UM0483 Library functions

SVPWM_IcsCalcDutyCycles

Synopsis void SVPWM_IcsCalcDutyCycles (Volt_Components


Stat_Volt_Input);
Description After execution of the IFOC algorithm, new stator voltages component
Vα and Vβ are computed. The purpose of this function is to calculate
exactly the three duty cycles to be applied to motor phases from the
values of these voltage components.
Refer to Section 4.2.3 for details about the theoretical approach of
SVPWM and its implementation.
Input Vα and Vβ
Returns None.
Note None.
Functions called None.

SVPWMEOCEvent

Synopsis void SVPWMEOCEvent();


Description Routine to be performed inside the end-of-conversion ISR. It computes
the bus voltage and temperature sensor sampling.
Input None.
Returns Always true.
Note None.
Functions called ADC_GetInjectedConversionValue

SVPWMUpdateEvent

Synopsis void SVPWMUpdateEvent(void);


Description Routine to be performed inside the update event ISR. Nothing is
performed.
Input None
Returns None.
Note None.
Functions called None.

61/112
Library functions UM0483

4.4.3 Current sampling in isolated current sensor topology and integrating


general-purpose A/D conversions
The three currents I1, I2, and I3 flowing through a three-phase system follow the
mathematical relationship:
I1 + I2 + I3 = 0
Therefore, 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 relationship.
The flexibility of the STM32F103xx A/D converter trigger makes it possible to synchronize
the two A/D conversions necessary for reconstructing the stator currents flowing through the
three-phase AC induction motor with the PWM reload register updates. The update rate can
be adjusted using the repetition counter. This is important because, as shown in Figure 47,
it is precisely during counter overflow and underflow that the average level of current is
equal to the sampled current. Refer to the STM32F103xx Reference Manual to learn more
about A/D conversion triggering and the repetition counter.
Regular conversions are reserved for the user and must be configured manually (See also
firmware standard library user manual UM0427).

Figure 47. Stator currents sampling in ICS configuration (REP_RATE=1)

PWM Counter

Compare A

Compare B

Low side A

Low side B

Phase current
Average current

TIM1 Update, TIM1 Update, TIM1 Update,


ADC trigger ADC trigger ADC trigger

ai14854

62/112
UM0483 Library functions

4.5 Induction motor IFOC vector control: MC_IFOC_Drive


module

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.

4.5.2 List of available C functions


● IFOC_Init on page 63
● IFOC_Model on page 64
● IFOC_CalcFluxTorqueRef on page 66
● CalcIm on page 67
● CalcRotFlxSlipFreq on page 68

IFOC_Init

Synopsis void IFOC_Init(void)


Description This function is normally called at every motor startup. It performs
the initialization of some of the variables used for IFOC
implementation by the MC_IFOC_Drive.c module.
Input None.
Returns None.
Note None.
Functions called if working with ICs:
SVPWM_IcsCalcDutyCycles;
if working with three shunts:
SVPWM_3ShuntCalcDutyCycles;
if working with a single shunt:
SVPWM_1ShuntCalcDutyCycles.

63/112
Library functions UM0483

IFOC_Model

Synopsis void IFOC_Model (void)


Description The purpose of this function is to perform AC-IM torque and flux
regulation, implementing the IFOC vector algorithm.
Current commands iqsλr * and idsλr * (which, under field oriented
conditions, can control machine torque and flux respectively) are defined
outside this function (in Speed control mode they are provided, by means
of speed and flux regulators, by the IFOC_CalcFluxTorqueRef function,
while in Torque control mode they are settled by the user).
Therefore, as a current source is required, the function has to run the
power converter as a CR-PWM. For this purpose, it implements a high
performance synchronous (d, q) frame current regulator, whose operating
frequency is defined, as explained in Section 2.2.2, by the parameter
REP_RATE (in conjunction with PWM_FREQ).
Triggered by ADC JEOC ISR, the function loads stator currents (read by
ICS or shunt resistors) and carries out Clark and Park transformations,
converting them to iqsλr and idsλr (see Figure 5).
Then, these currents are fed to PID regulators together with reference
values iqsλr * and idsλr *. The regulator output voltages vqsλr * and vdsλr *
then must be transformed back to a stator frame (through Reverse Park
conversion), and finally drive the power stage.
In order to correctly perform Park and Reverse Park transformation, it is
essential to accurately estimate the rotor flux position (θ λr) (because
currents have to be oriented in phase and in quadrature with rotor flux). To
manage this task:
– function CalcIm is called to provide lm, that is the estimated value of the rotor
flux as a response to the variation of input current idsλr (see CalcIm function
description);
– function CalcRotFlxSlipFreq (see CalcRotFlxSlipFreq function description)
evaluates rotor flux slip frequency ωsλr (relying on known rotor time constant); if
using a tachogenerator, the rotor flux position θ λr is calculated by integrating the
sum of ωsλr and rotor electrical speed ω r (Figure 49) while, with an incremental
encoder, θ λr is determined by summing the rotor electrical angle and the integral
of ωsλr (Figure 48).
Input None.
Returns None.

64/112
UM0483 Library functions

Functions CalcIm, CalcRotFlxSlipFreq;


called Clarke, Park, RevPark_Circle_Limitation;
PID_Regulator, Rev_Park;
If working with encoder:
ENC_Get_Electrical_Angle;
if Working with tachogenerator:
TAC_GetRotorFreq;
if working with ICS:
SVPWM_IcsGetPhaseCurrentValues, SVPWM_IcsCalcDutyCycles;
if working with three shunts:
SVPWM_3ShuntGetPhaseCurrentValues,
SVPWM_3ShuntCalcDutyCycles;
if working with a single shunt:
SVPWM_1ShuntGetPhaseCurrentValues,
SVPWM_1ShuntCalcDutyCycles.

Figure 48. Rotor flux angle calculation (quadrature encoder)


θλr calculation
uncompensated flux
response controller

ids λ i im
im = dr = ds
Lm τrs + l

iqs l i ωsλr θsλr


ωsλr = × qs
τr im

θr (electrical degrees) θλr


+

ai14790

65/112
Library functions UM0483

Figure 49. Rotor flux angle calculation (tachogenerator)


θλr calculation
uncompensated flux
response controller

ids λ i im
im = dr = ds
Lm τrs + l

iqs l i ωsλr
ωsλr = × qs
τr im

ωr (electrical degrees) ωλr θλr


+

ai14791

IFOC_CalcFluxTorqueRef

Synopsis void IFOC_CalcFluxTorqueRef (void)


Description This function provides current components iqs* and ids* to be used
as reference values (by the IFOC_Model function) in Speed control
mode (see “Torque & Flux optimization” block in Figure 50).
Speed setpoint and actual rotor speed ωr are compared in a PID
control loop, whose output is iqs**. This component, together with
the previous flux reference and the rotor speed ωr, is used to work
out the stator frequency that has to be generated. With this
information, two lookup-tables (described in MC_ACmotor_prm,
Section 2.2.5, defined by taking into account the field weakening
strategy explained in Section 4.5.4) are run through, in order to get
the optimal flux reference (ids*) and the saturation value of the
torque current component (iqs max) that allow to reach the desired
speed (under the obvious limitations of rated torque and rated
power).
Input None.
Returns None.
Functions called PID_Regulator;
mul_q15_q15_q31, div_q31_q15_q15.

66/112
UM0483 Library functions

Figure 50. Torque and flux optimization block

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

Synopsis s16 CalcIm (s16 hId_input);


Description The purpose of this routine is to supply (to the calling function) the
estimated value of the rotor flux, as a response to variations of the
input current value idsλr (see “uncompensated flux response
controller” block in Figure 48 and Figure 49).
See Section 4.5.3 for in-depth information about the computations
implemented.
Input Stator current idsλr in q1.15 format.
Returns Magnetizing current im (defined as rotor flux λr divided by
magnetizing inductance Lm) in q1.15 format.
Functions called mul_q15_q15_q31

67/112
Library functions UM0483

CalcRotFlxSlipFreq

Synopsis s32 CalcRotFlxSlipFreq (s16 hIq_input, s16 hIm_input)


Description This function estimates the rotor flux slip frequency ωsλr (central
block in Figure 48 and Figure 49), as result of currents iqsλr and im
(λdrλr/Lm).
See Section 4.5.3 for an in-depth comprehension of the
implemented computations.
Input Stator current iqsλr and magnetizing current im, both in q1.15 format.
Returns Rotor flux slip frequency, expressed in pulses per PWM period *
65536 (65536 pulses = 2π radiants).
Functions called mul_q15_q15_q31
div_q31_q15_q15

4.5.3 Detailed explanation about indirect field oriented control (IFOC)


Consider the voltage equations of an induction machine, being transformed on a reference
frame (q, d) that is synchronous with the rotor flux λr (about reference frame theory see [1]
in Appendix A.7: References on page 110):

λ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

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

where τ r is the rotor time constant, τ r = Lr / rr.


Therefore, a lag in flux response is caused to this first order transfer function between idsλr
and λdrλr.
The CalcIm routine performs a numerical integration using Euler’s method which, for a first
order ODE written as y' = f (t,y) , may be summarized in this way: y n + 1 = y n + Δt ⋅ f (t n,y n) ,
where t is the sampling time.
λr λr
⎛ λ dr⎞ 1- ⎛ λ r λ dr⎞
Putting the equation above in the explicit form, we have: ⎜ -------
-⎟ ' = ---- × ⎜ i ds – --------⎟
⎝ Lm ⎠ τr ⎝ Lm ⎠
λr λr λr
⎛ λ dr⎞ ⎛ λ dr⎞ Δt ⎛ λ ⎛ λ dr⎞ ⎞
⎜ --------⎟ = ⎜ --------⎟ + ----- × ⎜ ( i ds ) n – ⎜ --------⎟ ⎟
L
⎝ m⎠ n + 1 ⎝ m⎠ n τ r
L ⎝ ⎝ L m ⎠ n⎠

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

This equation (implemented in the CalcRotFlxSlipFreq function, see CalcRotFlxSlipFreq on


page 68) is at the foundation of indirect field oriented control: it tells us that the rotor flux slip
frequency ωsλr may be simply calculated from stator current components (relying on
knowledge of the rotor time constant of the machine).
If rotor angle or rotor speed is known (see Figure 48 and Figure 49 respectively), then we
have managed to determine the rotor flux position θλr. This information is essential to
achieve optimum control.

69/112
Library functions UM0483

4.5.4 Detailed explanation about field weakening operation


Many applications need to operate induction machines above their rated speed: this is
achieved by means of field weakening.
The conventional method for the field weakening operation is to vary the rotor flux reference
in proportion to the inverse of the rotor speed ωr.
In this approach, if maximum inverter modulation index is required when attaining rated
speed and rated power, then the voltage margin, enough to regulate current beyond that
point, is not available: this is caused by increased voltage drop across the stator leakage
inductance.
That’s why, when 1/ωr method is implemented, the inverter voltage is generally limited at
95% of its means.
The AC IM IFOC software library, however, makes use of a maximum torque capability
scheme (see [2] in Appendix A.7: References on page 110), which aims to exploit the
system resources completely.
In both cases, DC bus voltage limitation (VDCmax), inverter current rating and motor thermal
rating (usually, in order to provide better dynamic response, the inverter current rating is
higher than that of the machine) must be considered, and a precise knowledge of motor
parameters, such as magnetizing inductance Lm, rotor leakage inductance Llr, rotor
resistance rr, is required.
There are two different field weakening operation regions (see Figure 51):
● the constant power region, where rotor flux is decreased inversely with the speed
(considering the influence of the voltage drop across Lls) while slip frequency increases
until breakdown value;
● the constant power speed region, where rotor flux is decreased, but keeping the slip
frequency fixed at breakdown value.

70/112
UM0483 Library functions

Figure 51. Torque vs. speed characteristic curve

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 Reference frame transformations: MC_Clarke_Park module

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

Figure 52. Clarke, Park, and reverse Park transformations

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

4.6.2 List of available C functions


● Clarke on page 73
● Park on page 73
● Rev_Park on page 74
● Rev_Park_Circle_Limitation on page 74

Clarke

Synopsis Curr_Components Clarke (Curr_Components Curr_Input)


Description This function transforms stator currents ias and ibs (which are
directed along axes each displaced by 120 degrees) into currents iα
and iβ in a stationary (α, β) reference frame; α, β axes are directed
along paths orthogonal to each other.
See Section 4.6.3 for the details.
Input Stator currents ias and ibs (in q1.15 format) as members of the
variable Curr_Input, which is a structure of type Curr_Components.
Returns Stator currents iα and iβ (in q1.15 format) as members of a structure
of type Curr_Components.
Functions called mul_q15_q15_q31

Park

Synopsis Curr_Components Park (Curr_Components Curr_Input, s16 Theta)


Description The purpose of this function is to transform stator currents iα and iβ,
which belong to a stationary (α, β) reference frame, to a rotor flux
synchronous reference frame (q,d) (properly oriented), so as to
obtain iqs and ids.
See Section 4.6.3 for details.
Input Stator currents iα and iβ (in q1.15 format) as members of the variable
Curr_Input, which is a structure of type Curr_Components; rotor flux
angle θλr (65536 pulses per revolution).
Returns Stator currents iqs and ids (in q1.15 format) as members of a
structure of type Curr_Components.
Functions called mul_q15_q15_q31

73/112
Library functions UM0483

Rev_Park

Synopsis Volt_Components Rev_Park (Volt_Components Volt_Input)


Description This function transforms 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β.
See Section 4.6.3 for details.
Input Stator voltages vqs and vds (in q1.15 format) as members of the
variable Volt_Input, which is a structure of type Volt_Components.
Returns Stator voltages vα and vβ (in q1.15 format) as members of a
structure of type Volt_Components.
Functions called mul_q15_q15_q31

Rev_Park_Circle_Limitation

Synopsis void RevPark_Circle_Limitation(void)


Description After the two new values (Vd and Vq) of the stator voltage producing
flux and torque components of the stator current, have been
independently computed by flux and torque PIDs, it is necessary to
2 2
saturate the magnitude of the resulting vector, equal to V d + V q
before passing them to the Rev_Park function. The purpose of this
routine is to perform the saturation. Refer to Section 4.6.4: Circle
limitation on page 76 for more detailed information
Input None.
Returns None.
Note The limitation of the stator voltage vector must be done in
accordance with the PWM frequency as shown in Table 2: PWM
frequency vs. maximum duty cycle relationship for three-shunt
topology on page 48.
Functions called None.

4.6.3 Detailed explanation about reference frame transformations


Induction machines show very complex voltage equations, because of the time-varying
mutual inductances between stator and rotor circuits.
By making a change of variables, that refers stator and rotor quantities to a frame of
reference rotating at any angular velocity, it is possible to reduce the complexity of these
equations.
This strategy is often referred to as the Reference-Frame theory (see [1] in Appendix A.7:
References on page 110).
Supposing fax, fbx, fcx are three-phase instantaneous quantities directed along axis each
displaced by 120 degrees, where x can be replaced with s or r to treat stator or rotor
quantities (see Figure 53); supposing fqx, fdx, f0x are their transformations, directed along
paths orthogonal to each other; the equations of transformation to a reference frame
(rotating at an arbitrary angular velocity ω) can be expressed as:

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

4.6.4 Circle limitation


As discussed above, FOC allows to separately control the torque and the flux of a 3-phase
induction motor. After the two new values( Vd and Vq ) of the stator voltage producing flux
* *

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.

Figure 54. Circle limitation working principle

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

4.7 Encoder feedback processing: stm32f10x_encoder


module

4.7.1 List of available functions and interrupt service routines


The following is a list of available functions as listed in the stm32f10x_encoder.h header
file:
● ENC_Init on page 79
● ENC_Get_Electrical_Angle on page 79
● ENC_Get_Mechanical_Angle on page 79
● ENC_Clear_Speed_Buffer on page 80
● ENC_Get_Mechanical_Speed on page 80
● ENC_Calc_Average_Speed on page 80
● ENC_ErrorOnFeedback on page 80
● TIMx_IRQHandler - interrupt routine on page 81

78/112
UM0483 Library functions

ENC_Init

Synopsis void ENC_Init(void)


Description The purpose of this function is to initialize the encoder timer. The
peripheral clock, input pins and update interrupt are enabled. The
peripheral is configured in 4X mode, which means that the counter is
incremented/decremented on the rising/falling edges of both timer
input 1 and 2 (TIMx_CH1 and TIMx_CH2 pins).
Functions called RCC_APB1PeriphClockCmd, RCC_APB2PeriphClockCmd,
GPIO_StructInit, GPIO_Init, NVIC_Init, TIM_DeInit,
TIM_TimeBaseStructInit, TIM_TimeBaseInit,
TIM_EncoderInterfaceConfig, TIM_ICInit, TIM_ClearFlag,
TIM_ITConfig, TIM_Cmd
See also STM32F103xx datasheet: synchronizable standard timer.

ENC_Get_Electrical_Angle

Synopsis s16 ENC_Get_Electrical_Angle(void)


Description This function returns the electrical angle in signed 16-bit format. This
routine returns: 0 for 0 degrees, -32768 (S16_MIN) for -180 degrees,
+32767 (S16_MAX) for +180 degrees.
Input None
Output Signed 16 bits
Functions called None

ENC_Get_Mechanical_Angle

Synopsis s16 ENC_Get_Mechanical_Angle(void)


Description This function returns the mechanical angle in signed 16-bit format. This
routine returns: 0 for 0 degrees, -32768 (S16_MIN) for -180 degrees,
+32767 (S16_MAX) for +180 degrees.
Input None
Output Signed 16 bits
Functions called None
Note Link between Electrical/Mechanical frequency/RPM:
Electrical frequency = number of pair poles x mechanical frequency
RPM speed = 60 x Mechanical frequency (RPM: revolutions per minute)
Example: electrical frequency = 100 Hz, motor with 8 pair poles:
100Hz electrical <-> 100/8 =12.5Hz mechanical <-> 12.5 x 60=750
RPM

79/112
Library functions UM0483

ENC_Clear_Speed_Buffer

Synopsis void ENC_Clear_Speed_Buffer(void)


Description This function resets the buffer used for speed averaging.
Functions called None

ENC_Get_Mechanical_Speed

Synopsis s16 ENC_Get_Mechanical_Speed(void)


Description This function returns the rotor speed in Hz. The value returned is given
with 0.1Hz resolution, which means that 1234 is equal to 123.4 Hz.
Input None
Output Signed 16 bits
Functions called None
Note This routine returns the mechanical frequency of the rotor. To find the
electrical speed, use the following conversion:
electrical frequency = number of pole pairs * mechanical frequency

ENC_Calc_Average_Speed

Synopsis void ENC_Calc_Average_Speed(void)


Description This function must be called every SPEED_MEAS_TIMEBASE ms; it
computes the latest speed measurement, if it is out of the range
specified in MC_encoder_param.h, then the error counter is
incremented and the speed is saturated. Furthermore, if the error
counter is higher than MAXIMUM_ERROR_NUMBER, the boolean variable
storing the error status is set. Finally, the new average value is computed
based on the latest SPEED_BUFFER_SIZE speed measurement.
Functions called ENC_Calc_Rot_Speed
Input None
Returns None

ENC_ErrorOnFeedback

Synopsis bool ENC_ErrorOnFeedback(void)


Description This function simply returns the status of the boolean variable
containing the speed measurement error status which is updated every
SPEED_MEAS_TIMEBASE ms by the ENC_Calc_Average_Speed
function. In the proposed firmware library this function is called in Run
state by the main to check for possible faults of the speed feedback
(such as disconnected encoder wires).
Functions called None
Input None
Returns boolean, TRUE if an error occurred, FALSE otherwise.

80/112
UM0483 Library functions

TIMx_IRQHandler - interrupt routine

Synopsis void TIMx_IRQHandler(void)


Description This is the encoder timer (TIMER 2, 3 or 4) update routine. An
interruption is generated whenever an overflow/underflow of the
counter value occurs (TIMx_CNT). The ‘Encoder_Timer_Overflow’
variable is then incremented.
Functions called None
Note This is an interrupt routine.
See also STM32F103xx reference manual: TIMx in encoder interface mode.

4.8 Tachogenerator feedback processing: stm32f10x_tacho


module

4.8.1 List of available functions and interrupt service routines


The following is a list of available functions as listed in the stm32f10x_tacho.h header
file:
● TAC_TachoTimerInit on page 82
● TAC_InitTachoMeasure on page 82
● TAC_GetRotorFreqInHz on page 82
● TAC_GetRotorFreq on page 83
● GetLastTachoPeriod on page 83 (this is a private function defined inside the
stm32f10x_tacho.c file)
● GetAvrgTachoPeriod on page 83 (this is a private function defined inside the
stm32f10x_tacho.c file)
● TAC_IsTimedOut on page 84
● TAC_ClrTimeOut on page 84
● TAC_GetCaptCounter on page 84
● TAC_ClrCaptCounter on page 84
● TAC_StartTachoFiltering on page 85
● TAC_ValidSpeedInfo on page 85
● TIMx_IRQHandler on page 86

81/112
Library functions UM0483

TAC_TachoTimerInit

Synopsis void TAC_TachoTimerInit(void)


Description The purpose of this function is to initialize the timer that will perform the
tacho signal period measurement (the timer can be chosen in the
MC_tacho_prm.h file). The peripheral clock and the capture interrupt are
enabled, and the timer is initialized in Slave reset mode.
Functions TIM_ICStructInit, TIM_TimeBaseInit, TIM_ICInit, TIM_PrescalerConfig,
called TIM_InternalClockConfig, TIM_SelectInputTrigger, TIM_SelectSlaveMode,
TIM_UpdateRequestConfig, NVIC_Init, TIM_ClearFlag, TIM_ITConfig
Note The timer starts counting at the end of the routine.
See also STM32F103xx datasheet: general-purpose timer (TIMx).

TAC_InitTachoMeasure

Synopsis void TAC_InitTachoMeasure(void)


Description This function clears the software FIFO where the latest speed data
are stored. This function must be called every time the motor is started
to initialize the speed measurement process.
Input None.
Output None.
Functions called TIM_ITConfig, TIM_Cmd
Note The first measurements following this function call are done without
filtering (the rolling average mechanism is disabled).
See also STM32F103xx datasheet: general-purpose timer (TIMx).

TAC_GetRotorFreqInHz

Synopsis u16 TAC_GetRotorFreqInHz (void)


Description This routine returns the rotor frequency with [0.1Hz] definition. The
result is given by the following formula:
Frotor = K x (FOSC / (Capture + number of overflow x FFFF)) where K
depends on the number of motor and tacho pole pairs.
Input None.
Output Rotor mechanical frequency, with 0.1 Hz resolution, unsigned 16 bits
(direction cannot be determined using a tacho).
Functions called GetAvrgTachoPeriod, GetLastTachoPeriod (both private functions)
Note Result is zero if speed is too low (glitches at start for instance).
Excessive speed (or glitches) will result in a pre-defined value returned
(see Section 2.2.4 on page 18).
Maximum expectable accuracy depends on CKTIM: 72 MHz will give
the best results.
Caution This routine returns the mechanical frequency of the rotor. To find the
electrical speed, use the following conversion:
electrical frequency = mechanical frequency * number of pole pairs

82/112
UM0483 Library functions

TAC_GetRotorFreq

Synopsis u16 TAC_GetRotorFreq (void)


Description This routine returns rotor frequency with a unit that can be directly
integrated (accumulated) to get the rotor angular position in the main
control loop.
Input None.
Output Rotor mechanical frequency with rad/PWM period unit
(2π rad = 0xFFFF), assuming the control loop is executed in each
and every PWM interrupt service routine.
Functions called GetAvrgTachoPeriod, GetLastTachoPeriod (both private functions)
Note Result is zero if speed is too low (glitches at start for instance).
Excessive speed (or glitches) will result in a pre-defined value
returned (see Section 2.2.4 on page 18).
Maximum expectable accuracy depends on CKTIM: 72 MHz will give
the best results.

GetLastTachoPeriod

Synopsis u32 GetLastTachoPeriod(void)


Description This routine returns the rotor period based on the last tacho capture.
Input None.
Output Tacho signal period, unit is 1 CKTIM period, unsigned 32-bit format.
Functions called None.
Note This function is private to the stm32f10x_tacho.c module.

GetAvrgTachoPeriod

Synopsis u32 GetAvrgTachoPeriod(void)


Description This routine returns the rotor period based on the average of the four
last tacho captures.
Input None.
Output Tacho signal period, unit is 1 CKTIM period, unsigned 32-bit format.
Functions called None.
Note This function is private to the stm32f10x_tacho.c module.

83/112
Library functions UM0483

TAC_IsTimedOut

Synopsis bool TAC_IsTimedOut(void)


Description This routine indicates to the upper layer software that tacho information
has disappeared (or that the period of the signal has drastically
increased).
Input None.
Output Boolean, TRUE in case of time-out
Functions called None.
Note The time-out duration depends on tacho timer pre-scaler, which is
variable: the time-out is higher at low speed.
The boolean will remain set to TRUE until the TAC_ClrTimeOut is called.

TAC_ClrTimeOut

Synopsis void TAC_ClrTimeOut (void)


Description This routine clears the flag indicating that information is lost, or that
speed is decreasing sharply.
Input None.
Output None.
Note This function must be called to re-arm the time-out detection mechanism
and re-start rotor frequency measurements: the returned frequency is 0
as long as the timeout flag is set.

TAC_GetCaptCounter

Synopsis u16 TAC_GetCaptCounter(void)


Description This routine gives the number of tacho capture interrupts since the last call
to the TAC_ClrCaptCounter function.
Input None.
Output Unsigned 16-bit integer. This variable cannot roll-over (this is prevented in
the tacho capture routine itself): it will be limited to max u16 value.
Note This function is typically used to monitor the interrupts activity (while the
motor is running, tacho-related interrupts must not be stopped or too
frequent).
See also TAC_ClrCaptCounter

TAC_ClrCaptCounter

Synopsis void TAC_ClrCaptCounter(void)


Description This routine clears the number of capture events variable.
Input None.
Output None.

84/112
UM0483 Library functions

TAC_StartTachoFiltering

Synopsis void TAC_StartTachoFiltering(void)


Description This routine initiates the tacho value smoothing mechanism. The
result of the next capture will be copied in all storage array locations
to have the first average equal to the last value.
Input None.
Output None.
Note The initialization of the FIFO used to do the averaging will be done
when the next tacho capture interrupt occurs. Consequently, the
TAC_GetRotorFreq will continue to return a raw period value until the
next interrupt event.

TAC_ValidSpeedInfo

Synopsis bool TAC_ValidSpeedInfo(u16 hMinRotorFreq)


Description This routine indicates if the information provided by the
tachogenerator is reliable: this is particularly important at startup,
when the signal of the tacho is very weak and cannot be properly
conditioned by the external circuitry (glitches). It is also used in
startup functions to find out if the rotor shaft is turning at the right
speed.
Input Rotor frequency (0.1Hz resolution) above which speed information is
not considered reliable (rolling averages cannot be computed).
Output Boolean, TRUE if the tacho provides clean signals.
Caution Because there is no way to differentiate rotation direction with a
tachogenerator, you must be aware that this routine may return
TRUE in certain conditions (re-start with very short or no stop time
and high inertia load). You should, therefore, manage a minimal
amount of time before re-starting.
This function is not effective if the startup duration (time for the
voltage to settle) is much shorter than the time needed to obtain at
least two consecutive speed data.

85/112
Library functions UM0483

TIMx_IRQHandler

Synopsis void TIMx_IRQHandler(void)


Description This function handles
● the capture event interrupt in charge of tacho signal period
measurement. It updates an array where the 4 latest period
measurements are stored, resets the overflow counter and
updates the clock prescaler to optimize the accuracy of the
measurement. If the average is enabled, the last captured
measurement is copied into the whole array. Period captures
are managed as follows:
– If too low (capture value below 0x5500), the clock prescaler
is decreased for the next measurement
– If too high (for example, the timer overflowed), the result is
re-computed as if there was no overflow and the prescaler
is increased to avoid overflows during the next capture.
● the overflow of the timer in charge of the tacho signal period
measurement. It updates a Counter of overflows, which is reset
when next capture occurs
Input None.
Output None.
Note This is an interrupt routine.

4.8.2 Integration tips


In the MC_tacho_prm.h file of your project, select the Timer you have chosen and the input
channel on which the tacho signal arrives, using the right #define (see Section 2.2.4 on
page 18).
In the main.c module (or the c module just above stm32f10x_tacho), include the
stm32f10x_tacho.h file, call TAC_TachoTimerInit() after MCU reset and
TAC_InitTachoMeasure() before motor startup. TAC_GetRotorFreqInHz returns a
frequency directly with 0.1Hz, while TAC_GetRotorFreq returns a value that can be
directly accumulated in the FOC algorithm to get the rotor angular position (the unit is 2π rad
(that is 0xFFFF) per sampling period).

4.8.3 Operating principle


Although the principle of measuring a period with a timer is quite simple, you must pay
attention to keeping the best resolution, in particular for signals such as the one provided by
a tachogenerator, which can vary with a ratio of up to 1:100.
In order to have always the best resolution, the timer clock prescaler is constantly adjusted
in the current implementation.
The basic principle is to speed-up the timer if captured values are too low (for an example of
low periods, see Figure 55), and slow it down when the timer overflows between two
consecutive captures (see example of large periods in Figure 56).

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.

Figure 55. Automatic tacho timer prescaler decrease


Capture Capture Capture Capture

0xFFFF

Capture value is too low,


the prescaler is decreased

0x5500

0x0000

Prescaler (preload) 30 29 29 29

Prescaler (active) 30 30 29 29
Transfer from preload to active on
next capture (= update) event

Figure 56. Automatic tacho timer prescaler increase

Capture Capture Capture Capture

0xFFFF
ovf ovf
Timer overflowed, the
prescaler is increased

0x5500

0x0000

Prescaler (preload) 30 31 31 31

Prescaler (active) 30 30 31 31

Transfer from preload to active on


next capture (= update) event

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

4.8.4 Converting Hertz into pseudo frequency


From the definition of frequency (1Hz is equal to 2π rad.s-1), it is easy to define a pseudo
frequency format, so that the rotor angular position can be easily determined by
accumulating the rotor speed information every time the control loop is executed (for
example, during PWM update interrupt service routine). Providing that 2π = 0xFFFF (so that
angle roll-overs do not need to be managed), the frequency with 0.1Hz unit can easily be
converted into pseudo frequency using the following formula:

0xFFFF
F pseudo = F [ 0.1Hz ] × -------------------------------------
10 × F pwm ( Hz )

4.9 PID regulators: MC_PID_regulators module

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

4.9.2 List of available functions and interrupt service routines


The following is a list of available functions in the MC_PID_regulators module:
● PID_Init on page 88
● PID_Regulator on page 89
● PID_Speed_Coefficients_update on page 89

PID_Init

Synopsis void PID_Init (PID_Struct_t *PID_Torque, PID_Struct_t *PID_Flux,


PID_Struct_t *PID_Speed)
Description The purpose of this function is to initialize the PIDs for torque, flux
and speed regulation. For each one, a set of default values are
loaded: target (speed, torque or flux), proportional, integral and
derivative gains, lower and upper limiting values for the output.
Input PID_Struct_t *, PID_Struct_t *, PID_Struct_t * (see MC_type.h for
structure declarations)
Functions called None
Note Default values for PID regulators are declared and can be modified
in the MC_Control_Param.h file (see Section 2.2.2 on page 15).

88/112
UM0483 Library functions

PID_Regulator

Synopsis s16 PID_Regulator(s16 hReference, s16 hPresentFeedback,


PID_Struct_t *PID_Struct)
Description The purpose of this function is to compute the output of a PID
regulator instance at a certain step K, to make the sum of its
proportional, integral and derivative terms (the derivative term is
computed if the DIFFERENTIAL_TERM_ENABLED option is
uncommented, see Section 2.2.1)
Input hReference (the desired setpoint), hPresentFeedback (the
measured output of the controlled system), PID_Struct_t
*PID_Struct (pointer to a PID_Struct_t variable which is the regulator
instance itself, as it retains its gains, internal states, integral sum
limits and output limits (see MC_type.h for structure declarations)
Output The controller output (signed 16 bits)
Functions called None
Note The demo program has several “instances” of this PID regulator;
default values for the PID regulation of currents and speed can be
modified in the MC_Control_Param.h file (see Section Section 2.2.2
on page 15). The PID_Regulator function updates the internal
states of the PID regulator instance (integral sum, previous error)
through the input pointer to the PID_Struct_t variable.
See also Function PID_Init

PID_Speed_Coefficients_update

Synopsis void PID_Speed_coefficients_update(s16 motor_speed)


Description This function automatically computes the proportional, integral and
derivative gain for the speed PID regulator according to the actual
motor speed. The computation is done following a linear curve
based on 4 set points. See Section 4.9.5 on page 91 for more
information.
Functions called None
Caution Default values for the four set points are declared and can be
modified in the MC_Control_Param.h file (see Section 2.2.2 on page
15).

89/112
Library functions UM0483

4.9.3 PID regulator theoretical background


The regulators implemented for Torque, Flux and Speed are actually Proportional Integral
Derivative (PID) regulators (see note below regarding the derivative term). PID regulator
theory and tuning methods are subjects which have been extensively discussed in technical
literature. This section provides a basic reminder of the theory.
PID regulators are useful to maintain a level of torque, flux or speed according to a desired
target.

Figure 57. PID general equation

torque = f(rotor position) torque and flux regulation for maximum


flux = f(rotor position) system efficiency

torque = f(rotor speed) torque regulation for speed regulation


of the system

Where: Error sys Error of the system observed at time t = T


T

Error sys Error of the system observed at time t = T - Tsampling


T–1

f ( X T ) = K p × Error sys + K i ×
T ∑Errorsys + Kd × ( Errorsys
t T
– Error sys
T–1
) (1)
0

Derivative term can be disabled

Equation 1 corresponds to a classical PID implementation, where:


● Kp is the proportional coefficient,
● Ki is the integral coefficient.
● Kd is the differential coefficient.
Note: As mentioned in Figure 57, the derivative term of the PIDs can be disabled (through a
compiler option, see stm32f10x_MCconf.h file).

4.9.4 Regulator sampling time setting


The sampling time needs to be modified to adjust the regulation bandwidth. As an
accumulative term (the integral term) is used in the algorithm, increasing the loop time
decreases its effects (accumulation is slower and the integral action on the output is
delayed). Inversely, decreasing the loop time increases its effects (accumulation is faster
and the integral action on the output is increased). This is why this parameter has to be
adjusted prior to setting up any coefficient of the PID regulator.
In order to keep the CPU load as low as possible and as shown in equation (1) in Figure 57,
the sampling time is directly part of the integral coefficient, thus avoiding an extra
multiplication. Figure 58 describes the link between the time domain and the discrete
system.

90/112
UM0483 Library functions

Figure 58. Time domain to discrete PID equations

t d Error
Time domain f ( t ) = K p × Error sys ( t ) + K i × ∫ 0
Error sys ( t )dt + K d ×
dt
( sys ( t ) )

Discrete f ( X T ) = K p × Error sys + k i × T s ∑Error sys + K d × ( Error sys – Error sys )


T t T T–1
domain
0
(sampling done at Fs = 1/Ts frequency)
ki × Ts = Ki

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

//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

//Settings for intermediate frequency 1


#define F_1 50 // 5 Hz mechanical
#define Ki_F_1 2000 // Intermediate frequency 1 coefficient settings
#define Kp_F_1 1000
#define Kd_F_1 2500

//Settings for intermediate frequency 2


#define F_2 200 // 20 Hz mechanical
#define Ki_F_2 1000 // Intermediate frequency 2 coefficient settings
#define Kp_F_2 750
#define Kd_F_2 1200

//Settings for max frequency


#define Freq_Max 500 // 50 Hz mechanical
#define Ki_Fmax 500 // Frequency max coefficient settings
#define Kp_Fmax 500
#define Kd_Fmax 500

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

Figure 59. Linear curve for coefficient computation


Ki, Kp, Kd

Ki_F_2, Kp_F_2, Kd_F_2

Ki_Fmax, Kp_Fmax
Kd_Fmax

Ki_F_1, Kp_F_1, Kd_F_1

Ki_Fmin, Kp_Fmin, Kd_Fmin

Rotor mechanical
F_min F_1 F_2 F_max frequency

92/112
UM0483 Library functions

Disabling the linear curve computation routine, stm32f10x_Timebase


module
If you want to disable the linear curve computation, you must comment out the
PID_Speed_Coefficients_update(..) routine. In this case, the default values for Ki,
Kp, Kd for torque, flux and speed regulation are used. See PID_TORQUE_Kx_DEFAULT,
PID_FLUX_Kx_DEFAULT, PID_SPEED_Kx_DEFAULT, in the MC_control_Param.h file.
To disable the linear curve computation routine in stm32f10x_Timebase.c:
void SysTickHandler(void)
{
[…]
if(State == RUN)
{
if ((wGlobal_Flags & CLOSED_LOOP) == CLOSED_LOOP)
{
[…]
//PID_Speed_Coefficients_update(hRot_Freq_Hz); //to be commented out
[…]
}

4.10 Main interrupt service routines: stm32f10x_it module

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.

4.10.2 List of non-empty interrupt service routines


As mentioned above only three interrupts are managed by motor control tasks:
● TIM1_BRK_IRQHandler on page 94
● TIM1_UP_IRQHandler on page 94
● ADC1_2_IRQHandler on page 94

93/112
Library functions UM0483

TIM1_BRK_IRQHandler

Synopsis void TIM1_BRK_IRQHandler(void)


Description The purpose of this function is to manage a break input signal on
the dedicated BRK IN pin. In particular, TIM1 outputs are disabled,
the main state machine is put into FAULT state.
Input None.
Returns None.
Functions called MCL_SetFault, TIM1_ClearITPendingBit
See also Advanced control timer (TIM1) in STM32F103xx reference manual

TIM1_UP_IRQHandler

Synopsis void TIM1_UP_IRQHandler(void)


Description This interrupt handler is executed after an update event when an
underflow of the TIM1 counter occurs. Inside this handler, the
specific SVPWMUpdateEvent routine related to the selected
current-sampling method (single-shunt, three-shunt or ICS) is
called.
Input None.
Returns None.
Functions called ADC_ClearFlag, TIM1_ClearFlag, SVPWMUpdateEvent

ADC1_2_IRQHandler

Synopsis void ADC1_2_IRQHandler(void)


Description The purpose of this function is to handle the ADC interrupt
request.
The end of the stator current conversion interrupt routine (JEOC)
is utilized to trigger execution of the IFOC algorithm. External ADC
triggering is disabled until the next TIM1 update event is
generated. Inside the handler, the specific routine
SVPWMEOCEvent related to the current-sampling method
(single-shunt, three-shunt or ICS) is called. This routine returns
true if the current sampling has completed for this PWM period, so
that FOC-related routines can be executed.
Input None.
Returns None.
Functions called SVPWMEOCEvent, IFOC_Model
See also Section 4.2.4 and Section 4.4.3 on page 62 for more details.

94/112
UM0483 Library functions

4.11 General purpose time base: stm32f10x_Timebase module

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.

4.11.2 List of available functions and interrupt service routines


The following is a list of available functions as listed in the stm32f10x_Timebase.h
header file:
● TB_Init on page 95
● TB_Wait on page 95
● TB_StartUp_Timeout_IsElapsed, TB_Delay_IsElapsed,
TB_DisplayDelay_IsElapsed, TB_DebounceDelay_IsElapsed on page 96
● TB_Set_Delay_500us, TB_Set_DisplayDelay_500us,
TB_Set_StartUp_Timeout, TB_Set_DebounceDelay_500µs on page 96
● SysTickHandler on page 97

TB_Init

Synopsis void TB_Init(void)


Description The purpose of this function is to initialize the STM32 system tick
timer to generate an interrupt every 500 µs, thus providing a
general purpose timebase.
Input None
Returns None
Functions called SysTick_CLKSourceConfig, SysTick_SetReload,
SysTick_CounterCmd, NVIC_SystemHandlerPriorityConfig,
SysTick_ITConfig

TB_Wait

Synopsis void TB_Wait(u16 time)


Description This function produces a programmable delay equal to variable
‘time’ multiplied by 500µs.
Input Unsigned 16 bit
Returns None
Functions called None
Caution This routine exits only after the programmed delay has elapsed.
Meanwhile, the code execution remains frozen in a waiting loop.
Care should be taken when this routine is called at
main/interrupt level: a call from an interrupt routine with a higher
priority than the timebase interrupt will freeze code execution.

95/112
Library functions UM0483

TB_Set_Delay_500us, TB_Set_DisplayDelay_500us,
TB_Set_StartUp_Timeout, TB_Set_DebounceDelay_500µs

Synopsis void TB_Set_Delay_500us(u16)


void TB_Set_DisplayDelay_500us(u16)
void TB_Set_StartUp_Timeout(u16)
void TB_Set_DebounceDelay_500us
Description These functions are used to respectively update the values of the
hTimebase_500us, hTimebase_display_500us,
hStart_Up_TimeBase_500us and hKey_debounce_500us
variables. They are used to maintain the main state machine in
Fault state, to set the refresh rate of the LCD, the Startup timeout
and, to filter the user key bouncing.
Input Unsigned 16 bits
Returns None
Functions called None

TB_StartUp_Timeout_IsElapsed, TB_Delay_IsElapsed,
TB_DisplayDelay_IsElapsed, TB_DebounceDelay_IsElapsed

Synopsis bool TB_StartUp_Timeout_IsElapsed(void)


bool TB_Delay_IsElapsed(void)
bool TB_DisplayDelay_IsElapsed(void)
bool TB_DebounceDelay_IsElapsed(void)
Description These functions return TRUE if the related delay is elapsed,
FALSE otherwise.
Input None
Returns Boolean
Functions called None

96/112
UM0483 Library functions

SysTickHandler

Synopsis void SysTickHandler(void)


Description This is the System Tick timer interrupt routine. It is executed every
500µs, as determined by TB_Init and is used to refresh various
variables used mainly as counters (for example, PID sampling
time). Moreover, this routine implements the startup torque ramp
described in Section 3: Running the demo program on page 22.
Input None
Returns None
Functions called IFOC_CalcFluxTorqueRef, TB_ClearFlag,
If Encoder is used:
ENC_Get_Average_Speed
If Tacho is used:
TAC_GetRotorFreqInHz
Note This is an interrupt routine

4.12 Routines for monitoring and handling the system critical


parameters: MC_MotorControl_Layer module

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.

4.12.2 List of available functions


● MCL_Init on page 98
● MCL_Init_Arrays on page 98
● MCL_Chk_OverTemp on page 98
● MCL_Chk_BusVolt on page 99
● MCL_SetFault on page 99
● MCL_ChkPowerStage on page 99
● MCL_ClearFault on page 99
● MCL_Compute_BusVolt on page 100
● MCL_Compute_Temp on page 100

97/112
Library functions UM0483

MCL_Init

Synopsis void MCL_Init(void)


Description This function implements the motor control initializations to be
performed at each motor startup; it affects the initialization of PID
regulators, ADC calibration, speed sensors and high side driver boot
capacitors.
Functions called ENC_Clear_Speed_Buffer (or, alternatively,
TAC_InitTachoMeasure), IFOC_Init, TB_Set_StartUP_Timeout,
TIM1_CtrlPWMOutputs, TB_StartUp_Timeout_IsElapsed,
SVPWM_3ShuntCurrentReadingCalibration (or, alternatively,
SVPWM_IcsCurrentReadingCalibration)

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

Synopsis void MCL_Init_Arrays(void)


Description This function initializes the arrays used for temperature and bus
voltage measurements to avoid erroneous fault detection after an
MCU reset.

MCL_Chk_OverTemp

Synopsis bool MCL_Chk_OverTemp(void)


Description This function checks for overtemperature fault occurrences on the
heatsink connected to the power stage switches. The thresholds for
temperature and hysteresis values are defined by the user.
Returns Returns TRUE if the voltage on the thermal resistor connected to
ADC channel ADCIN_10 has reached the threshold level (or if it has
not yet returned to the threshold level minus the hysteresis value
after an overheat detection).
Functions called ADC_GetInjectedConversionValue.
See also Section 3.7: Fault messages on page 33 on how to set temperature
thresholds.

98/112
UM0483 Library functions

MCL_Chk_BusVolt

Synopsis BusV_t MCL_Chk_BusVolt(void)


Description This function checks for over and/or undervoltage faults on inverter
DC bus. The thresholds for under and overvoltages are defined by
the user.
Returns It returns a BusV_t type variable reporting the fault value.
Functions called ADC_GetInjectedConversionValue
See also Section 3.7: Fault messages on page 33 on how to set DC bus
voltage thresholds.

MCL_SetFault

Synopsis void MCL_SetFault (u16)


Description On an event fault occurrence, this function puts the state machine in
Fault state and disables the motor control outputs of Advanced
Control Timer TIM1 (PWM timer).
Input Sets the motor control status flag variable according to the cause of
the fault.
Functions called TB_Set_Delay_500us, TIM1_CtrlPWMOutputs

MCL_ChkPowerStage

Synopsis void MCL_ChkPowerStage(void)


Description This function checks the power stage operation under critical
conditions of temperature and bus voltage.
Functions called MCL_SetFault, MCL_Chk_OverTemp, MCL_Chk_BusVolt

MCL_ClearFault

Synopsis bool MCL_ClearFault(void)


Description This function checks if the fault source is over. If it is the case, it
clears the related flag and returns TRUE. Otherwise it returns
FALSE.
Returns TRUE or FALSE according to fault source status.
Functions called MCL_Chk_BusVolt, MCL_Chk_OverTemp, GPIO_ReadInputDataBit,
TAC_ClrTimeout (if Tacho speed sensor is used).

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

Synopsis u16 MCL_Compute_BusVolt(void)


Description This function computes the DC bus voltage in volt units.
Returns A value representing the bus voltage in volt units

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.

4.13 Application layer


Besides the implementation of the motor control state machine, the application layer
(main.c module) includes the configuration and initialization of basic peripherals.
Moreover, in this layer the LCD display and user input keys are managed by means function
calls belonging to two other modules. These modules are briefly described below.
● MC_Keys.c module
Centralizes all information regarding the keyboard reading. Any action on the keyboard
is processed in the Keys_process routine.
● MC_Display module
Centralizes all information regarding the LCD display management.
● stm32f10x_lcd module
Contains some dedicated routines for the control of the LCD embedded with the starter
kit.

100/112
UM0483 Additional information

Appendix A Additional information

A.1 Adjusting CPU load related to IFOC algorithm execution


The advanced control timer (TIM1) peripheral has the built-in capability of updating PWM
registers only after a given number of PWM semi-periods. This feature is handled by a
programmable repetition counter. It is particularly useful to adjust the CPU load related to
IFOC algorithm execution for a given PWM frequency (refer to STM32F103xx reference
manual for more information on programmable repetition counter).
When using ICSs, the injected chain of conversions for current reading is directly triggered
by a PWM register update event. Moreover, since the IFOC algorithm is executed at the end
of the injected chain of conversions in the related ISR, changing repetition counter has a
direct impact on IFOC refresh rate and thus on CPU load.
However, in the case of single- or three-shunt topology current reading, to ensure that the
IFOC algorithm is executed once for each PWM register update, it is necessary to keep the
synchronization between current conversion triggering and PWM register update. In the
proposed software library, this is automatically performed, so that you can reduce the
frequency of execution of the IFOC algorithm by simply changing the default value of the
repetition counter (the REP_RATE parameter in the MC_Control_Param.h header file).
Figure 60 shows current sampling triggering, and IFOC algorithm execution with respect to
PWM period when REP_RATE is set to 3.

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

ADC triggering interval


FOC algorithm execution

New duty cycle values ready


ai14849

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

A.2 Selecting the update repetition rate based on PWM


frequency for single or three-shunt resistor configurations
Beyond the well known trade-off between acoustical noise and power dissipation,
consideration should be given to selecting the PWM switching frequency using the AC IM
IFOC software library.
As discussed in Section 4.2.5 on page 44 and Section 4.3.4 on page 57, depending on the
PWM switching frequency, a limitation on the maximum applicable duty cycle could occur if
using the single- or three-shunt resistor configuration for current reading. Table 2: PWM
frequency vs. maximum duty cycle relationship for three-shunt topology on page 48 and
Table 4: PWM frequency vs. maximum duty cycle relationship for single-shunt topology on
page 58 summarize the performance of the system when the software library is used in
conjunction with STM3210B-MCKIT hardware. 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.
Note: The MB459 board is an evaluation platform; it is designed to support different motor driving
topologies (PMSM and AC induction) and current reading strategies (single and three shunt
resistors). Therefore, the figures given in Table 2 on page 48 and Table 4 on page 58 should
be understood as a starting point and not as a best case.
Moreover, in order to guarantee the proper working of the algorithm and be sure that the
new computed duty cycles will be applied in the next PWM period, it is always necessary to
finish executing the IFOC algorithm before the next PWM period begins as shown in
Figure 61.

102/112
UM0483 Additional information

Figure 61. AD conversion intervals for three shunt topology stator currents reading
and IFOC algorithm execution
PWM Period

Case 1: REP_RATE = 1, FPWM < 19 kHz


U U U
New duty cycles ready before next U
event: OK

PWM Period

Case 2: REP_RATE = 1, FPWM > 19 kHz

U U U U New duty cycles ready after next U


event; necessary to increase REP_RATE

PWM Period

Case 3: REP_RATE = 3, FPWM > 19 kHz

U U New duty cycles ready before next U


event: OK

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

A.3 Fixed-point numerical representation


The AC IM IFOC software library uses fixed-point representation of fractional signed values.
Thus, a number n is expressed as n = m ⋅ f , where m is the integer part (magnitude) and f
the fractional part, and both m and f have fixed numbers of digits.
In terms of two’s complement binary representation, if a variable n requires QI bits to
express - as powers of two - its magnitude (of which 1 bit is needed for the sign), QF bits –
as inverse powers of two - for its fractional part, then we have to allocate QI + QF bits for that
variable.
Therefore, given a choice of QI and QF, the variable representation has the following
features:
● Range: -2(QI-1) < n < 2(QI-1) – 2(-QF);
● Resolution: = 1 / 2QF.
The equation below converts a fractional quantity q to fixed-point representation n:
QF
n = floor ( q ⋅ 2 )
A common way to express the choice that has been made is the “q QI.QF” notation.
So, if a variable is stored in q3.5 format, it means that 3 bits are reserved for the magnitude,
5 bits for the resolution; the expressible range is from -4 to 3.96875, the resolution is
0.03125, the bit weighting is:

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

A.4 Tacho-based speed measurement flow charts


This section summarizes the main tasks achieved in the tacho capture interrupt in the form
of flow charts. The purpose of these flow charts is to help understand how the automatic
prescaler adjustment is done.

Figure 62. Tacho capture overview


No
Cnt<0xFFFF? Cnt++

Yes
No Yes
Index++ End of array? Index = 0

See “overflow” See “no overflow”


diagram Yes No diagram
Did the timer
Decrease resolution overflow? Increase resolution if
if possible possible

Yes Copy last value into


Init rolling average?
the whole array
No
Clear interrupt flag

Figure 63. Processing captured value when timer did not overflow
Store capture value

Prescaler decreased Store current prescaler value + 1


in prev. int? Reset flag indicating decrement

No
No
Capture < 0x5500? Store current prescaler value
Yes

Is the prescaler Yes


Store current prescaler value
already 0?

No
Store current prescaler value
Decrease prescaler register
Set flag indicating decrement for next
capture interrupt

105/112
Additional information UM0483

Figure 64. Processing captured value when timer did overflow

Store capture value in CaptBuf


Store prescaler value in PrscBuf

Compute total number of clock


Is overflow Cnt=0?
cycle (+0x10000 per overflow

Does Capture
exceeds 16-bit Make it fit 16-bit by increasing PrscBuf
format?

Prescaler will
overflow?

Set max value to CaptBuf and PrscBuf

Store CaptBuf and PrscBuf in array

Did previous capture


Reset flag indicating increment
cause overflow?

Is prescaler at Increase Timer clock presale


max value Set flag indicating increment for next
already? capture interrupt

106/112
UM0483 Additional information

A.5 A priori determination of flux and torque currents PI gains


The purpose of this appendix is to provide a criterion for the computation of the initial values
of torque/flux PI parameters (KI and KP). Successive fine tuning is then performed in the
practical system.
To calculate these starting values it is required to know the electrical characteristics of the
motor in terms of stator resistance Rs and inductance Ls plus the electrical characteristics of
the hardware board, that is, shunt resistor RShunt, current sense amplification gain Aop and
direct current bus voltage VBusDC.
The derivative action of the controller is not considered using this method.
Figure 65 shows the PI controller block diagram used for torque or flux regulation.

Figure 65. Block diagram of PI Controller

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.

Figure 66. Closed loop block diagram

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

By putting KP/KI = LS/RS, it is possible to perform pole-zero cancellation as described in


Figure 67. Figure A6.3.

Figure 67. Pole-zero cancellation

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.

A.6 MMI (maximum modulation index): automatic calculation


It is possible to customize the maximum modulation index versus PWM frequency table
using the provided tool.
To do so, open the MMIvsPWMFreq.exe file (the file location is STM32MC-KIT\design
tools\).
Then, set the desired current-reading method: Single-shunt or Three-shunt, and fill the
required fields with the customized parameters as shown in Figure 69.
The MMI field will then indicate the maximum modulation index allowable for the selected
PWM frequency (PWM Freq field) based on the given noise parameter values (T Noise, T
Rise), A/D converter settings and Dead Time value.

Figure 69. Maximum modulation index configuration tool

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

Figure 70. MMI vs. PWM freq. define table

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

Table 5. Document revision history


Date Revision Changes

08-Jan-2008 1 Initial release.


ACIM IFOC software library updated to revision V2.0 (see AC IM
IFOC software library V2.0 features (CPU running at 72 MHz) on
page 8).
The library modules are now compatible with more toolchains than
previously.
Single-shunt resistor configuration added.
Added:
– SVPWMEOCEvent and SVPWMUpdateEvent on page 40
– Section 4.3: Current reading in single shunt resistor topology and
space vector PWM generation: stm32f10x_svpwm_1shunt module
on page 48
– SVPWMEOCEvent and SVPWMUpdateEvent on page 52
– SVPWMEOCEvent and SVPWMUpdateEvent on page 61
– A.6: MMI (maximum modulation index): automatic calculation
Updated:
– Section 1: Getting started with tools on page 9.
21-Aug-2008 2 – Section 2.2.1: Library configuration file: stm32f10x_MCconf.h
– Power device control parameters, Section 3.5: Setting up the
system when using ICSs
– Figures in Section 3: Running the demo program on page 22
– Caution: on page 34, Section 4.3.3: Definition of the noise
parameter and boundary zone
– IFOC_Model on page 64, IFOC_CalcFluxTorqueRef on page 66
– MMI range in Section 4.6.4: Circle limitation on page 76
– Section 4.9: PID regulators: MC_PID_regulators module on
page 88
– TIM1_UP_IRQHandler and ADC1_2_IRQHandler on page 94
– ADC1_2_IRQHandler on page 94, MCL_Init on page 98
– Appendix A: Additional information on page 101
Removed:
– How to define and add a c module section
– PID block diagrams appendix

111/112
UM0483

Please Read Carefully:

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.

ST and the ST logo are trademarks or registered trademarks of ST in various countries.

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.

© 2008 STMicroelectronics - All rights reserved

STMicroelectronics group of companies


Australia - Belgium - Brazil - Canada - China - Czech Republic - Finland - France - Germany - Hong Kong - India - Israel - Italy - Japan -
Malaysia - Malta - Morocco - Singapore - Spain - Sweden - Switzerland - United Kingdom - United States of America
www.st.com

112/112

You might also like