Video length is 33:03

Rapid Control Prototyping for Permanent Magnet Synchronous Motor (PMSM) Control

Overview

This webinar will show you how to develop and test field-oriented control (FOC) algorithms for a PMSM operating at a 20kHz inverter switching frequency. A MathWorks engineers will show you how to go from control algorithms developed in Simulink to performing Rapid Control Prototyping (RCP) using Simulink Real-Time on a Speedgoat Real-Time Target Machine.  You will learn how to prepare the control algorithms for real-time testing, generate code and download them to the Speedgoat Real-Time Target Machine, interact with the motor and inverter from Simulink, and import test results into MATLAB for analysis.

Highlights

In this webinar, you will learn how to:

  • Review performance of closed-loop motor control algorithms in Simulink
  • Deploy and test controls algorithm in real-time on Speedgoat hardware
  • Connect and interact with motor and inverter hardware from Simulink
  • Estimate parameters using data collected from the motor
  • Log data and tune parameters while the test is running in real-time
  • Automate real-time testing with Simulink Test

About the Presenter

Chirag Patel works with engineers in control system design to streamline the transition from desktop simulations to real-time testing and hardware-in-loop (HIL) testing. Prior to joining MathWorks, Chirag worked at Lucid Motors, where he led the efforts of adopting Model-Based Design for electric powertrain, developed algorithms for battery management system for Formula-E and built HIL test systems for vehicle control systems. While at the Cessna Aircraft Company, Chirag developed simulations for electro-hydraulics systems, built iron bird test rigs for anti-skid brake systems, and designed integrated environmental control system for business jets. Chirag received Bachelor of Engineering (Mechatronics) from Sardar Patel University, India and M.S degree (Control Systems) from Wichita State University, Kansas, USA.  

Recorded: 27 Aug 2020

Hello, and welcome to this webinar on rapid control prototyping for permanent magnet synchronous motors. My name is Chirag Patel. I'm an application engineer at MathWorks.

If you are currently working on a motor control project or have worked on that in the past, you may agree with me that the first major and exciting milestone of your project is when you successfully spin the motor for the first time. It is also the beginning of a long journey of making small, incremental improvements until you feel safe to connect the motor to its load. Nobody spins motors just for fun, unless you are doing it for a webinar.

The second milestone is when you integrate the motor with its load and drive it successfully. That can be, for example, moving your robot arm, driving an electric scooter, or operating a ventilator for the first time. This is certainly the most important milestone for the entire project team, including you, the motor, and inverter control engineers. But this excitement wears off very quickly as we get busy fixing integration and performance issues from previous phases.

We also need to develop detailed diagnostic and fault detection routines, which have very little to do with the actual motor control problems. Along the way, we incorporate major hardware and software revisions in preparation for the final product launch.

The goal of this webinar is to demonstrate how MathWorks and Speedgoat's real-time testing solutions can help you get to the first milestone of spinning the motor as quickly as possible and make subsequent design iterations short and efficient. You will learn how this integrated yet flexible hardware and software programming environment can help you drive product innovation.

Using field-oriented control for permanent magnet synchronous motor as an example, I will demonstrate how to transition between desktop simulations and real-time testing with prototype hardware. In the process, I will show you key features of Simulink Real-Time, such as measuring and monitoring signals, tuning control parameters, and logging experimental data, all in real-time.

Next, you will learn how to estimate model parameters from experimental data using MATLAB's data analysis capabilities. Test automation is an essential part of real-time testing. I will show you how to automate your test routines and generate test reports using Simulink Test. While your application or projects will be different, you will be able to apply techniques and features learned from this webinar in your project.

In this webinar, we will not discuss detail of working of permanent magnet synchronous motors or details of field-oriented control algorithms. We will list all the relevant learning resources available on the MathWorks website at the end of this presentation. We will also provide you a link from where you can download all the examples used in this webinar.

Now let's quickly look at our hardware setup. A host computer with MATLAB, Simulink, Simulink Real-Time, and other required tools is used to design control algorithms and supervisory logic. Once we are happy with our initial desktop simulation results, we would like to validate our design on hardware to gain more confidence. So we take our control algorithms and deploy them onto Speedgoat real-time target computers using Simulink's automatic code generation technology. Speedgoat's real-time target computers with IO modules allows you to interact with your device under test.

