Software application note FOC

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 control modes of FOC. The position control mode is less common. Most 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 that 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 (using 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 at the https://www.mathworks.com/solutions/electrification/field-oriented-control.html or Field Oriented Control (FOC) - A Deep Dive.

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) to two components in an orthogonal stationary frame (αβ). The Park transform converts the two components in the αβ frame to an orthogonal rotating reference frame (dq). Implementing these two transforms in a consecutive manner simplifies computations by converting AC current and voltage waveform into DC signals. Thanks to the DC magnitudes obtained by these transformations, we obtain the PI current control (to Id and Iq vectors) facility and this allows us to perform 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 to time domain components (in abc frame) thanks to 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 mechanical angle of the rotor 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

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.

Figure 2 - Field-Oriented Control Software project’s folder structure

The FOC, MCL, and HAL components are initialized into the main.c file from lower layers to upper layers (HAL → MCL → CORE). Desired API function is used through Handles, which is obtained after FOC initialization. The MATH library can be accessed by all layers. The public folder specifies the header files that are open to the user. The Public folder contains 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” is used to create the main application task timer of the FOC application and is designed with the flexibility to adapt to future requirements. 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“ provides the control of the driver chip used the drive the motor. The “Quadrature Encoder Interface“ (QEI) is used to estimate the rotor position. The “Hall Sensors“ captures information from the GPIOs that are connected to the Hall-Effect sensors (built into the motor), therefore indicating the current state of the rotor. In other words, 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 while doing this, it is to provide 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, and this retrieved information is processed according to the FOC algorithm. This algorithm includes various blocks such as PI controllers, Transformation blocks, Space Vector Modulators, Low-pass filters and 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 calibration. The “FOC Control” component provides the main FOC control. That is, it is the place where operations such as Torque control, vector transformations, Space Vector Modulation, etc. are done. The “Calibration“ component provides the calibrating process, which is used to determination of the electrical rotor position angle in Hall sensor sectors. The “Position & Speed Estimation“ (PSE) component makes the data received from HAL QEI and HAL Hall Sensors processed.

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 components of the relevant layers, their functionality, and connections can be seen in the block diagram in Figure 3.

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 provides the main motion application task timer event of the FOC. It is designed with the flexibility to adapt to future requirements.

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

Unit

Channel 0

Channel 1

Channel 2

Channel 3

Channel 4

Channel 5

Channel 6

Channel 7

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

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 the https://hilscher.atlassian.net/l/cp/EEEWubbe.

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 get from DRV832x 6 to 60-V Three-Phase Smart Gate Driver and CSD88599Q5DC 60-V Half-Bridge NexFET™ Power Block. The Gate Driver 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, and brake mode. 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 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 “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. Ayrica MPWM can be synchronized to hardware-assisted cyclic network events. For detailed information, see 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 manual). Also, this component supports the encoder direction inversion functionality. For detailed information, see section 5.14.4 from netX 90 - Technical data reference guide.

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. Hall sensor inputs are connected to GPIOs and according to these GPIO statuses, it can be easily determined in which hall sector the rotor is.

 

Motor Control Layer (MCL)

The “Motor Control Layer“ (MCL) contains 4 components.

Motion

The “Motion“ component provides basic motion functionality. Thanks to the HAL Timer component, the motion task event is created and called Timer Callback. The period of this timer callback is 1 ms, that is, a timer event occurs every 1 ms. The processes that are handled when the timer event occurs are described below.

 

