PMSM Motor Control
This example shows closed-loop simulation of a motor control system. The system is partitioned into an environment model and a software model. The environment model simulates the PMSM motor, the inverter and the analog portion of the microcontroller peripherals interfacing software to the analog world. The software model simulates the controller algorithm running on the microcontroller and interacts with the environment model through the ADC and PWM peripherals. Modeling the entire system in this fashion enables detecting design errors early in simulation phase while facilitating one-click deployment of the software model to hardware when design is ready for deployment.
Supported hardware platforms:
Required hardware:
Required support packages:
- Simulink Coder Support Package for STMicroelectronics Nucleo Boards
This example uses:
- Simulink
- SoC Blockset
- Simscape
- Simscape Electrical
- Fixed-Point Designer
- MATLAB Coder
- Simulink Coder
Challenges in Controller Development
A motor control system can be conceptually modeled as shown in the diagram below. Here, the microcontroller drives a Motor Driver board through PWM peripheral and receives feedback from the motor through a current sensor over ADC peripheral. The controller algorithm executes in a Microcontroller and comprises the software portion of the overall system. The motor driver, the motor and the current sensor are all part of the environment. The ADC and PWM peripherals have software components as well as environment components. The environment portion of the ADC and PWM peripherals represent analog to digital conversion process, and vice versa, as well as the timing of conversion events. A model of the entire system is needed to accurately measure the performance of the controller algorithm in simulation.
Figure 1: Conceptual representation of a motor control system.
Often, the system is modeled in two stages in Simulink. A closed-loop model of the plant and controller is used to develop the controller algorithm. This model ignores the timing effects of hardware peripherals and the scheduling of the controller algorithm. A second model containing a modified version of the controller algorithm is used for deployment. The deployment model configures hardware peripherals and introduces scheduling constructs such as interrupt service routines (ISR). There are several issues with this two-stage modeling approach:
- Simulation model does not capture the effects of hardware peripherals such as saturation and finite resolution of the ADC peripheral or the latency introduced by the analog to digital conversion time. This translates into differences between simulation behavior and the deployment.
- When developing the deployment model, the controller algorithm often needs to be partitioned between different ISR's. This leads to divergence between simulation and deployment models.
- The scheduling behavior of the software such as pre-emption, finite and non-zero execution time and latencies introduced when servicing hardware events are not simulated in the deployment model. This often leads to motor control algorithm not working at all on hardware.
- In some cases, the hardware may not be easily accessible or might be very expensive to operate. In such instances, virtual testing and development of the motor controller in simulation can be cost effective. You can simulate scenarios such as shorted inverter switch with ease in simulations while this would be catastrophic in real life.
SoC Blockset introduces a new paradigm to model the entire motor control system. The system is partitioned into an analog domain that captures the dynamics of the plant and the microcontroller peripherals and a software model that captures the scheduling of the controller algorithm. The interactions between the software model and the environment are represented as asynchronous events. The controller algorithm is executed in Simulink with accurate representation of scheduling behavior. The system behavior with respect to software scheduling can be studied in simulation. This helps proving the correctness of the scheduler design for certification workflows. Modeling the entire system with SoC Blockset helps discovering issues at design phase dramatically reducing the need for debugging on hardware.
Feature Highlights
List of SoC Blockset toolbox capabliity for motor control applications:
- Asynchronous event simulation - PWM-ADC synchronization by triggering ADC start of conversion event during middle of PWM period. - ADC end of conversion event simulation to trigger Torque control.
- Simulation of ADC acquistion time and its impact.
- Simulation of PWM with deadtime in variable-step solver for faster simulation. (PWM simulation allows users to model inverter to study current ripples and harmonics)
- External mode data logging with real time stamps.
- Profiling of tasks in simulation and code generation.
- Task duration impact in simulation using Task manager and visualization.
- Modelling semantics to allow Variable-step simulation and Fixed-step code generation options in one-model approach.
Hardware Connections
Figure 2 shows the pinout diagram of the BOOSTXL-DRV8305EVM. Table 1 shows the pin connections from STMNucleo board to the BOOSTXL-DRV8305EVM. Connect the STM32F767ZI Nucleo board to the BOOSTXL-DRV8305EVM motor driver as shown in Table 1. Connect the motor to the driver board through "Motor Header" pins.
Figure 2. Pinout of BOOSTXL-DRV8305EVM.
Table 1. Table of pin connections between STMNucleo board and the BOOSTXL-DRV8305EVM.
Table 2: Pin connections between STMNucleo board and QEP (Quadrature encoder pulse) connected to BLY171D-24V-4000 PMSM motor. Field Oriented Control
Filed Oriented Control (FOC) is a commonly used control method for PMSM because of high efficiency and accuracy. It is based on two mathematical transformations, Clarke and Park, to transform the actual phase currents from stator-fixed to field-synchronous coordinate systems with two dimensions: the motor’s current flux (d-axis) and the motor’s torque (q-axis). It uses current and velocity controller (usually PI controller) to control the torque of 3-phase motors based on the current and speed measurement from motor. A conceptual FOC of PMSM control system is shown in the diagram below.
Design Using SoC Blockset
Figure 3: Simulink representation of a PMSM motor control system.
This model contains an area called Plant which represents the motor, the motor driver board and current sensing apparatus. The area labeled Controller captures the software model of the system and runs the controller algorithm. The areas labeled as ADC Channel and PWM Channel simulate analog dynamics of the ADC and PWM peripherals. Compare the representation of the motor control system in this model to Figure 1. Open the Inverter and Motor subsystem. This subsystem contains a Simulink representation of the BOOSTXL-DRV8305EVM motor driver board (labeled as Inverter) and the PMSM motor (BLY171D-24V-4000 or BLY172s-24V-4000 based on parameter option). The input to the Plant model is the PWM waveform generated by the microcontroller. The outputs contain voltage values corresponding to the current sense circuit as well as the rotor angle. The phase voltages are sampled by the ADC peripheral and sent to the Controller algorithm. Open the Processor subsystem. This subsystem represents the software running on the microcontroller. The Task Manager block simulates the scheduling of the torque control and speed control algorithms. Double click on the Task Manager to open the block mask. Inspect the Task simulation pane. The Task Manager executes a timer-driven task called SpeedLoop 100 times a second. It also executes an event-driven task called ADC_IRQHandler. Both tasks have finite execution times as specified in the Simulation pane of the Task Manager block. The Task Manager block triggers the execution of the ADC_IRQHandler task upon reception of an ADC end-of-conversion event from the ADC. ADC in turn is triggered by the PWM. The model parameters such as the motor and inverter parameters, PID gains, etc. is loaded in model PreloadFcn from the following files based on the motor:
soc_stmnucleo_pmsmfoc_data
soc_stmnucleo_pmsmfoc_BLY171D_data
You can adapt the simulation model to a different motor and inverter by changing the parameters in this file and if necessary updating the Plant model.
Open Simulation Data Inspector. Click 'Play' to simulate the model. The simulation may take a while to complete. Open Simulation Data Inspector and view motor rpm and ADC_currents signals as a function of time as shown in Figure 4 below. Figure 4: Motor RPM and ADC current as a function of time.
As can be seen in Figure 4, the motor RPM stabilizes to a steady state value at around 1.9 seconds. In this example, a Sliding Mode Observer (SMO) is used to estimate the motor shaft speed. Due to the use of the SMO, the shaft speed is not perfect and oscillates around a bit. Figure 5 shows a magnified version of the rpm and ADC_current signals when motor shaft speed reaches a steady state. The commanded RPM is 2000 (0.5 times maximum RPM for the motor which is 4,000).
Figure 5: Motor RPM and ADC current at steady state.
Figure 6 shows the ADC voltage values captured at the input pin A2 of the STM Nucleo board. As you can see the actual ADC voltage values are very close to the simulation results.
Figure 6: ADC voltage captured via an oscilloscope at pin A2 of STM Nucleo board at steady state.
Figure 7 shows the oscilloscope trace of the ADC voltage at pin A2 at steady state. As can be seen from the trace, the oscilloscope estimates the waveform frequency as 138.8 Hz. The motor shaft speed can be calculated as
RPM = 120 * <ADC peak-to-peak frequency> / <Number of pole pairs>
RPM = 120 * 138.8 / 8; % 2082 rpm
Figure 7: Oscilloscope trace for ADC voltage at pin A2 of the STM Nucle board. Note the voltage waveform frequency (138.8 Hz).
The actual shaft speed obtained from ADC current measurements is in close agreement with simulation results.
Choosing ADC Acquisition Time
ADC hardware contains a sample and hold circuit which contains a hold capacitor. The ADC peripheral has a parameter to set the acquisition time window needed to charge this capacitor. The required acquisition window time is based on several factors: the ADC hold capacitor value, impedance of the internal analog multiplexer, output impedance of the analog source. Calculating ADC acquisition time is challenging, and an improper value may result in inaccuracies in the ADC output count values.
Open the pmsm_foc_stm_switching_top.slx model. Open the ADC Channel subsystem. ADC Front-End simulation blocks in this subsystem simulates the acquisition time and output counts based on acquisition window time parameter. This block contains a number of parameters to set the effective resistance and effective capacitance of the hardware as well as the charge time constant, as shown in the figure below.
To see the effect of the ADC acquisition time on the controller algorithm, set Acquisition window time to 20ns in ADC Front-End blocks as seen in the figure below. Simulate the model.
Open Simulation Data Inspector and examine simulation results. The motor rpm shows excessive ripple. Repeat the simulation by setting the Acquisition window time to 100ns. Open Simulation Data Inspector and examine simulation results. In contrast to previous simulation results, observe that the motor rpm has stabilized and shows very little fluctuation around the set point.
The figure below shows the sampled ADC values as a function of acquisition window time. As can be seen from the graph below the measured current contains large inaccuracies for 20ns . Acquisition window values above 50ns give good results with +/-1 count error margin. You can trade-off ADC conversion latency with ADC accuracy using simulation results. Without an accurate model of the ADC peripheral, this step in the simulation would most likely be performed on actual hardware which is a lot more expensive.
Current Sense Measurement Timing
BOOSTXL-DRV8305EVM motor driver is essentially a 3-phase inverter built using 6 power MOSFETS. This motor driver board uses a low-side shunt resistor to sense motor currents as shown in Figure 3. Voltage drop across the shunt is amplified by a current sense circuit. This setup ensures low power dissipation since the current is not flowing all the time through the shunt and the sensing happens when the bottom switches are on and away from PWM commutation. In general, current sensing and measurement is one of the most critical aspects of a motor control system design.
Figure 3. A circuit schematic of the current sense circuit in BOOSTXL-DRV8305EVM. The shunt resistor used for current sensing is placed on the low side of the power MOSFET Q4.
Since the current flows through the shunt resistor only when the low-side MOSFET is activated, the ADC must sample the current in the mid-period of the PWM waveform. Otherwise the current measurement will be zero resulting in undefined behavior of the controller algorithm.
Open the pmsm_foc_stm_switching_top.slx model. The ADC is triggered to sample current measurements via a synchronization event from the PWM. Open PWM Channel subsystem. Double click on the PWM Generator A to open the block mask. Set Event condition parameter to EndOfPeriod(P, 2P, 3P ...) as shown in the figure below. Repeat this operation for PWM Generator B and PWM Generator C blocks. Wrong current sampling
Simulate the model. Monitor the triggered PWM events and ADC sampling events on the Simulation Data Inspector as shown in the figure below.
Note that ADC sampling occurs at the instant bottom MOSFET switches are off. Sampling at this instant results in sampled ADC value of 2252 which corresponds to zero currents (+V currents have values above 2252 and -V currents have values below 2252). This results in control loop going unstable and producing wildly fluctuating values for motor rpm as seen in the figures below.
Right current sampling
Repeat the same simulation steps, this time setting the Event condition parameter to MidPeriod(P/2, 3P/2, 5P/2 ...), as shown in the figure below.
Inspecting the simulation results reveals a stable control loop and expected results as shown in the figure below.
It would be very difficult to determine the source of a problem like this if the timing accurate, event-based interaction of the ADC and PWM peripherals were not simulated. The simulations the motor control system with SoC Blockset are very accurate and can provide design time identification of deployment issues in advance. The price paid for accuracy is the simulation speed. In future releases, you will be able to trade-off simulation fidelity with speed allowing you to accommodate workflows where you can concentrate on controller numerics initially.
Controller Algorithm Scheduling
Application development often includes simulating an algorithm to ensure the correct behavior. Such simulations usually ignore the real-time aspects of an embedded system environment. This may allow certain timing problems to remain undiscovered until the application runs on hardware. The timing problems often lead to incorrect application behavior. SoC Blockset helps you detect these problems in simulation rather than on hardware. This can help you avoid costly debugging on hardware.
Double click on the Task Manager block an open the block mask. Simulation pane of the ADC_IRQHandler is shown in the figure below. The Task Manager block allows you to configure execution of the tasks in your model. In the block dialog, you define how many tasks you need in your system using Add and Delete buttons. On the Main tab of the dialog, you set the main task properties, while on the Simulation tab you set the simulation task properties.