For our example, we are using a Speedgoat baseline target computer with multicore CPU and IO397 to interface with Speedgoat's electric motor control kit. This kit includes a pre-assembled three-phase inverter, three-phase 7-pole pair motor with quadrature encoder for rotor position and velocity feedback.

In this section, we will learn how to spin three-phase PMSM in open-loop mode using just a few Simulink blocks and Speedgoat hardware. Let's assume that you received a hardware development kit with all the key components, such as motor and inverter from your vendor, and you had just enough time to go through the data sheet, getting started documentation, or watch a video. If you're like me, at this point, you are super-excited to wire everything up and spin the motor.

So let's just do that. We will jump into MATLAB and Simulink and spin a three-phase permanent magnet synchronous motor. From the Simulink start page, we will select the template for Simulink Real-Time as this option will preconfigure our model with the right solver and coordination settings.

To spin a three-phase motor, we need to apply three-phase sinusoidal voltages at 120-degree phase shift, or 2 pi by 3 in radians. We will attempt to spin the motor at two revolutions per second by multiplying the target frequency with the number of pole pairs of the motor. Since we will spin the motor in open-loop mode without the knowledge of phase currents, we need to make sure that the applied voltage is small enough to prevent an over current situation. It is very easy to damage a motor in open-loop mode if there is no provision for over current protection in hardware.

Let's add the bias of 0.5 to keep the PWM duty cycle values between 0 and 1. Before we connect the signal to PWM block, we need to configure a setup block for the right IO module. Speedgoat provides a variety of IO modules to interact with your hardware. For our setup, we are using IO397, which is a configurable FPGA module. A bitstream file defines IO functionalities and pin mapping of a configurable FPGA module. You will get this [INAUDIBLE] file from Speedgoat as part of your hardware solution.

For example, the bitstream file for IO397 implements three channels of PWM output, five general-purpose IOs, one channel of quadrature encoder inputs, and four differential analog inputs. These two tables in the documentation defines the pin mapping between a code module channel and physical pin on the terminal board. For example, the high side of the PWM-A a is mapped to pin 3b on the terminal board.

I have already made all the required hardware connections on the Speedgoat target computer, inverter, motor, and quadrature encoder. Now let's add a PWM generation block. Here we define three channel vectors, one for each leg of PWMs. Now let's configure a few more PWM parameters, such as type of PWM, symmetric or asymmetric, whether PWM B is independent or complement of PWM A, PWM period. Select an option to prevent both inverter legs being high at the same time. And when to update PWM generation, and so on.

A very important parameter for PWM is inverter switching frequency. Here we are going to assume 20 kilohertz frequency for our inverter. In addition to PWM signals, we also need to provide inverter enable signal via digital output. According to the pin mapping we saw earlier, GPIO channel 4 and 5 are connected to the inverter Enable and NOT Enable pins via pins 15b and 16b on the terminal board. Let's add a digital output block and configure it for channel 4 and 5. We need to enter initial values and reset values to ensure the inverter is disabled when applications start and stop.

Next, enter the sample time of 1 kilohertz for digital output block, as it does not need to be updated any faster than that. We will use a constant block and logical NOT block to feed inputs to these two digital output channels. Let's go ahead and take care of data type conversion for these two signals. And add a slider switch to control inverter and connect that to this constant block.

I think we are ready to test this model and spin the motor. Since our model is already pre-configured with Simulink Real-Time settings, a Real-Time tab is available in the tool strip to help us with Real-Time testing workflow. First, we will select a Speedgoat target computer and connect. The Run on Target button combines the process of code generation and compilation to build a real-time application file, then build this application file onto the target computer.

Next, connect Real-Time application to your Simulink model on the host machine. And finally, start the execution on target computer. We also have option to perform all these tasks separately, step by step. Let's go ahead and click Run on Target to start the build process. Let me bring camera to see the motor in action. We can see that the motor is not spinning even after the target computer has started the execution. This is expected because we haven't turned the inverter on yet.

So let's turn on the inverter, and here we can see that the motor is slowly spinning at about two revolutions per second. But we don't have any way to measure its speed. Now, let's add driver blocks for reading phase current and quadrature encoder pulses and convert them into physical signals. We will run one more test to see if we are reading our feedback signals OK.

This time, let's use simulation Data Inspectors to monitor signals of interest, such as phase currents and motor velocity. We can modify our scaling values of phase currents in real-time to ensure all phase current values are close to zero when the inverter is switched off and the motor is not spinning.