Figure 4 - MCL Layer Motion Component’s handled processes when the timer event occurs.

 

  • MOTION - Auto Configure Encoder Direction: The direction of the encoder mounted on the motor may differ according to the manufacturer and the motor. In order for the motor direction to be determined correctly for each motor, the motor direction must be determined automatically and reversed if necessary. As seen in Figure 4, this is done by determining the turning direction by the motor’s hall sensor, and thus correcting the encoder direction if necessary.

  • PSE - Estimate Rotor Speed: Before handling the Motion Control State Machine, The Rotor Speed must be determined. Because this speed data is the feedback of the speed controller(contains Speed and Field-weakening PI controllers).

  • MOTION - Motion State Machine: It is the state machine where all FOC coordination is done. These are calibration coordination, motor speed control, coast stop mode control, fault handling and etc. Stall detection fault support is currently available. However, Gate Driver and Motor fault handling support will be provided with updates in the future. The state machine in Figure 5 is processed according to the motor setpoint and operation mode commands receiver from the FOCAPI layer. The explanations of the states are given in Table 3. Coast stop mode is to bring the MOSFET gates to the Hi-Z and ensure that the motor spins down at whatever speed the load imparts on it. The explanations of the operation modes used in the state machine are given in Table 9. FOC operation mode is asynchronous because it comes from the upper layer. Therefore, the operation value set to ensure synchronization creates a request to be processed on the state machine. According to the set operation, the operation of the FOC control component is coordinated by this state machine. MCL Motion Control State Machine is implemented in the mcl_MotionStateMachine(…) function in the “Components\Mcl\Sources\Mcl_Motion.c”.

 

Figure 5 - MCL Layer Motion Component’s Motion Control State Machine

State

Description

State

Description

UNINITIALIZED

This is the first state and it is active as long as there is the initalization. Nothing is done in this state, it is only used for feedback. Motor PWM is disabled.

INITIALIZED

This states prepares the MCL layer components to motion process. It remains active until a calibration request is received. The calibration request is provided indirectly using “CTRL_START_SELF_CALIBRATION“ command. Motor PWM is disabled.

CALIBRATION IN PROGRESS

Calibration process of the motor. Calibration is a process performed to determine the positions of the Hall Sensor states. Motor PWM is active.

IDLE

Waiting the ”CTRL_START_SELF_CALIBRATION” or “CTRL_START_OPERATION“ from API. Motor PWM is disabled.

OPERATE RUN

The requested speed[RPM] is set by API function. Speed controller becomes active. Motor PWM is active.

OPERATE STOP

Motor is in standstill, but the Motor PWM is active.

CRITICAL FAULT

A critical error has occurred. This state will remain active until the restart occurs. Motor PWM is active.