The simulation uses safe values for the task duration. You can, however, simulate conditions within the software environment that may cause momentary changes in task execution times due to pre-emption, cache misses or context switches. To simulate real-time task effects, such as preemption and overruns, SoC Blockset requires you to provide the duration of each task. The duration is defined as the time elapsed between the task start and the task end. Ideally, you will measure the task duration on your hardware board. If that is not possible, look up the task duration in the data sheets provided by the task algorithm developers. As a last resort, you should set the duration relative to the task period or the shortest recurrence interval for aperiodic tasks.
Deploy Controller to Hardware
Following products are required for this section:
To deploy the controller on an STM767ZI board use the baremetalBuilder command line utility.
b = baremetalBuilder('pmsm_foc_stm_top')
The commands above generate code for the Controller in the pmsm_foc_stm_top.slx model, compile and link the generated code and deploy it to STM32 767ZI hardware. Once the generated code starts running on hardware, you will see the motor spinning. You can just generate code and compile without deploying the binary executable by using the build method.
External Mode Simulation
To run the controller in external mode and log the real-time data, set the Serial port and Baudrate values in top model and reference model using Model Settings > Hardware Implementation > Target hardware resources > External mode pane. Then execute the following on the MATLAB command line:
The runExternalMode function of the baremetalBuilder runs the simulation in External Mode. Note that both the top model and reference model Serial port and Baudrate values must be identical.
Data drops may be observed from the native ST-Link port. Connect an external FTDI FT232H to get better exteranl mode results. Connecting External FTDI
- Connect PB_11 Receive pin of STM32 F767ZI hardware to Transmit pin of FT232H
- Connect PB_10 Transmit pin of STM32 F767ZI hardware to Receive pin of FT232H
- Connect the ground of STM32 F767ZI hardware with ground of FT232H
- In Configuration Parameters > Hardware Implementation > Target Hardware Resources > SCI0(default) > In Receive pin select PB_11 and Transmit pin select PB_10 to communicate over external FTDI.