Now, let's turn on the motor. From the camera, we see the motor's spinning. Our rotor velocity is -6 point something in radians per second, which is approximately two revolutions per second. And the phase current values are no longer zero. Let's turn off the motor and take a closer look at phase current signals. The shape of the phase current is not sinusoidal, but it is expected under normal conditions.

Looking at these results, we can say that our calculations for converting raw values to physical units are correct. That's all it takes to spin a three-phase PMSM in open-loop using Simulink Real-Time and Speedgoat hardware. It's a small but important milestone in the project.

This milestone gives us a functional, well-integrated rapid prototyping platform that we can use to continue developing closed-loop control algorithms. Hopefully, this short demonstration gave you confidence that you can also reach the first milestone of your next project quickly using solutions from MathWorks and Speedgoat.

We just learned how to spin a motor in open-loop mode. In this section, we will review the implementation of field-oriented control algorithm and test its performance in Real-Time using Speedgoat target computer, power inverter, and a three-phase permanent magnet synchronous motor.

Let's start by reviewing our Simulink model with FOC algorithm already implemented. Starting from its inputs and outputs, we have used Simulink bus element ports to define the interfaces of the controller logic. userInputs and controllerFeedback bus object pack all input signals to the controller. Similarly, motor commands bus packs three PWM output signals and one digital output going onto the power inverter.

Mode and rotor velocity signals are purely for debugging purposes. Packed in controllerInfo bus, which is not connected to anything else in this example. Looking inside the controller model, these first two blocks convert raw sensor signals into physical signals, such as phase current, mechanical rotor position, rotor velocity, and electrical position.

Inside the Controller_Mode subsystem, we have a detailed implementation of different control modes-- Disable mode, Open-loop Velocity Control, Calibration of Encoder Offset, and Closed-loop Velocity Control. These control modes are enabled or disabled by the main mode scheduler logic. The state logic is implemented using state flow, as it offers the most intuitive way to design, debug, and test supervising logic, task scheduling, temporal logic, and truth tables.

Here we can clearly see the three main operating states-- Stand_By, Enable_Inverter, and Error. Sub-states within Enable_Inverter state represent different control modes we saw earlier. The transition between these states and sub-states are regarded by transition conditions based on user input and feedback signals.

Additionally, to protect the motor from over current conditions, we have implemented fault detection logic. When Over Current Event is detected, Disabled mode is activated and the main mode scheduler will enter the error state. In the Open-loop Velocity mode, we vary stator voltage and frequency to control the rotor speed without using any feedback from the rotor. This technique can be used to check the integrity of the hardware connections, as we did in the previous section.

The Calibrate Encoder Offset mode calculates the offset between the [? Z-axis ?] of the rotor and the encoder index position. The closed-loop FOC algorithm needs this value to compute rotor position in [? Z-axis ?] [INAUDIBLE]. Looking into Closed Loop Velocity Control mode, it is divided into two cascaded closed loops. The outer loop is for velocity control, which takes Command_Velocity and feedback Rotor_Velocity as inputs and generates quadrature current command using PI_Controller.

This Current Control block implements filed-oriented control algorithm. Clarke and Park transforms are applied to stator currents to derive the D_Currents. Two PI current controllers are implemented to calculate reference rotor voltages in D and Q axis. Then, Inverse Park and Inverse Clarke transforms are applied to get reference phase voltages in a, b, c reference wave.

We use Space_Vector_Modulation to generate PWM signals, which are then applied to the power inverter. To separate colors in the model, red and green represents two different simple times. The Velocity Control and Mode_Schedulers have an update rate of 1 kilohertz, and the control algorithm and other modes updating the values of PWM signals are implemented at a switching frequency of 20 kilohertz. This results in the base sample time of 50 microseconds for the entire model.

To test if the controller logic works on hardware, we need to interface this controller model with the hardware interfaces we created in the previous section. To perform interactive manual testing, we are using dashboard blocks from Simulink library. For more systematic testing, we will use SignalEditor blocks to alter various test cases. We can use this test harness model to test our controller interactively in real-time.

After completing code generation, compilation, and build process, the real-time application is deployed onto the target machine. Upon starting the execution of the test, when we switch the motor on while commanding Closed-Loop mode, we can see that the rotor speed quickly reaches the target speed with very small overshoot.

If we are not satisfied with the controller performance, or would like to debug its functionality in real-time, we can tune model parameters and observe signals of our interest in real-time while staying in Simulink environment. Here we can see the response of the controller after the new gain values has been applied. This interactive, Real-Time testing workflow eliminates the need of generating and maintaining calibration and measurement files.

