Neural Network Based Position Estimation for Field-Oriented Control of PMSM on Infineon AURIX TC4x Microcontrollers
This example shows how to implement field-oriented control (FOC) of a permanent magnet synchronous motor (PMSM) using a rotor position estimated by an autoregressive neural network (ARNN) trained with Deep Learning Toolbox™.
An FOC algorithm requires real-time rotor position feedback to implement speed control as well as to perform mathematical transformation on the reference stator voltages and feedback currents. Traditionally, such algorithms rely on physical sensors. However, due to increased accuracy and cost effectiveness, sensorless position estimation solutions can act as a better alternative to physical sensors.
This example provides one such sensorless solution that uses neural network-based artificial intelligence (AI) to estimate real-time rotor position. You can use this example to train a neural network using data generated by an existing quadrature encoder sensor-based FOC algorithm. The trained neural network acts as a virtual position sensor and estimates the rotor position.
The example guides you through the workflow to train, simulate, and implement the neural network using the following steps:
Generate data needed to train the neural network.
Extract relevant data from the generated data.
Concatenate extracted data.
Process concatenated data.
Train neural network using processed data.
Export trained neural network to Simulink® model associated with this example.
Simulate and deploy the exported Simulink model with the trained neural network to the hardware.
You can skip the steps for training data generation if you already have training data obtained from hardware running on an actual motor. Use that data set to train the neural network.
The following figure shows the entire workflow to implement a neural network based virtual position sensor.

Prerequisites
Complete the Getting Started with Embedded Coder Support Package for Infineon AURIX TC4x Microcontrollers example.
Required Hardware
Infineon AURIX™ TC4x hardware board
AURIX™ TC3xx motor control power board
Nanotec DB42S02 Electric motor
WEDL5541-B14-KIT (5 mm) incremental encoder
Hardware Connection
Connect the hardware as shown in this figure.

Model
The example includes the target model tc4x_mcb_pmsm_foc_NN_Pos_Estimation.slx.

You can use this model to:
Generate the data needed to train the neural network.
Integrate the trained neural network into the workflow.
Run FOC for a PMSM in simulation or on hardware using either an quadrature encoder sensor or a neural network-based virtual sensor.
The example includes these functions:
TrainingDataCapture— Captures simulation data by running the Simulink model at various speed and torque operating points.TrainingdataCapture_parallel— Captures simulation data by running the Simulink model at various speed and torque operating points. This function uses Parallel Computing Toolbox to speed up the computations. For more information, see What Is Parallel Computing? (Parallel Computing Toolbox).OneElectCycleExtract— Extract one electrical cycle of information from the captured simulation data.DataConcatenate— Combine the extracted simulation data into a single array.DataPreparation— Split simulation data into training, validation, and testing sets and prepares input-output arrays for neural network training.CreateNetwork— Build a deep learning network, train it using the training data, validate it during training, and evaluate performance on the test data.
Target Model Architecture
The following figure shows the architecture of the FOC algorithm that the target model implements:

As shown in the figure, the neural network uses the Vα, Vβ, Iα, and Iβ inputs to output θe, sinθe, and cosθe, where:
Vα and Vβ are the voltages across α and β axes respectively (in per-unit values).
Iα and Iβ are the currents across α and β axes respectively (in per-unit values).
θe is the motor electrical position (in per-unit values).
For details about the per-unit system, see Per-Unit System (Motor Control Blockset).
You must train the neural network using the Vα, Vβ, Iα, Iβ, and θe data so that it can accurately map the inputs into the output and act like a virtual position sensor by estimating the rotor position.
Generate Training Data from Target Simulink Model
To generate training data by simulating the model in this example, in the Data Collection and Sensor Selection section of the model, select Data Collection Enabled.
The data capture functions TrainingDataCapture and TrainingDataCapture_parallel obtain the training data by simulating the model tc4x_mcb_pmsm_foc_NN_Pos_Estimation.slx, which contains a quadrature encoder sensor-based FOC algorithm. The functions simulate the model and perform sweep operation across speed and torque reference values to capture the electrical position as well as the α- and β-equivalents of the stator voltages and currents.
What Is Sweep Operation?
The data capture functions use sweep operation to select a range of speed-torque operating points, simulate the model at each operating point, and record Vα, Vβ, Iα, Iβ, and θe once the stator voltages and currents reach steady state.
The following figures show the constant blocks that the data capture functions use to select each operating point:
The data capture functions use the
Speed_Trainingblock (available intc4x_mcb_pmsm_foc_NN_Pos_Estimation/Speed Ref) to select a speed reference value.

