AN93637 PSoC 4 Sensorless Field-Oriented Control (FOC).pdf

AN93637
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Author: Bob Hu
Associated Project: Yes
Associated Part Family: CY8C42xx
Software Version: PSoC Creator™ 3.1 or higher
Related Application Notes: For a complete list of the application notes, click here.
To get the latest version of this application note, or the associated project file, please visit
http://www.cypress.com/go/AN93637.
AN93637 shows how to implement sensorless field-oriented control (FOC) for a permanent magnet synchronous motor
(PMSM) with a CY8C42xx device. A code example using the CY8CKIT-037 Motor Control Evaluation Kit is included to
demonstrate sensorless FOC.
Contents
Introduction
Introduction .......................................................................1
Motor Control Terms and Definitions .................................2
Sensorless FOC Basics ....................................................2
Code Example ...................................................................5
Features .......................................................................5
Design Overview ..........................................................6
Firmware ......................................................................8
CY8CKIT-037 Kit ..........................................................9
Operation.................................................................... 10
Performance ............................................................... 13
Design Details ................................................................. 14
Current Sampling ....................................................... 14
Transformations ......................................................... 20
Slide Mode Observer (SMO) ...................................... 21
PI Controllers.............................................................. 23
SVPWM Generation ................................................... 24
Summary ......................................................................... 27
Related Application Notes ............................................... 27
Appendix A: PMSM Model .............................................. 28
Appendix B: Slide Mode Observer (SMO) ....................... 31
Appendix C: SVPWM Theory .......................................... 32
Appendix D: Q Number Format (Fixed-Point Number) .... 35
Characteristics............................................................ 35
Conversion ................................................................. 36
Math Operations ......................................................... 36
Appendix E: Adapting the Design to Other Motors .......... 38
Appendix F: Tunable Parameters List ............................. 41
Worldwide Sales and Design Support ............................. 43
This application note shows how to control a permanent
magnet synchronous motor (PMSM) with the sensorless
®
field-oriented control (FOC) algorithm, using an ARM
®
Cortex -M0-based PSoC 4 device.
www.cypress.com
The FOC algorithm is frequently used in motor control
applications because it allows motors to operate with less
noise and more stable torque output than other algorithms.
Sensorless FOC adds the advantage of reducing the cost
due to the absence of rotor position sensors. Sensorless
FOC is used in many applications including consumer (air
conditioner, refrigerator), industrial (blower, pump), and
commercial (elevator, escalator) products.
Sensorless FOC is calculation-intensive, and thus has
been traditionally implemented with expensive digital
signal processing (DSP) devices. However, with 32-bit
ARM Cortex-M cores, it is possible to implement
sensorless FOC with more cost-effective 32-bit MCUs.
This application note assumes that you are familiar with
PSoC 4 and the PSoC Creator IDE. If you are new to
PSoC 4, see AN79953 – Getting Started with PSoC 4 and
the PSoC 4200 family datasheet. If you are new to PSoC
Creator, see the PSoC Creator home page.
You should also understand motor control fundamentals;
start with “electric motor” on Wikipedia.
Finally, this application note includes a code example to
be used with the Cypress CY8CKIT-037 Motor Control
Evaluation Kit. This kit includes a 24-V 53-W PMSM motor.
Note The CY8CKIT-037 kit board can operate at voltages
as high as 48 V DC, and some components may operate
at high temperatures. Use this kit with caution to avoid
personal injury or equipment damage.
Document No. 001-93637Rev. **
1
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Motor Control Terms and Definitions
BEMF: Back electromotive force. Commonly refers to the voltage that occurs in electric motors where there is relative motion
between the armature of the motor and the magnetic field from the motor's field magnets or windings. See Appendix B.
BLDC: Brushless DC motor. It has a trapezoidal BEMF; see Appendix E and Figure 38.
PMSM: Permanent-magnet synchronous motor, or permanent-magnet motor (PMM). A synchronous motor that uses
permanent magnets rather than windings in the rotor. It has a sinusoidal BEMF; see Appendix E and Figure 38.
Sensorless FOC Basics
This section introduces the hardware structure of a typical sensorless FOC system as well as a firmware overview of the FOC
algorithm. If you are familiar with these concepts, you can skip this section and go to the Code Example section.
Figure 1 shows the diagrams of the two types of PMSM motor; they differ in how magnets are placed in the rotor:

Surface PMSM (SPMSM) – Left

Interior PMSM (IPMSM) – Right
Figure 1. Rotor Structure for SPMSM and IPMSM
Source: http://www.hamaco.jp
SPMSM is widely used due to the ease of manufacture and assembly, while IPMSM has a larger torque output with the same
sized motor. The sensorless FOC algorithm varies depending on the motor type; this application note uses SPMSM, referred
to as just “PMSM”.
www.cypress.com
Document No. 001-93637Rev. **
2
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Figure 2 shows the hardware block diagram of a
typical sensorless FOC system. It consists of:





Figure 2. Overview of a Typical Sensorless FOC System
MCU
Power
Power
Inverter
Vdd
PMSM
Vbus, Vdriver
Current sampling and signal conditioning
circuit to determine the rotor position
A
PWMs
Communication interface
MCU
B
Inverter
These components can be on the same controller
board or separated in the system such as on an
MCU board and an inverter board.
PMSM
C
Motor
Motor
Figure 3 shows the details of the Inverter block
shown in Figure 2. The inverter is composed of
gate drivers and six MOSFETs (two for each
motor phase). Turning different MOSFETs ON or
OFF changes the current direction through the
motor’s stator windings or phases.
Opamps
Opamps
Signal Conditioning
RR RR RR
For example, turning ON Q1 and Q4 generates a
current from phase A to phase B, while turning ON
Q3 and Q2 reverses the current direction in those
phases. Changing the current direction changes
the stator flux direction and makes the rotor rotate.
Sensing Resistors
Communication
Communication Interface
Interface
Controller
Controller board
board
Figure 3. Details of Inverter Block
PWMAH
Gate
PWMAL Driver
AH
AL
PWMBH
Gate
PWMBL Driver
BH
BL
PWMCH
Gate
PWMCL Driver
CH
CL
Vbus
Q1
AH
Q3
BH
Q2
AL
Q5
CH
Q4
BL
Q6
CL
B
A
C
Vbus is a higher-voltage DC supply to power the motor. For example, it is 24 V in the CY8CKIT-037 kit.
Note that the pairs of MOSFETs on the same phase (for example, Q1 and Q2) must not be turned ON at the same time – the
resultant low resistance causes high currents that can damage the MOSFETs.
www.cypress.com
Document No. 001-93637Rev. **
3
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Figure 4 and Figure 5 show diagrams of the sensorless FOC algorithm and its calculation flow. The algorithm controls either
the motor speed or motor torque using a proportional-integral (PI) controller based on a mathematical model of the PMSM
(Appendix A describes the PMSM model). The control result is sent to a Space Vector Pulse Width Modulation (SVPWM)
block (Appendix C). The SVPWM block generates three-phase voltages that change the stator currents.
Figure 4. Sensorless FOC Control Block Diagram
Sensorless FOC
θ
ω_ref
Speed PI
uα
Inverse
uβ
Park
Inverse
Clarke
ua
ub
uc
SVPWM
duty a
duty b
duty c
P
W
M
Inverter
uq ud
iq_ref
id_ref
iq
Iq PI
Park
id
Id PI
iα
iβ
Clarke
A
D
C
iα iβ
θ
ω
ia
ib
ic
Speed and Position
Estimation
Motor
Figure 5. Sensorless FOC Calculation Flow
Ia
Ib
Ic
Iα
Clarke
3-Phase System
Iβ
Id
Park
Iq
Ud
PIs
Uq
Ua
Ub
Uc
Uα
Inverse
Park
Uβ
Inverse
Clarke
2-Phase System
SVPWM
3-Phase System
The Clarke and Park transformation calculations convert
these three sampled motor phase currents into two values
that are used by the PI controller. The Inverse Clarke and
Inverse Park transformations are the opposites of the
Clarke and Park transformations, respectively.
Figure 6 shows the Clarke transformation, where the three
motor phase currents ( , , ) are converted to and .
The (a, b, c) frame is a three-phase stator reference frame,
where the axes are 120° apart from each other. The
transformation method is to project ( , , ) onto the
(α, β) axes, which produce the outputs and .
Duty a
Duty b
Duty c
Figure 6. Clarke Transformation
β
b
iβ
is
ib
ic
ia a
iα
α
c
www.cypress.com
Document No. 001-93637Rev. **
4
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Figure 7 shows the details of the Park transformation. This
transformation converts the current vectors from the
Clarke transformation, and , to a frame on the rotating
part of the motor. The axes of the rotating frame are
called (d, q). The current vectors on these axes are called
and .
is
d axis
to the
and
the flux linkage vector of the rotor magnet. The
is always aligned with
, and the q axis is at 90°
d axis. The rotor rotates at an angular speed
,
is the angle between the α and d axes.
Figure 7. Park Transformation
β
ωr
q
In the (d, q) frame, the motor torque is proportional to .
We can control to achieve the desired torque by using
the proportional-integral (PI) controller. For details on the
Clarke and Park transformations as well as the torque
output, see Appendix A: PMSM Model.
d
iβ
is
Ψf
id
θr
iq
iα
a
α
The angle
used in the Park transformation is derived from the speed and position estimation. An algorithm called “Slide
Mode Observer” (SMO) uses
and
to derive the
value. Then, the angular speed
is calculated based on
. For
more information, see Appendix B: Slide Mode Observer (SMO).
Code Example
This application note includes an example project to demonstrate sensorless FOC algorithm implemented with CY8C42xx
devices. The code example is a complete design with all the code already written. It is intended to be used directly with the
Cypress’s motor kit, CY8CKIT-037.
This kit can be used with other motors if the motor’s power level is in the range supported by the CY8CKIT-037 kit. See
Appendix E: Adapting the Design to Other Motors. Appendix F: Tunable Parameters List provides a quick reference for tuning
the parameters for other motors.
If the motor’s power level is greater than the range supported by this kit, you must design your custom control board with
higher-power MOSFETS, power supply, and other components. The code example can still be used.
Features