- In External Mode tab specify the COM Port in Serial port to which external FTDI FT232H is connected and Baudrate as 12e6.

- Set the above parameters in both top model and reference model.
Task profiling
To view task profilling on processor connect external FTDI as mentioned above and in Configuration Parameters > Hardware Implementation > Task profiling on processor > check Show in SDI (SImulink Data Inspector). And then execute runExternalMode(b) command.
Add custom device driver block
SoCB provides Task Manager, PWM Output, and Analog Input device driver block for code generation which can be placed in the processor model. And corresponding device driver block for simulating Task Manager, PWM Generator, and ADC Front-End blocks in plant model. And to add any other custom device driver block other than the above-mentioned block in SoCB semantics use following steps: - Create a custom device driver block. (Example for QEP block.)
- Open new model and add a Matlab System Block in it.
- Set the System object name on the mask of Matlab system block with the system object name from Step 1.

- Select the Matlab system block and run the following command in MATLAB command window "socCreateDriverBlock(gcbh,'Source')" for a source block and "socCreateDriverBlock(gcbh,'Sink')" for a sink block.
- Save the generated library, and use the block for code generation in processor model. This block will be passthrough is simulation.(QEP device driver block)
- Create a simulation block representing the custom device driver block and place it in plant model. (QEP simulation block)
- Use Message Send block to send signal from plant model to processor model(for source driver block) and Message receive block from processor model to plant model(for sink driver block).
- pmsm_foc_stm_qep_top shows how QEP driver block used in codegen and simulation.
%SOCCREATEDRIVERBLOCK Creates device driver block for given MATLAB system which can be used in SoCB semantics.
% matlabSystemBlkHandle - MATLAB system block handle
% deviceDriverBlockType - Device driver block type ('source','sink')
% character vector | string scalar
% Name-Value Pair Input Arguments:
% Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value.
% Name must appear inside single quotes (' '). You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
% 'Name' - Name of generated device driver block (character vector or string)
% Default name of MATLAB system object block is retained withs soc_ as prefix.
% socCreateDriverBlock(gcbh,'Source');
% socCreateDriverBlock(gcbh,'Sink');
% socCreateDriverBlock(gcbh,'Source','Name','QEP');
% Copyright 2019 The MathWorks, Inc.
Limitaions
Custom device driver block does not support
- Event generation
- Variable size of input/ouput after genrating the libarary. Workaround - Generate library with required input/ouput port
- Mask on mask system object. Workaround - Create a mask on top of generated library.