The data capture functions use the
Torque_Trainingblock (available intc4x_mcb_pmsm_foc_NN_Pos_Estimation/Inverter and Motor/Simulation/Load_Profile (Torque)) to select a speed-torque operating point.

The subsystem
tc4x_mcb_pmsm_foc_NN_Pos_Estimation/Data Collection/Subsystemcaptures Vα, Vβ, Iα, Iβ, and θe values that correspond to the captured operating point and records them in aSimulink.SimulationOutputobject.

The data capture functions compute and record the sinθe and cosθe values for these operating points.
Speed Ranges for Sweep Operation
The data capture functions TrainingDataCapture and TrainingDataCapture_parallel perform the sweep operation by selecting operating points across these two speed ranges:
Zero to low speed — This range corresponds to 0–10% of the motor’s rated speed. Within this range, the utility functions make minimal changes to the load torque because real-world applications typically exhibit little torque variation at low speeds. To keep the training data set lean, the utility function maintains an almost constant torque reference and primarily varies only the speed reference, collecting limited training data from this range.
Low to high speed — This range corresponds to 10–100% of the motor rated speed. The utility functions vary both the reference speed and torque values in this speed range to create operating points and collect most of the required training data.
Duration of Capture for Each Operating Point
The data capture functions simulate the model at each speed-torque operating point. During this simulation, they capture the Vα, Vβ, Iα, Iβ, and θe data only for a limited duration defined by these variables:
The variables dCStartTime1 and dCEndTime1 specify the data capture duration for the zero-to-low speed range. Because motor speeds are lower in this range, the capture duration is typically longer.
The variables dCStartTime2 and dCEndTime2 specify the data capture duration for the low-to-high speed range. Because motor speeds are higher in this range, the capture duration is typically shorter
This approach ensures these functions capture data only after the stator currents and voltages reach steady state during the simulation.
Number of Reference Speed and Torque Data Capture Points
Use the following variables to specify the number of reference speed and torque capture points:
The variable
dPSpdZtoLspecifies the number of reference speed points that the utility function uses in the zero-to-low speed range.The variable
dPSpdLtoHspecifies the number of reference speed points that the utility function uses in the low-to-high speed range.The variable
dPTorLtoHspecifies the number of reference torque points that the utility function uses in the low-to-high speed range.
The data capture function keeps the torque reference nearly constant in the zero-to-low speed range, so the number of torque points remains fixed in this range.
You can edit and tune these variables in the TrainingDataCapture.m and TrainingDataCapture_parallel.m functions included with this example.
Run the following code to generate the training data.
%% Capture the training data using Simulink Environment model = 'tc4x_mcb_pmsm_foc_NN_Pos_Estimation'; % Minor updates in model required for obtaining training data dCStartTime1 = 3.8; % dataCaptureStartTime for low to high speed dCEndTime1 = 4; % dataCaptureEndTime for low to high speed dCStartTime2 = 3.5; % dataCaptureStartTime for zero to low speed dCEndTime2 = 4; % dataCaptureEndTime for zero to low speed dPSpdLtoH = 40; % dataPointsSpeedLowtoHigh dPSpdZtoL = 100;% dataPointsSpeedZerotoLow dPTorLtoH = 25; % data points torque (low(0.1pu) to high(1pu) speed) [lowtohighspeeddata,zerotolowspeeddata] = ... TrainingDataCapture_parallel(model,[dCStartTime1,dCEndTime1],[dCStartTime2,dCEndTime2], ... [dPSpdZtoL,dPSpdLtoH,dPTorLtoH]); % Use this function to speed up the computations. You can also use the TrainingDataCapture function with same arguments.
The data capture functions store the generated data in two Simulink.SimulationOutput objects: zerotolowspeeddata for the zero-to-low speed range and lowtohighspeeddata for the low-to-high speed range.
Note: Running the data capture utility functions using these parameters can take a long time (approximately three hours).
Refine and Process Data
The example provides utility functions that extract and process relevant data from the data set collected during the sweep operation.
Extract One Electrical Cycle Data
For each speed–torque operating point, the data capture functions capture data across multiple electrical cycles during the time intervals defined by dCStartTime1, dCEndTime1, dCStartTime2, and dCEndTime2.
To extract information from one electrical cycle for all the operating points, run the following code.
oneCycleDataLtoH = OneElecCycleExtrac(lowtohighspeeddata); oneCycleDataZtoL = OneElecCycleExtrac(zerotolowspeeddata);
The OneElecCycleExtrac function stores the refined data in two Simulink.SimulationOutput objects: oneCycleDataZtoL stores the electrical cycle data for the zero-to-low speed range and oneCycleDataLtoH stores the electrical cycle data for the low-to-high speed range.
Concatenate Data from One Electrical Cycle
Execute this command to concatenate the extracted data stored in the Simulink.SimulationOutput objects oneCycleDataZtoL and oneCycleDataLtoH.
completeData = DataConcatenate(oneCycleDataLtoH,oneCycleDataZtoL);
The DataConcatenate function stores the concatenated data in the Simulink.SimulationOutput object completeData.
Process Concatenated Data
This example divides the concatenated data into the following data sets:
The training data set includes 70% of the data in the object completeData. The example uses this data set to train the neural network.
The validation data set includes the remaining 15% of the data in the object completeData. The example uses this data set to validate the trained neural network.
The testing data set includes the next 15% of the data in the object completeData. The example uses this data set to test the trained neural network.
Execute these commands to split the data in the object completeData.
tPLtoH = dPSpdLtoH*dPTorLtoH; % Total data points from speed and torque sweep in the low to high range tPZtoH = (dPSpdLtoH*dPTorLtoH)+dPSpdZtoL; % Total data points from speed and torque sweep in the zero to high range [traindatain,traindataout,testdatain,testdataout,validatedatain,validatedataout] ... = DataPreparation(completeData,tPLtoH,tPZtoH);
The function returns the split data and stores it in these dlarray objects:
The
traindatainobject stores the subset of the training data that the neural network uses as input.The
traindataoutobject stores the subset of the training data that the neural network uses as output.The
testdatainobject stores the subset of the testing data that the neural network uses as input.The
testdataoutobject stores the subset of the testing data that the neural network uses as output.The
validatedatainobject stores the subset of the validation data that the neural network uses as input.The
validatedataoutobject stores the subset of the validation data that the neural network uses as output.
Train and Test Neural Network
This example uses an autoregressive neural network (ARNN) with the below series-parallel architecture, where it uses Vα, Vβ, Iα, Iβ, , and inputs to predict the and outputs.
Vα, Vβ, Iα, Iβ, , and are the true values of the time-series training data inputs.
and are the true values of the time-series training data inputs with a delay of one sample time.
and are the outputs predicted by the neural network.