Implements the sensorless FOC algorithm and closed-loop speed control in a multilayer, extensible, binary library
architecture


Estimates the rotor position with the Slide Mode Observer (SMO) algorithm


Employs open-loop control at startup, which is changed to closed-loop control after the rotor position is determined


Can adjust the motor speed by using the the potentiometer on the kit
Uses the PSoC 4 internal opamps and the 888.89-Ksps successive approximation register (SAR) ADC for signal
conditioning and measuring the motor phase current
Supports motor speeds from 500 to 4000 RPM by default. Can support higher speeds in other motors by modifying the
tuning parameters in the code example
Provides control accuracy 5% over the default speed range. Using high-resolution sensing resistors and advanced control
algorithms can improve the accuracy; this topic is outside the scope of this application note.
www.cypress.com
Document No. 001-93637Rev. **
5
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Design Overview
Figure 8 illustrates sensorless FOC implementation in PSoC 4. A 12-bit SAR ADC and two opamps are used to sample the
motor phase currents (only two phase currents need be sampled; the third phase can be calculated from the other two.) The
three TCPWMs generate six PWM outputs applied to the Inverter. A serial communication block (SCB) implements a UART to
communicate with the host. Figure 9 is the corresponding implementation in PSoC Creator. For details, see Design Details.
Figure 8. PSoC4 Sensorless FOC Implementation Block Diagram
PSoC4
TCPWM
Flash
LPCOMP
SRAM
Cortex-M0
48MHz
Ibus
i
SCB
UART
A B
SAR ADC
R
Inverter
Inverter
Motor
TCPWM
iDAC
<
TCPWM
C
Opamp
M
U
X
Opamp
Vbus
POT
R
R
R
Figure 9. PSoC Creator Schematic Overview
www.cypress.com
Document No. 001-93637Rev. **
6
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Table 1 shows the PSoC 4 resources that are used by this code example:
Table 1. Resource Usage Summary
www.cypress.com
Item
Used
Available
CPU Frequency
48 MHz
48 MHz
PWM Frequency
10 kHz
NA
Flash (GCC compiler, size optimization)
17,216 bytes
32,768 bytes
SRAM without stack and heap (GCC compiler, size optimization)
860 bytes
NA
SRAM in total (GCC compiler, size optimization)
2140 bytes
4096 bytes
UDB
0
4
UDB Control Registers
1
4
UDB Status Registers
0
4
Interrupts
3
32
TCPWM Blocks
3
4
Opamps
2
2
Low-Power Comparators
1
2
8-bit current DAC (IDAC)
1
1
Document No. 001-93637Rev. **
7
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Firmware
Figure 10 shows the firmware execution flow. The FOC algorithm requires the PWM duty cycle to be updated every control
cycle. Therefore, FOC calculations must be done in a periodic interrupt service routine (ISR). The ISR is triggered by the PWM
every 100 µs (10-kHz PWM) – this is the control cycle period. Note that this interrupt should be high priority for effective duty
cycle control – see SVPWM Generation.
The cycle period can be decreased by increasing the PWM frequency. A shorter control period results in a higher-bandwidth
control system with two benefits:


Motor can be run faster
Better response to load changes
The communication and other functions that do not require real-time processing are executed in the main loop.
Figure 10. Firmware Execution Flow
Start
Cymc_HAL_ADCReadSample
Cymc_BCL_Clark
System Initialization
(main.c)
Cymc_ACL_SMOCal
interrupt signal
PWM_MainLoop_ISR
from PWM_A
Main Loop
(main.c)
FOC_MainLoop_ISR
(foc.c)
Cymc_BCL_Park
Cymc_GFL_PICal
Cymc_BCL_InvPark
Cymc_BCL_InvClark
Cymc_BCL_SVPWM
Cymc_HAL_PWMOutputUpdate
The code example associated with the kit and this application note includes a multilayer, extensible, library architecture as
Figure 11 shows.
Figure 11. Sensorless FOC Motor Control Library Architecture
www.cypress.com
Document No. 001-93637Rev. **
8
PSoC® 4 Sensorless Field-Oriented Control (FOC)
CY8CKIT-037 Kit
The Cypress kit CY8CKIT-037 is a motor-driver board designed to support three control algorithms: trapezoidal, FOC, and
microstepping control for stepper motors. It has no MCU; it is a peripheral board to be used with the CY8CKIT-042 (Figure 12),
through the Arduino-compatible interface. For more information, refer to the CY8CKIT-037 User Guide.
Figure 12. CY8CKIT-037 (Top) and CY8CKIT-042 (Underneath)
A PMSM, manufactured by Anaheim Automation, is included in this kit. Table 2 lists the motor parameters. See Appendix E:
Adapting the Design to Other Motors for information on how to change the code example by changing the motor parameters
listed in this table.
Table 2. Parameters for CY8CKIT-037 Motor
www.cypress.com
Item
Parameter
Part Number
BLY172S-24V-4000
Rated Torque (oz-in)
18.0
Rated Voltage (V)
24
Rated Power (watts)
53
Rated Speed (RPM)
4000
Torque Constant (oz-in/A)
5.03
Back EMF Voltage (V/kRPM)
4.14
Line-to-Line Resistance (ohm)
0.8
Line-to-Line Inductance (mH)
1.2
Rotor Inertia (oz-in-sec2)
0.000680
"L" Length (in)
2.37
Shaft
Single
Document No. 001-93637Rev. **
9
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Operation
Step 1 – Configure CY8CKIT -042
Select 3.3 V as the VDD power at jumper J9 on the CY8CKIT-042, as Figure 13 shows.
Figure 13. CY8CKIT-042 Configuration
Note In this application, the USB cable is used only for firmware programming, so it can be removed after programming. If you
keep the cable connected, ensure that the other end is NOT connected to the PC. Connecting the cable to the PC causes the
firmware to generate an “undervoltage” error, and the motor will not start.
www.cypress.com
Document No. 001-93637Rev. **
10
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Step 2 – Configure CY8CKIT -037
Configure the board via jumpers J13-J24 as listed in the row “BLDC 2-SHUNT FOC” printed on the board. See Figure 14 and
Figure 15.
Figure 14.CY8CKIT-037 Configuration for Sensorless FOC Motor Control
Figure 15. Jumper Table for CY8CKIT-037
Step 3 – Plug CY8CKIT-037 into CY8CKIT-042
Plug the CY8CKIT-037 into the CY8CKIT-042 via Arduino connectors J1-J4, as Figure 12 shows.
www.cypress.com
Document No. 001-93637Rev. **
11
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Step 4 – Connect the Power Supply and Motor
Connect the BLDC motor to J9 and J10 on CY8CKIT-037. The other motor cable routes the signals from the sensors inside
the motor. (The kit hardware supports sensored BLDC motors and sensored FOC.) Because this is a sensorless example, we
do not need to connect this cable. Connect the 24-V power adapter to J7. See Figure 16.
Figure 16. Connect Motor and Power Supply
S t e p 5 – B u i l d t h e P r o j e c t a n d P r o g r a m t h e P S o C 4 D e vi c e
Open the sensorless FOC motor control code example project provided with this application note in PSoC Creator 3.1 or later.
Select Build > Build Sensorless FOC Motor Control. When the build is complete, select Debug > Program to program the
PSoC 4 device.
www.cypress.com
Document No. 001-93637Rev. **
12
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Step 6 – Press the SW2 Button to Start Motor Rotation
Press the SW2 button (Figure 17) to start the motor rotation. If the motor does not rotate and LED2 is blinking, an error has
occurred. In this case, first confirm that steps 1 to 5 have been done correctly. Press the Reset button to clear the error status
and press SW2 again. If LED2 still blinks, there must be a problem in the hardware or software. You can debug it using a
multimeter or oscilloscope to observe the signals, or set breakpoints to monitor variables. You can also contact Cypress for
technical support.
Figure 17. Buttons and Status LED
Reset
LED2
SW2
Performance
Figure 18 to Figure 20 show one of the phase currents for different motor speeds using the motor provided in the kit.
Figure 21 shows the phase current during startup.
Figure 18. Phase Current – 600 RPM
Figure 19. Phase Current– 2000 RPM
Figure 20. Phase Current– 4000 RPM
Figure 21. Phase Current at Startup
www.cypress.com
Document No. 001-93637Rev. **
13
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Design Details
This section presents implementation details for each stage of the sensorless FOC processing listed in the PWM ISR (Figure
10), including current sampling, Clarke and Park transformations, SMO, PI controller, and SVPWM.
Current Sampling
PSoC Creator Schematic
Figure 22 shows that four input channels are periodically sampled by the SAR ADC. The channels are:



Two motor phase currents: OP_I_a_Vout_Filt and OP_I_b_Vout_Filt
Bus voltage (OP_V_bus_Vout_Filt). This is the Inverter power supply (default 24 V) divided by resistors.
Voltage input from variable resistor (potentiometer).
Note that resistors and capacitors are included in the design but are not shown in this figure. For details, see the kit schematic.
Figure 22. PSoC Creator Schematic – Current Sampling
www.cypress.com
Document No. 001-93637Rev. **
14
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Figure 23 and Figure 24 on page 16 show the SAR ADC configuration with the following features:

Sampling clock is 16 MHz for an 888.89-ksps sampling rate. The actual sample rate shown in Figure 23 indicates that four
channels are being sampled (888 / 4 = 222).




Voltage reference is VDDA/2 to obtain a 0-to-VDDA input range.
All channels are single-ended.
The sampling result is unsigned.
A hardware trigger starts sampling. After four channels are sampled, the ADC stops and waits for the next trigger signal.
The trigger frequency is 10 kHz. The PWMs provide a common timing for ADC sampling, CPU interrupt, and MOSFET
control – see Figure 9, Figure 10, and the SVPWM Generation section.
Figure 23. SAR ADC Configuration, General Tab
www.cypress.com
Document No. 001-93637Rev. **
15
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Figure 24. SAR ADC Configuration, Channels Tab
www.cypress.com
Document No. 001-93637Rev. **
16
PSoC® 4 Sensorless Field-Oriented Control (FOC)
The motor phase current is converted to a voltage by the sensing resistors, as Figure 25 shows. The figure also shows that,
because the sum of the three currents must be zero at the sampling point, we can sample just two of the currents and
calculate the third.
The opamp gains and the sensing resistor values are selected so that:

The voltage stays in the ADC input range when the current is at the rated maximum. Sensing resistors are typically on the
order of milliohms.