Table 3 - MCL Motion Control State Machine’s state definitions

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-looped control, it is ensured that the maximum torque value is reached by making the Id and Iq vectors orthogonal by the current PI controllers (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. Above, we talked about the MPWM ECZ event 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 has an important role in FOC control. 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. The corresponding HAL Gate Driver operation state machine is shown in Figure 7 and the behavior of the states is explained in detail in Table 4. 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

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.

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 4 - HAL Gate Driver operation state machine’s state definitions.

 

  • MCL FOC Control - FOC Control Main State Machine: It is a large-scale state machine that provides 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 motion control state machine. Please keep this in mind when examining the state machine in Figure 8. The corresponding FOC Control Main state machine is shown in Figure 8 and the behavior of the states is explained in detail in Table 5. 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. The aim here is to keep the torque constant for accurate measurement during calibration, rather than reaching the maximum torque. The CURRENT CONTROL state provides the desired closed-loop vector control. This is the behavior we want during motor control. It keeps the motor torque at the maximum level thanks to the dq current PI controllers it contains. It is the state that is active when the motor is operating. The FAIL 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

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 5 - 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. In order to measure the phase currents with the ADC and interpret it as signed in the variable, we need to make the Current Offset Bias calculation and compensate for the measured values. In the CURRENT OFFSET state, the state machine, the Current Offset Bias Calculation state machine is handled. The corresponding FOC Control Main state machine is shown in Figure 9 and the behavior of the states is explained in detail in Table 6. 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

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 parameter 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 6 - 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. To do this, it associates the position information from the feedback device (Encoder, Resolver, etc.) related to each motor hall sensor sector for both rotation directions(CW and CCW). Then it is validated whether the position values determined in the 6 Hall Sensor sector are within certain limits in both directions. If all is well, the values obtained in both directions in each sector are averaged and these values are recorded to be used in correct position estimation. The corresponding Calibration state machine is shown in Figure 10 and the behavior of the states is explained in detail in Table 7. 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

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.

EVALUATE

It is checked whether the position values determined in the 6 Hall Sensor sector are within certain limits in both directions. If all is well, 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 7 - MCL Calibration state machine’s state definitions

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. Currently, only Encoder (with QEI interface) and Hall Sensors provide speed and position information. However, in the future, different encoder interfaces and Resolver(SinCos) will be supported.

 

MCL Specific Configurations

The MCL_CFG_PRM_T structure contains some MCL-specific parameters. It provides the possibility to change configuration based on MCL and is initialized in “Components\Mcl\Includes\Public\Mcl.h”. Normally these parameters are not supposed to be modified because they are tuned for the current demo application which is not expected to be changed once configured properly. Related parameters are shown in Table 8.

Parameter name

Data type

Default value

Description

Related module

Parameter name

Data type

Default value

Description

Related module

MCL_INIT_PRM_MAX_PHASE_CURRENT_AMP

float

40.0f

Maximum phase current.

MCL

MCL_INIT_PRM_MAX_ADC_VREF_PIN_VOLTAGE

float

3.3f

Maximum ADC Vref pin voltage.

MCL_INIT_PRM_MAX_PHASE_SHUNT_RES_OHM

float

12.0f

Maximum phase shunt resistor value[Ω].

DEFAULT_MCL_MOTION_PAR_MECH_SPEED_LOW_PASS_FILTER_HZ

uint16_t

1500

Mechanical speed low pass filter's cut-off frequency[Hz].

MCL Motion

DEFAULT_MCL_MOTION_PAR_FIELDWEAK_CONTROLLER_KP

float

0.0f

Proportional gain of the field-weakening controller.

DEFAULT_MCL_MOTION_PAR_FIELDWEAK_CONTROLLER_KI

float

0.2f

Integral gain of the field-weakening controller.

DEFAULT_MCL_MOTION_PAR_FIELDWEAK_START_VOLTAGE_RATIO

float

1.1f

Threshold voltage vector magnitude to start field-weakening. Value is less than maximum voltage vector magnitude to allow a transition region.

DEFAULT_MCL_MOTION_PAR_STALL_DETECTION_SPEED_DIFFERENCE

uint16_t

300

Speed difference threshold to detect stall.

DEFAULT_MCL_MOTION_PAR_STALL_DETECTION_TIME_MS

uint32_t

3000

Time[ms] it takes to set stall error.

DEFAULT_MCL_FOC_CTRL_PAR_CURRENT_AMP_GAIN

float

20.0f

DRV8323 gate driver current sense amplifiers gate. It gains the measured current value through shunt resistor. It is using for the current measurement purposes.

MCL Foc Control

DEFAULT_MCL_FOC_CTRL_PAR_DCBUS_VOLTAGE_OFFSET_DIGITS

int8_t

 

10

Experimentally determinced DC-bus Voltage offset value.

DEFAULT_MCL_FOC_CTRL_PAR_NUMBER_OF_CURRENT_OFFSET_MEAS

uint8_t

8

Number of measurements to calculate average current offset.

DEFAULT_MCL_FOC_CTRL_PAR_CURRENT_OFFSET_THRESHOLD_DIG

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)
Minimum current offset range = (2048 - 88)
Maximum current offset range = (2048 + 88)

DEFAULT_MCL_FOC_CTRL_PAR_MAX_DUTY_CYCLE_PERCENT

float

96.0f

Maximum allowed duty cycle percentage.

DEFAULT_MCL_PSE_PAR_SPEED_EST_METHOD

MCL_SPEED_EST_METHOD_E

MCL_SPEED_EST_QEI

Speed estimation method.

MCL_SPEED_EST_QEI - Quadrature Encoder Interface

MCL_SPEED_EST_HALL_SENSOR - Hall Sensor

MCL Position and Speed Estimation

DEFAULT_MCL_PSE_PAR_MAF_CAPTURE_SIZE

uint8_t

4

Moving average filter size. Captured position is filtered with a MAF. It is designed experimentally and disabled by default.

DEFAULT_MCL_CAL_PAR_REQUESTED_VOLTAGE

float

0.12f

Length of the voltage vector used for calibration in units of the commutation. The direction is always Vd.

MCL Calibration

