FOC Example Structure Guide_V1.2.0.0
- 1 Introduction
- 2 FOC Architecture
- 2.1 What is FOC?
- 2.2 FOC Block Diagram
- 3 Changes in V1.2.0.0
- 4 Software Details
- 4.1 Folder structure
- 4.2 Program Structure
- 4.2.1 Hardware Abstraction Layer (HAL)
- 4.2.2 Motor Control Layer (MCL)
- 4.2.3 FOC API Layer (CORE)
- 4.2.4 Mathematical Library(MATH)
- 4.2.5 Targets
- 4.2.6 FOC Demo
- 5 Abbreviations
Introduction
This article is prepared to provide information about FOC-based (Field-Oriented Control) “Motor Control Example”. We aim to offer solutions in this field and to introduce the capabilities of netX 90 in Motion.
FOC Architecture
What is FOC?
Field-oriented control (FOC), also known as vector control, is a technique used to control Permanent Magnet Synchronous Motor (PMSM) and Brushless-DC Motor (BLDC). FOC provides good control capability over the full torque and speed ranges. The FOC implementation requires the transformation of stator currents from the stationary reference frame to the rotor flux reference frame (also known as the d-q reference frame).
Speed control and torque control are the most commonly used FOC control modes. The position control mode is less common. Most of the traction applications use the torque control mode in which the motor control system follows a reference torque value. In the speed control mode, the motor controller follows a reference speed value and generates a torque reference for the torque control, which forms an inner subsystem. In the position control mode, the speed controller forms the inner subsystem.
FOC algorithm implementation requires real-time feedback of the currents and rotor position angle. Measure the current and position by using sensors. The sensorless techniques can be used to estimate feedback values (by motor hall sensors and phase angles) instead of the actual sensor-based measurements. This technique is called Sliding-mode based rotor estimation.
More detailed information about FOC can be found on the https://www.mathworks.com/solutions/electrification/field-oriented-control.html, https://www.trinamic.com/technology/motor-control-technology/field-oriented-control/, https://www.pmdcorp.com/resources/type/articles/get/field-oriented-control-foc-a-deep-dive-article.
FOC Block Diagram
In Figure 1, the block diagram of the FOC is seen in detail. The Clarke transform converts the time domain components of a three-phase system (in abc frame) into two components in an orthogonal stationary frame (αβ). The Park transform converts the two components in the αβ frame to an orthogonal rotating reference frame (dq). Consecutively implementing these two transforms simplifies computations by converting AC and voltage waveforms into DC signals. Thanks to the DC quantities obtained by these transformations, we obtain the possibility of PI current control (on Id and Iq vectors) facility which allows for performing torque control.
Thanks to the feedback provided by the motor, the speed feedback(Encoder, Resolver, Hall Sensor, … ) is sent to the speed PI controller for the speed control of the motor. Likewise, after motor PI controls, these two components in the orthogonal rotating reference frame (dq) are converted to the two components in the orthogonal stationary frame (αβ) using the Inverse Park Transform. It is converted into time-domain components (in abc frame) using the Space Vector PWM Generator. You may have noticed the absence of the Inverse Clarke Transform. The Inverse Clarke Transform takes place indirectly during the Space Vector Modulation computation. Park Transform and Inverse Park Transform need the instantaneous rotor electrical angle[Θ]'s sin and cos values. Respectively, the instantaneous rotor’s mechanical angle is converted to its electrical angle with relevant calculations, and the sin and cos values of this angle are calculated.
Field-weakening or flux-weakening is a technique for increasing the speed of an electric motor above its rating at the expense of reduced torque. This concept is especially evident when operating at high motor speeds. More information can be found at the https://www.mathworks.com/solutions/electrification/field-weakening-control.html.
ωref - Reference angular speed [rad/s]
ωfb - Angular speed feedback of rotor [rad/s]
Tref - Reference torque [N.m]
idref, iqref - Orthogonal rotating reference frame current components [A]
id, iq - Orthogonal rotating reference frame current feedbacks [A]
vdref, vqref - Orthogonal rotating reference frame voltage components [V]
Vα, Vβ - Orthogonal stationary frame voltage components [V]
ia, ib, ic - Currents flowing in the stator windings [A]
va, vb, vc - Applied voltages to the motor [V]
Vdc - DC Bus Voltage [V]
θm - Instantaneous rotor mechanical angle [rad]
θe - Instantaneous rotor electrical angle [rad]
Gah, Gal, Gbh, Gbl, Gch, Gcl - A,B,C phase MOSFETs' Gate PWM duty cycles [%]
Figure 1 - Block Diagram of Field-Oriented Control
Changes in V1.2.0.0
Support for setting/getting motor PI configuration parameters (valid for Torque (current) and Speed PI controllers) via API functions has been added. In this way, FOC can be used flexibly with different PI values in multi-axis systems without compiling. It plays an important role, especially in multi-axis systems where there are axes with different moments of inertia.
Software Details
This chapter describes how the software is structured and how to configure it according to the requirements.
Folder structure
While the layers are in separate folders by design, the components of that layer are separated as *.c, *.h pair. The folder structure of the FOC project is shown in Figure 2.
The FOC, MCL, and HAL components are initialized into the main.c file from lower to upper layers (HAL → MCL → CORE). The desired API function is used via handles obtained after FOC initialization. The MATH library is accessible from all layers. The public folder specifies the header files available to the user. The public folders contain the user-accessible header files.
Program Structure
The FOC application consists of four layers. The “Hardware Abstraction Layer“ (HAL) provides 6 components to communicate with the hardware. The “Timer” manages the motor self-calibration process and measures elapsed time for the timeout feature. It is also designed to be highly flexible and adaptable to future requirements (e.g. diagnostics). The “Analog-to-Digital Converter“ (ADC) provides information from the board sensors (input voltage, phase voltages, phase current, SinCos Resolver, board potentiometer, etc.). The “Motion Pulse-Width Modulation“ (MPWM) serves as the configured PWM for the motor. The “Gate Driver“ controls the driver chip that drives the motor. The “Quadrature Encoder Interface“ (QEI) accurately determines the rotor position and speed. The “Hall Sensors“capture information from the GPIOs connected to the Hall-Effect sensors built into the motor and indicate the current state of the rotor. They are mainly combined with the encoders to determine the rotor position. Their role is to determine the rotor starting angle. They are also used for speed estimation in the absence of an encoder. However, they don’t provide precise position control due to their poor resolution. The main purpose of the HAL layer is to provide feedback information to the higher layers and to transmit the control request it receives from there to the motor. And in doing so, the aim is to create an abstraction with hardware.
The “Motor Control Layer” (MCL) retrieves the latest speed setpoint and operation mode from the “Core Layer“ (FOC API). Depending on the active operation mode, it retrieves relevant feedback from the HAL, to process according to the FOC algorithm. This algorithm includes various blocks such as PI controllers, Transformation blocks, Space Vector Modulators, Low-pass filters, etc. The latest set speed is kept at the desired value by the Speed PI Controller using the motor's speed feedback. In addition, the motor’s torque is tried to be held at the maximum level thanks to the d and q Current Vector PI controller. The feedback given to the current PI controllers is the current vectors Id and Iq obtained by transformations using the measured motor current values and the electrical angle[Θ]. Then the calculated dq vectors are converter into 3-phase modulated amplitudes and thus motor rotation is provided. The algorithm described above is executed in the MCL layer. The “Motion“ component includes motion-related functions. It is actually where all FOC application is coordinated. Motor Speed and Operation functions from the FOC API layer are received by this component, processed, and transmitted to the relevant components. It also coordinates the motor position determination in self-calibration and calibration with parameters. The “FOC Control” component provides the main FOC control. Operations such as Torque control, vector transformations, Space Vector Modulation, etc. are done. The “Calibration“ component provides the self-calibration and calibration using user calibration parameters. The self-calibration process associates the hall sensor sectors with the electrical rotor position angles. Calibration with user parameters is done using predetermined self-calibration parameters without any physical movement. The “Position & Speed Estimation“ (PSE) component makes the data received from HAL QEI and HAL Hall Sensors processed. It contains all position and speed estimation functions.
The “Mathematical Library“ (MATH) provides the FOC-based mathematical functionality used by all layers.
The “Foc Api(Core) Layer” contains the necessary API functions for FOC initialization and control.
Figure 3 - Block Diagram of netX90 Field-Oriented Control Software
The block diagram depicted in Figure 3 visually represents the components, their functionalities, and their interconnections.
Hardware Abstraction Layer (HAL)
The “Hardware Abstraction Layer“ (HAL) contains 6 components to communicate with the hardware. The HAL layer uses motor control-related peripherals embedded in the netX90 IC. More detailed information about these peripherals can be obtained from netMOTION and netX 90 in Motion. For even more detailed information, see section 5.14 from netX 90 - Technical data reference guide.
Timer
It manages the motor self-calibration process, measures elapsed time for the timeout feature and generates delay. It is also designed to be highly flexible and adaptable to future requirements (e.g. diagnostics).
ADC(Analog-to-Digital Converter)
It provides information from the netX90-MC board sensors (Temperature, Reference voltages, …), motor position feedbacks (Hall sensor sectors, Resolver, …), board voltages (DC bus voltage,…), and Gate driver feedbacks (Measured phase currents, measured phase voltages, …). In Table 1, the signals connected to the MADC matrix of the netX90-MC Rev. 3 board are shown. Green cells indicate signals used in this project are described in Table 1.
Unit | Channel 0 | Channel 1 | Channel 2 | Channel 3 | Channel 4 | Channel 5 | Channel 6 | Channel 7 |
---|---|---|---|---|---|---|---|---|
ADC 0 | SIN240_HC (X901) | ISENA (DRV8323R) | TSENS (INTERNAL) | VREF_ADC (INTERNAL) | - | - | - | - |
ADC 1 | - | ISENB (DRV8323R) | VDDIO/2 (INTERNAL) | VREF_ADC (INTERNAL) | - | - | - | - |
ADC 2 | SIN0_HA (X901) | AIM (X901) | POT (R33) | VSENA (J5) | VSENVM (J1) | - | NTC (R39) | - |
ADC 3 | SIN120_HB (X901) | AI (X901) | ISENC (DRV8323R) | VSENB (J5) | - | VSENC (J5) | - | - |
Table 1 - MADC matrix
Signal | Description | Note |
---|---|---|
SIN0_HA (X901) | Hall Sensor - Sector A | These signals differ depending on the type of motor connected (Hall Sensor Sector, Resolver, EnDat, Biss). For more detailed information check out the X901 - Sensor connector section in 2.6.5 of NXHX 90-MC. |
SIN120_HB (X901) | Hall Sensor - Sector B | |
SIN240_HC (X901) | Hall Sensor - Sector C | |
ISENA (DRV8323R) | Current measured and amplified by Gate Driver - Phase A | - |
ISENB (DRV8323R) | Current measured and amplified by Gate Driver - Phase B | |
ISENC (DRV8323R) | Current measured and amplified by Gate Driver - Phase C | |
VSENVM (J1) | DC-Bus Voltage | - |
POT (R33) | Soldered board potentiometer used with FOC Demo application. | - |
Table 2 - ADC-sampled signals used by the FOC application.
Gate Driver
It provides a Gate Driver control interface. The Gate Driver used in our netX90-MC Rev. 3 board is Texas Instruments DRV8323RSRGZR, 6 to 60V Three-Phase Smart Gate Driver. This driver also drives Texas Instruments' 60-V Half-Bridge Power Block Mosfets named CSD88599Q5DC (1 for each motor phase). More detailed information can be obtained from DRV832x 6 to 60-V Three-Phase Smart Gate Driver and CSD88599Q5DC 60-V Half-Bridge NexFET™ Power Block. It communicates with netX90 via the SPI channel. The Gate Driver component contains important functions such as fault detection, enabling/disabling the gate driver, coast stop, brake mode and auto current measurement offset trim mode (see Auto Current Offset Trim using DRV8323RS Gate Driver). Especially thanks to fault detection, the burning of the motor windings can be prevented in cases such as over-current conditions.
MPWM (Motion Pulse-Width Modulation)
The MPWM component is used to modulate the 3-phase PWM signal required for the motor control. Thanks to the “Event Counter Zero (ECZ)“, it generates events so that measurements, transformations, and PI controls are made and new SVPWM duty cycle values are adjusted. Event Counter Zero (ECZ) is the reduced frequency of the “Beginning of Period (BOP)” events variant. If the field evt_cnt_top of register mpwm_cfg is set to a value N, an ECZ event will be sent every N+1 period. MPWM can be synchronized to hardware-assisted cyclic network events. In this way, since the MPWM callback event will be synchronized with the Bus Cycle, jitter problems will be partially prevented and motor control will be realized in a determined way. For detailed information, see FOC Runtime Analysis and section 5.14.3 from netX 90 - Technical data reference guide.
QEI (Quadrature Encoder Interface)
The QEI component provides information from the Quadrature Encoder, which is mounted on the motor. Method 4 was used as the speed estimation method (see section 5.14.4.11 from netX 90 - Technical data reference guide). It supports working with ENC0(QEI 5V TTL) and ENC1(RS422) encoder sources. The NXHX-DH adapter module serves to connect digital transmitters as TTL or RS422 (see section 3.4 from NXHX 90-MC). Also, this component supports the encoder direction inversion functionality. For detailed information, see section 5.14.4 from netX 90 - Technical data reference guide. Unlike V1.0.0.0, the QEI capture structure is changed. In the previous version, the encoder positions were captured using the GPIO TIMER trigger internally. But, because of the IRT compatibility reasons, this capturing is realized with a specialized function asynchronously. So, it must be synchronized with the external bus cycle. In this way, flexible operation with different bus cycle periods will be ensured.
Hall Sensor
The Hall Sensor component provides information from the Hall Sensors, which are integrated into the motor. The Rotor position can be known by the currently active Hall Sensor. The hall sensor inputs are directly connected to GPIOs and used to determine the active hall state.
Motor Control Layer (MCL)
The “Motor Control Layer“ (MCL) contains 4 components.
Motion
The “Motion“ component provides basic motion functionality. Unlike the previous FOC version V1.0.0.0, the structure of the Motion component had been changed. The main purpose of the change is to ensure motion synchronization with the Bus Cycle on the Application layer instead of Hal Timer. In this way, Isochronous mode support is provided.
At the new FOC, the Motion layer commands are categorized under two command types.
Acyclic: The first goal here is to make FOC ready for use with relevant operation mode commands and calibration is one of these examples. The second one is changing the operation modes dynamically: Coast mode, Start operation, etc. In Figure 4, the acyclic operations are depicted.
Figure 4 - MCL Layer Motion Component’s handled processes by the Application (ProfiDrive, EtherCat Motion, etc.) acyclically through FOC API.
These functions are called directly from the Application through FOC API functions.
MOTION - Coast Stop: The Coast Stop mode is designed to bring the MOSFET gates to Hi-Z (Gate driver outputs are switched to Hi-Z) and ensure that the motor will spin down at whatever speed the load imposes. It is generally used to perform the Pulse Disable operation on ProfiDrive. Likewise, the same process is performed on EtherCat Motion and its equivalents.
MOTION - Start Operation: It disables the coast stop mode. In this way, the motor control PWM pulses are enabled. The speed controller starts to handle the speed setpoint value set by a related application. So speed and position control are activated.
MOTION - Calibration with user parameters: Motor calibration can now be performed by setting calibration parameters externally (Motor self-calibration can pose a safety risk when the motors are linked to a mechanical mechanism because the drives begin to move). The calibration parameters acquired after a successful motor self-calibration are stored in the Remanent area on the Application (e.g. PLC). As long as there is valid calibration data in the remanent data on Application start-up, the calibration will be executed instantly by configuring these parameters (the motor will not move). More detailed information can be found here: PDMC AC1/4 Motor Calibration.
MOTION - Start self-calibration: The operation of the Field-oriented control (FOC) component is highly dependent on determining the rotor position angle. For this, the FOC needs to know the hall sensor sequence and the corresponding rotor position for each hall sensor. The motor self-calibration is achieved by providing the FOC with the correct values of these parameters (given the specific motor and load). During the self-calibration process, the motor turns at low RPMs in clockwise (capture the start points) and counterclockwise (capture the endpoints) directions and the following parameters are measured. In addition, the hall sensor sequences of the motor are determined. The Start self-calibration function starts the internal timer when triggered from an App via the FOC API. Thanks to the timer callback, the self-calibration process starts to be performed cyclically. All necessary Foc Control, Calibration and PSE components are handled through timer callback within the scope of the self-calibration process. The started internal timer automatically stopped with the completed calibration process.
Cyclic: The associated cyclic process provides the motor speed and position control processes. In contrast to the V1.0.0.0, the timer performing the cyclic control has been moved into the external application layer. In this way, all motion control processes are synchronized with the Application. Full synchronization support is provided indirectly with the hardware-assisted bus cycle(by XCTRIGGER). In this way, IRT (Isochronous Real-Time) mode support is provided and jitters occurring in the Bus Cycle can be tolerated to a certain level (by MPWM Synchronization - FOC Run-Time Analysis). In Figure 5, the acyclic operations are depicted.
Figure 5 - MCL Layer Motion Component’s handled processes by the Application (ProfiDrive, EtherCat Motion, etc.) cyclically through FOC API.
MOTION - Set motor speed: The set motor speed is called cyclically by the external application timer. It is fully compatible with the different timer periods (The response of the speed and position control will vary depending on the period of the relevant external timer). The position control mentioned above is realised by the external application through the position feedback from the encoder. It logically generates a position path integrating the set motor speed including the ramp-up and ramp-down.
MOTION - Get motor speed: The get motor speed is called cyclically by the external application timer the same way. It returns the actual estimated motor speed. Triggering this component cyclically is of vital importance as it performs the speed and position estimation process by the PSE component. The PSE component has been modified to work flexibly with different bus cycle periods. Unlike V1.0.0.0, the PSE component calls the capture QEI (Quadrature Encoder Interface) function by the PSE estimate speed function to calculate estimate speed. Please don’t forget the trigger Get Motor Speed function through FOC API cyclically to ensure error-free motion control.
These related functions are implemented in the “Components\Hal\Sources\Mcl_Motion.c”.
FOC Control
The “FOC Control“ component takes care of the vector part of the FOC application. It allows the motor to be driven with closed-looped(current vector control) and open-looped(voltage vector control). With the closed-loop control, it is ensured that the maximum torque value is reached by making the Id and Iq vectors orthogonal by the current PI controllers for the set speed (Figure 1). In open-looped control, on the other hand, the vd and vq vectors are directly determined and given to the Inverse Park Transform block to control the motor, and maximum torque cannot be guaranteed. It is used in our application during calibration and will be implemented for more precise position control. Above, the MPWM ECZ event is mentioned while explaining the MPWM component. The ECZ counter value is 2 in your application. That is, 1 ECZ event will occur in every 2 BOP events and the MPWM Event Callback will be handled. The functions handled (Figure 6) each time the MPWM event callback is invoked are described below.
Figure 6 - MCL Layer FOC Control component’s MPWM event task
HAL GATE DRV - Gate Driver Operation State Machine: The Gate Driver component plays a crucial role in controlling the FOC. This state machine processes the operation control command given to the Gate Driver. These are respectively to enable/disable the Gate Driver, write the desired configuration registers, read the status registers, and perform fault detection. Since the Gate Driver is responsible for measuring the current flowing through the motor windings, it's essential to trim this offset value to minimize any potential measurement errors. For trimming these offset values, The current offset compensation algorithm trims these offset values into the Foc Control component. However, this algorithm compensates for all cascaded offsets generated by the ADC input offset and other onboard components. When compensating the gate driver's current measurement offset value before entering the ADC, reduces the risk of measurement error. Because this separated offset values from ADC and other parasitic effects, only ADC errors and these parasitic effects will be filtered with the offset compensation algorithm in Foc Control. More detailed information can be accessed at the relevant link: Auto Current Offset Trim using DRV8323RS Gate Driver. The corresponding HAL Gate Driver operation state machine is shown in Figure 7, and the states' behaviour is explained in detail in Table 3. HAL Gate Driver Operation State Machine is implemented in the Hal_GateDrvCyclicRoutine(…) function in the “Components\Hal\Sources\Hal_GateDrv.c”.
Figure 7 - HAL Gate Driver operation state machine
State | Description |
---|---|
INIT | The Set Gate Driver operation command is directed. |
WAIT FOR WAKEUP | “HAL_GATEDRV_OPERATION_START“ command has arrived. Gate Driver is enabled and waiting for it to wake up. |
WAIT FOR SLEEP | “HAL_GATEDRV_OPERATION_STOP“ command has arrived. Gate Driver is disabled and waiting for it to sleep. |
AUTO OFFSET CAL | Activating the automatically current measurement offset calibration to compensate it automatically. MPWM is disabled during this process. |
WRITE CONFIG REGS | All configuration registers are being written. |
READ CONFIG REGS | It performs the reading process for the verification purposes of the written configuration registers. |
READ STATUS REGS | “HAL_GATEDRV_GET_STATUS“ command has arrived or verification is successes. All status registers will be read. |
DONE | The operation is successful. Stay in this state until the new set operation command arrives. |
FAILED | SPI communication error. Stay in this state until the new set operation command arrives. |
Table 3 - HAL Gate Driver operation state machine’s state definitions.
MCL FOC Control - FOC Control Main State Machine: This state machine is a large-scale state machine providing the FOC control. The state transitions of this state machine are indirectly controlled by the Motion component using the Transit state function. That is, its control is performed indirectly by the MCL Motion component. Please keep this in mind when examining it. The corresponding FOC Control Main state machine is shown in Figure 8, and the states' behaviour is explained in detail in Table 4. IDLE state stops all FOC operation including stopping MPWM when the motor is not operating. The purpose of the VOLTAGE CONTROL state is to provide open-loop vector control for the calibration process (It will be used with implemented torque control). The aim is not to reach the maximum torque but to keep the torque constant for accurate measurement during calibration. The CURRENT CONTROL state provides the desired closed-loop vector control. This is the behaviour we want during motor control. It keeps the motor torque at the maximum level at set speed thanks to the dq current PI controllers it contains. It is the state that is active when the motor is operating. The FAILED state is triggered after a critical error in the Motion Control State and MPWM is stopped. Then it is checked whether there is an error in the Gate Driver Unit and if there is an error, Fault Handling is performed. If necessary, the Gate Driver Unit is restarted. MCL Foc Control Main State Machine is implemented in the Mcl_FocCtrlMainSMCtrl(…) function in the “Components\Mcl\Sources\Mcl_FocCtrl.c”. It is transited with the Mcl_FocCtrlTransitMainSMState(…) function on the same path.
Figure 8 - MCL FOC Control main state machine
State | Description |
---|---|
IDLE | DQ request voltage and current vectors are set to 0. Disable the MPWM outputs. |
VOLTAGE CONTROL | Open-looped vector control of the motor. It is used for the control of the motor without current vector feedback during calibration. Enable the MPWM outputs. |
CURRENT OFFSET | Current offset bias calculation is performed. MPWM outputs will be enabled by inheritance. |
CURRENT CONTROL | Closed-looped vector control of the motor is performed. Enable the MPWM outputs. |
FAILED | Disable the MPWM outputs. If there is an error due to Gate Driver, restart it. |
Table 4 - MCL Foc Control state machine’s state definitions
The CURRENT OFFSET state is used for current offset bias calculation. Phase currents are AC by nature, that is they are bidirectional currents. However, the integrated ADC we measured is DC, so it is unidirectional. Measuring the phase currents with the ADC and interpreting it assigned in the variable, we need to make the Current Offset Bias calculation and compensate for the measured values. The state machine manages the current offset bias calculation in the CURRENT OFFSET state. The corresponding FOC Control Main state machine is shown in Figure 9 and its states' behaviours are explained in detail in Table 5. MCL Current Offset Bias Calculation State Machine is implemented in the mcl_FocCtrlCurrentOffsetSMCtrl(…) function in the “Components\Mcl\Sources\Mcl_FocCtrl.c”.
Figure 9 - MCL Current Offset Bias Calculation state machine
State | Description |
---|---|
INIT | Reset Measurement Index counter and Sum of the Current Offset measurement variables on phases U, V, W. |
MEASURE | Add measured phase currents(U,V,W) to the Sum of Current Offset measurements on phases. Increase Measurement Index counter. This state is active until the measurement index is equal to the 8 (number of measurement parameters that is defined in MCL config parameters). |
CALC | Check whether the Sum of Current Offsets of each phase (U,V,W) are inside defined borders. If Sum of Current Offsets is inside the defined borders, set the offsets as the average of the sum of current offsets. |
DONE | Current offsets of the phases(U,V,W) are calculated successfully. |
FAILED | An error occurred during the measurement. It will be tried again after the specified waiting time. Disable the MPWM outputs. |
Table 5 - MCL Foc Control current offset bias calculation state machine’s state definitions
Calibration
The purpose of the MCL Calibration component is to make the correct position estimation. It can be performed in two different ways.
Motor self-calibration: The motor self-calibration provides associate position information from the feedback device (Encoder, Resolver, etc.) related to each motor hall sensor sector for both rotation directions(CW and CCW). The purpose of rotating the motor in two directions is to compensate for the Hysteresis effect by determining the start and end positions of each Hall Sensor sector. Then it is validated whether the position values obtained for the six Hall Sensor sectors are within certain limits in both directions. After successful validation, the values obtained in both directions in each Hall Sensor sector are averaged and recorded for the correct position estimation. The corresponding Calibration state machine is shown in Figure 10, and the states' behaviour is explained in detail in Table 6. MCL Calibration State Machine is implemented in the Mcl_CalCyclicRoutine(…) function in the “Components\Mcl\Sources\Mcl_Cal.c”.
Figure 10 - MCL Calibration state machine
State | Description |
---|---|
INIT | Reset the calibration Electrical Rotor Position Angle[θ], Mechanical Speed[RPM] and set the calibration Vd and Id vectors with defaults(Defined in MCL config parameters). Transit the Foc Control Main State to Voltage Control. Set the elec. rotor position manually. Set requested DQ voltage vectors. Set initial alignment waiting time to 500ms(Config parameter). |
WAIT FOR INITIAL ALIGNMENT | Wait until the waiting time becomes 0. Just before switching to TURN CW state, save last captured Hall Sensor Sector and Electrical Rotor Position Angle[θ], set the calibration Mechanical Speed[RPM] to 12(Defined in MCL config parameters). Set calibration speed manually. |
TURN CW | This state is active until the rotor completes the 4(Config parameter) CW revolutions. Thus, when Hall Sensor sector change occurs, its current electrical rotor position angle value is associated with that sector. Reset the calibration Electrical Rotor Position Angle[θ], Mechanical Speed[RPM]. Set the direction change alignment waiting time to 500ms(Config parameter). Thus, preparations are made for the next state. |
WAIT FOR DIR CHANGE ALIGNMENT | Before changing the direction, the rotor is kept at a standstill. It is similar to the “WAIT FOR INITIAL ALIGNMENT” state. Differently, Mechanical Speed[RPM] is set to -12. |
TURN CCW | It is similar to “TURN CW” state, except that the motor rotates in the opposite direction. |
VALIDATE | Hall sector sequences, hall position alignment trend and position deviation values are checked respectively. |
EVALUATE | After successful validation, the values obtained in both directions in each sector are averaged and these values are recorded to be used in correct position estimation. |
DONE | Calibration is successful. Transit the Foc Control Main State to Idle. |
FAILED | Calibration is failed. Transit the Foc Control Main State to Idle. |
Table 6 - MCL Calibration state machine’s state definitions
Motor calibration using user parameters: This feature was implemented with V1.1.0.0. Hall Sector sequence and position values obtained through previously successful self-calibration are required to perform this functionality. These values can be obtained and recorded in the remanent area in the external Application. This allows the motor to be calibrated instantaneously without moving the rotor. (Motor self-calibration can pose a safety risk when the motors are linked to a mechanical mechanism because the drives begin to move)
PSE (Position & Speed Estimation)
The PSE component transforms the data it receives from the relevant feedback devices(Encoder, Resolver, Hall Sensor from HAL layer) into meaningful and provides speed and position information for FOC control. Speed and position information is currently only provided by the encoder (with the QEI interface) and the Hall sensors.
The PSE component has been modified to work flexibly with different bus cycle periods. Unlike V1.0.0.0, the PSE component calls the capture QEI (Quadrature Encoder Interface) function by the PSE estimate speed function to calculate estimate speed. Thus, synchronization with the external Application is possible.
In the future, various encoder interfaces and resolvers (SinCos) will be supported.
FOC API Layer (CORE)
The “Foc Api Layer“ provides an interface for the user to control the FOC application. The following functions can be accessed from the “Targets\Common\Include\Foc_Api.h” file.
Initialize FOC layer
FOC_H /* FOC handle*/
Foc_Init(FOC_INIT_PRM_T* ptFocInitPrm); /* FOC initalization parameters */
Initializes the FOC. After successful initialization, creates resources, starts the FOC, and returns the handle to the user.
The FOC_INIT_PRM_T stores the low layers' handles.
Deinitialize FOC layer
uint32_t /* Hilscher status code */
Foc_DeInit(FOC_H hFoc); /* FOC handle */
Deinitializes the FOC. It stops the FOC and frees up the resources for the corresponding handle.
Hilscher status codes are defined into the Hil_Results.h file.
Set Motor Speed
uint32_t /* Hilscher status code */
Foc_SetMotorSpeed( FOC_H hFoc, /* FOC handle */
const int32_t lSpeed); /* Motor speed request[RPM]
Positive values - CW direction
Negative values - CCW direction */
Sets the motor speed in RPM. This function must be set cyclically using either the hardware-assisted bus cycle callback (XCTRIGGER) or a timer callback you have created. Because the speed controller indirectly handled using these callbacks.
Get Motor Speed
Gets the actual motor speed in RPM. The get speed is estimated through the encoder by default. The Hall sensor can also be used for speed estimation, although this is not our recommendation. Resolver support will be available in the future as well. This function must be set cyclically using either the hardware-assisted bus cycle callback (XCTRIGGER) or a timer callback you have created. Because the speed is indirectly estimated using these callbacks.
Set Operation Mode
Sets the FOC’s operation mode. It allows FOC to perform different operations. The function ”Set operation mode” activates the related mode acyclically. Related operation mode descriptions can be found in Table 7.
Operation mode | Description |
---|---|
CTRL_START_SELF_CALIBRATION | Start the self-calibration process. Thus, the calibration request is created and processed by the state machine. |
CTRL_START_OPERATION | Coast stop mode is disabled and pulse is enabled. The speed controller handles the speed setpoint value. |
CTRL_COAST_STOP | Activate the coast stop mode. Pulse disabled. |
Table 7 - FOC Operation modes
Get Operation Mode
Gets the motion control state machine's state. The enum type “MCL_MOTION_CTRL_STATE_E“ shows the current operation mode. Related motion control states' descriptions can be found in Table 8.
Motion Control State | Description |
---|---|
MCL_MOTION_CTRL_UNINITIALIZED | The motion layer is uninitialized. |
MCL_MOTION_CTRL_INITIALIZED | The motion layer is initialized and ready for the calibration process. |
MCL_MOTION_CTRL_CALIBRATION_IN_PROGRESS | The self-calibration process is started. Wait until it completed. |
MCL_MOTION_CTRL_READY_TO_OPERATE | The calibration process is completed successfully. (self-calibration or calibration using user parameters). It is ready to operate. (Pulse disabled) |
MCL_MOTION_CTRL_OPERATING | FOC is operating. Set the desired motor speed. (Pulse enabled) |
MCL_MOTION_CTRL_COAST_STOP | The coast stop is activated. Applying Hi-Z to the MOSFET gates. (Pulse disabled) |
MCL_MOTION_CTRL_CRITICAL_FAULT | A critical error has occurred. It will make sense after fault handling integration. |
Table 8 - Motion control states
Set Reference External Trigger Period
Set the reference external trigger period. The reference external trigger (XCTRIGGER or Timer callback) period information set by the user is used to synchronize the PWM event with the external trigger. As mentioned above, the IRT mode was introduced with FOC V1.1.0.0 and must be synchronised with MPWM to ensure deterministic synchronised operation.
Get Reference External Trigger Period
Get the reference external trigger period. This is the reference external trigger (XCTRIGGER or Timer callback) period last set by the user.
Get Motor Position
Gets the provided position information obtained and processed by the relevant peripheral modules. In V1.1.0.0 this peripheral module is QEI (Quadrature Encoder Interface). The position information data details are described in Тable 9.
Parameter | Data Type | Description |
---|---|---|
ptMotorPos | MCL_PSE_MOTOR_POS_T | Motor position information data |
| uint8_t | Fine resolution |
| uint8_t | Quadrant information (signs of sine and cosine) |
| uint16_t | Number of pulses in one revolution |
| uint32_t | Number of revolutions |
Table 9 - Motor position information data structure
Get Motor Position Format
Gets the provided motor position format information. It gives automatically calculated bit lengths depending on the resolution of the position estimation sensor integrated into the motor. This format’s structure details are described in Тable 10.
Parameter | Data Type | Description |
---|---|---|
ptMotorPosFormat | MCL_PSE_MOTOR_POS_FORMAT_T | Motor position format information |
| MCL_PSE_POS_SENSOR_TYPE_E | Motor position sensor type MCL_PSE_INCREMENTAL_ENCODER - Incremental encoder MCL_PSE_ABSOLUTE_ENCODER - Absolute encoder MCL_PSE_RESOLVER - Resolver |
| uint8_t | Fine resolution bit length |
| uint8_t | Quadrant info bit length |
| uint8_t | Number of pulses bit length |
| uint8_t | Number of revolution bit length |
Table 10 - Motor position format information structure
Set Motor Calibration Parameters
As mentioned above, V1.1.0.0 supports motor calibration using the User Parameters feature. This function sets the motor calibration parameters. It should not be forgotten that the motor calibration parameters must be obtained during the previous self-calibration process (MCL_PSE_NUM_OF_HALL_SECTORS: 6) and must be valid. The calibration parameters' structure is described in Table 12.
Parameter | Data Type | Description |
---|---|---|
ptMotorCalParams
| MCL_MOTION_MOTOR_CAL_PARAMS_T | Motor calibration parameters |
| uint16_t[6] | Hall sector positions during clockwise motor rotation |
| uint16_t[6] | Hall sector positions during counter-clockwise motor rotation |
| uint8_t[6] | Hall sector order during clockwise motor rotation |
Table 11 - Motor calibration parameters' structure.
Get Motor Calibration Parameters
This function gets the motor calibration parameters obtained by previous valid calibration. (MCL_PSE_NUM_OF_HALL_SECTORS: 6). The calibration parameters' structure is described in Table 11.
Set Speed PI controller parameters
The speed PI controller values must be optimized according to each mechanism to which the motor is connected. The point to be noted is that the set values will be applied with new Self Calibration, Manual Calibration, or Start Operation requests.
Get Speed PI controller parameters
This function gets the speed PI controller parameters.
Set Torque(Current) PI controller parameters.
The torque PI controller values must be optimized according to each mechanism to which the motor is connected. The point to be noted is that the set values will be applied with new Self Calibration, Manual Calibration, or Start Operation requests.
Get Torque(Current) PI controller parameters.
This function gets the torque(current) PI controller parameters.
Mathematical Library(MATH)
Contains all the transform and calculation functions of the FOC. You may be wondering why some general mathematical functions are also included here. They are optimized for speed.
This layer is accessible from all layers. In Figure 3, the functions included in the MATH library are shown.
Targets
It is the place where all layers of the FOC component are initialized, configured, started, etc.
The “Targets\Common\Include\McBoardHwConfig.h” file contains the board definitions (voltage divider resistors, shunt resistors, etc.) associated with the netX90-MC board used by the FOC. Thus, definitions can be configured easily after new board revisions.
The “Targets\NXHX90-MC\Sources\main.c” file is where all the initialization, configuration, and motor demo functionality resides. Only the parameters that users can modify will be discussed here.
Board configuration
The MCL_MC_BOARD_CFG_PRM_T
structure contains some board-specific parameters. It provides the ability to change configurations based on hardware changes and is initialized in “Targets\NXHX90-MC\Sources\main.c”. Normally these parameters are not supposed to be modified because they are tuned for the current NXHX90-MC board which is not expected to be changed once configured properly. Related parameters are shown in Table 12.
Parameter | Data Type | Defaults | Description | Note |
---|---|---|---|---|
tMcBoardCfgPrm | MCL_MC_BOARD_CFG_PRM_T |
| Motor control board's configuration structure | |
flAdcVrefExtPin | float | 3.3f | ADC external reference voltage. The reference voltage determines the highest signal level that the ADC can convert, and all quantized digital outputs from an ADC will be some ratio of this input reference voltage. |
|
tMotorPhaseShuntRes | MCL_MOTOR_PHASE_SHUNT_RES_T |
| Motor phases shunt resistor structure |
meas_curr = Iph_curr x Rsh x Gcurr_gain Iph_curr: Phase current[A]; Rsh: Shunt resistor[Ω]; Gcurr_gain: Current amp. gain |
| float | 0.007f | Phase A - Current measurement shunt resistor[Ω]. | |
| float | 0.007f | Phase B - Current measurement shunt resistor[Ω]. | |
| float | 0.007f | Phase C - Current measurement shunt resistor[Ω]. | |
tMotorPhaseVoltageDivRes | MCL_MOTOR_PHASE_VOLTAGE_DIV_T |
| Motor phases voltage divider structure |
Vin: Input voltage Vout: Attenuated signal voltage Rlow_side: Low-side resistor Rhigh_side: High-side resistor |
| MCL_VOLTAGE_DIV_T |
| Phase A voltage divider structure | |
I. flHighSideResOhm | float | 82000.0f | Phase A voltage divider high-side. | |
II. flLowSideResOhm | float | 4990.0f | Phase A voltage divider low-side. | |
| MCL_VOLTAGE_DIV_T |
| Phase B voltage divider structure | |
I. flHighSideResOhm | float | 82000.0f | Phase B voltage divider high-side. | |
II. flLowSideResOhm | float | 4990.0f | Phase B voltage divider low-side. | |
| MCL_VOLTAGE_DIV_T |
| Phase C voltage divider structure | |
I. flHighSideResOhm | float | 82000.0f | Phase C voltage divider high-side. | |
II. flLowSideResOhm | float | 4990.0f | Phase C voltage divider low-side. | |
flManualCtrlPotValOhm | float | 50000.0f | NXHX90-MC board potentiometer resistance [Ω]. |
|
tMcBoardLimits | MCL_MC_BOARD_LIMIT_T |
| NXHX90-MC Board’s limits |
|
| float | 3.3f | Maximum ADC pin reference voltage [V]. |
|
| float | 40.0f | Maximum phase current [A]. | 1. It is related to the used output MOSFETs' current handling. |
| float | 12.0f | Maximum phase shunt resistance [Ω]. |
|
Table 12 - Board configuration parameters
Motor-specific Configuration
The Motor-specific parameters are typically found in the Manufacturer's specification for the motor. In the PROFIdrive example, this configuration is found in the structure. Related parameters are shown in Table 13.
The parameters defined by the following structure affect fundamental motor behaviour - torque, speed, etc. A few of the parameters require experimental fine-tuning to acquire the best results. All parameters have already been checked and fine-tuned for the predefined motors supplied with this example. However, if a new motor is to be adapted those parameters might/should be changed accordingly. If not set properly the motor can emit strange noises and heat. Please keep the motor under continuous supervision until the parameters are adapted and approved.
(in Targets/NXHX90-MC/main.c).
Parameter | Data Type | Description | Note |
---|---|---|---|
bMotorPolePairs | uint8_t | Number of Motor pole pairs. |
|
flMaxPhaseCurrAmp | float | Max continuous motor phase current[A]. |
|
usMotorSvpwmFreqHz | uint16_t | Space-Vector modulation PWM working frequency[Hz]. |
|
tMotorSpeedCfg | MCL_MOTOR_SPEED_CFG_T | Motor speed configuration structure |
|
| uint16_t | Minimum speed value - used for “stall” detection. |
|
| uint16_t | Nominal speed of the Motor [rpm]. |
|
| uint16_t | Maximum speed of the Motor [rpm]. Setting speed to greater values will result in error. |
|
tSpeedPiCtrlCfg | MCL_PI_CTRL_CFG_T | Motor speed PI control parameters structure |
|
| float | Proportional gain - Kp | |
| float | Integral gain - Ki | |
tTorquePiCtrlCfg | MCL_PI_CTRL_CFG_T | Motor torque PI control parameters structure |
|
| float | Proportional gain - Kp | |
| float | Integral gain - Ki | |
usQeiNumOfSlots | uint16_t | Maximum counts per revolution (Encoder resolution). |
|
eQeiMotorEncSrc | MCL_QEI_MOTOR_ENC_SRC_E | Connected encoder source to the NXHX-DH adapter.
|
|
eQeiInvMotorEncDir | HAL_QEI_INV_ENC_DIR_E | Invert encoder direction.
|
|
fInvMotorDir | bool | Invert the direction of rotation. If “false” positive speed values refer to clockwise rotation, negative - counter clockwise. If “true” - positive speed values refer to counter clockwise direction of rotation. |
|
Table 13 - Motor-specific configuration parameters
FOC System Configuration
These parameters, situated in the lower layers (MCL, HAL) of the FOC, are crucial for ensuring the effective operation of its algorithms. The MCL_FOC_SYS_CFG_PRM_T
structure contains these parameters.
They are initialized in “Targets\NXHX90-MC\Sources\main.c”. Normally they are not supposed to be modified because they are tuned for the current FOC algorithm. Related parameters are shown in Table 14.
(in Targets/NXHX90-MC/main.c).
Parameter | Data Type | Defaults | Description | Note |
---|---|---|---|---|
tHallPiCtrlCfg | MCL_FIXEDPT_PI_CTRL_CFG_T |
| Hall sensor position estimation PI control parameters structure. |
|
| int32_t | 1062 | Proportional gain - Kp | |
| int32_t | 49 | Integral gain - Ki | |
tFieldWeakPiCtrlCfg | MCL_PI_CTRL_CFG_T |
| Motor Field-weakening PI control parameters structure. |
|
| float | 0.0f | Proportional gain - Kp | |
| float | 0.15f | Integral gain - Ki | |
flFieldWeakStartVoltageRatio | float | 1.1f | Threshold voltage vector magnitude to start field-weakening. |
|
chDcBusVoltageOffsetAdcDig | int8_t | 10 | Experimentally determined DC-bus Voltage offset value. |
|
bNumOfCurrentOffsetMeas | uint8_t | 8 | Number of measurements to calculate average current offset. |
|
bCurrentOffsetThresholdAdcDig | uint8_t | 88 | It is the threshold value that defines the range where the average Current Offset value can be found. Ideal current offset = 2048 (The half of the 12-bit ADC’s max range) |
|
flSvpwmMaxDutyCyclePercent | float | 96.0f | Maximum allowed duty cycle percentage. |
|
eSpeedEstMethod | MCL_SPEED_EST_METHOD_E | MCL_SPEED_EST_QEI | Speed estimation method.
|
|
flCalRqstVdVector | float | 0.12f | Length of the voltage vector(vd) used for calibration in units of the commutation. |
|
sCalSamplingSpeedRPM | int16_t | 12 | Rotor speed at calibration stage. Slow speeds are generally more accurate. |
|
bCalNumOfTurns | uint8_t | 4 | Number of turns (mechanical angle, electrical angle) of the linear regression in one direction. |
|
usCalMaxDeviationAngleDig | uint16_t | 4000 | Deviation angle of hall sensor position when turning CW and CCW. |
|
usCalWaitTimeBetweenEachSample | uint16_t | 0 | Adding wait time[ms] when turing CW and CCW before performing linear regression on another sample of (mechanical angle, electrical angle). |
|
usCalWaitTimeAfterAlignment | uint16_t | 500 | Add wait time[ms] delay after each alignment process. |
|
Table 14 - FOC system configurations
FOC Demo
Demo behaviours
There are two demo modes:
Cyclical demo mode: This demo is created to demonstrate the speed control capabilities of the FOC. Additionally, the coast-stop functionality is added to the demo to be understood and observed by the user. Figure 11 shows the exact behaviour of the demo. The specific times from t1 to t14 are not provided due to the possibility of changes with new updates.
Demo mode with potentiometer: The motor speed is adjusted with the potentiometer on the board.
The desired demo mode is activated from the “Targets\wscript” file by manipulating the __USE_DEMO_POTENTIOMETER
parameter.
Figure 12 shows the FOC Demo Run-time diagram including the behaviour of the FOC. Using two job timers is to adapt the Demo to isochronous mode. The Bus Cycle Emulation process was performed with these two timers. Additionally, the FOC details mentioned above are summarized in Figure 12.
Initialization
Configures the structures mentioned in Targets according to the selected target.
Initializes the FOC modules and gives the user the FOC handle after the successful initialization.
Initializes the FOC job timers.
Sets the reference external trigger period to give feedback for MPWM synchronization.
Realizes the calibration process dependent on the
__USE_MOTOR_CALIBRATION_WITH_PARAMS
parameter’s value and waits until it is completed.Sets the operation mode with the Start Operation parameter and waits unit it is completed.
Start selected demo mode dependent on the
__USE_DEMO_POTENTIOMETER
parameter’s value.
Abbreviations
Abbreviation | Description |
---|---|
FOC | Field-Oriented Control |
HAL | Hardware Abstraction Layer |
ADC | Analog-to-Digital Converter |
MPWM | Motion Pulse-Width Modulation |
RPM | Revolutions per minute |
MTPA | Maximum Torque per Ampere |
MTPV | Maximum Torque per Voltage |
PI | Proportional Integral |
PMDC | Permanent Magnet Direct Current |
BLDC | Brushless Direct Current |
QEI | Quadrature Encoder Interface |
MCL | Motor Control Layer |
API | Application Programming Interface |
CW | Clockwise |
CCW | Counter-Clockwise |
ECZ | Event Counter Zero |
BOP | Beginning of Period |
DIR | Direction |
MC | Motor Control |
Hi-Z | High Impedance |
NTC | Negative Temperature Coefficient |
MECH | Mechanical |
ELEC | Electrical |
GPIO | General-Purpose Input/Output |
SVM | Space Vector Modulation |
GDU | Gate Driver Unit |
PSE | Position and Speed Estimation |
MENC | Motion Encoder |
IRT | Isochronous Real-Time |