The measurement of low currents is accurate. The sensing resistors have a tolerance of 1%.
Figure 25. Dual-Shunt Current Sampling
Opamp
Ia
A B
C
Ic=-(Ia+Ib)
Opamp
Ib
R
R
R
Figure 26 shows the schematic design for the CY8CKIT-037 kit. The kit board has 30-mΩ sensing resistors (not shown) and a
2.1-A rated current. Bias resistors (R40, R41) are included to handle positive and negative currents.
Figure 26. CY8CKIT-037 Schematic: Signal Conditioning for Phase-A Current
www.cypress.com
Document No. 001-93637Rev. **
17
PSoC® 4 Sensorless Field-Oriented Control (FOC)
The PSoC 4 internal opamps are used. Figure 27 shows the configuration of each Opamp Component.
Figure 27. PSoC 4 Internal Opamp Configuration
Figure 28 shows the pin assignments for the SAR ADC and opamps. The opamp pins are direct connected to the internal
opamps. Using these pins reduces the usage of analog routing resources as well as resistances between the pins and the
opamp terminals.
Figure 28. Pin Assignments for Opamp and SAR ADC
www.cypress.com
Document No. 001-93637Rev. **
18
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Current Sampling Firmware
The firmware for current sampling consists of initialization function calls and functions to read and use the sample data. The
code example associated with the kit and this application note includes a Cypress-proprietary motor control library. This library
manages the sensorless FOC procedure, as described in the Firmware section. Some system parameters such as DC bus
voltage and sensing resistors value are defined as macros in the motor control library. For more information, see Appendix E:
Adapting the Design to Other Motors.
For system initialization, the Opamp Component API has a Start() function, as Code 1 shows. The SAR ADC is initialized by a
motor control library function (see Figure 11).
Code 1. Current Sampling Initialization
/* main.c */
void main()
{
/* Initialize Opamps */
Opamp_A_Start();
Opamp_B_Start();
/* Initialize SAR ADC */
Cymc_HAL_ADCStart();
}
/******************************************************/
/* Cymc_HAL_ADC.c */
void Cymc_HAL_ADCStart();
{
/* start SAR ADC */
SADC_Start();
}
Current sampling is done in the ISR, as Code 2 shows. A motor control library function (see Figure 11) is called to read the
ADC raw data.
Code 2. Current Sampling in the ISR
/* foc.c */
CY_ISR(FOC_MainLoop_ISR)
{
. . .
/* Read ADC and get phase current*/
Cymc_HAL_ADCReadSample();
. . .
phaseCurrentU = adcRawData[ADC_IA_CHAN];
}
/******************************************************/
/* Cymc_HAL_ADC.c */
void Cymc_HAL_ADCReadSample()
{
uint8 i = 0;
for(i = 0; i < CHANNEL_NUM; i++)
{
adcRawData[i] = SADC_GetResult16(i) & (0x0FFF);
}
}
www.cypress.com
Document No. 001-93637Rev. **
19
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Transformations
Four structures are defined in the motor control library (Figure 11) for Clarke and Park transformations and the inverse
transformations, as Code 3 shows. Four functions are defined to do the transformations. The structures and function
prototypes are declared in the motor control library file Cymc_BCL_Transform.h:
Code 3. Clarke and Park Transformation Structures and Function Prototypes
/* Cymc_BCL_Transform.h */
/* struct definition for Clarke transformation*/
typedef struct
{
q15_t inU;
/* phase-U variable
q15_t inV;
/* phase-V variable
q15_t outAlpha; /* Output: α-axis variable
q15_t outBeta;
/* Output: β-axis variable
} ClarkTrans;
/* struct definition
typedef struct
{
q15_t outU;
q15_t outV;
q15_t outW;
q15_t InAlpha;
q15_t InBeta;
} InvClarkTrans;
/* struct definition
typedef struct
{
q15_t inAlpha;
q15_t inBeta;
q15_t outD;
q15_t outQ;
q15_t inSin;
q15_t inCos;
} ParkTrans;
*/
*/
*/
*/
for inverse Clarke transformation */
/*
/*
/*
/*
/*
Output:
Output:
Output:
α-axis
β-axis
phase-U variable
phase-V variable
phase-W variable
variable
variable
*/
*/
*/
*/
*/
for Park transformation */
/*
/*
/*
/*
/*
/*
α-axis variable
β-axis variable
Output: d-axis variable
Output: q-axis variable
angle sin value
angle cos value
*/
*/
*/
*/
*/
*/
/* struct definition for inverse Park transformation */
typedef struct
{
q15_t outAlpha; /* α-axis variable
*/
q15_t outBeta;
/* β-axis variable
*/
q15_t inD;
/* Output: d-axis variable */
q15_t inQ;
/* Output: q-axis variable */
q15_t inSin;
/* angle sin value
*/
q15_t inCos;
/* angle cos value
*/
} InvParkTrans;
extern
extern
extern
extern
void
void
void
void
www.cypress.com
Cymc_BCL_Clark(ClarkTrans *clark);
Cymc_BCL_Park(ParkTrans *park);
Cymc_BCL_InvPark(InvParkTrans *invPark);
Cymc_BCL_InvClark(InvClarkTrans *invClark);
Document No. 001-93637Rev. **
20
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Code 4 shows how to use these functions:
Code 4. Using Clarke and Park Transformation Functions
/* foc.c */
CY_ISR(FOC_MainLoop_ISR)
{
. . .
/* Clarke Transformation uvw -> αβ */
clarkTrans.inU = phaseCurrentU0 << 2; /* Phase U current */
clarkTrans.inV = phaseCurrentV0 << 2; /* Phase V current */
Cymc_BCL_Clark(&clarkTrans);
. . .
/* Park Transformation αβ -> dq */
parkTrans.inAlpha = clarkTrans.outAlpha;
parkTrans.inBeta = clarkTrans.outBeta;
Cymc_GFL_SinCosCal_Q15(curAngle, &parkTrans.inSin, &parkTrans.inCos);
Cymc_BCL_Park(&parkTrans);
. . .
invParkTrans.inSin = parkTrans.inSin;
invParkTrans.inCos = parkTrans.inCos;
Cymc_BCL_InvPark(&invParkTrans);
. . .
invClarkTrans.InAlpha = invParkTrans.outAlpha;
invClarkTrans.InBeta = invParkTrans.outBeta;
Cymc_BCL_InvClark(&invClarkTrans);
. . .
}
Slide Mode Observer (SMO)
An introduction to SMO theory is in Appendix B: Slide Mode Observer (SMO). The structure and function prototypes for SMO
calculation (Code 5) are defined in the motor control library (see Figure 11).
Code 5. SMO Calculation Structure and Function Prototypes
/* Cymc_ACL_SMO.h */
typedef struct
{
q15_t Vbus;
q15_t volAlpha;
q15_t volBeta;
q15_t speedRef;
q15_t Ggain;
q15_t Fgain;
q15_t slideCoff;
q15_t slideError;
q15_t curAlpha;
q15_t curBeta;
q15_t Theta;
}SMO;
/*
/*
/*
/*
/*
/*
/*
/*
/*
/*
/*
DC-bus voltage */
α-axis stator voltage */
β-axis stator current */
Current speed reference */
control gain */
filter gain */
coefficient K for slide control */
error threshold for slide control */
α-axis stator current */
β-axis stator current */
Output: angle */
void Cymc_ACL_SMOCal(SMO *smo);
void Cymc_ACL_SMOParamtersInit(floatRs, floatLs, floatTs, floatbaseFrequency, SMO *smo);
www.cypress.com
Document No. 001-93637Rev. **
21
PSoC® 4 Sensorless Field-Oriented Control (FOC)
A global variable of type SMO structure (Code 6) is also defined in the motor control library (see Figure 11).
Code 6. SMO Structure Variable
/* Cymc_MAL.h */
SMO smoEst; /* slide mode observer struct */
To use the SMO module, you must first call the motor control library function Cymc_MAL_MotorInit() in your initialization code.
Code 7 shows initialization and usage of SMO:
Code 7. SMO Initialization and Usage
/* main.c */
void main()
{
. . .
/* Initialize Motor Parameters */
Cymc_MAL_MotorInit();
. . .
}
/* Cymc_MAL.c */
void Cymc_MAL_MotorInit()
{
motor.Rs = M_RS;
motor.Ls = M_LS;
motor.Poles = M_POLES;
motor.Ts = M_TS;
motor.baseFrequency = M_BASEFREQUENCY;
motor.ratedSpeedRPM = M_RATED_SPEED;
/* Ω */
/* H */
/* S */
/* Hz */
/* RPM */
/* Initialize the SMO parameters */
Cymc_ACL_SMOParamtersInit(motor.Rs, motor.Ls, motor.Ts,
motor.baseFrequency, &smoEst);
smoEst.slideError = _FQ(0.5); /* see Appendix D */
}
Code 8 shows how to use the SMO routines to obtain and use the angle information that is stored in the variable ‘curAngle’:
Code 8. Using the SMO Module in the ISR
/* foc.c */
CY_ISR(FOC_MainLoop_ISR)
{
. . .
/* Position Calculation*/
smoEst.Vbus = _FQ(1.0); /* see Appendix D */
smoEst.speedRef = rampUp.output;
smoEst.volAlpha = invParkTrans.outAlpha;
smoEst.volBeta = invClarkTrans.InBeta;
smoEst.curAlpha = clarkTrans.outAlpha;
smoEst.curBeta = clarkTrans.outBeta;
Cymc_ACL_SMOCal(&smoEst);
. . .
Cymc_GFL_SinCosCal_Q15(curAngle, &parkTrans.inSin, &parkTrans.inCos);
. . .
}
www.cypress.com
Document No. 001-93637Rev. **
22
PSoC® 4 Sensorless Field-Oriented Control (FOC)
PI Controllers
The PI control equation for a continuous control system is:
Where:
Proportional factor
Integration factor
Error between actual value and reference
Initial output at system startup
Three parameters – motor speed, , and – are controlled by separate PI controllers. The speed PI controller uses the error
between the calculated rotation speed and a given speed reference to calculate the control output, which in turn is the
reference for the PI controller. The and PI controllers control
and , respectively, using the errors for
and .
See Figure 4.
th
Code 9 shows how to implement PI control. Note that the speed PI control is only executed in every N control cycle. N is
defined by the macro DEFAULT_SPEEDLOOPSCALER in Cymc_MAL.h, and saved in ‘speedLoopPrescaler’.
The motor can be controlled in two modes: speed mode and torque mode. The speed mode controls the rotation speed in
relation to a given speed reference. The torque mode controls the torque output in relation to a given torque reference.
Depending on the mode selected, one of the references is used in the PI controller, as Code 9 shows.
Code 9. PI Controllers
/* foc.c */
CY_ISR(FOC_MainLoop_ISR)
{
. . .
/* Speed PI Controller */
if(speedLoopCount == speedLoopPrescaler)
{
pidSpeed.ref = rampUp.output; /* motor.speedRef */
pidSpeed.fbk = speedEst.estimatedSpeed;
Cymc_GFL_PICal(&pidSpeed);
speedLoopCount = 0;
updateSpeedrefFromVR();
}
speedLoopCount++;
/* Iq PI Controller */
/* select speed or torque control */
if(motor.runState == M_SPEEDLOOP)
{
pidIq.ref = pidSpeed.out;
}
else
{
pidIq.ref = motor.vqRef;
}
pidIq.fbk = parkTrans.outQ;
Cymc_GFL_PICal(&pidIq);
/* Id PI Controller */
pidId.ref = motor.vdRef;
pidId.fbk = parkTrans.outD;
Cymc_GFL_PICal(&pidId);
. . .
}
www.cypress.com
Document No. 001-93637Rev. **
23
PSoC® 4 Sensorless Field-Oriented Control (FOC)
SVPWM Generation
PSoC Creator Schematic Design
The SVPWM subsystem produces sinusoidal currents on the motor phases by changing the output duty cycles of the three
PWMs (for details, see Appendix C: SVPWM Theory). The PWM outputs – two complementary outputs for each motor
phase – turn the MOSFETs ON or OFF (see Figure 3).
Figure 29 shows the SVPWM implementation in PSoC Creator. A common 48-MHz clock synchronizes the PWM outputs. The
output enable (OE) feature of the output pins is enabled and controlled by the firmware through a control register.
Figure 29. PSoC Creator Schematic: SVPWM and Timing
Figure 30 shows the timing for all three PWMs as well as the details of PWM_A. In addition to the PWM signals, PWM_A
generates the trigger signals for ADC sampling and CPU interrupt – see the Firmware section.
ADC sampling is triggered by the PWM’s overflow event (‘ov’). The ADC takes approximately 4.5 µs to sample four channels,
as described previously. ADC conversion must be completed before the PWM underflow event occurs.
The interrupt is triggered by the PWM’s underflow event (‘un’). The result is that the ISR controls the PWM duty cycle on every
cycle by updating the PWM compare buffer register (Figure 31). The register must be updated before the next underflow event
occurs, or the duty cycle will be incorrect, which in turn causes an increased motor noise.
Note that each PWM has a different duty cycle.
Figure 30. PWM Timing and PWM_A Detail
www.cypress.com
Document No. 001-93637Rev. **
24
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Figure 31 shows the configuration for PMW_A (phase A); it applies to all three PWM Components:

The alignment mode is “Center align”. This produces the complementary PWM outputs ‘line’ and ‘line_n’. The outputs turn
the MOSFETs of one of the motor phases ON and OFF (such as Q1 and Q2 in Figure 3).

A deadband time is inserted to avoid turning ON both MOSFETs at the same time, which can damage the MOSFETs. In
this code example, 40 cycles of a 48-MHz clock results in a dead time of 0.833 µs.

The period value is the clock frequency divided by twice the desired PWM frequency minus 1. We double the desired
PWM frequency because the count mode is up-down (see Figure 30). For a 48-MHz clock and a desired PWM frequency
of 10 kHz, the period is (48,000,000 / (2 * 10,000)) - 1, or 2,399.

To implement the duty cycle control technique described previously, we do the following:



route the PWM_A ‘un’ output back to the ‘switch’ input of all PWMs (signal ‘PWM_UPDATE’ in Figure 29)
check the “switch on rising edge” and “swap” boxes (Figure 31)
Update the PWM compare buffer register in firmware. On each cycle, the PWM hardware copies (by swapping) the
compare buffer register into the compare register, which changes the duty cycle.
Figure 31. PWM_A Configuration Window
www.cypress.com
Document No. 001-93637Rev. **
25
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Firmware implementation
Code 10 shows how to initialize the PWMs and update them in the FOC ISR.
Code 10. SVPWM Control
/* main.c */
void main()
{
. . .
/* TCPWM Init */
Cymc_HAL_PWMOutputDisable();
Cymc_HAL_PWMStart();
/* Motor Paramters Init */
Cymc_MAL_MotorInit();
/* PWM Main ISR Init */
PWM_MainLoop_ISR_StartEx(FOC_MainLoop_ISR);
. . .
}
/**********************************************/
/* foc.c */
CY_ISR(FOC_MainLoop_ISR)
{
. . .
/* SVPWM Calculation */
svpwmCal.Uu = invClarkTrans.outU;
svpwmCal.Uv = invClarkTrans.outV;
svpwmCal.Uw = invClarkTrans.outW;
Cymc_BCL_SVPWM(&svpwmCal);
/* Update PWM duty cycles */
pwmCmp[0] = svpwmCal.CmpU;
pwmCmp[1] = svpwmCal.CmpV;
pwmCmp[2] = svpwmCal.CmpW;
Cymc_HAL_PWMOutputUpdate();
. . .
}
www.cypress.com
Document No. 001-93637Rev. **
26
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Summary
Related Application Notes
This application note has shown how to design a
sensorless FOC control algorithm for a permanent magnet
synchronous motor (PMSM), using a PSoC 4 CY8C42xx
device. PSoC 4’s resources and flexible internal routing
make it an excellent fit for motor control applications. For
more information on motor control using PSoC 4, go to the
Cypress website.
AN88619 – PSoC4
Considerations
4100/4200
Hardware
Design
AN90799 – PSoC4 Interrupts
AN80994 – PSoC3, PSoC4, and PSoC 5LP EMC Best
Practices and Recommendations
About the Author
www.cypress.com
Name:
Bob Hu
Title:
Application Engineer Staff
Background:
Graduated from Shanghai Jiao Tong
University with a master’s degree. He
has worked at Cypress since 2009.
Document No. 001-93637Rev. **
27
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Appendix A: PMSM Model
This appendix presents the mathematical model of a permanent magnet synchronous motor (PMSM). To simplify the model,
some assumptions are made:



The PMSM motor winding connection is the “star” type. “Delta” type connections must be converted to the “star” type.
Magnetic saturation is neglected.
Eddy currents and hysteresis losses are negligible.
Figure 32 illustrates the PMSM motor model in a threephase stator reference frame, also called the (a, b, c)
frame. In this frame, the a, b, and c axes are aligned with
the currents
in the three phases of the PMSM
stator, and are 120° apart from each other.
is the flux
linkage vector of the rotor magnet. The rotor rotates with
an angular speed
, and
is the angle between
and phase a.
Figure 32. Three-Phase Stator Reference Frame
b
is
Ψf
ωr
N
The a, b, and c phases are each called “line”. The
connection point of a, b, and c is called the neutral point.
See Appendix B for information on usage of these terms.
θr
a
S
c
The voltages on the stator windings are represented as:
Stator voltage vector
where:
Stator resistance
Stator current vector
Stator flux linkages
The stator winding flux linkage is the sum of the flux linkages from their own excitation, mutual flux linkages from other winding
currents, and flux linkages from the rotor magnet. Because the current phases on the stator windings are 120° apart, the stator
flux linkages are written as:
where:
Equivalent inductances of stator phases
,
Mutual equivalent inductances of stator phases
Amplitude of rotor flux linkage
Angle between
www.cypress.com
and phase a
Document No. 001-93637Rev. **
28
PSoC® 4 Sensorless Field-Oriented Control (FOC)
The above model is of a high order, is strongly coupled,
and has nonlinearity; analyzing it and controlling the
torque and flux based on it is difficult. Therefore, the (d, q)
frame is used to simplify the three-phase model. The (d, q)
frame defines a rotating two-phase reference frame where
the d axis is aligned with the rotor flux direction.
Figure 33. Clarke Transformation
β
b
iβ
There are two transformations to convert the (a, b, c)
frame to the (d, q) frame. The first one is a Clarke
transformation – it converts the (a, b, c) frame to a twophase stationary reference frame (α, β) (Figure 33).
ib
is
ic
ia a
iα
α
c
The current vectors in the (α, β) frame are:
For “star” type winding connections, the sum of the
currents in the three phases is zero:
Therefore, the current vectors in the (a, b, c) frame are
transformed to the (α, β) frame as:
The Park transformation then converts the (α, β) frame to
the (d, q) frame. The (d, q) frame has two axes – direct
and quadrature – that rotate with the same angle
speed
as the current vector. The direct axis is aligned
with the rotor flux
(Figure 34). The angle between the d
axis and the α axis is
.
Figure 34. Park Transformation
β
ωr
q
d
iβ
is
Ψf
id
θr
iq
iα
a
α
The current vectors in the (d, q) frame are calculated as:
The voltages in the (d, q) frame are calculated from
and , as:
www.cypress.com
Document No. 001-93637Rev. **
29
PSoC® 4 Sensorless Field-Oriented Control (FOC)
and:
The torque equation is expressed as:
where:
Inductances of direct and quadrature axes
Note that for a SPMSM (Figure 1),
independent of
, and
is equal to
torque equation is simplified for SPMSM as:
and
are
. Thus, the
Number of pole pairs in rotor
and
are motor characteristics that are not affected by the motor rotation. Compared to the three-phase model, the
torque is proportional only to the q-axis current , which is easier to control.
www.cypress.com
Document No. 001-93637Rev. **
30
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Appendix B: Slide Mode Observer (SMO)
Obtaining the position of a rotating rotor is critical for FOC. The Park transformation (see Appendix A) requires the rotor
position angle
between the rotor flux linkage
and the α axis. Originally, this information came from physical sensors,
such as Hall-effect sensors, optical encoders, and so on. These sensors not only increase the system cost, but they also
require maintenance. Later, the sensorless technique was developed to remove the need for sensors. Some high-precision
applications such as robotics still require encoders.
The idea of the sensorless technique is to estimate the
angle
based on the BEMF value in the (α, β) frame.
The typical algorithm to do this is called a slide mode
observer (SMO). In this algorithm, the two-phase voltages
in the (α, β) frame is expressed as:
Line-to-neutral resistance
where:
Line-to-neutral resistance
Line-to-neutral inductance
BEMF on (α, β) axes
In the digital domain, the
equation is changed to:
where:
Solving for
Period of PWM on inverter
:
We now define two new parameters that are related to motor parameters:
Note that
and
are motor characteristics that can be measured.
is a constant system parameter,
is the sampled
result from the last control cycle, and
is the calculation result of the last control cycle. Therefore, if given an estimated
, an estimated current value
can be calculated (“*” indicates an estimated value).
Comparing
with the actual current value
sampled by the ADC, the error between these two values is
used to adjust
for a better estimation. Repeat this process until the error between
and
is small
enough to meet the design requirements. Then, the estimated
can represent the actual BEMF
. The
is
obtained in the same manner.
Because
The angle
and
are expressed as:
is calculated as:
The angular speed
is calculated by accumulating
over m samples and multiplied by the speed constant
:
Thus, the position and speed information are calculated from the estimated BEMF.
www.cypress.com
Document No. 001-93637Rev. **
31
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Appendix C: SVPWM Theory
In Figure 3, Q1, Q3, and Q5 are the upper MOSFETs of the inverter. If you consider the MOSFET ON state as “1” and the
OFF state as “0”, there are eight combinations of ON/OFF states, which lead to eight inverter outputs.
Table 3 lists the ON/OFF state combinations and their corresponding inverter outputs. , , and
are the phase (line-toneutral) voltages (see Appendix A), while
,
, and
are the line-to-line voltages. The values in each cell indicate the
voltage as a percentage of the bus voltage,
. For example, 2/3 means 2/3 of
.
Table 3. Output Combination in Three-Phase Frame
Q1
Q3
Q5
(A)
(B)
(C)
1
0
0
2/3
-1/3
-1/3
1
0
-1
1
1
0
1/3
1/3
-2/3
0
1
-1
0
1
0
-1/3
2/3
-1/3
-1
1
0
0
1
1
-2/3
1/3
1/3
-1
0
1
0
0
1
-1/3
-1/3
2/3
0
-1
1
1
0
1
1/3
-2/3
1/3
1
-1
0
0
0
0
0
0
0
0
0
0
1
1
1
0
0
0
0
0
0
The eight combinations can be considered as six non-zero vectors and two zero vectors (000 and 111). As Figure 35 shows,
the non-zero vectors are the axes of a hexagon; the angle between any two adjacent axes is 60 degrees. This divides the
hexagon into six sectors (Roman numerals I to VI). The zero vectors are at the origin, and they generate zero voltage on the
three phases. These eight vectors, called “basic space vectors,” are called ,
,
,
,
,
,
and
.
A voltage vector is synthesized by one or two of the six nonzero basic space vectors.
Figure 35. Basic Space Vectors
U120(010)
U60(110)
II
I
III
O111(111)
O000(000)
U180(011)
IV
U0(100)
VI
V
U240(001)
www.cypress.com
U300(101)
Document No. 001-93637Rev. **
32
PSoC® 4 Sensorless Field-Oriented Control (FOC)
For example, as Figure 36 shows, the voltage vector
is in sector I, and the period of the PWM is .
is the duration of ;
is the duration of
; and
is the duration of the two zero vectors. The vectors
and
compose a voltage vector,
that can also be composed by basic space vectors
and
.
Figure 36. Voltage Vector in Sector I
β
U60
Sector-I (U0,U60)
Uβ
Us
U60 *T2/T
θ π/3
T0
U0 *T1/T
Uα
U0
α
can be expressed as:
Therefore:
Then:
Where:
www.cypress.com
Document No. 001-93637Rev. **
33
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Note that all basic space vectors are generated with a specific ON/OFF state of upper MOSFETs; the duration is actually the
time of the PWM being high, or the duty cycle. Thus, generating a
is related to a change in duty cycle of the PWMs applied
to the inverter. In this example, both
and
require phase A to be turned ON, and
requires phase B to be turned
ON. Therefore:
Depending on how you use zero vectors, the SVPWM has two output patterns: a five-phase pattern and a seven-phase
pattern. The five-phase pattern uses only
or
.The seven-phase pattern uses both
and
, and their
durations are equal. Figure 37 illustrates these two patterns. Note that in 5-phase SVPWM, phase A is always on or always off.
Figure 37. Five- and Seven-Phase SVPWM in Sector I
T
U0
U60
5-phase SVPWM
O111
O111
U60
U0
1
Phase A
0
Phase B
Phase C
T1/2
T2/2
T0/2
T0/2
T2/2
T1/2
7-phase SVPWM
O000
U0
U60
O111 O111
U60
U0
O000
T2/2
T0/4 T0/4
T1/2
T2/2 T0/4
Phase A
Phase B
Phase C
T0/4 T1/2
There is no difference in the synthesized voltage vector generated by these two methods. However, the five-phase pattern
reduces the number of MOSFETs that are switching. This can reduce the switching losses in the power components, but it
creates more harmonics than the seven-phase pattern.
www.cypress.com
Document No. 001-93637Rev. **
34
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Appendix D: Q Number Format (Fixed-Point Number)
The Q number format is a well-known method to store and process floating-point numbers. It enables faster floating-point
operations done by the CPU, so that a separate floating-point unit is not needed. However, some accuracy may be lost by
using floating-point.
The example project provided in this application note uses the Q number format. Although understanding the Q number format
is not mandatory, gaining a fundamental knowledge of it will help you master the example code faster.
An introduction to the Q number format can be found in Wikipedia. This appendix contains a copy of the “Q (number format)”
page from the Wikipedia site, if you are not able to connect to the Internet but need to know about the Q number format when
reading this application note.
Note The following content is from Wikipedia. Cypress does not maintain this content for accuracy, nor guarantee that it is up
to date. If you have access to the Internet, go to the Wikipedia website to read the latest version by clicking the following link or
entering it in your browser.
This material from Wikipedia is reproduced under the Creative Commons Attribution-ShareAlike 3.0 Unported License, which
you can view at the following URL: http://creativecommons.org/licenses/by-sa/3.0/. For more information, please see
Wikipedia’s
licensing
statement
at
http://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_AttributionShareAlike_3.0_Unported_License. Your rights to this Wikipedia material are governed by the foregoing license.
From Wikipedia, the free encyclopedia:
Q (number format) on Wikipedia: http://en.wikipedia.org/wiki/Q_%28number_format%29
Q is a fixed point number format where the number of fractional bits (and optionally the number of integer bits) is specified. For
example, a Q15 number has 15 fractional bits; a Q1.14 number has 1 integer bit and 14 fractional bits. Q format is often used
in hardware that does not have a floating-point unit and in applications that require constant resolution.
Characteristics
Q format numbers are (notionally) fixed point numbers (but not actually a number itself); that is, they are stored and operated
upon as regular binary numbers (i.e. signed integers), thus allowing standard integer hardware/ALU to perform rational
number calculations. The number of integer bits, fractional bits and the underlying word size are to be chosen by the
programmer on an application-specific basis—the programmer's choices of the foregoing will depend on the range and
resolution needed for the numbers.
Some DSP architectures offer native support for common formats, such as Q1.15. In this case, the processor can support
arithmetic in one step, offering saturation (for addition and subtraction) and renormalization (for multiplication) in a single
instruction. Most standard CPUs do not. If the architecture does not directly support the particular fixed point format chosen,
the programmer will need to handle saturation and renormalization explicitly with bounds checking and bit shifting.
There are 2 conflicting notations for fixed point. Both notations are written as Qm.n, where:

Q designates that the number is in the Q format notation—the "Q" being reminiscent of the standard symbol for the set of
rational numbers.

m. (optional, assumed to be zero or one) is the number of bits set aside to designate the two's complement integer portion
of the number, exclusive or inclusive of the sign bit (therefore if m is not specified it is taken as zero or one).

n is the number of bits used to designate the fractional portion of the number, i.e. the number of bits to the right of the
binary point. (If n = 0, the Q numbers are integers—the degenerate case).
One convention includes the sign bit in the value of m, and the other convention does not. The choice of convention can be
determined by summing m+n. If the value is equal to the register size, then the sign bit is included in the value of m. If it is one
less than the register size, the sign bit is not included in the value of m.
In addition, the letter U can be prefixed to the Q to indicate an unsigned value, such as UQ1.15, indicating values from 0.0 to
+1.99997.
Signed Q values are stored in 2's complement format, just like signed integer values on most processors. In 2's complement,
the sign bit is extended to the register size.
For a given Qm.n format, using an m+n+1 bit signed integer container with n fractional bits:
www.cypress.com
Document No. 001-93637Rev. **
35
PSoC® 4 Sensorless Field-Oriented Control (FOC)


its range is
its resolution is
For a given UQm.n format, using an m+n bit unsigned integer container with n fractional bits:


its range is
its resolution is
For example, a Q14.1 format number:



requires 14+1+1 = 16 bits
14
its range is [-2 , 2
its resolution is 2
14
−1
−1
- 2 ] = [-16384.0, +16383.5] = [0x8000, 0x8001 … 0xFFFF, 0x0000, 0x0001 … 0x7FFE, 0x7FFF]
= 0.5
Unlike floating point numbers, the resolution of Q numbers will remain constant over the entire range.
Conversion
Float to Q
To convert a number from floating point to Qm.n format:
1.
Multiply the floating point number by 2
2.
Round to the nearest integer
n
Q to float
To convert a number from Qm.nformat to floating point:
1.
Convert the number to floating point as if it were an integer
2.
Multiply by 2
−n
Math Operations
Q numbers are a ratio of two integers: the numerator is kept in storage, the denominator is equal to 2n.
Consider the following example:
The Q8 denominator equals 28 = 256
1.5 equals 384/256
384 is stored, 256 is inferred because it is a Q8 number.
If the Q number's base is to be maintained (n remains constant) the Q number math operations must keep the denominator
constant. The following formulas shows math operations on the general Q numbers
and
.
Because the denominator is a power of two the multiplication can be implemented as an arithmetic shift to the left and the
division as an arithmetic shift to the right; on many processors shifts are faster than multiplication and division.
To maintain accuracy the intermediate multiplication and division results must be double precision and care must be taken in
rounding the intermediate result before converting back to the desired Q number.
www.cypress.com
Document No. 001-93637Rev. **
36
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Using C the operations are (note that here, Q refers to the fractional part's number of bits):
Addition
signed int a, b, result;
result = a + b;
With saturation
signed int a, b, result;
signed long int tmp;
tmp = a + b;
if (tmp > 0x7FFFFFF) tmp = 0x7FFFFFFF;
if (tmp < -1 * 0x7FFFFFFF) tmp = -1 * 0x7FFFFFFF;
result = (signed int) tmp;
Subtraction
signed int a, b,result;
result = a - b;
Multiplication
// precomputed value:
#define K
(1 << (Q-1))
signed int
a, b, result;
signed long int temp;
temp = (long int)a * (long int)b; // result type is operand's type
// Rounding; mid values are rounded up
temp += K;
// Correct by dividing by base
result = temp >> Q;
D i vi s i o n
signed int a, b, result;
signed long int temp;
// pre-multiply by the base (Upscale to Q16 so that the result will be in Q8 format)
temp = (long int)a << Q;
// So the result will be rounded ; mid values are rounded up.
temp += b/2;
result = temp/b;
Text is available under the Creative Commons Attribution-ShareAlike License.
www.cypress.com
Document No. 001-93637Rev. **
37
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Appendix E: Adapting the Design to Other Motors
This appendix helps you to drive other motors with the code example provided with this application note. You should follow the
operation guide step by step. A bold font indicates a mandatory action or critical information that requires more attention.
Hardware: CY8CKIT-037 or your own motor driver board
Firmware: Sensorless FOC project from the latest version of this application note
Equipment: Oscilloscope, multimeter, PC, USB cable for CY8CKIT-042 or MiniProg3 for programming your own board
Operation guide:
1.
Check the power range and motor type.
a.
Power range
CY8CKIT-037 supports a 12-V to 48-VDC supply voltage with up to 2 A input DC current. You should use the kit
only in this power range; using the kit out of this power range may damage it.
b.
Motor type
A motor with sinusoidal back electromotive force (BEMF) is recommended. A motor with trapezoidal BEMF may
not rotate or achieve the desired performance with the sensorless FOC project. Figure 38 illustrates these two
BEMF types. To measure BEMF, connect the ground of the oscilloscope probe to one motor phase and the probe to
another motor phase. Leave the other motor phases floating. Rotate the motor either by hand or by using another
motor. You should see the BEMF waveform on the oscilloscope.
The sinusoidal BEMF contains the complete angle information, which can be calculated with the SMO algorithm.
The trapezoidal BEMF is almost flat at the wave crest and trough and therefore is missing sufficient angle
information. As a result, the SMO algorithm cannot reliably retrieve the angle from this waveform, which may halt
the motor rotation.
Figure 38. Sinusoidal BEMF Versus Trapezoidal BEMF
(a) Sinusoidal BEMF
2.
(b) Trapezoidal BEMF
Change the parameters in the example project.
a.
Change the parameters for the motor.
These parameters are defined in the MotorController structure and initialized in the Cymc_MAL_MotorInit
function (Cymc_MAL.c). You should change them based on your motor specifications.
float Rs
Motor line-to-line resistance, unit: ohm
float Ls
Motor line-to-line inductance, unit: henry
uint8 Poles
Motor poles count
float baseFrequency
www.cypress.com
float Ts
PWM period,
uint16 ratedSpeedRPM
Rated speed based on motor specification, unit: RPM
Document No. 001-93637Rev. **
, unit: second
38
PSoC® 4 Sensorless Field-Oriented Control (FOC)
b.
Change the macro definitions for the system parameters.
These macro definitions are related to system parameters, such as DC bus voltage (Vbus, see Figure 3),
device VDD, and so on. You should change them (Cymc_MAL.h) if the default values are different from your system.
#define
#define
#define
#define
#define
#define
#define
c.
DC_BUS
VDD
SENSING_RESISTOR
OPAMP_GAIN
DC_BUS_SCALER
MAX_PHASE_CURRENT
ADC_RESOLUTION
(uint16)(24)
(3300)
(uint16)(30)
(uint16)(10000/2400)
(uint16)((590+5490)/590)
(uint16)(5)
(4096)
/*
/*
/*
/*
/*
/*
V
*/
mV
*/
mOhm
*/
10K / 2.4K
*/
(R9 + R10) / R10 */
A
*/
Change the parameters for the sensorless algorithm (SMO).
You may need to change two parameters in the SMO controller if the SMO cannot calculate the angle reliably with
your motor. You can change them in the Cymc_MAL_MotorInit function (Cymc_MAL.c).
q15_t slideCoff
q15_t slideError
d.
Coefficient K for slide control
Error threshold for slide control
Change the parameters for the PI controllers.
You may need to change the PI coefficient parameters in the PI controller if the PI controller does not work well with
your motor. You can change them in the Cymc_MAL_MotorInit function (Cymc_MAL.c) for the three PI controllers:
speed PI, Id PI, and Iq PI.
q15_t
q15_t
q15_t
q15_t
q15_t
3.
kr
kp
ki
outMax
outMin
Reference set point weighting
Proportional loop gain
Integral gain
Output upper limit
Output lower limit
Set up the hardware.
If you are using the CY8CKIT-037 kit, you can use the adapter provided with the kit for any motor whose maximum power
is 24 V DC / 2.1 A. If a different voltage (such as 48 V) or current (such as 3 A) is required, connect the DC voltage
source to the J8 connector (yellow marker in Figure 39) instead of the supplied power adapter.
Figure 39.Connector for DC Power Input
4.
Program the CY8CKIT-042 and observe the performance.
www.cypress.com
Document No. 001-93637Rev. **
39
PSoC® 4 Sensorless Field-Oriented Control (FOC)
5.
Tune the SMO module if the motor does not rotate.
a.
The motor starts up in open-loop control and then switches to closed-loop speed control later. If switching to the
closed loop control fails (motor halts very soon after the rotation starts), you may need to tune the SMO module. Try
the following methods:
i. Confirm that the motor parameters are set correctly in step 2.a.
ii. Change the smoEst.slideError parameter to a larger value. When the value of this variable is larger, it is easier
to switch to closed loop however the rotor angle calculation is less accurate.
b.
If the motor rotates with a vibration, try tuning the Kp and Ki parameters in the PI controller. The larger the Kp value,
the faster the system closes in on the reference value; however it may make the system unstable. The Ki value can
reduce the static error and make the system stable; however a larger Ki may make the integration value saturate.
www.cypress.com
Document No. 001-93637Rev. **
40
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Appendix F: Tunable Parameters List
Variable’s Name in Project
Name: motor
Type:structMotorController
Location:Cymc_MAL.c
Comments:
Motor parameters and running status
Name: rampUp
Type:StructRampUp
Location:Cymc_MAL.c
Comments:
Motor parameters struct
Name: pidSpeed
Type:StructPIController
Location:Cymc_MAL.c
Comments:
PID controller for speed
Name: pidId
Type:StructPIController
Location:Cymc_MAL.c
Comments:
PID controller for d-axis current
Name: pidIq
Type:StructPIController
Location:Cymc_MAL.c
Comments:
PID controller for q-axis current
Name: smoEst
Type: structSMO
Location: Cymc_MAL.c
Comments:
Only list tunable parameters in the SMO structure
www.cypress.com
Structure Member
float Rs
float Ls
uint8 Poles
float baseFrequency
float Ts
uint16 speedRPM
uint16 ratedSpeedRPM
uint8 runState
q15_t speedRef
q15_t vdRef
q15_t vqRef
q15_t RefSpeed
Comments
Motor line-to-line resistance, unit: ohm
Motor line-to-line inductance, unit: henry
Motor poles count
q15_t delayPrescaler
Delay prescaler
q15_t stepSpeed
Step pace for speed increasing
q15_t output
Output speed in open-loop startup
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
q15_t
Reference setpoint
Feedback
Controller output
Referencesetpoint weighting
Proportional loop gain
Integral gain
Output upper limit
Output lower limit
Reference setpoint
Feedback
Controller output
Referencesetpoint weighting
Proportional loop gain
Integral gain
Output upper limit
Output lower limit
Reference setpoint
Feedback
Controller output
Referencesetpoint weighting
Proportional loop gain
Integral gain
Output upper limit
Output lower limit
DC-bus voltage
Voltage on α-axis
Voltage on β-axis
Current speed reference
Control gain
Filter gain
Coefficient K for slide control
Error threshold for slide control
α-axis stator current
β-axis stator current
Output: angle
ref
fbk
out
kr
kp
ki
outMax
outMin
ref
fbk
out
kr
kp
ki
outMax
outMin
ref
fbk
out
kr
kp
ki
outMax
outMin
Vbus
volAlpha
volBeta
speedRef
Ggain
Fgain
slideCoff
slideError
curAlpha
curBeta
Theta
PWM period,
, unit: second
Current rotation speed, unit: RPM
Rated speed based on motor specification, unit: RPM
Motor run state
Speed reference
vd reference
vq reference
Speed reference
Document No. 001-93637Rev. **
41
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Document History
®
Document Title: AN93637 – PSoC 4 Sensorless Field-Oriented Control (FOC)
Document Number:001-93637
Revision
**
ECN
4556106
www.cypress.com
Orig. of
Change
BOBH
Submission
Date
04/01/2015
Description of Change
New application note
Document No. 001-93637Rev. **
42
PSoC® 4 Sensorless Field-Oriented Control (FOC)
Worldwide Sales and Design Support
Cypress maintains a worldwide network of offices, solution centers, manufacturer’s representatives, and distributors. To find
the office closest to you, visit us at Cypress Locations.
PSoC® Solutions
Products
Automotive
cypress.com/go/automotive
psoc.cypress.com/solutions
Clocks & Buffers
cypress.com/go/clocks
PSoC 1 | PSoC 3 | PSoC 4 | PSoC 5LP
Interface
cypress.com/go/interface
Lighting & Power Control
cypress.com/go/powerpsoc
Memory
cypress.com/go/memory
PSoC
cypress.com/go/psoc
Touch Sensing
cypress.com/go/touch
USB Controllers
cypress.com/go/usb
Wireless/RF
cypress.com/go/wireless
Cypress Developer Community
Community | Forums | Blogs | Video |Training
Technical Support
cypress.com/go/support
PSoC is a registered trademark and PSoC Creator is a trademark of Cypress Semiconductor Corp. All other trademarks or registered trademarks
referenced herein are the property of their respective owners.
Cypress Semiconductor
198 Champion Court
San Jose, CA 95134-1709
Phone
Fax
Website
: 408-943-2600
: 408-943-4730
: www.cypress.com
© Cypress Semiconductor Corporation, 2015. The information contained herein is subject to change without notice. Cypress Semiconductor
Corporation assumes no responsibility for the use of any circuitry other than circuitry embodied in a Cypress product. Nor does it convey or imply any
license under patent or other rights. Cypress products are not warranted nor intended to be used for medical, life support, life saving, critical control or
safety applications, unless pursuant to an express written agreement with Cypress. Furthermore, Cypress does not authorize its products for use as
critical components in life-support systems where a malfunction or failure may reasonably be expected to result in significant injury to the user. The
inclusion of Cypress products in life-support systems application implies that the manufacturer assumes all risk of such use and in doing so indemnifies
Cypress against all charges.
This Source Code (software and/or firmware) is owned by Cypress Semiconductor Corporation (Cypress) and is protected by and subject to worldwide
patent protection (United States and foreign), United States copyright laws and international treaty provisions. Cypress hereby grants to licensee a
personal, non-exclusive, non-transferable license to copy, use, modify, create derivative works of, and compile the Cypress Source Code and derivative
works for the sole purpose of creating custom software and or firmware in support of licensee product to be used only in conjunction with a Cypress
integrated circuit as specified in the applicable agreement. Any reproduction, modification, translation, compilation, or representation of this Source
Code except as specified above is prohibited without the express written permission of Cypress.
Disclaimer: CYPRESS MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, WITH REGARD TO THIS MATERIAL, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Cypress reserves the
right to make changes without further notice to the materials described herein. Cypress does not assume any liability arising out of the application or
use of any product or circuit described herein. Cypress does not authorize its products for use as critical components in life-support systems where a
malfunction or failure may reasonably be expected to result in significant injury to the user. The inclusion of Cypress’ product in a life-support systems
application implies that the manufacturer assumes all risk of such use and in doing so indemnifies Cypress against all charges.
Use may be limited by and subject to the applicable Cypress software license agreement.
www.cypress.com
Document No. 001-93637Rev. **
43