DEFAULT_MCL_CAL_PAR_SAMPLING_SPEED_RPM

int16_t

12

Rotor speed at calibration stage. Slow speeds are generally more accurate.

DEFAULT_MCL_CAL_PAR_NUM_OF_TURNS

int16_t

4

Number of turns (mechanical angle, electrical angle) of the linear regression in one direction.

DEFAULT_MCL_CAL_PAR_WAIT_TIME_BETWEEN_EACH_SAMPLE_MS

uint16_t

1

Adding wait time[ms] when turing left and right before performing linear regression on another sample of (mechanical angle, electrical angle). During the calibration process, the motor rotating occurs using the samples of the mechanical and electrical angles. This parameter specifies the waiting time between two samples. It is one of the parameters that should be checked when proper calibration doesn't occur.

DEFAULT_MCL_CAL_PAR_WAIT_AFTER_ALIGNMENT_MS

uint16_t

500

Add wait time[ms] delay after each alignment process. During the calibration process, motor positioning alignment is performed during initial alignment, direction change and validation states. This parameter represents the waiting time after each motor alignment. It is one of the parameters that should be checked when proper calibration doesn't occur.

DEFAULT_MCL_CAL_PAR_MAX_DEVIATION_ANGLE

uint16_t

4000

Deviation angle of hall sensor position when turning CW and CCW. Angle is in digits (2^16 is 360 degrees). Maximum electrical angle deviation when validating the calibration values, unit complies with Angle definition above.

Table 8 - MCL-specific configurations

FOC API Layer (CORE)

The “Foc Api Layer“ provides an interface for the user to control the FOC application. The functions mentioned below 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 gives the user the corresponding handle.

The FOC_INIT_PRM_T type will be explained in more detail in the Target section.

 

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. The set speed is processed by the speed controller if the motor is operating.

 

Get Motor Speed

Gets the actual motor speed in RPM. The get speed is estimated through the encoder by default. If desired, the hall sensor can also be used for speed estimation, although it is not recommended. Resolver support will be available in the future as well.

 

Set Operation Mode

Sets the FOC’s operation mode. It allows FOC to perform different operations. The function ”Set operation mode” manipulates the Motion Control state machines through requests indirectly. Related operation mode descriptions can be found in Table 9.

Operation mode

Description

Operation mode

Description

CTRL_START_SELF_CALIBRATION

Start the self-calibration process. Thus, the calibration request is created and processed by the Motion control 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. Thus, the coast stop request is created and processed by the Motion control state machine. Pulse disabled.

Table 9 - FOC Operation modes

 

Get Operation Mode

Gets the motion control state machine's state. Since the function ”Set operation mode” manipulates the motion control state machine, the enum type “MCL_MOTION_CTRL_STATE_E“ shows the current operation mode. Related motion control state machine’s state descriptions can be found in Table 3.

 

Mathematical Library(MATH)

Contains all the transform and calculation functions of the FOC. It is accessible from all layers. In Figure 3, the functions included in the MATH library are shown. At the same time, hardware-related files are located here. The Targets folder structure is shown in Figure 2. The McBoardHwConfig.h file in the Common folder contains the definitions(voltage divider resistors, shunt resistors, etc.) associated with the netX90-MC board used by FOC. Thus, new values can be configured easily after a new revision.

 

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 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 parameters that can be changed by the user, in any case, will be mentioned here.

Board configuration

The MCL_MC_BOARD_CFG_PRM_T structure contains some board-specific parameters. It provides the possibility to change configuration 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 10.

Parameter

Data Type

Meaning

Note

Parameter

Data Type

Meaning

Note

tMcBoardCfgPrm

MCL_MC_BOARD_CFG_PRM_T

Motor control board's configuration structure

flAdcVrefExtPin

float

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.

  1. Maximum Vref is 3.3V.

  2. For more detailed information, refer to the datasheet.

tMotorPhaseShuntRes

MCL_MOTOR_PHASE_SHUNT_RES_T

Motor phases shunt resistor structure

  1. These resistors are used to measure the current flowing through the phases in terms of voltage.

  2. These provide feedback to the gate driver. It is multiplied by 20 using the internal operational amplifier inside the Gate driver and read by the netX90's ADCs.

  3. Formula: V