The example includes the CreateNetwork function which you can use to train a neural network and build a nonlinear ARNN that can estimate rotor positions. This function uses the dlnetwork (Deep Learning Toolbox) object and trainnet (Deep Learning Toolbox) function to create and train the neural network.
To train, test, and validate the neural network, run the following code.
[posnet_new_M,testdatamse] = CreateNetwork(traindatain,traindataout,testdatain, ...
testdataout,validatedatain,validatedataout);
This function accepts the dlarray objects (traindatain, traindataout, testdatain, testdataout, validatedatain, and validatedataout) and returns a trained ARNN and mean-squared-error information.
The
posnet_new_Mobject stores the trained ARNN.The
testdatamsevariable stores the mean-squared-error information that the function generated from the testing data set.
For more details on the training process, see Building Neural Network for Virtual Position Sensing (Motor Control Blockset).
Export Trained Neural Network to Target Simulink Model
The CreateNetwork function generates a trained ARNN that contains two fully connected layers and an activation layer. The following figure shows the code snippet that defines the neural network layers.

To export the trained ARNN network as Simulink blocks, run this code, which uses the exportNetworkToSimulink (Deep Learning Toolbox) function.
exportNetworkToSimulink(posnet_new_M)
The function accepts the dlnetwork object posnet_new_M to create the Simulink layers blocks in a new Simulink model as shown in the following screenshot:

Copy these blocks and add them to the subsystem tc4x_mcb_pmsm_foc_NN_Pos_Estimation/Current Control/Neural Network Observer1/Neural Network/NN_Model_ARNN (available in the target model tc4x_mcb_pmsm_foc_NN_Pos_Estimation.slx) as shown in the following screenshot:

The following figures show the resulting architecture of the ARNN, which acts as a virtual position sensor. To achieve good performance with time-series predictions, this example provides the previous output values (sinθe and cosθe) as additional inputs (with a delay).


Simulate and Deploy Code
After you export the neural network to Simulink, run the following command to open the updated target Simulink model.
open_system('tc4x_mcb_pmsm_foc_NN_Pos_Estimation.slx');
Simulate Model
Follow these steps to simulate the model.
1. In the Data Collection and Sensor Selection section of the target model tc4x_mcb_pmsm_foc_NN_Pos_Estimation.slx, select Data Collection Disabled. Alternatively, use this command to disable the data collection in the model.
set_param('tc4x_mcb_pmsm_foc_NN_Pos_Estimation/Data Collection ','Value','0') % Set value to 0 to disable data collection
2. In the Data Collection and Sensor Selection section, select one of the following options:
Sensor feedback — Use the quadrature encoder position sensor.
NN Observer — Use the trained neural network as virtual sensor.
Alternatively, use these command to set the sensor selection.
set_param('tc4x_mcb_pmsm_foc_NN_Pos_Estimation/Sensor Selection','Value','1') % Set value to 1 to use neural network for simulation set_param('tc4x_mcb_pmsm_foc_NN_Pos_Estimation/Sensor Selection','Value','0') % Set value to 0 to use encoder for simulation
3. To simulate the model, in the Simulation tab, click Run.
4. To view and analyze the simulation results, in the Simulation tab, click Data Inspector.
Observe that the position estimated by the trained neural network approximately matches the position obtained using quadrature encoder sensor. This match verifies the performance of the trained neural network as a virtual sensor.

Generate Code and Deploy Model to Target Hardware
To generate code and deploy the model, on the Simulation tab, click Build, Deploy & Start.
Download and install the One Eye tool from Infineon to monitor signals from the hardware. Before using the One Eye tool, ensure that you download and install the latest version of the TAS/DAS tool.
Open the OneEye tool. To load the OneEye configuration file
tc4x_mcb_pmsm_foc_NN_Pos_Estimation.OneEyeshipped with this example, click File > Load Configuration. Reset the hardware and check the TAS/DAS connection status to monitor the signals.
This figure shows the reference speed (SpeedRef) and feedback speed (Speed_fb) signals while using virtual sensor for rotor speed estimation. Observe that speed of the motor (Speed_fb) approximately matches the target speed (SpeedRef) while using the virtual sensor.

Other Things to Try
The example model automatically calculates the ADC (or current) offset values. To disable this default functionality, set the variable
inverter.ADCOffsetCalibEnableto0in the shipped Simulink Data Dictionary file (FOCPMSMUsingPosEstByNeuralNtwExample.sldd). Alternatively, you can manually compute the ADC offset values and update them in the same data dictionary file. For instructions, see Run 3-Phase AC Motors in Open-Loop Control and Calibrate ADC Offset (Motor Control Blockset).Compute the encoder index offset value and update it in the included Simulink Data Dictionary file (
FOCPMSMUsingPosEstByNeuralNtwExample.sldd). For instructions, see Quadrature Encoder Offset Calibration for PMSM (Motor Control Blockset).Change the Reference Speed (RPM) in the
Speed_Trainingblock (available intc4x_mcb_pmsm_foc_NN_Pos_Estimation/Speed Ref) and observe the performance of the trained neural network as a virtual sensor.
See Also
Get Started with Deep Learning Toolbox (Deep Learning Toolbox)
Building Neural Network for Virtual Position Sensing (Motor Control Blockset)
Analyze Sensorless Observers for Field-Oriented Control Using Multiple Cores of Infineon AURIX
Accelerate AI Based Software Development on Infineon AURIX TC4x Microcontroller