Motor Control
This example shows how to develop a motor control application Texas Instruments™ C2000™ processors using Simulink®. The steps illustrated in this example, depicted as incremental model refinements, suggest an example workflow for designing and implementing a motor control application on an embedded platform. This example highlights advanced processor-specific capabilities of code generation software.
Optional hardware:
- Digital Motor Controller board: Spectrum Digital® DM550
- Three-phase permanent magnet motor(PMSM): Applied Motion® A0100-103-3-000
- Vector® CAN card and CAN cable
- Serial cable
- CAN/serial transceiver modules for F2812 eZdsp
Supported configuration:
- IDE/Tool chain: Texas Instruments™ Code Composer Studio™
- Boards: Spectrum Digital F2812 eZdsp™, F2808 eZdsp™, or F28335 eZdsp™
Recommended tutorials:
Contents
- Introduction
- Task 1 - Simulate Field Oriented Control (FOC) Algorithm
- Task 2 - Profile the Algorithm Execution Time
- Task 3 - Verify the Algorithm Implementation
- Configure PIL to Use Serial Communication Interface (SCI)
- Task 4 - Optimize Generated Code
- Task 5 - Simulate Plant-Controller Interaction
- Task 6 - Integrate Device Drivers
- Task 7 - Integrate the Algorithm with the Asynchronous Scheduler
- Task 8 - Monitor Target Signals Using SCI or CAN
- Task 9 - Monitor Target Signals Using External Mode
- Task 10 - Generate Standalone Code
- Summary
Introduction
This example suggests a development workflow for a motor control application. It is suggested that you complete the workflow examples provided by the IDE Link component before continuing with this example.
NOTE: Before continuing, verify that you have configured F2812 eZdsp, F2808 eZdsp or F28335 eZdsp board in the Code Composer Studio™ (CCS) Setup. If not, please go to CCS Setup and select one of these boards.
Task 1 - Simulate Field Oriented Control (FOC) Algorithm
In this task you will use the blocks from the C28x™ Digital Motor Control (DMC) library and the C28x™ IQMath library to create a Field Oriented Control algorithm suited for three-phase PMSM.
The inputs to the algorithm are simulated using Simulink source blocks. To represent the input signals in this algorithm, we use fixed-point variables with normalized format. For example, DMC blocks expect a position signal changing from 0 to 1 as the electrical angle of the system varies from 0 to 2*pi. Therefore, the position signal is a normalized conversion of the electrical angle that we are going to express using the Q17 fixed-point format. The Ia and Ib inputs in the Field Oriented Control model shown below represent the phase currents for phase A and B of the system. They are also represented in normalized fixed-point format, where 1 corresponds to the maximum current allowed per phase.
The algorithm outputs are voltages that should be applied to the PMSM, and are also expressed in normalized fixed-point format. These outputs usually feed the PWM blocks on the C2000 processor. Therefore, we will scale them to fit a range from 0% to 100% of PWM duty cycle.
1. Open the Field Oriented Motor Control template.
2. Open the C28x Digital Motor Control Library and drag the "Clarke transformation", "Park transformation", "Inverse Park Transformation", and "Space Vector Generator" blocks to your template model.
3. Connect the signal lines to the corresponding input and output ports of the blocks introduced in the model. If you prefer, use a pre-configured FOC model to execute this task.
4. Start the simulation by pressing the Run button of the Simulink model and observe the simulation results. Note that D-axis current becomes zero when the current Ia crosses the zero axis on its way down, when the position signal equals 0. This is the reference position. The current Ib is lagging the current Ia by 120 electrical degrees or by 1/3 of the normalized electrical angle. The voltage outputs are of the same amplitude as the current input in the normalized format.
5. You can now observe the effects of changing the simulation inputs on the controlled PMSM system. Increase the amplitudes of Ia and Ib to 1. Observe that this creates a Q-axis current of 1 and that the voltage outputs have the same amplitude. To create non-zero D-axis current, click the Ia block and change "Phase Offset" to 12500, then click the Ib block and change the "Phase Offset" to 12500-20000/3. The generated sine waves have 20000 samples per period. Advancing the phase of Ia and Ib by 2500 samples corresponds to 2*pi/8, or 1/8 of the per unit angle, which leads to a D-axis current with -amplitude*sqrt(2)/2 and a Q-axis current with amplitude*sqrt(2)/2.
Task 2 - Profile the Algorithm Execution Time
In this task, we will profile the real-time execution of the motor control algorithm created in Task 1. This will help us estimate the time needed to execute the control loop. Based upon the profiling results we will determine if the proposed design is feasible for the given application.
1. Open the Field Oriented Control Profiler Template Model.
2. Set the target hardware resources of the model to one of the supported configurations specified at the top of this example. For more information on setting the target hardware resources, see this section in the IDE Link documentation.
3. Open the Simulink Model Explorer by selecting "View" > "Model Explorer" (or by entering Ctrl+H). In Model Explorer, go to "Configuration" > "Solver" and set the "Fixed step Size" to 10 microseconds.
4. While in Model Explorer, open the "Simulation Configuration" > "Code Generation". In the "Coder Target" pane, select "Tool Chain Automation" tab and enable "Profile real-time execution".
5. Generate code by clicking the "Build Model" button on the toolbar of your model (Ctrl+B). Once code has been generated, let it run for a few seconds and then halt the execution on the C2000 processor from the CCS IDE. At the MATLAB® prompt enter: profile(CCS_Obj, 'execution', 'report').
6. Inspect the profiling report to see the execution time for the Field Oriented Control algorithm.
7. You can automate the profiling operation with a MATLAB script. This script can be run on the current active model.
Task 3 - Verify the Algorithm Implementation
After you have simulated the algorithm and have confirmed the correctness of the simulation results, you will want to verify the generated code. The processor-in-the loop (PIL) co-simulation feature can be invoked to automatically compare results of the generated code running on the embedded processor against the corresponding simulation results.
1. Open the Field Oriented Control PIL Template Model.
2. Open the Model Configuration Parameters dialog and select "Coder Target" under "Code Generation". Click "Target Hardware Resources" and set "IDE/Tool Chain" and the "Board" to match one of the supported configurations specified at the top of this example. Click OK.
If you use F28335 eZdsp board and CCS is set up as simulator, do following before going to step 3:
- Open the Model Configuration Parameters dialog and select "Coder Target" under "Code Generation". Next, click "Target Hardware Resources".
- Click on ".adc_cal" from "Compiler sections" on "Section" tab;
- Choose "ZONE7P" from "Placement";
- Click "OK".
3. Open the Simulink Model Explorer by selecting "View" > "Model Explorer" (or by entering Ctrl+H). In Model Explorer, go to "Configuration" > "Code Generation". Under the "Coder Target" pane, change the "Build Action" to "Create_Processor_In_the_Loop_project".
4. Generate code for the "Algorithm Subsystem" by right-clicking the "Algorithm Subsystem" and selecting "C/C++ Code" > "Build This Subsystem" > "Build". Once code has been generated in CCS, you should see a new "untitled" Simulink model with an automatically generated PIL block. Drag this block to your original model. Connect the signal lines to the corresponding input and output ports in the model.
5. Start the simulation by clicking the "Run" button on the Simulink model. Simulink will execute the generated code on the embedded processor and the algorithm simulation in synchronous fashion. Observe that the results are identical, verifying the generated code against the original simulation design.
Configure PIL to Use Serial Communication Interface (SCI)
This step uses the IDE debugger for communication between the top Simulink model and the compiled component executing on target hardware.
Depending on your execution platform, you may be able to use serial communication interface for PIL simulation. PIL simulation using serial communication interface is generally much faster than the PIL simulation using IDE debugger.
For steps to enable serial communication interface for PIL simulation, see Enabling Serial Communication PIL Simulation.
Task 4 - Optimize Generated Code
After you have confirmed the correctness of the generated code on the embedded processor you will optimize the generated code.
1. Optimize Code by Using Optimized Library Blocks
Open Field Oriented Control with inputs and profile the execution of this model using the steps in Task #2. Note that the execution is slower by a factor of 10 compared to the execution result obtained in Task #2. The only difference between the two models is that we added sine wave inputs. This is because the Simulink Sine Wave block generates ANSI® C code that is not optimized for the selected processor.
To generate more efficient code, replace the Sine Wave blocks with the optimized IQMath sine function blocks from the C28x IQmath Library. Open the Inputs Comparison Model and run the model in simulation to confirm that these source blocks are emitting signals comparable to the Sine Wave blocks.
Open Field Oriented Control with optimized inputs. Follow the steps described in Task #2 to profile the execution of this model. Note that the execution time is not much closer to the results obtained in Task #2.
2. Optimize Code by Using Compiler-Specific Intrinsics
Using compiler-specific intrinsics can improve the performance of the generated code even further. This is accomplished by replacing standard C constructs for certain fixed-point numerical operations with processor and compiler-specific instructions. You will use the Code Replacement Library (CRL) feature to specify the replacement scheme that matches your processor family. More information about CRL can be found in the CRL Help.
For this step, you will include PID controllers in the FOC algorithm. The DMC library provides an efficient PID controller. However, in this exercise we are going to create a PID controller using generic Simulink blocks.
Open the Field Oriented Control with PID controllers template.
Open the Simulink Model Explorer (Ctrl+H). Go to "Configuration" > "Code Generation". Under the "Interface" tab, change the Code Replacement Library to "TI C28x". When possible, this option replaces all generic fixed-point operations in Simulink with TI IQMath optimized functions.
Follow the steps described in Task #2 to profile the execution of this model. You can enable and disable CRL and compare the profiling results to measure the performance effect of these optimizations.
3. Optimize Code by Using Simulink® Coder™ Optimizations
Open the Simulink Model Explorer (Ctrl+H). Go to "Configuration" > "Optimization". Enable "Inline Parameters" to inline block parameters for increased efficiency.
4. Optimize Code by Using Compiler Optimizations
Texas Instruments C2000 compiler can apply various optimizations while compiling the generated code. This can lead to substantial execution performance gains. You can control the CCS compiler optimization flags from Simulink.
Task 5 - Simulate Plant-Controller Interaction
This step requires SimPowerSystems™.
In this task, you will validate your Field Oriented Control algorithm with closed-loop simulation using a motor model. The Id current request will be set to 0, while the Iq current request will come from the speed controller. The requested speed is fixed while external torque applied on the motor simulation varies with time.
1. Open the C2808 Field Oriented Motor Control Plant-Controller or the equivalent C2812 Field Oriented Motor Control Plant-Controller.
2. Start the simulation by pressing the "Run" button of the Simulink model.
Note that we have added a speed controller to the model.
Note that the outputs of the motor have been scaled to match the values that you will get from physical devices on the hardware. The following task describes how this scaling is being done.
Task 6 - Integrate Device Drivers
In this task, you will learn how to integrate device drivers in your models. You will get signals from physical peripherals, such as Quadrature Encoder Pulse (QEP) and the Analog-to-Digital Converter (ADC) available on the chip. You will also output Pulse Width Modulator (PWM) signals. The approach is slightly different between f2808/f28335 and f2812, accounting for differences in their respective peripherals.
f280x/f28x3x: Integrate device drivers in synchronous scheduling mode
1. Open the c280x/c28x3x Field Oriented Motor Control Synchronous Drivers Template Model.
2. Set the target hardware resources of the model to one of the supported configurations specified at the top of this example. For more information on setting the target hardware resources, see this section in the IDE Link documentation.
3. Open the C280x Chip Support Library or the equivalent C2833x Chip Support Library and drag the "ADC", "QEP", and "PWM" device driver blocks to your template model.
4. Set the device driver parameters according to the descriptions given in the "Device Driver Parameters" section below.
5. Connect the device driver blocks as shown in the Simulink diagram above.
6. If you prefer, you can use pre-configured models for F2808, or F28335 eZdsp.
f281x: Integrate device drivers in synchronous scheduling mode
1. Open the c2812 Field Oriented Motor Control Synchronous Drivers Template Model.
2. Set the target hardware resources of the model to one of the supported configurations specified at the top of this example. For more information on setting the target hardware resources, see this section in the IDE Link documentation.
3. Open the C281x Chip Support Library and drag the "ADC", "QEP", and "PWM" device driver blocks to your template model.
4. Set the device driver parameters according to the descriptions given in the "Device Driver Parameters" section below.
5. Connect the device driver blocks as shown in the Simulink diagram above.
6. If you prefer, you can use pre-configured models for F2812 eZdsp.
Device Driver Parameters
1. ADC
There are three signals we want to sample from the ADC, Ia and Ib coming from the current sensors on phase A and B of the motor and a third signal used as a speed request. These three signals are respectively connected to ADCINA0, ADCINA1 and ADCINA7.
Block Mask Settings:
Leave the settings on the "ADC Control" tab unchanged. On the "Input Channels" tab, set the number of inputs to 3 and select ADCINA0, ADCINA1 and ADCINA7 for conversion #1, #2, and #3. For more information on ADC block parameters, see c280x ADC or c281x ADC help. The ADC block outputs 12-bit conversion values.
The current sensors measure positive and negative values, calibrated so the 0 A mark corresponds to half the range of the ADC (2048 counts). 4095 counts represents the maximum current that can be measured. 0 counts represents the maximum negative current that can be measured.
An efficient way to scale these inputs is to shift the 12-bit ADC values for the current sensors by 6 bits to the left. The result is a normalized representation of the current in fixed-point Q17 format, where -1 is the maximum negative current and +1 is the maximum positive current. This operation is executed in the "Scaling" subsystem.
2. QEP
One way to get a position signal is to use an incremental encoder. You can use the QEP decoder to translate signals from the encoder into an angle value that can feed the FOC algorithm. This example shows how to decode signals coming from a 2000-slit optical encoder disk.
The FOC algorithm needs the absolute position of the rotor. To achieve this, the QEP index pulse is used to establish a reference position, and the QEP counter to find a position relative to the reference position. For start-up the strategy in this example uses a ramp signal generated for the position until the index pulse is hit. During that initialization period, the init_latch signal is set to 0 and a small amount of torque is applied to spin the shaft of the motor until the reference position is found. This operation is performed in "Scaling/CAP3INT1". This subsystem will also output the value of the counter saved on each hit of the index pulse. "Scaling/CAP3INT1/QEP_scaling" converts the counter value into a per-unit position signal, given the counter value of the last index pulse.
Block Mask Settings:
c281x QEP: Open the block's mask and set the sample time to 50 microseconds.
c280x/c28x3x eQEP: Open the block's mask and set the sample time to 50 microseconds.
c280x/c28x3x eQEP uses a 32-bit counter. To get the same behavior as the c2812, you can configure the counter to reset when it reaches 65535. You can also configure the block to outputs a latched value of the counter on every index pulse. To do these operations, open the eQEP block and:
On the "Position counter" tab of c280x/c28x3x eQEP:
- Set the "Maximum position counter value" to 65535 (2^16-1)
- Select the "Enable software initialization" and set the initialization value to 0
- Set the "Position counter rest mode" to "Reset on the maximum position"
- Select the "Output latch position counter on index event"
3. PWM
Using a PWM frequency close to the frequency used for the FOC algorithm, you will see in task #7 how to initiate the ADC conversion and the FOC algorithm based on a PWM event. It is desirable for the PWM frequency to be a multiple of the clock cycles by a power of 2 in order to switch from a per-unit signal to number of clock cycles with minimal processing.
Scaling
The output of the FOC is in Q17 fixed-point format. The range of the signal is therefore from -1 to 1. Adding 1 to this signal converts the range so it goes from 0 to 2. You only need to shift the integer value of this signal to match the PWM period and feed the compare value of the PWM block. If the PWM period is set to 2^12, a shift by 6 to the right is needed on the [0 - 2] Q17 FOC output signal to feed the PWM compare value. This operation is done in c2812_drivers/Motor Control Algorithm/PWM scaling and c2808_drivers/Motor Control Algorithm/PWM scaling.
Deadbands
You can use PWM deadband option to add timing protection between transitions of the upper and lower switches of the H bridge on the motor controller hardware.
Block Mask Settings:
c281x PWM:
- On the "Timer" tab, set the "Waveform period" to (2^12)+1
- Set the "Waveform type" to "Symmetric(Up-down)"
- Set the "Waveform period units" to "Clock cycles"
- On the "Outputs" tab, enable all PWM modules
- Set the respective Duty cycle sources to "input port"
- Set the "Duty cycle units" to "Clock cycles"
- On the "Logic" tab set control logic for PWMs
- Set PWM1, PWM3 and PWM5 Control Logic to "Active Low"
- Set PWM2, PWM4 and PWM6 Control Logic to "Active High"
- On the "Deadband" tab, set "Use deadband" for all modules
- On the "ADC Control" tab set "ADC start event" to Counter underflow.
c280x/28x3x PWM:
- On the "General" tab, set the "Timer initial period" to (2^12)+1
- Set the "Counting mode" to "Up-Down"
- On the "ePWMA" tab, set the "CMPA source" to "Input port"
- Set the "CMPA initial value" to 2^11
- Set the "Action when counter=CMPA on CAU" to "Clear"
- Set the "Action when counter=CMPA on CAD" to "Set"
- On the "Deadband unit" tab, select "Use deadband for ePWMxA" and "Use deadband for ePWMxB"
- Set the "Deadband polarity" to "AHC" (Active High Complementary)
- Set the "RED deadband period" to 15
- Set the "FED deadband period" to 15
Task 7 - Integrate the Algorithm with the Asynchronous Scheduler
This task shows you how to trigger the FOC algorithm off of a hardware interrupt. Specifically, it shows how to:
- Trigger the FOC algorithm in synchronization with PWM.
- Launch the ADC conversion outside PWM transitions.
- Launch the FOC algorithm when the ADC conversion completes.
This strategy insures that the ADC conversion is performed when PWM transitions are less likely. This minimizes impacts of the PWM switching on the ADC conversion results.
The FOC algorithm is triggered when the ADC finishes converting. This guarantees that the FOC algorithm starts with updated sensor values. The algorithm is synchronized with the PWM module so that the PWM compare values are updated at the right rate.
1. Open from the model constructed in task #6.
2. Put all the blocks except the "Edit Parameters" block in a "Function-Call Subsystem" that you can find in the Simulink browser under "Simulink > Ports & Subsystems".
3. The FOC algorithm is going to be triggered using the ADC interrupt. Drag the "Hardware Interrupt" block for your target board from the library.
For C281x, set the following Hardware Interrupt block mask parameters:
- PIE interrupt number to 1
- CPU interrupt number to 6
- Simulink task priority to 30
- Preemption flag to 0
For C280x/C28x3x, set the following Hardware Interrupt block mask parameters:
- PIE interrupt number to 1
- CPU interrupt number to 1
- Simulink task priority to 30
- Preemption flag to 0
4. Connect the Hardware interrupt output to the trigger input on the "Function-call Subsystem".
5. Open the "Function-call Subsystem"
On 2812, open the PWM block's mask and go to the "ADC Control" tab. Select "Counter underflow" for the ADC start event to launch the ADC conversion when the PWM counter is equal to 0.
On 2808/28335, open the first PWM block's mask and go to the "Event Trigger" tab. Select "Enable ADC start module A". The default settings for the other parameters trigger the ADC conversion every time the PWM counter reaches 0.
Open the ADC block's mask and set "Start of conversion" to "ePWMxA" (C2808/C28335) or EVA" (C2812).
6. If you prefer, use pre-configured models for F2808, F2812, or F28335 eZdsps.
Task 8 - Monitor Target Signals Using SCI or CAN
This task shows how to use SCI and CAN to monitor target signals. This task requires additional connections between the host and the target. For SCI, use a serial cable connected from the Target to the host via appropriate RS232 transceivers. For CAN, use a Vector® CAN card on the host with appropriate cables and transceivers to communicate to the target.
1. Open the 2808 Monitor Model / 28335 Monitor Model or the corresponding 2812 Monitor Model. The baud rate for CAN and SCI can be set in the Target Hardware Resources dialog.
2. Generate code for the model, provided that you have made the necessary hardware connections.
3. While the target model is running on the processor, open the CAN host model or the Serial host model. Start the simulation on the host models to monitor the target signals in real-time.
Task 9 - Monitor Target Signals Using External Mode
External Mode feature allows you to monitor model signals and tune model parameters in real-time directly from the Simulink model. In this task you will use External Mode to monitor position and knob signal data (POSITION_SIGNAL and KNOB_SIGNAL) coming from the code running on the target board. During code generation for this model an ASAP2 file is generated. The ASAP2 file contains symbol and memory address information that is used by External Mode.
This task requires extra connections between the host and the target board. You can use a variety of CAN interface cards for your host. You will also need appropriate cables and transceivers.
1. Open the 2808 External Mode Model, 28335 External Mode Model or the corresponding 2812 External Mode Model. The baud rate for CAN Calibration Protocol block can be set in the Model Configuration Parameters dialog under "Code Generation" > "Coder Target" > "Target Hardware Resources". Baud rates for host and target should be the same.
2. While opening the model, a script will be processed as a Pre-Load Function callback. This can be viewed by selecting "File" > "Model Properties" > "Model Properties" > "Callbacks" > "PreLoadFcn". The script is setting Simulink signals and parameters to define Simulink objects needed for CCP DAQ lists and Simulink tunable parameters as described in the CCP documentation. This is required to interact with these signals in real-time using CCP.
3. Double-click the convenience block "Switch External Mode Configuration", select the "Build an executable" option (default value) and click "OK".
4. Generate code by clicking "Build Model" button in your model (Ctrl+B). Make sure that you have the required hardware connections.
5. Double-click the convenience block Switch External Mode Configuration, select the "External mode" option and click OK.
6. Run the model in External Mode by selecting "Code" > "External Model Control Panel" > "Connect" or by clicking "Connect To Target" button on the Simulink toolbar.
7. You can view selected signals in the Simulink scopes while the application is executing on the target board.
Task 10 - Generate Standalone Code
This task shows how to use the on-chip flash memory to create a standalone program for production applications. First, configure the model to generate code that is targeted for flash memory. Then, configure the model to load application to flash memory as part of the build operation.
1. Using the model from the previous task, in the Target Hardware Resources dialog select the board representing your hardware that enables booting from the flash memory.
2. In the Target Hardware Resources dialog, on the "Peripheral" tab, go to "Flash_loader" and set "Enable Flash Programmer" to "Erase, Program, Verify". Make sure that the path specified in the "Specify API Location" edit box correctly points to your flash APIs location.
3. If you prefer, use pre-configured models for F2808, F2812, and F28335 eZdsps.
4. Build the model to generate code and download to flash memory.
Summary
This example showed a workflow to generate and verify code for a motor control application. It showed how to profile the generate code, run PIL simulation on the hardware, simulate the controller against a motor simulation, integrate peripherals, monitor target signals on host models and generate production code using the on-chip flash memory.