meas_curr = Iph_curr x Rsh x Gcurr_gain

Iph_curr: Phase current[A];

Rsh: Shunt resistor[Ω];

Gcurr_gain: Current amp. gain

  • flPhaseAOhm

float

Phase A - Current measurement shunt resistor[Ω].

  • flPhaseBOhm

float

Phase B - Current measurement shunt resistor[Ω].

  • flPhaseCOhm

float

Phase C - Current measurement shunt resistor[Ω].

tMotorPhaseVoltageDivRes

MCL_MOTOR_PHASE_VOLTAGE_DIV_T

Motor phases voltage divider structure

  1. Since the motor operating voltage is between 12V and 36 volts, the voltage must be attenuated to be read by the microcontroller's ADC.

  2. Formula: Vout = Vinx[Rlow_side/(Rlow_side+Rhigh_side)]

Vin: Input voltage

Vout: Attenuated signal voltage

Rlow_side: Low-side resistor

Rhigh_side: High-side resistor

  • tPhaseA

MCL_VOLTAGE_DIV_T

Phase A voltage divider structure

I. flHighSideResOhm

float

Phase A voltage divider high-side.

II. flLowSideResOhm

float

Phase A voltage divider low-side.

  • tPhaseB

MCL_VOLTAGE_DIV_T

Phase B voltage divider structure

I. flHighSideResOhm

float

Phase B voltage divider high-side.

II. flLowSideResOhm

float

Phase B voltage divider low-side.

  • tPhaseC

MCL_VOLTAGE_DIV_T

Phase C voltage divider structure

I. flHighSideResOhm

float

Phase C voltage divider high-side.

II. flLowSideResOhm

float

Phase C voltage divider low-side.

Table 10 - 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 11.

The parameters defined by the following structure affects fundamental motor behavior - torque, speed, etc. A few of the parameters require experimental fine-tuning for acquiring the best results. For the pre-defined motors provided with this example all the parameter have been already inspected and fine-tuned. 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 being adapted and approved.

(in Targets/NXHX90-MC/main.c).

Parameter

Data Type

Meaning

Note

Parameter

Data Type

Meaning

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

  1. It is generally greater than 10 kHz and differs depending on the motor.

tMotorSpeedCfg

MCL_MOTOR_SPEED_CFG_T

Motor speed configuration structure

 

  • usMinSpeedRpm

uint16_t

Minimum speed value - used for “stall” detection.

 

  • usNominalSpeedRpm

uint16_t

Nominal speed of the Motor [rpm].

 

  • usMaxSpeedRpm

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

  1. They varies depending on the motor and must be tuned.

  • flKp

float

Proportional gain - Kp

  • flKi

float

Integral gain - Ki

tTorquePiCtrlCfg

MCL_PI_CTRL_CFG_T

Motor torque PI control parameters structure

  1. They varies depending on the motor and must be tuned.

  • flKp

float

Proportional gain - Kp

  • flKi

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.

  • Single-ended encoder(QEI_TTL) - MCL_QEI_MOTOR_ENC_SRC_ENC0

  • Differential encoder(QEI__RS422) - MCL_QEI_MOTOR_ENC_SRC_ENC1

  1. Since these encoders are connected to the NXHX-DH adapter, the encoder source differs according to the electrical characteristics of the encoder.

  2. Single-ended encoder is connected directly to ENC0 input, and differential encoder is connected to ENC1 input via transiever. This routing is provided by NXHX-DH.

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 11 - Motor-specific configuration parameters

FOC Cycle TIme

FOC cycle time is totally programmable for experienced users. When the users adapt the FOC application to their software, they can tune the CPU load according to their own software by playing with the __FOC_CYCLE_TIME_MS parameter (Default cycle time is 1ms).

FOC Demo

There are two demo modes:

  1. Cyclical demo mode: Ramp-up, ramp-down, and coast stop demo.

  2. 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 with manipulation of the __USE_DEMO_POTENTIOMETER parameter.

Compilation and Flashing

See section FOC QEI + Hall demo

Abbreviations

Abbreviation

Description

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