A well-integrated testing workflow using Simulink Real-Time removes the need for undesired model translation and handover between multiple tools, departments, and engineers, making every design iteration short and efficient.

In the previous section, we learned how to tune motor controller gains interactively. Motor control engineers need to have a good estimate of motor parameters such as stage resistance, the [INAUDIBLE] of constant, rotator inertia, et cetera to compute controller gains. Some of these parameters are often not available in the datasheet, and sometimes motor performance deviates from its datasheet. In this section, we will discuss how to use Simulink Real-Time and its integration with MATLAB to estimate motor parameters from experimental data.

We will use MATLAB Live Script to perform this estimation. First, we load and set up a Simulink model with Coastdown Experiment. Using MATLAB command line interface for Simulink Real-Time, we build the model for Speedgoat target, deploy the application, and start the experiment.

In this experiment, we spin the motor to high enough target speed for first two seconds and then disable the inverter. We continue to record data until the rotor comes to a complete halt. We bring experimental data in MATLAB and plot results. From MATLAB plot, we select data points from coastdown phase and save as new data in MATLAB Workspace.

During coastdown, the rotor is spinning under its initial load and friction. Assuming we have good confidence in the value of rotor inertia, H, we can use this equation and saved data points to perform curve fitting and estimate friction coefficients. To do that, we can either use an interactive app from Curve Fitting toolbox to fit a custom equation or CallFitFunction with the required input argument as shown here.

These are our new estimated values of friction coefficients. We can see from this plot that the Fit results and experimental data match very closely. We can further evaluate this Fit performance from goodness of Fit value. Let's update values of friction parameters in our desktop simulation model and compare simulation results with experimental data.

Here we can see that we have a very good match for rotor speed during coastdown phase. Hence, we use experimental data to improve results of our desktop simulation. We can use the same workflow and technique and create more experiments to estimate other model parameters.

In this section, we learned that applications of rapid control prototyping are not limited to testing logic and tuning controller gains. Experimental data can be used to characterize a system under test and improve understanding of the interaction among different components. Hopefully, this short exercise showed you how Simulink Real-Time and MATLAB can help you integrate your design, analysis, and testing workflows.

So far, we learned how to spin the motor in open-loop, test FOC algorithm, and analyze experimental data using MATLAB. We engineers prefer to automate tasks we perform frequently so that we can focus on doing more engineering. This is also true for hardware and software testing of motor control application, where we run certain tests after every software and hardware revision to make sure we did not break anything. We wish to automate this kind of regression testing. In this section, we will learn how to use Simulink Test, Simulink Real-Time, and Speedgoat hardware to automate real-time testing workflow.

You will learn to author test cases and validate test results against baseline criteria and complex logical and temporal requirements. To demonstrate this, let's imagine two test scenarios. In the first scenario, one of the hardware properties, such as friction or inertia, change due to unknown reasons. Since the source of the change is not in software logic, the only way to catch this is through hardware testing and compare the test results with baseline test data.

In the previous section, we performed a coastdown test to estimate rotor friction. We will use these test results as our baseline criteria. When we perform our regression test, if the difference in the rotor velocity during coastdown phase is larger than expected tolerance, we can say with a certain degree of confidence that something is not right and we should take a closer look.

The second test case is about over current detection. Since this feature is directly related to the safety of our hardware, we want to make sure we don't run into over current situation when we don't expect. And if there is a real over current event, we want to be 100% sure that not only our fault detection logic works but also the controller takes required action in time, for example, shutting down the inverter.

To set up the test automation environment, we will use Test Manager, a utility from Simulink Test which helps in creating, managing, and executing test cases and reviewing test results. We have created a test file, which includes our test cases under a container called Testsuite. Since our tests will execute on Speedgoat hardware, we have converted these test cases to a Real-Time test. This adds new fields, such as an option for loading Real-Time application and which Speedgoat target computer to use to run this test case.

Since the coastdown test is only five seconds long, we override the simulation settings for stop time to 5 seconds. We can either define test inputs manually here in the test case or use test scenarios defining the signal editor block inside the test harness model. Here we will select ClosedLoop_CoastdownTest. Next, we select the simulation outputs of our interest. Here, we will select rotor velocity, phase currents, and mode as simulation output.

To validate this test run, we need to define pass or fail criteria. Our goal is to compare this test run with one we used for motor parameter estimation in the previous section. If rotor velocity from this test run deviates beyond an acceptable tolerance, our estimation for friction coefficients may not be valid anymore. In such a scenario, we declare that the test run has failed. Here we will assign the absolute tolerance of three variants per second and a relative tolerance of 2%. This becomes our baseline criteria.

We have used logical and temporal assessment to detect an over current event. We will explore this feature more in the next test case. You can also use MATLAB functions to define custom criteria. Our second test case is designed to purposefully create an over current condition by commanding a large step change in rotor velocity and modifying a default value of saturation calibration. Here, in the assessment section, we have altered a temporal assessment from TriggerResponse pattern, for which we have an English-like readable description and visual representation.

Our assessment criteria reads as, at any point in time, if absolute value of phase current is higher than the current limits of five ampere, and stays higher for at least one millisecond, then starting from that point, with delay of at least two milliseconds, the mode signal should be Error.

Now let's run this test case. You can alter and execute multiple test cases for software in the loop, processing the loop, and Real-Time hardware in the loop modes. For Real-Time test cases, first the model is built and deployed onto the target computer. Then the Test Manager will start execution on target computer and collect all the test data and perform assessments.

Now, let's look at our test results. The first coastdown test case failed due to baseline condition. The deviation in rotor velocity is larger than the defined tolerance. This can lead us to further investigate the motor's behavior under normal conditions. Under logical and temporal assessment, we can see the test criteria passed, as no over current event occurred.

Our second test case passed. We can see phase current was higher than 5 amperes. That led to controller entering Error mode within two milliseconds before disabling the rotor. Looking at the assessment result, it gives detailed explanation with plots. We can save our test results for future reference and generate a PDF report to share with others in the team.

In this section, we learned to alter and execute Real-Time test cases and analyze test results all in a single environment. With Simulink Test, you can re-use your test cases created for desktop simulations and compare results against Real-Time experiments. This allows us to identify discrepancies early in the development phase. Using its integration with Simulink Real-Time, you can automate testing of controller performance, supervisory logic, and hardware IO functionalities.

I hope this short demonstration gave you confidence to automate your Real-Time testing and stay focused on solving key design issues. In this presentation, we did not get into the details of how PMSM or FOC algorithm works, and left out details about implementation on production intended hardware.

Let's review some of the resources, MathWorks and Speedgoat how to help you learn more about these topics. The Motor Control solution page on MathWorks website is a great place to start. It list all the resources, including a short video series on PMSM, induction motors, and FOC algorithms. There is even a short video on how reinforcement learning can be applied to this application area.

Starting from released 2020A, MathWorks launched a new product called Motor Control Blockset, which helps you design and implement motor control algorithms. It provides fully assembled reference applications and domain-specific algorithm blocks that generate target-optimized fast and will code. Additionally, it provides fully-instrumented models to estimate motor parameters and automatically tune controller parameters using FOC Autotuner block.

To learn more about Speedgoat's hardware solutions, we invite you to visit speedgoat.com. More specifically, explore their programmable FPGAs, which can help accelerate execution of controls over rhythms For example, you can deploy field-oriented control algorithms on Speedgoat FPGA to achieve sample rates even higher than 20 kilohertz. You can even deploy [? Simulink ?] plant models on FPGAs using MathWorks HDL coder to perform hardware-in-the-loop testing for power electronics applications.

And finally, to help you learn these tools, MathWorks and Speedgoat offer hands-on interactive training. We started this presentation with the goal of helping you get to the first milestone of spinning the motor as quickly as possible and make subsequent design iteration short and efficient.

In the first section, using just a few Simulink blocks and Speedgoat hardware, we spin a three-phase motor in open-loop control mode. Then we use this integrated, rapid control prototyping environment to design and test field-oriented control algorithms and supervisory logic in real-time. This interactive testing environment can be used to tune and calibrate controls parameters and debug logic while staying in Simulink environment.

Next, we learn how to gain insight from experimental data. The integration of Real-Time testing framework with MATLAB's data analysis capabilities help you better understand the system under test. And finally, we learn how to automate real-time testing using Simulink Test. This workflow is fully integrated with the model verification and validation workflow from MathWorks, resulting in a simplified tool chain.

We hope this presentation offered insight into rapid control prototyping of permanent magnet synchronous motors and how MathWorks and Speedgoat solutions help you make design iterations short and efficient.