Texasinstrumentsc2000 Ug
Texasinstrumentsc2000 Ug
Texasinstrumentsc2000 Ug
R2019b
How to Contact MathWorks
Phone: 508-647-7000
v
Setting Up the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-32
Adding Blocks to the Model . . . . . . . . . . . . . . . . . . . . . . . . . 1-33
Generating Code from the Model . . . . . . . . . . . . . . . . . . . . . 1-35
vi Contents
Configure Model to Log Signals on SD Card . . . . . . . . . . . . . . . 2-7
To Workspace Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
Scope Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9
Outport Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12
Examples
4
ADC-PWM Synchronization Using ADC Interrupt . . . . . . . . . . . 4-2
vii
Parameter Tuning and Signal Logging with Serial
Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-60
viii Contents
1
Before you install the software, if you install the Texas Instruments (TI) Code Composer
Studio™ on Windows®, then, make sure that:
Using this installation process, you can download and install the following items on your
host computer:
1 On the MATLAB® Home tab, in the Environment section, select Add-Ons > Get
Hardware Support Packages.
1-2
Install Support for Texas Instruments C2000 Processors
2 In the Add-On Explorer window, click the support package and then click Install.
On the MATLAB Home tab, in the Environment section, select Help > Check for
Updates.
1 On the MATLAB Home tab, in the Environment section, click Add-Ons > Manage
Add-Ons.
2 In the Add-On Manager window, find and click the support package, and then click
Uninstall.
Hardware Setup
Hardware boards and devices supported by MathWorks® require additional configuration
and setup steps to connect to MATLAB and Simulink. Each support package provides a
hardware setup process that guides you through registering, configuring, and connecting
to your hardware board.
1-3
1 Working with Texas Instruments C2000 Processors
If the support package is already installed, you can start the hardware setup by opening
the Add-On Manager.
In the Add-On Manager, start the hardware setup process by clicking the Setup button,
After starting, the Hardware Setup window provides instructions for configuring the
support package to work with your hardware.
Follow the instructions on each page of the Hardware Setup window. When the hardware
setup process completes, you can open the examples to get familiar with the product and
its features.
Install the Code Composer Studio (CCS) version that supports your hardware board. For
example, install CCS v6 or later versions to work on Texas Instruments C2000 F2807x,
Texas Instruments C2000 F2837xD, and Texas Instruments C2000 F2837xS processors.
See Also
“Modeling”
1-4
Supported Texas Instruments C2000 Processors
1-5
1 Working with Texas Instruments C2000 Processors
See Also
“Install Support for Texas Instruments C2000 Processors” on page 1-2
1-6
Set Up Serial Communication with Target Hardware
There are different control card versions available for C2000 processors. In some control
cards, the SCI_A module pins are directly connected to the USB docking station. Some
other control cards have a MAX32xx chip for RS–232 communication on the control card.
These control cards have a ‘switch’ to connect or disconnect the Rx (Receive) line
between the USB docking station and the MAX32xx chip.
You can establish a serial communication with the target hardware using RS-232 or Serial
over USB as shown below.
1-7
1 Working with Texas Instruments C2000 Processors
Note To use a USB JTAG on the USB docking station that is connected to SCI_A, use the
switch to disconnect the Rx line that comes from the MAX3221 as it conflicts with the
data you send to SCI_A.
1-8
Set Up Serial Communication with Target Hardware
1-9
1 Working with Texas Instruments C2000 Processors
Follow these steps to set up CAN communication between the target hardware and your
host computer.
1 Make sure that the Vector Hardware is installed properly in the Windows Device
Manager.
2 Open the c28x_CAN_Tx model that sends message from the board to the host.
3 Select the target hardware that you are using. The model is set to use a CAN baud of
1Mbit/ sec; you can change the baud settings in the Target Preferences settings.
4 Use btest32.exe (Vector tool) on the host to receive the messages. ‘btest32.exe’
comes with the Vector drivers that you can find in the driver installation zip file from
vector.
Make sure that ‘btest32’ returns the message values with no errors.
5 Set the baud for btest32 as follows:
1-10
Set Up CAN Communication with Target Hardware
The CAN settings, connection, and the cable on the target are working properly.
6 Download and install the latest version of the Vector XL Library from the Vector
Web site. After installing the library, copy the file vxlapi64.dll from the installation
folder (for example C:\Softwares\Vector_Driver_Setup_9_3_0\Common) to the
windows root\system32 folder.
This folder name may vary depending on the Windows OS (for example C:\Windows
\Sys32).
7 Run the vcanconf.exe in the vector driver installation.
8 Right-click the application and select "Add application".
This baud has to match your Simulink model CAN baud that you can change
using the Target Preferences settings.
1-11
1 Working with Texas Instruments C2000 Processors
9 Open the CCP example model c28x_ccp_ert. Open the Configuration Parameters
dialog box to select the desired processor and verify the CAN baud. The default baud
is 1 Mbits/sec.
10 To run the model in External mode, click Run.
CAN communication is now set up between your host computer and the C2000 target
hardware. Click the Info button on the model to get help on this example.
1-12
Data Type Support
If you select int8 or uint8 in your model, your simulation runs with 8-bit data, but in the
generated code this data is represented as 16-bit. This may cause instances where data
overflow and wraparound occurs in the simulation, but not in the generated code.
For example, to make the overflow behavior of the simulation and generated code match
for a Simulink Add block in your model, select Saturate on integer overflow in that
block.
In C2000 devices, in the generated code, the double data type is represented as single
precision floating point values (32-bit). This representation results in a difference in data
values in the simulation and the generated code.
1-13
1 Working with Texas Instruments C2000 Processors
This execution scheduling model is not flexible enough for many systems, especially
control and communication systems, which must respond to external events in real time.
Such systems require the ability to handle various hardware interrupts in an
asynchronous fashion.
Embedded Coder software lets you model and generate code for such systems by creating
tasks driven by Hardware Interrupt blocks in addition to the tasks that are left to be
handled in the context of the timer interrupt.
The timer is configured so that the base rate sample time of the model corresponds to the
interrupt rate. The timer period and prescaler are calculated and set up to produce the
desired rate as follows:
The minimum achievable base rate sample time depends on the model complexity. The
maximum value depends on the maximum timer period value (232-1) and the CPU clock
speed .
If the blocks in the model inherit their sample time value, and a sample time is not
explicitly defined, the default value is 0.2 s.
The Event Managers and their general-purpose timers, which drive PWM waveform
generation use the high-speed peripheral clock (HISCLK). By default, this clock is
1-14
Scheduling and Timing
selected in Embedded Coder software. This clock is derived from the system clock
(SYSCLKOUT):
The high-speed peripheral prescaler is determined by the HSPCLK bits set in SysCtrl. The
default value of HSPCLK is 1, which corresponds to a high-speed peripheral prescaler
value of 2.
1-15
1 Working with Texas Instruments C2000 Processors
TMS320x281x DSP devices have four General Purpose (GP) timers. Each Event Manager
(EV) module includes two GP timers:
You can use the GP Timers independently or to operate peripherals associated with the
EV Manager, such as PWM, QEP, and CAP.
The following table describes the timer-peripheral mapping of the c281xlib block library.
Each PWM or QEP peripheral has access to only one timer, while each CAP peripheral has
access to two timers. In the PWM and QEP blocks, you can set the Module option to A or
B to determine which unique timer-peripheral combination the block configures. By
comparison, in the CAP block, you can use the Time base option to select one of two
timers for each CAP peripheral.
1-16
Sharing General Purpose Timers Between C281x Peripherals
The PWM, QEP, CAP, and Timer blocks each provide independent access to key timer
registers. If the blocks in your model share a specific GP timer, check that the timer-
related settings are compatible. If the peripheral settings for a shared timer are not
compatible, the software generates an error when you update the model or generate
code.
The model contains Timer and CAP blocks that both use Timer 1 (GP Timer 1).
1-17
1 Working with Texas Instruments C2000 Processors
1-18
Sharing General Purpose Timers Between C281x Peripherals
Both blocks have the same values for Timer prescaler and Counting mode. However,
each block has different values for Timer period. The value of Timer period for Timer 1
is 65535 in the CAP block and 10000 in the Timer block.
1-19
1 Working with Texas Instruments C2000 Processors
Since both blocks configure the same timer, and settings conflict, the software generates
an error when you update the model.
1-20
Sharing General Purpose Timers Between C281x Peripherals
The model contains QEP and CAP blocks that both use Timer 2. In the CAP block, the
Time base option shows which timer the block uses. In the QEP block, setting Module to
A configures the block to use QEP1–QEP2. GP Timer Use for C281x Peripheral Blocks
shows that QEP1–QEP2 use Timer 2.
1-21
1 Working with Texas Instruments C2000 Processors
1-22
Sharing General Purpose Timers Between C281x Peripherals
Currently, both blocks define different clock sources for Timer 2. The CAP block uses
Internal as a Clock source. The QEP block, which does not have a configurable Clock
source setting, uses the QEP circuit as a clock source. If you build the model, the
software generates the following error message.
To avoid generating errors when you build the model, change Clock source in the CAP
block to QEP device.
1-23
1 Working with Texas Instruments C2000 Processors
• The libraries in the c2000lib block library (for handling input and output
functions for on your target hardware)
• Simulink Coder™ software
• Discrete time blocks from Simulink
• Another blockset that meets your needs and operates in the discrete time domain
When you are creating a custom device driver block using S-function, use the
MATLAB_MEX_FILE macro to differentiate between simulation and code generation
behaviors. For example, when you include the Texas Instruments header file in the
1-24
Overview of Creating Models for C2000 Processors
generated code for creating the MEX file, use the #else section to avoid compilation
errors, as shown:
#ifdef MATLAB_MEX_FILE /*
/* Simulation behavior */
#else
/* Code generation behavior*/
#endif
During the build operation, the Texas Instruments cross-compiler builds an executable file
from the generated code. If you select the Build, load and run option in
Hardware Implementation > Target Hardware Resources > Build options
> Build action parameter then the generated executable is automatically
downloaded to the target. For CCS v5 and the later versions, a CCS project file is also
generated during the build process. You can use this project file for debugging in the CCS
IDE.
1-25
1 Working with Texas Instruments C2000 Processors
1 Install the TI C2000 support package and complete the additional setup tasks
mentioned in “Install Support for Texas Instruments C2000 Processors” on page 1-2 .
2 Open the model c28x_LedBlink_ert.slx.
This model is configured for a default target hardware (TI Piccolo F28035). To select
a different target hardware, go to Configuration Parameters > Hardware
Implementation > Hardware board.
3 If you select a different processor, make sure to replace the GPIO blocks and the
GPIO pins connected to the LED with the GPIO blocks of the selected processor.
1-26
Creating CCS Project from a Model
4 By default, the model is configured with the Texas Instruments Code Composer
Studio (C2000) toolchain to build, load, and run.
1-27
1 Working with Texas Instruments C2000 Processors
5 Click Build Model to build, load, and run the program and to create the CCS project.
6 Click ‘View Diagnostics’ to open the Diagnostic Viewer.
7 Under the Code Composer Studio Project section in the Diagnostic Viewer, click the
link 'Open Project in Code Composer Studio'.
1-28
Creating CCS Project from a Model
The Code Composer Studio IDE launches with the generated project.
8 Open the 'Project Explorer' from View tab in CCS.
9 Right-click the Target Configuration File (.ccxml) and click 'Set as Active Target
Configuration'.
10 On Project Explorer pane, right-click the project in CCS and click 'Build Project' to
start the build process.
Make sure that the target hardware is connected to the host computer.
11 Click Run in CCS and click Debug (F11) to start the debug session.
1-29
1 Working with Texas Instruments C2000 Processors
12 Click the Play icon in the Debug mode to execute the code on the target hardware.
Note
• CCS project creation feature is not supported with CCS v3.3 and CCS v4.
• For CCS v5, the compiler and linker settings are not reflected in the CCS GUI, even
though these flags are visible in the ‘Summary of flags set’ section. However, these
flags are considered while building the CCS project.
• Compiler tools that are installed outside the CCS Installation directory are not
detected automatically. Add the Code generation tool path manually from the CCS GUI
path:
Window > Preferences > Code Composer Studio> Build > Compilers > Tool Discovery.
• You can open only one instance of CCS at a time. To open a new project in CCS, use
the ‘Restart CCS’ option in the MATLAB prompt that shows while clicking the
diagnostic Viewer link. The current instance is closed and a fresh instance of CCS with
the new project is opened.
1-30
Apply the c2000lib Blockset
Introduction
This section uses an example to show how to create a Simulink model that uses
Embedded Coder Support Package for Texas Instruments C2000 Processors blocks to
target your board. The example creates a model that performs PWM duty cycle control
via pulse width change. It uses the C2812 ADC block to sample an analog voltage and the
C2812 PWM block to generate a pulse waveform. The analog voltage controls the duty
cycle of the PWM and you can observe the duty cycle change on the oscilloscope.
Hardware Setup
The following hardware is required for this example:
1 Connect the function generator output to the ADC input ADCINA0 on the eZdsp
F2812.
2 Connect the output of PWM1 on the eZdsp F2812 to the analog input of the
oscilloscope.
3 Connect VREFLO to AGND on the eZdsp F2812. See the section on the Analog
Interface in Chapter 2 of the eZdsp F2812 Technical Reference, available from the
Spectrum Digital website at https://c2000.spectrumdigital.com/ezf2812/
1-31
1 Working with Texas Instruments C2000 Processors
c2000lib
This command opens the c2000lib library blockset, which contains libraries of blocks
designed for targeting your board.
1 In the Simulink Editor of your model, select Simulation > Model Configuration
Parameters > Hardware Implementation.
2 Select a TI C2000 Hardware board. The Texas Instruments Code Composer
Studio (c2000) option automatically gets selected for Toolchain.
1-32
Apply the c2000lib Blockset
Note The generated code does not honor Simulink ‘stop time’ from the simulation. The
‘stop time’ is interpreted as inf. To implement a stop in the generated code, you must put
a Stop Simulation block in your model.
1-33
1 Working with Texas Instruments C2000 Processors
1-34
Apply the c2000lib Blockset
There are three ways to start the automatic code generation process:
•
In the Simulink Editor, click Build Model or Deploy to Hardware .
• On your model, press Ctrl+B.
• Press the Build button on the Code Generation pane of the Configuration Parameters
dialog box.
1-35
1 Working with Texas Instruments C2000 Processors
To set the Bitrate for a block whose bitrate cannot be set directly:
For example, the Target Hardware Resources tab for the F2812 eZdsp shown in the
following figure.
1-36
Configuring Timing Parameters for CAN Blocks
1-37
1 Working with Texas Instruments C2000 Processors
The following sections describe the series of steps and rules that govern the process of
setting these timing parameters.
To determine the values for the timing parameters, complete the following steps:
• CAN module clock = 100 MHz for the F2808 (Same as SYSCLKOUT)
• CAN module clock = 150 MHz for the F2812 (Same as SYSCLKOUT)
• CAN module clock = 75 MHz for the F28x3x (150 SYSCLKOUT/2)
1-38
Configuring Timing Parameters for CAN Blocks
The following illustration shows the relationship between the eCAN bit timing
parameters.
1-39
1 Working with Texas Instruments C2000 Processors
Assume that CAN Module Clock Frequency = 75 MHz, and a Bitrate of 1 Mbits/s is
required.
1 Set the BRP to 5. Then substitute the values of CAN Module Clock Frequency, BRP,
and Bitrate into the following equation, solving for BitTime:
The following table provides example values for several bit rates when CAN Module Clock
Frequency = 75 MHz, as it is with the F28335. Other combinations of the register values
are possible.
The following table provides example values for several bit rates when CAN Module Clock
Frequency = 100 MHz, as it is with the F2808. Other combinations of the register values
are possible.
1-40
Configuring Timing Parameters for CAN Blocks
The following table provides example values for several bit rates when CAN Module Clock
Frequency = 150 MHz, as it is with the F2812. Other combinations of the register values
are possible.
1-41
1 Working with Texas Instruments C2000 Processors
1-42
Configuring Acquisition Window Width for ADC Blocks
Ideally, when the measurement window is opened, the actual signal coming in would be
measured perfectly. In reality the signal does not reach its full magnitude immediately.
The measurement process can be modeled by a circuit similar to the one shown in the
following figure for the ADC found on the F2812 eZdsp,
1-43
1 Working with Texas Instruments C2000 Processors
Acquisition
Actual Signal Window
Width
Because the signal acquisition is not instantaneous, it is very important to set a wide
enough acquisition window to allow the signal to ramp up to full strength before the
measurement is taken. If the window is too narrow, the measurement is taken before the
signal has reached its full magnitude, resulting in erroneous data. If the window is too
wide, the source signal itself may change, and the sampling may be too infrequent to
reflect the actual value, also resulting in erroneous data. You must calculate the width of
the acquisition window based on the circuit characteristics of resistance and capacitance
of your specific circuit. Then, using the ADC parameters described in the following
section, you can configure the acquisition window width.
The ADC parameters can be set from the Peripherals tab of the Target hardware
resources tab.
• You can set ACQ_PS — Acquisition Prescaler — to a value from 0 to 15. To obtain the
actual value, increment the setting by 1. This increment produces an actual range
from 1 to 16.
• You can set ADCLKPS — AD Clock Prescaler — to a value from 0 to 15. To obtain the
actual value, increment the setting by 1. This increment produces an actual range
from 1 to 16.
• You can set CPS — Clock Prescaler — to a value from 0 to 1. To obtain the actual
value, increment the setting by 1. This increment produces an actual range from 1 to
2.
1-44
Configuring Acquisition Window Width for ADC Blocks
These three prescalers serve to reduce the speed of the clock and to set the acquisition
window width. The following diagram shows how these prescalers are used.
1-45
1 Working with Texas Instruments C2000 Processors
ADCLKPS CPS
1 - 16
(4 bit clock ACQ_PS
divider) CPS
ADCCLK -
HISPCLK this is the
(high speed CPS - ADC clock
peripheral further reduces signal
clock) ADCLKPS - the clock
reduces the frequency by a
incoming clock factor of 1 or 2 ACQ_PS -
frequency by a Acquisition
factor of 1 to 16 Prescaler -
indicates Sample
how many Hold
ADCCLK clock
ticks will pulse
comprise
the window
In the preceding diagram, the high-speed peripheral clock frequency is received and then
divided by the ADCLKPS. The reduced clock frequency is then further divided by CPS.
The resulting frequency is the ADCCLK signal. The value of ACQ_PS then determines
how many ADCCLK ticks comprise one S/H (sample and hold) period, or in other words,
the length of the acquisition window.
The following examples show how you can use ADC parameters to configure the
acquisition window width:
Example 1:
If the HISPCLK = 30 MHz, and ADCLKPS=1 (which is a value of 2), the result is 15 MHz.
If ACQ_PS = 0 (which is a value of 1), then the sample/hold period is 1 ADCCLK tick,
or .1333 microseconds.
Example 2:
1-46
Configuring Acquisition Window Width for ADC Blocks
If the HISPCLK = 30 MHz, and ADCLKPS=1 (which is a value of 2), the result is 15 MHz.
If ACQ_PS = 15 (which is a value of 16), then the sample/hold period is 16 ADCCLK ticks,
or 2.1333 microseconds.
Note HISPCLK is set automatically for the user, and it is not possible to change the rate.
For more information, see “High-Speed Peripheral Clock” on page 1-14
1-47
1 Working with Texas Instruments C2000 Processors
In this section...
“Monitor and Tune over Serial Communication” on page 1-48
“Monitor and Tune over CCP” on page 1-51
With Monitor & Tune (External Mode), you can log signals and tune parameters while
the model is running on the target hardware in real time. When you change parameter
values from within Simulink, the modified parameter values are communicated to the
target hardware immediately. Also, you can monitor the effects of the parameters tuning
activity by viewing the algorithm signals on the scopes.
You can run your model on the external mode via two communication interfaces, serial or
CAN.
For external mode with serial communication, you have a ready-to-use COM port on the
USB drive if your target hardware supports it or the COM1 port on your computer with
RS–232 cable. For more information on how to set up serial communication, see “Set Up
Serial Communication with Target Hardware” on page 1-7. You can configure the external
mode for different baud rates that your communication interface supports.
To run your model in external mode with CAN Calibration Protocol(CCP), use the CAN
Calibration Protocol block and a Vector CAN case hardware. External mode uses the
eCAN module to run external mode. You can configure the external mode with any
available eCAN module. For more information, see “Set Up CAN Communication with
Target Hardware” on page 1-10. You can configure the baud for eCAN.
The external mode with ‘ert.tlc’ downloads the executable, runs the model, and
establishes external mode connection in a single step.
1-48
Parameter Tuning and Signal Logging over Serial Communication
In this method, you will setup Serial communication between Simulink and Texas
Instruments C2000 board to tune the parameters and monitor the signal of an
algorithm running on the board.
• External Mode over Universal Measurement and Calibration (XCP)
Simulink provides these additional features for the targets that support XCP:
• Dashboard objects such as Slider and Dashboard Scope. For more information, see
Dashboard (Simulink)
• Simulation Data Inspector (SDI) for visualizing the logged signals. For more
information, see Simulation Data Inspector (SDI)
• Running External mode over XCP has a few limitations. For a detailed list, see
External Mode Simulation with XCP Communication(Simulink Coder)
Based on the maximum and the minimum baud that the SCI_A module supports, you can
run your model in external mode over different baud rates.
For the COM port on your computer, select Start > Control Panel > Device
Manager > Ports (COM & LPT)
1-49
1 Working with Texas Instruments C2000 Processors
6 Make sure that the Verbose check box is selected to view the external mode
execution progress and updates in the Diagnostic Viewer or in the Command Window.
7 To execute your model with a specific baud:
Under Target Hardware Resources, select the SCI_A pane and then specify the
desired baud in Desired baud rate in bits/sec parameter.
The default baud is 115200 bits/sec. For better performance, you may increase the
baud to a value that your hardware board permits.
Your model is now ready to perform Monitor and Tune action (External Mode) over serial
communication.
1-50
Parameter Tuning and Signal Logging over Serial Communication
For more information, see “Parameter Tuning and Signal Logging with Serial
Communication”
Note
• For targets with small RAM such as F28027, the code has to be booted from flash. To
boot the code from flash, select TI Piccolo F2802x (boot from flash) in Hardware
Implementation > Hardware board drop-down list
• Parameter tuning and signal logging for 8-bit data type is not supported in external
mode over serial
The external mode is supported using the CAN Calibration Protocol block and ASAP2
interface. The ASAP2 interface is used to get information about where a parameter or
signal exists in the target memory. The CAN Calibration Protocol block is used to
communicate with the target, download parameter updates, and upload signal
information.
To prepare your model for external mode over CCP, perform these tasks:
1-51
1 Working with Texas Instruments C2000 Processors
1 To set up external mode, see “Set Up Your Model for External Mode” on page 1-52.
2 To run your model in external mode with ert.tlc, see “Monitor and Tune Your Model
(External Mode)” on page 1-53.
3 To tune your parameters, see “Tuning Parameters” on page 1-55.
1 Add a CCP driver block to your model from the Simulink Block Library.
2 Identify signals that you want to tune. Associate them with Simulink.Parameter or
canlib.Parameter objects with ExportedGlobal storage class. Set the data type
and value of the object. See “Using Supported Objects and Data Types” on page 1-
54.
3 Identify signals you want to log. Associate them with canlib.Signal objects. Set
the data type of the canlib.Signal. See “Using Supported Objects and Data Types”
on page 1-54.
For information about visualizing logged signal data, see “Viewing and Storing Signal
Data” on page 1-55.
4 Load the Simulink.Parameter or canlib.Parameter and canlib.Signal data
objects into the base workspace.
5 Select Simulation > Model Configuration Parameters.
6 In the Configuration Parameters dialog box, select Optimization > Signals and
Parameters pane.
7 Select Default parameter behavior > Inlined and click Configure.
8 In the Model Parameter Configuration dialog box that opens, define the (global)
tunable parameters for your models.
9 In the Configuration Parameters dialog box, select Code Generation > Interface
pane.
1-52
Parameter Tuning and Signal Logging over Serial Communication
For external mode, the host-side CAN connection must use the 'MATLAB 1' application
channel. To configure the application channel that the Vector CAN drivers use, in the
Command Window:
TargetsComms_VectorApplicationChannel.configureApplicationChannels
If you try to connect using an application channel other than 'MATLAB 1', you see the
following warning:
Warning:
It was not possible to connect to the target using CCP.
An error occurred when issuing the CONNECT command.
If you have not already installed the Vector CAN drivers, you get the following error
message in the command window:
??? Error using ==>
TargetsComms_VectorApplicationChannel.TargetsComms_VectorApplicationChannel>
TargetsComms_VectorApplicationChannel.configureApplicationChannels at 40
1-53
1 Working with Texas Instruments C2000 Processors
If you want to use CAN to transmit or receive CAN messages between your host PC and
your target, you need VN1600 supported by the Vector CAN Driver Library. Choose the
driver libraries to support profiling, downloading, and external mode. Make sure that the
library, vcand32.dll, is placed in the Windows system32 folder.
• uint8, int8
• uint16, int16
• uint32, int32
• single
Define data objects for the signals and parameters of interest for ASAP 2 file generation.
For ease of use, create a MATLAB file to define the data objects so that you only have to
set up the objects only once.
stepSize = Simulink.Parameter;
stepSize.DataType = 'uint8';
stepSize.CoderInfo.StorageClass = 'ExportedGlobal';
stepSize.Value = 1;
2 Associate the signals that you want to log with canlib.Signal objects.Set the data type
of the canlib.Signal. The following code example shows how to declare such a
canlib.Signal object for logging.
1-54
Parameter Tuning and Signal Logging over Serial Communication
counter = canlib.Signal;
counter.DataType = 'uint8';
3 Associate the data objects that you defined in the MATLAB file with parameters or
signals in the model. For the previous code examples, you can set the Constant
value in a Source block to stepSize, and set a Signal name to counter in the
Signal Properties dialog box. stepSize and counter are the data objects defined in
the code.
Tuning Parameters
1 In the workspace, set dataobject.value while the model is running in external
mode. For example, to tune the parameter stepSize (that is, to change its value)
from 1 to 2, at the command line, enter:
stepSize.value = 2
Value: 2
CoderInfo: [1×1 Simulink.CoderInfo]
Description: ''
DataType: 'uint8'
Min: []
Max: []
Unit: ''
Complexity: 'real'
Dimensions: [1 1]
2 Update the model (press Ctrl+D) to apply the changed parameter.
To view the logged signals, attach a supported scope type to the signal.
1-55
1 Working with Texas Instruments C2000 Processors
Storing signal data for further analysis. You can further analyze the logged data in
MATLAB.
1 To use the data archiving in external mode, in the External Mode Control Panel, click
Data Archiving.
1-56
Parameter Tuning and Signal Logging over Serial Communication
a In the Enable Data Archiving dialog box, select the check box Enable archiving.
b Edit the Directory and File fields. Review the other settings.
c Click Apply and close the dialog box.
2 Open the Scope parameters by clicking the scope parameters icon in the scope
window toolbar.
1-57
1 Working with Texas Instruments C2000 Processors
3 In the Variable name field, edit the variable name. The data that is displayed in the
scope at the end of the external mode session is available in the workspace with this
variable name.
The data that was previously displayed in the scope is stored in .mat files.
For example, at the end of an external mode session, the following variable and files
are available in the workspace and the current folder:
ScopeData5
ScopeData5 =
1-58
See Also
ExternalMode_0.mat
ExternalMode_2.mat
ExternalMode_1.mat
Limitations
Only the following kinds of scopes are supported with external mode logging:
Before connecting to external mode, right-click the signal and select Signal
Properties. In the dialog box, select the Test point check box, and click OK.
See Also
“Parameter Tuning and Signal Logging with Serial Communication”
1-59
1 Working with Texas Instruments C2000 Processors
Before you generate ASAP2 files with Embedded Coder software, see “Generating an
ASAP2 File” in the Simulink Coder help. The help describes how to define the signal and
parameter information required by the ASAP2 file generation process.
The build process creates an ASAM-compliant ASAP2 data definition file for the generated
C code.
• The standard ASAP2 file generation does not include the memory address attributes in
the generated file. Instead, it leaves a placeholder that you must replace with the
actual address by postprocessing the generated file.
• The map file options in the project template has to be set up a certain way for this
procedure to work. If you have created your own project templates, and you do not
have the correct settings, you see the following instructions:
Warning: It was not possible to do ASAP2 processing on your
.map file.This is because your IDE project template is not
configured to generate a .map file in the correct format.
To generate a .map file in the correct format you need to
setup the following options in your IDE project template:
Generate section map should be checked on
1-60
CAN Calibration Protocol with Third Party Tools
1-61
1 Working with Texas Instruments C2000 Processors
Introduction
Note Implementation of this library for the TI C28x processor produces the same
simulation and code-generation output as the TI version of this library, but it does not use
a global Q value, as does the TI version. The Q format is dynamically adjusted based on
the Q format of the input data.
The IQmath Library blocks generally input and output fixed-point data types and use
numbers in Q format. The C28x IQmath Library block reference pages discuss the data
types accepted and produced by each block in the library. For more information, consult
the “Fixed-Point Numbers” on page 1-63 and “Q Format Notation” on page 1-65 topics,
as well as the Fixed-Point Designer™ product documentation, which includes more
information on fixed-point data types, scaling, and precision issues.
You can use IQmath Library blocks with some core Simulink blocks and Fixed-Point
Designer blocks to run simulations in Simulink models before generating code. Once you
develop your model, you can generate equivalent code that is optimized to run on a TI
C28x DSP. During code generation, a call is made to the IQmath Library for each IQmath
1-62
Using the IQmath Library
Library block in your model to create target-optimized code. To learn more about creating
models that include IQmath Library blocks and blocks from other blocksets, consult
“Building Models” on page 1-68.
Common Characteristics
To learn more about characteristics particular to each block in the library, see the
individual block reference pages.
References
For detailed information on the IQmath library, see the user guide for the C28x IQmath
Library - A Virtual Floating Point Engine, Literature Number SPRC087, available at the
Texas Instruments website. The user guide is included in the zip file download that also
contains the IQmath library (registration required).
Fixed-Point Numbers
• “Notation” on page 1-63
• “Signed Fixed-Point Numbers” on page 1-64
• “Q Format Notation” on page 1-65
Notation
In digital hardware, numbers are stored in binary words. A binary word is a fixed-length
sequence of binary digits (1s and 0s). How hardware components or software functions
interpret this sequence of 1s and 0s is defined by the data type.
Binary numbers are used to represent either fixed-point or floating-point data types. A
fixed-point data type is characterized by the word size in bits, the binary point, and
whether it is signed or unsigned. The position of the binary point is the means by which
fixed-point values are scaled and interpreted.
1-63
1 Working with Texas Instruments C2000 Processors
where
Note For Embedded Coder, the results of fixed-point and integer operations in
MATLAB/Simulink match the results on the hardware target down to the least
significant bit (bit-trueness). The results of floating-point operations in MATLAB/
Simulink do not match those on the hardware target, because the libraries used by the
third-party compiler may be different from those used by MATLAB/Simulink.
Signed binary fixed-point numbers are typically represented in one of three ways:
• Sign/magnitude
• One's complement
• Two's complement
Two's complement is the most common representation of signed fixed-point numbers and
is used by TI digital signal processors.
1-64
Using the IQmath Library
Q Format Notation
The position of the binary point in a fixed-point number determines how you interpret the
scaling of the number. When it performs basic arithmetic such as addition or subtraction,
hardware uses the same logic circuits regardless of the value of the scale factor. In
essence, the logic circuits do not have knowledge of a binary point. They perform signed
or unsigned integer arithmetic — as if the binary point is to the right of b0. Therefore, you
determine the binary point.
In the IQmath Library, the position of the binary point in the signed, fixed-point data types
is expressed in and designated by Q format notation. This fixed-point notation takes the
form
Qm.n
where
In Q format, the most significant bit is designated as the sign bit. Representing a signed
fixed-point data type in Q format requires m+n+1 bits to account for the sign.
Note The range and resolution varies for different Q formats. For specific details, see
Section 3.2 in the Texas Instruments C28x Foundation Software, IQmath Library Module
User's Guide.
When converting from Q format to floating-point format, the accuracy of the conversion
depends on the values and formats of the numbers. For example, for single-precision
floating-point numbers that use 24 bits, the resolution of the corresponding 32-bit number
cannot be achieved. The 24-bit number approximates its value by truncating the lower
end. For example:
32-bit integer 11110000 11001100 10101010 00001111
Single-precision float +1.1110000 11001100 10101010 x 231
Corresponding value 11110000 11001100 10101010 00000000
1-65
1 Working with Texas Instruments C2000 Processors
For example, a signed 16-bit number with n = 15 bits to the right of the binary point is
expressed as
Q0.15
Q.15
sfrac16
or
sfix16_En15
[16 15]
Multiplying two Q0.15 numbers yields a product that is a signed 32-bit data type with n =
30 bits to the right of the binary point. One bit is the designated sign bit, thereby forcing
m to be 1:
Q1.30
sfix32_En30
[32 30]
1-66
Using the IQmath Library
Consider a signed 16-bit number with a scaling of 2(-17). This requires n = 17 bits to the
right of the binary point, meaning that the most significant bit is a sign-extended bit.
Sign extension fills additional bits with the value of the MSB. For example, consider a 4-
bit two's complement number 1011. When this number is extended to 7 bits with sign
extension, the number becomes 1111101 and the value of the number remains the same.
Q-2.17
sfix16_En17
[16 17]
Consider a signed 16-bit number with a scaling of 2^(2) or 4. This means that the binary
point is implied to be 2 bits to the right of the 16 bits, or that there are n = -2 bits to the
right of the binary point. One bit must be the sign bit, thereby forcing m to be 17:
m+n+1 = 17+(-2)+1 = 16
Q17.-2
sfix16_E2
[16 -2]
1-67
1 Working with Texas Instruments C2000 Processors
Building Models
• “Overview” on page 1-68
• “Converting Data Types” on page 1-68
• “Using Sources and Sinks” on page 1-68
• “Choosing Blocks to Optimize Code” on page 1-68
• “Double and Single-Precision Parameter Values” on page 1-69
Overview
You can use IQmath Library blocks in models along with certain core Simulink, Fixed-
Point Designer, and other blockset blocks. This section discusses issues you should
consider when building a model with blocks from these different libraries.
It is vital to make sure that blocks you connect in a model have compatible input and
output data types. In most cases, IQmath Library blocks handle only a limited number of
specific data types. You can refer to the block reference page for a discussion of the data
types that the block accepts and produces.
When you connect IQmath Library blocks and Fixed-Point Designer blocks, you often need
to set the data type and scaling in the block parameters of the Fixed-Point Designer block
to match the data type of the IQmath Library block. Many Fixed-Point Designer blocks
allow you to set their data type and scaling through inheritance from the driving block, or
through backpropagation from the next block. This can be a good way to set the data type
of a Fixed-Point Designer block to match a connected IQmath Library block.
Some DSP System Toolbox blocks and core Simulink blocks also accept fixed-point data
types. Choose the right settings in these blocks' parameters when you connect them to an
IQmath Library block.
The IQmath Library does not include source or sink blocks. Use source or sink blocks
from the core Simulink library or Fixed-Point Designer in your models with
IQmath Library blocks.
In some cases, blocks that perform similar functions appear in more than one blockset.
For example, the IQmath Library and Fixed-Point Designer software have a Multiply
1-68
Using the IQmath Library
block. When you are building a model to run on C2000 DSP, choosing the block from the
IQmath Library yields better optimized code. You can use a similar block from another
library if it gives you functionality that the IQmath Library block does not support, but
you will generate code that is less optimized.
When you enter double-precision floating-point values for parameters in the IQ Math
blocks, the software converts them to single-precision values that are compatible with the
behavior on c28x processor. For example, with the Ramp Generator block, the software
converts the value of the Maximum step angle parameter to a single-precision value.
1-69
1 Working with Texas Instruments C2000 Processors
Overview
The LIN communications architecture supports a single master node and up to 16 slave
nodes on a LIN network.
LIN nodes use message frames to exchange data. The message has two parts:
• Add a LIN Transmit block to the model. This block enables the Master to generate
message headers.
• To send data, set the ID input and Tx ID Mask input to make Tx ID Match happen on
this node.
1-70
Configuring LIN Communications
• To receive data, place LIN Receive block in the model. Set the Rx ID Mask input to
make Rx ID Match happen on this node.
For example, to configure a model with a master node that receives data from a slave
node:
• Add a LIN Transmit block and a LIN Receive block to the model.
• In the Target Hardware Resources tab, configure the ID Slave Task Byte.
• For the LIN Transmit block, set the ID input.
• For the LIN Receive block, set the Rx ID Mask input so that: Rx ID Mask = ID XOR
Slave Task ID Byte.
• To send data, place LIN Transmit block in the model. Set the ID input to match the
LIN frame header issued by the remote Master. Set Tx ID Mask to make a Tx ID
Match happen on this node.
• To receive data, place LIN Receive block in the model. Set the Rx ID Mask input to
make an Rx ID Match happen on this node.
For example, to configure a model with a slave node that transmits data to a master node:
Set the Data type and Data length values in your LIN Receive blocks to match the type
and length of the transmitted data. These values enable the receive block reconstruct the
data from the message frames.
Note The LIN Transmit block inherits the data type and length from its input.
1-71
1 Working with Texas Instruments C2000 Processors
1-72
2
• Scope
• To Workspace
• Outport
This topic is for Embedded Coder Support Package for Texas Instruments C2000
Processors. This uses Embedded Coder
Without MAT-file logging on SD card, you can only log and analyze the data on the target
hardware through External mode or by sending the signal to a computer (using Serial)
and storing it in MATLAB. These mechanisms need an active connection between a
computer and the target hardware when logging data. With SD card logging, you can log
data without any need to connect the target hardware to a computer. Other advantages of
logging data to SD card over other mechanisms are:
2-2
See Also
Note
• The SD card should be formatted with FAT32 format to support the logging from
C2000 processors.
• MAT-File Logging on SD Card does not support PIL (Processor in the loop) Mode
simulation.
• SD card logging does not support F2802x and F281x processors.
Before you start to save the signals from Simulink models on an SD card, complete the
steps listed in “Prerequisites for Logging Signals” on page 2-4.
1 “Configure Board Parameters and Enable MAT-File Logging” on page 2-5: To save
MAT-files on an SD card, the MAT-file logging option in the Configuration
Parameters dialog box must be selected. Also, the target hardware parameters must
be specified.
2 “Configure Model to Log Signals on SD Card” on page 2-7: SD card logging is
supported in models containing To Workspace, Scope, or Outport blocks. You must
specify the values for several block parameters.
3 “Run Model on Target Hardware” on page 2-17: Simulink deploys code and logs
signals on the SD card. These signals are saved as MAT-files on the target hardware.
4 “Import MAT-Files into MATLAB” on page 2-18: After logging is complete, you can
open MAT-files in MATLAB and use them for further analysis.
See Also
Related Examples
• “MAT-file Logging on SD Card for Texas Instruments C2000 Processors” on page 4-
112
• “Memory and Signal Logging limitations on SD Card” on page 3-2
2-3
2 MAT-File Logging on SD Card
Scope block
Outport block
2-4
Configure Board Parameters and Enable MAT-File Logging
1 In your model window, open the Configuration Parameters dialog box, go to the
Hardware Implementation pane, and select the name of the target hardware from
the Hardware board list.
2 In the Hardware board settings pane, expand Target hardware resources and
select SD card logging.
3 Select Enable MAT-file logging on SD card option.
Note
• For C2000 hardware boards, it is advisable to limit the data points for the signals
to be logged as C2000 hardware boards have limited memory. In case of memory
allocation failure, set *Limit data points to last* to lesser than |512| value.
• For F2803x, F2805x, F2833x, F280x and Concerto(35x and 36x) processors, select
*Save format* as |Array| to avoid memory overflow.
4 From the SPI module list, select the desired SPI module.
• Inherit from SPI settings - Inherits the value from the Desired baud rate in
bits/sec set in the corresponding SPI_x pane.
• Maximum achievable supported by the inserted SD Card - The baud rate for
SPI interface is automatically selected based on the SD card inserted on the
C2000 hardware. In this case, the Desired baud rate in bits/sec set in the
corresponding SPI_x pane is overwritten.
6 Click Apply. Click OK to save your changes.
2-5
2 MAT-File Logging on SD Card
See Also
Related Examples
• “Memory and Signal Logging limitations on SD Card” on page 3-2
2-6
Configure Model to Log Signals on SD Card
To configure a Simulink model to run on the target hardware, perform these steps:
1 On the Modeling tab, in the Simulate section, set the Stop Time. The signals are
logged for the time period specified in the Stop Time parameter. The default value is
Inf. Enter time in seconds to log signals for that time period.
2 In the Simulink model, set the parameter values of To Workspace, Scope, and Outport
blocks.
To Workspace Block
To set the parameter values of the To Workspace block:
1 Double-click the block, and specify these parameters in the Block Parameter dialog
box.
Parameter Description
Variable name Specify a variable name for the logged
data.
Limit data points to last Specify the number of data points to be
logged in the MAT-file. The maximum
number of data points that a MAT-file
can contain is 512.
2-7
2 MAT-File Logging on SD Card
Parameter Description
Decimation Use this parameter for the block to
write data points at every nth sample,
where n is the decimation factor. The
default decimation, 1, writes data at
every time sample.
2-8
Configure Model to Log Signals on SD Card
Scope Block
To set the parameter values of the Scope block:
2-9
2 MAT-File Logging on SD Card
Parameter Description
Limit data points to last Specify the number of data points to be
logged in the MAT-file. The maximum
number of data points that a MAT-file
can contain is 512.
Decimation Use this parameter for the block to
write data points at every nth sample,
where n is the decimation factor. The
default decimation, 1, writes data at
every time sample.
2-10
Configure Model to Log Signals on SD Card
Parameter Description
Save format Select a format of the variable to which
you save data. SD card logging
supports only these three formats:
Array, Structure with Time, or
Structure.
2-11
2 MAT-File Logging on SD Card
Outport Block
To set the parameter values of the Outport block:
1 Double-click the block, select the Signal Attributes tab, and specify the Sample
time parameter. When you specify this parameter as –1, the sample time is inherited
from the driving block.
2-12
Configure Model to Log Signals on SD Card
2 In the model window, open the Configuration Parameters dialog box and select
Data Import/Export.
2-13
2 MAT-File Logging on SD Card
Parameter Description
Time Saves time data to the specified
variable.
Output Saves signal data to the specified
variable.
2-14
Configure Model to Log Signals on SD Card
Parameter Description
Format Select a format of the variable to which
you save data. SD card logging
supports only these three formats:
Array, Structure with Time, or
Structure.
2-15
2 MAT-File Logging on SD Card
See Also
Related Examples
• “MAT-file Logging on SD Card for Texas Instruments C2000 Processors” on page 4-
112
• “Memory and Signal Logging limitations on SD Card” on page 3-2
2-16
Run Model on Target Hardware
To deploy the code on the target hardware, in the model window, go to Hardware tab. In
the Deploy section, click the Build Deploy & Start button. The lower left corner of the
model window displays status while Simulink prepares, downloads, and runs the model on
the target hardware. Wait for the logging to stop.
Note After the Simulation stop time elapses, the logging of signal stops. However, the
model continues to run. For example, if the Simulation stop time parameter is specified
as 10.0 seconds, the logging stops after 10.0 seconds. However, the model continues to
run for an indefinite time. If the Simulation stop time parameter is specified as Inf, the
logging continues until the SD card memory is full, or you remove the SD card from the
target hardware.
2-17
2 MAT-File Logging on SD Card
In C2000, remove the SD Card from the board, connect it to a computer and read
the .mat files from the explorer.
Suppose that the name of the model is sdcard. In the first run, Simulink creates
sdcard_1_1.mat file and starts logging data in this file. After the logging in the first file
is completed, Simulink creates sdcard_1_2.mat file and continues logging data in this
file. Likewise, the logging continues in mutiple MAT-files until the Simulation stop time
is elapsed. If the same model is run again, the new files are named as sdcard_2_1.mat,
sdcard_2_2.mat, and so on.
• The total file size exceeds the available SD card storage capacity.
• The signal logging rate is faster than the SD card writing speed.
2-18
See Also
See Also
Related Examples
• “MAT-file Logging on SD Card for Texas Instruments C2000 Processors” on page 4-
112
• “Memory and Signal Logging limitations on SD Card” on page 3-2
2-19
3
• Select lower value for Limit data points to last . Lower value can result in
smaller static memory allocation
Code memory allocation fails when the SD Card feature and the algorithm together is
generating code bigger than the allocated code memory. This can happen for the
processors with low RAM memory like F280x, F2803x, F2805x, F2833x and Concerto
(35x and 36x).
SD Card Logging Connection Limitation: SD card logging uses SPI (Serial Peripheral
Interface) to send the data between processor and memory. The data logging will be
affected based on the SPI connections and SPI parameter settings. Very few control cards
offer dedicated SD card logging slots (like F2837xD) to place the SD card. You have to use
external SD card module to log data for other control card.
If the signals are not logging on SD card, try the following steps:
3-2
See Also
See Also
“MAT-file Logging on SD Card for Texas Instruments C2000 Processors” on page 4-112
3-3
4
Examples
<xi:include href="urn:mathworks:ex:texasinstrumentsc2000/PFCMultiAxisKitExample.xml" xm
<xi:fallback><!-- Fallback for texasinstrumentsc2000/PFCMultiAxisKitExample --><link xm
</xi:include>
4 Examples
Required Hardware
Hardware Connections
Connect the function generator output to the ADC input (ADCINA0) on the board.
Connect the GPIO pin corresponding to PWM1A to the analog input of the oscilloscope.
Available Models
These are the Simulink models available for different C2000 processors:
Note: To use the F28M35x/F28M36x controlCARD, you need Embedded Coder® Support
Package for Texas Instruments C2000™ F28M3x Concerto™ Processors.
Model
4-2
ADC-PWM Synchronization Using ADC Interrupt
The analog voltage from the function generator controls the duty cycle of the PWM
waveform. Duty cycle changes can be observed on the oscilloscope. The Hardware
Interrupt block triggers an interrupt service routine (ISR) and schedules the execution of
the connected subsystem (ADC-PWM Subsystem) when the processor receives the ADC
interrupt (ADCINT).
The ADC-PWM Subsystem consists of an ADC block that drives the duty cycle input port
of the PWM block. The PWM block is configured to trigger the start of conversion (SOC)
of the ADC block.
1 Open the model corresponding to the target hardware you are using. Each model is
configured for a default target hardware. To select a different target hardware,
browse to Configuration Parameters > Hardware Implementation > Hardware
board.
2 On the Hardware tab, Click Build, Deploy & Start > Build Stand-Alone to
generate, build, load, and run the program.
4-3
4 Examples
More About
• C281x ADC
• C281x PWM
• C280x/C2802x/C2803x/C2805x/C2806x/C2833x/C2834x/F28M3x/F2807x/F2837xD/
F2837xS/F2838x/F28004x ePWM
• C2802x/C2803x/C2805x/C2806x/F28M3x/F2807x/F2837xD/F2837xS/F2838x/F28004x
ADC
• C28x Hardware Interrupt
4-4
LIN-Based Control of PWM Duty Cycle
Required Hardware
Available Models
Example Model
This example model runs a single LIN node in loopback mode. The Read Duty Cycle
subsystem passes the duty cycle values to the LIN Transmit block. The LIN Transmit
block transmits the values to the LIN Receive block, which sends them to the ePWM
Output block. The Verify Data block compares the original duty cycle values with the
values from the LIN Receive block. If the values do not match, the Data Non-Match LD3
block flashes the LD3 LED on the C28035 controlCARD. In addition, a LIN_STAT signal is
attached to the Status output from the LIN Receive block. To know the LIN
4-5
4 Examples
communication status, you can check the LIN_STAT variable in the generated code
running in Texas Instruments Code Composer Studio™.
The duty cycle of the generated pulse waveform is determined by the relative ratio of the
received pulse width value and the pulse period, which is fixed at 64,000 clock cycles. The
duty cycle toggles between 25%, 50%, and 75% based on the selection.
PWM duty cycle can be changed by double-clicking the Read Duty Cycle subsystem and
selecting either 25%, 50%, or 75% value from the window that opens up.
Hardware Connections
Connect the output of PWM1 on the board to the analog input of the oscilloscope.
The LIN module is set to work in loopback mode. No external LIN hardware is needed
because the LIN TX/RX signals are emulated in the software.
• Use the same ID Mask as input for both LIN TX ID Mask and RX ID Mask.
• Use LIN ID to make (LIN ID XOR ID Mask) == ID-Slave Task Byte.
For information about how to setup the LIN peripheral, see “Configuring LIN
Communications” on page 1-70.
1 Open the model, double-click the Duty Cycle block, and select a new duty cycle
value.
2 In the Configuration Parameters window, click Hardware Implementation and
go to Target hardware resources > External mode and set the Serial port
parameter to the COM port at Device Manager > Ports (COM & LTP) in Windows.
For more information, see
4-6
LIN-Based Control of PWM Duty Cycle
More About
4-7
4 Examples
Asynchronous Scheduling
This example shows how to use the Texas Instruments™ c28x peripherals and Hardware
Interrupt blocks to control the real-time execution of Simulink® function-call subsystems
in an asynchronous fashion.
Required Hardware
Available Models
These are the Simulink models available for different C2000 processors:
Note: To use the F28M35x/F28M36x controlCARD, you need Embedded Coder® Support
Package for Texas Instruments C2000™ F28M3x Concerto™ Processors.
4-8
Asynchronous Scheduling
Example Model
The EV Timer or ePWM blocks are used to configure the timer interrupts. The timer
interrupts are triggered based on the timer period, and the eCAN message receive
interrupt is triggered when a message is received. The Hardware Interrupt block triggers
the interrupt service routines (ISR) for the timer interrupts as well as for the eCAN
message receive interrupt. The ISRs in turn call the function-call subsystems connected
to the Hardware Interrupt block output ports.
The outputs of the first two subsystems are free-running counters. The sum of the
counters is used to control the duty cycle of PWMB for F2812 or ePWM2 for F2808/
F28335. The PWM waveform duty cycle increases linearly from 0 to 100%. The third
4-9
4 Examples
subsystem contains an eCAN Receive block whose message output controls the duty cycle
of the PWM block (PWMA for F2812 or ePWM1 for F2808/F28335). The duty cycle varies
from 0 to 100% because the eCAN messages are received from the eCAN Transmit block.
Note: The Self-Test mode of eCAN_A is enabled to connect the eCAN_A transmitter and
receiver internally to avoid external connection between the transmitter and the receiver.
For disabling the Self-Test mode of eCAN_A, the transmitter and the receiver must be
connected together externally.
To configure, build, and deploy the application that corresponds to your Simulink model:
1 Open the model corresponding to your target hardware. Each model is configured for
a default target hardware. To select a different target hardware, browse to
Configuration Parameters > Hardware Implementation > Hardware board.
2 Go to Target hardware resources > eCAN_A, select Self-Test Mode, and click OK.
3 On the Hardware tab, Click Build, Deploy & Start > Build Stand-Alone to
generate, build, load, and run the program.
4 Observe the changes of the PWM waveform on the oscilloscope.
More About
• C280x/C2802x/C2803x/C2805x/C2806x/C2833x/C2834x/F28M3x/F2807x/F2837xD/
F2837xS/F2838x/F28004x ePWM
• C28x eCAN Transmit
4-10
Using CAN Calibration Protocol for Monitoring and Tuning
Required Hardware
• Vector-Informatik CAN hardware and drivers must be installed on your host computer,
and the baud rate must be set to 1 MBd to match the processor CAN configurations.
For more information, see “Set Up CAN Communication with Target Hardware” on
page 1-10.
• Spectrum Digital F2812/F2808/F28335 eZdsp board or F2808/F28035/F28044/
F28069/F28335 controlCARD with Peripheral Explorer kit.
Available Models
These are the Simulink models available for different C2000 processors:
• The example model c28x_ccp_ert.slx can be used for Texas Instruments™ Piccolo
F2803x/F2806x, F28x3x, F280x, F281x, F2807x, F2837x, and F28004x target
hardware. By default, the F28335 target hardware is selected.
• To change the target hardware, browse to Configuration Parameters > Hardware
Implementation > Hardware board.
4-11
4 Examples
Example Model
During code generation, an ASAP2 file is generated. The ASAP2 file contains symbol and
memory address information. Either External mode or a third-party calibration tool can
4-12
Using CAN Calibration Protocol for Monitoring and Tuning
use the generated ASAP2 file to log the signals and update the parameters on the real-
time application generated for the model.
The c2000_ccp_data.m callback sets the Simulink® signals and parameters, thereby
resolving the Simulink objects needed for the CCP DAQ lists and Simulink tunable
parameters. Now, you can monitor the model signals and tune parameter values in real-
time using CCP.
4-13
4 Examples
4-14
Using CAN Calibration Protocol for Monitoring and Tuning
4-15
4 Examples
The model c28x_ccp_ert.slx contains a variety of signals and parameters that can be
logged or changed in real-time on the target hardware. Parameter tuning and signal
logging are enabled by the CCP block included in the model. Additionally, when the model
is built, it must be configured to generate an ASAP2 file. The ASAP2 file contains
information about the signals and parameters that are available for logging or tuning in
the real-time application.
The model contains a simple counter with parameterized step size, STEP_PARAM.
STEP_PARAM takes advantage of a custom storage class package labeled
tic2000demospkg to load the parameters on the flash memory and run them from the
RAM for calibration using the ramfuncs section available in the memory map.
For this example, a custom storage class package labeled tic2000demospkg has been
created. Run cscdesigner -advanced tic2000demospkg to view the definition of the
tic2000demospkg package.
This model can be run from the flash memory (standalone) and also from the RAM. In
both cases, STEP_PARAM is stored in the ramfuncs section. You can update the parameter
4-16
Using CAN Calibration Protocol for Monitoring and Tuning
STEP_PARAM and log the output of the counter, COUNTER_SIGNAL. Additional signals
available for logging are SINE_SIGNAL, PULSE_SIGNAL, and the RANDOMx signals.
As an alternative to Monitor and Tune, you can use a third-party calibration tool for
signal logging and parameter tuning. The same signals and parameters that are available
with External mode may be logged or updated using the third-party calibration tool. While
using a third-party calibration tool, ensure that the tool is set in compliance with the word
addressable nature of the Texas Instruments C2000 processors (16-bit addressable).
More About
4-17
4 Examples
Required Hardware
Note: The characteristics of the power supply and the amplifier must be the same as the
input characteristics of the selected motor.
Available Models
Model
The following figure shows the Permanent Magnet Synchronous Motor Field-Oriented
Control example model.
4-18
Simulation of FOC Using PMSM Model
The c2812 peripheral and DMC library blocks are used to control the speed and torque of
a three-phase Permanent Magnet Synchronous Machine from SimPowerSystems in a
speed-controlled closed-loop fashion using the field-oriented control technique.
To set up the Permanent Magnet Synchronous Machine, double-click the block and
specify the parameters to match your hardware configuration. For more information on
setting up the Permanent Magnet Synchronous Machine, see the SimPowerSystems
documentation.
External torque can be added to the simulation to reproduce the mechanical action on the
shaft of the motor. A default torque is applied at the beginning of the simulation and is
4-19
4 Examples
reversed after 3 seconds of simulation. The controller model executes a speed controller
algorithm and reacts to the torque changes to maintain the desired speed. You can
achieve optimal results by tuning the PID controllers on the Embedded Controller side to
suit the motor.
The following figure shows the speed of the PID controller in the speed controller
subsystem. The desired speed is filtered and ramps up to a defined speed value. This
value stays constant until the end of the simulation. At the beginning of the simulation,
torque is applied on the shaft so that the motor spins by itself in one direction until
enough opposite torque is accumulated in the controller to regulate the speed to the
desired value. At time = 3 seconds, a different value of external torque is applied on the
shaft of the motor, forcing the controller to change its output to maintain the desired
speed.
4-20
Simulation of FOC Using PMSM Model
To generate code for the Embedded Controller, delete the Plant Model and the Input
Parameters blocks and press Ctrl+B.
Connect the motor to the DM550 Digital Motor Controller and the eZdsp board to the
DM550 Digital Motor Controller, using the standard cables. Follow the instructions given
4-21
4 Examples
by the controller vendor. By default, the model is set up for motors with the following
characteristics:
Change the model parameters to suit the motor. Match the voltage and power
characteristics of the motor with the controller parameters. Use the Edit Parameters
button to change the model parameters of the motor.
The motor is driven by the conventional voltage-source inverter. The controller algorithm
generates six pulse width modulation (PWM) signals using vector PWM technique for six
power switching devices. Two input currents of the motor (ia and ib) are measured from
the inverter and sent to the processor through two analog-to-digital converters (ADCs).
More About
4-22
Permanent Magnet Synchronous Motor Field-Oriented Control
Required Hardware
DM550 Configuration
DRV8312 Configuration
• TI Dual Motor Control and PFC Developer's kit TMDS2MTRPFCKIT with F28035
• 2 Three-phase PMSM, one with optional Hall sensors attached to connector J4 of the
DRV8402-based Dual-Axis DMC EVM (TMDS2MTRPFCKIT)
• TI High Voltage Motor Control and PFC Developer's kit TMDSHVMTRPFCKIT with
F28035
• Three-phase PMSM with optional Hall sensors attached to connector H1 of the High
Voltage Motor Control Kit (TMDSHVMTRPFCKIT)
4-23
4 Examples
Note: Match the characteristics of the power supply and the amplifier with the input
characteristics of the selected motor.
Available Models
The following are the example models available for different driver-controller
combinations:
4-24
Permanent Magnet Synchronous Motor Field-Oriented Control
Note: In LaunchXL F28379D (Version 2.0), the ADC offset for Ia and Ib measurements are
different from the earlier boards. Open the model "c28379Dpmsmfocdual_cpu1_ert.slx",
"c28379Dpmsmfocdual_cpu2_ert.slx" and change the postion of the manual switch
appropriately, depending on the version of the board. To change the manual switch
setting in your model, browse to FOC Alogrithm Motor > Torque Control Algorithm
> Input Scaling. It is recommended to calibrate the ADC offset, because the ADC offset
varies for different boards.
Model
4-25
4 Examples
The algorithm in this example uses an asynchronous scheduling. The pulse width
modulation (PWM) block triggers the ADC conversion. At the end of conversion, the ADC
posts an interrupt that triggers the main FOC algorithm.
The example models named *pmsmfocflash.slx, place the code in the flash memory
section of the processor, allowing the application to run in a stand-alone fashion.
The model is set up for motors that have the following characteristics:
4-26
Permanent Magnet Synchronous Motor Field-Oriented Control
DM550 configuration
• 4 pole pairs
• 2000 slits/mechanical revolution
• Encoder index offset: 1850
DRV8312 Configuration
• 4 pole pairs
• Sensorless using sliding mode observer (SMO)
• 3 Hall sensors attached to connector J10 of the DRV8312EVM (optional)
• 4 pole pairs
• Sensorless using sliding mode observer (SMO)
• 3 Hall sensors attached to connector J4 of the Dual-Axis DMC EVM (optional)
• 4 pole pairs
• Sensorless using sliding mode observer (SMO)
• 3 Hall sensors attached to connector H1 of the High Voltage Motor Control Kit
(optional)
• 4 pole pairs
• Sensorless using sliding mode observer (SMO)
You may need to change the model parameters to fit your specific motor. Match motor
voltage and power characteristics to the controller.
4-27
4 Examples
If you select the flash version, you must do the appropriate jumper settings on the eZdsp
boards. Default jumper settings are set to execute the code from RAM, (refer to the eZdsp
Technical Reference for more information).
If you are using F28379D Launchpad, you must build and download CPU1 and CPU2
models to respective cores of the processor. Each core controls one motor on the dual
motor control kit. Two cores communicate each other using IPC. CPU1 model sends Load
Torque request to CPU2. CPU2 sends data to be logged to CPU1. For more information
about IPC communication, see “Inter-Processor Communication Using IPC Blocks”.
High power must be applied to the Inverter before running the program. Stopping the
program in the middle of its execution with high power on can damage the hardware. Use
"Reset" to stop the execution of the program.
In this example, we are using a 2000 slit encoder with a four pole pair motor. The encoder
has 2 channels (QEPA and QEPB) and an index pulse (QEPI).
The timer driven by the QEP increments by 4 for each slit as shown in the following
figure.
4-28
Permanent Magnet Synchronous Motor Field-Oriented Control
The 4-pole pair motor in this example produces: * 8000 counts per mechanical * 2000
counts per electrical revolution
The following figure shows an A-N back EMF waveform and the position of the encoder
index pulse relative to the back EMF of the motor. The neutral point is obtained by
connecting a star resistor network on the 3 legs of the motor.
Spin the motor externally to get B-N 120° out of phase on the right-hand side of A-N on
the oscilloscope (Figure 4). Make sure that the counter driven by the encoder is
increasing while spinning in this direction. The reference position of the encoder is when
4-29
4 Examples
A-N crosses the 0V axis on its way up. Measure the time from that point to the next
encoder index pulse on the right-hand side and convert that time into number of counts.
Put the result in the "index offset" parameter of "Edit Parameters" block in the model.
4-30
Permanent Magnet Synchronous Motor Field-Oriented Control
The following picture shows the position of the B-N waveform compared to A-N:
4-31
4 Examples
4-32
Permanent Magnet Synchronous Motor Field-Oriented Control
Model Calibration Using DRV8312EVM, Dual-Axis DMC EVM, and High Voltage
Motor Control Kit
The "Position Sensing Switch" in the model allows you to select sensorless position
sensing or position sensing using Hall sensors. In case of sensorless (default), no
calibration is needed. If using Hall sensors for position sensing, Hall sensors have to be
connected to J10 of the DRV8312EVM board, J4 of the Dual-Axis DMC EVM or H1 for the
High Voltage Kit. The model concatenates the three Hall signals into a variable with
Hall_A being the Least Significant Bit (LSB) and Hall_C being the Most Significant bit
(MSB) of the variable.
The "Speed Request Switch" allows you to select the source of the speed request. By
default the speed will come from a normalized constant setting the speed request to half
the acceptable speed range (0.5). For the DRV8312EVM, you can also select the speed
request to come from potentiometer R66.
4-33
4 Examples
This section is not relevant if using sensor-less control. The model is configured with one
interrupt for each Hall signal. In each Hall interrupt, there are four meaningful Hall
values. Any other Hall value indicates a hardware problem. The Hall value read in a
particular interrupt holds information about the motor's direction of rotation. For
example, in Hall_A interrupt, reading a Hall value of 2 indicates that the motor is spinning
in direction 0 and a falling edge has just occurred. If the model detects a direction
change, it invalidates the direction and speed of the motor. For the speed to be valid, the
model requires two consecutive edges with the same direction. Otherwise, the model sets
a flag to invalidate the speed.
4-34
Permanent Magnet Synchronous Motor Field-Oriented Control
• New_direction = Hall_direction
• New_valid_flag = Previous_direction == Hall_direction;
• Global_speed_and_direction_ready_flag = New_valid_flag && Old_valid_flag;
The Field Oriented Control algorithm takes a position signal from 0 to 1 reflecting an
electrical revolution. If the speed signal is valid, the model performs a linear extrapolation
from the Hall reading and accurately estimates the position.
The Hall decoder will be referenced (position = 0) when Hall_A is rising in direction 0. A
Hall_position_offset variable is used to inform the FOC algorithm of the position
difference between the Hall reference and the back EMF waveforms of the motor. Like
the QEP example, this value has to be calibrated by comparing the Hall signals with the
back EMF waveforms of the motor. In the DRV8312 example, Hall_position_offset is
normalized on the electrical revolution and is set to 0.57, to match the characteristics of
the motors included in the DRV8312EVM and Dual-Axis DMC EVM kits.
For the Dual-Axis DMC EVM kit, c28035pmsmfocdual.slx controls 2 motors from the same
F28035 processor. Motor2 can use position sensing coming from Hall sensors attached to
J4 of the Dual-Axis DMC EVM.
Evaluation boards often provide serial over USB connections allowing fast serial
transfers. The models running on the LaunchPads, are sending Ia and Ib currents over
serial. Use c2000_host_read.slx to receive these signals on your host computer. For
F28379D Launchpad example use c2000_host_read_F28379D.slx Select the appropriate
COM port matching your board in the following blocks:
4-35
4 Examples
Run the c2000_host_read model and observe the current signals updated at 20 kHz on the
time scope. You can use the same technique to monitor other signals on other processors.
Keep in mind that SCI_A is usually connected to the FTDI chip allowing serial transfers
over USB on Launchpads, docking stations and ISO control cards. The FTDI FT2232D
allows one way transfers up to 1.5 Mbps while the FTDI FT2232H allows one way
transfers up to 6 Mbps.
4-36
Using the Control Law Accelerator (CLA)
Required Hardware:
The following figure shows an example model configured to use the CLA available on the
hardware.
4-37
4 Examples
This model generates code for a Simulink model where one part of the algorithm runs on
the Control Law Accelerator (CLA) available on the device. The CLA is a co-processor that
allows parallel processing. Utilizing the CLA for time-critical tasks frees up the main CPU
to perform other system and communication functions concurrently.
The following section shows how to trigger a CLA task, exchange data from the C28x CPU
to the CLA using memory sections like CpuToCla1MsgRAM and Cla1ToCpuMsgRAM,
schedule C28x interrupts at the end of the CLA task, and replace the standard linker
command file to include CLA specific linking attributes.
In the c28069blink_cla.slx model, a CLA Task block is provided to trigger a CLA task. This
block runs the downstream function-call subsystem on the CLA. On the CLA Task block
4-38
Using the Control Law Accelerator (CLA)
mask, you can specify the CLA task number and the associated interrupt triggering
source. Ensure that you are using the CLA Trigger block from the library matching the
hardware board selected in the Configuration Parameters. CLA task trigger source
options are different for different processors. The downstream function-call subsystem is
executed using the selected CLA Task when the selected interrupt triggers. In this
example, CLA Task1 is used and "Software" is selected as the trigger source, which
means that the CLA task is triggered at the sample rate provided in the sample time
parameter.
For the CLA task subsystem, select the "Function packaging" as "Inline" under the "Code
Generation" tab of the Block Parameters. To open the Block Parameters, right-click on the
CLA subsystem and select "Block Parameters(Subsystem)".
4-39
4 Examples
For F28035 and F28069 processors, a specific linker command file has to be selected to
assign CLA memory sections. In the Model Configuration Parameters, under Hardware
Implementation > Target hardware resources > Build options, "Use custom linker
command file" is selected and the pre-configured "c28069_cla.cmd" is used as linker
4-40
Using the Control Law Accelerator (CLA)
command file. This file adds CLA memory sections description and can be found in the
"src" directory at the root of the support package installation.
A CLA interrupt is generated when the CLA Task completes. CLA Task1 interrupt (CPU =
11, PIE = 1-8) is used as the interrupt source on the C28x Hardware Interrupt block. The
function-call subsystem 'System executes at completion of CLA Task1' is executed when
the interrupt occurs. GPIO pin 34 (connected to the LED on control cards; for LaunchPad
boards the GPIO pin number is different) toggles on every occurrence of the CLA Task1
interrupt.
All the interfaces between CLA and CPU need to be placed in specific memory sections.
To gain specific access to these sections, custom storage classes CpuToCla1MsgRAM and
Cla1ToCpuMsgRAM are defined in the dataclass package tic2000demospkg.
4-41
4 Examples
4-42
Using the Control Law Accelerator (CLA)
All discrete state variables used inside CLA function-call subsystems must be stored in
Cla1DataRam. For example, delay blocks and integrators must be set to use the
Cla1DataRam storage class for state variables. See the 'State Attributes' of the Delay
block inside cla_subsystem for an example.
4-43
4 Examples
Avoid the creation of sub-functions provided on atomic subsystems inside CLA function-
call subsystems as this creates nested functions that are not supported on the CLA.
The specificity of the CLA may require more operations on the model or may prevent the
use of Simulink features. Make sure to go through the list of limitations provided in the
CLA C compiler documentation. Make sure to use the features of Embedded Coder to
restrict the generated code in the limited syntax supported by the CLA C compiler.
The debug function /*__mdebugstop()*/ is present at the beginning of the CLA task
(__interrupt void Cla1Task1 ( void )) in the generated cla_task.cla file.
• The data transfer is not atomic. For example, data transfers where the data size is
more than the atomic size (uint16).
• Tasks are not synchronized. For example, the CLA is triggered asynchronously.
• Sample time of the CPU and the CLA are different.
4-44
Using the Control Law Accelerator (CLA)
To ensure data integrity, data must be protected either using a double buffer algorithm or
by synchronizing both the CPU and the CLA.
In this model, the CPU and the CLA are not syncrhonized because the CLA is triggered
asynchronously using an ePWM interrupt. To ensure data integrity, a double buffer
algorithm along with control flags (Read_index and Write_index) are used.
In the double buffer algorithm, two buffers are used for data exchange. The CPU checks
the buffer that is being read by the CLA using the Read_index flag and writes the data to
the other buffer. Similarly, the CLA checks the buffer that is being written by the CPU
using the Write_index flag and reads the data from the other buffer.
By using the double buffer logic, data integrity is ensured even though the CPU and the
CLA are not synchronous.
4-45
4 Examples
4-46
Using the Control Law Accelerator (CLA)
In this model, data integrity is ensured by synchronizing the CPU and the CLA. The CLA
is software triggered using the sample time inherited from the inputs. The Simulink
scheduler ensures that all inputs are ready before the CLA subsystem is triggered.
Limitations
Specific interactions between the CLA and the C28x CPU along with CLA C compiler
limitations force the modeling practices to be followed. Below is a list of concepts that
reflects modeling practices described in this example:
• The CLA application code can only be triggered by a C28x event. CLA Task can be
triggered by C28x CPU via software or by different peripheral interrupts.
• All the interfaces between CLA and CPU need to be placed in specific memory
locations. The CpuToCla1MsgRAM memory section is used to exchange data from the
C28x to the CLA. The Cla1ToCpuMsgRAM memory section is used to exchange data
from the CLA to the C28x.
• The CLA application code does not have access to global variables.
• Early versions of the CLA C compiler support only 2 levels of function calls. CLA
interrupt service routines may call leaf functions only. Leaf functions may not call
other functions.
• Recursive function calls are not supported.
• Integer division, modulus, and integer unsigned comparison are not supported with
the CLA C compiler.
4-47
4 Examples
Troubleshooting
• Ensure that the Code Generation Tools version used supports the CLA C Compiler.
• Ensure that the latest C/C++ header files with CLA support are installed on your
system.
More About
4-48
Schedule a Multi-Rate Controller for a Permanent Magnet Synchronous Machine
Required hardware:
Note: Match the characteristics of the power supply and the amplifier with the input
characteristics of the selected motor.
Introduction
The goal is to create a real-time executable for a Spectrum Digital F28335 eZdsp and
schedule the controller execution using an ADC end-of-conversion interrupt. This goal is
achieved using an advanced technique where the controller and peripherals are
scheduled by a periodic ADC end-of-conversion interrupt.
This example builds upon the controller algorithm specified in the example “Field-
Oriented Control of Permanent Magnet Synchronous Machine” (Embedded Coder). Refer
to that example to explore how the controller algorithm behaves during system simulation
with a model of a Permanent Magnet Synchronous Machine.
4-49
4 Examples
To facilitate transitioning between simulation and code generation phases of a design, the
controller algorithm is specified in its own c28335_pmsmfoc model. The controller
algorithm is introduced in the example “Field-Oriented Control of Permanent Magnet
Synchronous Machine” (Embedded Coder). In this example the controller model is
configured for the TI F28335 target hardware. An archived library allowing incremental
build will be automatically generated for the controller model.
4-50
Schedule a Multi-Rate Controller for a Permanent Magnet Synchronous Machine
By default, a model set for a processor such as TI F28335 will use a hardware timer to
schedule all synchronous rates present in the model. If we keep this default behavior, the
controller algorithm will not be synchronized with the ADC which could introduce
latencies or drifts between the controller algorithm and the ADC conversions. In the
c28335_pmsmfoc_adcinterrupt Model Configuration Parameters, under Hardware
Implementation > Scheduler options, ADCINT1 is selected for the Scheduler interrupt
source. This option replaces the default scheduler interrupt source set to CPU Timer 0
interrupt with the ADC Interrupt coming from ADC module 1 (ADCINT1). On the ADC
block, an end-of-conversion interrupt is enabled for ADC module 1. Since the ADC
4-51
4 Examples
conversions are launched from the PWM module running at 25kHz, and since the base
rate (fundamental sample time) of the model is set to 40us, it is safe to replace the
scheduler interrupt source with the ADC interrupt triggering periodically at 40us. While
using the default CPU Timer 0 as a scheduler interrupt source, the tool will automatically
set the CPU Timer 0 to honor the base rate of the model. While replacing the scheduler
interrupt source with ADCINT1, like in this example, it is the responsibility of the user to
ensure that ADCINT1 will trigger periodically at the base rate used in the model.
Conclusion
This example showed how to create a real-time executable for a Texas Instruments
F28335 embedded target using an advanced scheduling technique triggering the
controller algorithm based on an ADC end-of-conversion interrupt. In this technique, the
hardware is configured to generate a periodic interrupt with the same rate as the fastest
rate specified in the controller.
More About
C28x eQEP
4-52
Code Verification and Validation with PIL
Introduction
In this example you will learn how to configure a Simulink model to run Processor-In-the-
Loop (PIL) simulation. In a PIL simulation, the generated code runs on the Texas
Instruments C2000 processor. The results of the PIL simulation are transferred to
Simulink to verify the numerical equivalence of the simulation and the code generation
results. The PIL verification process is a crucial part of the development cycle to ensure
that the behavior of the deployment code matches the design.
This example introduces how to configure a Simulink model for code generation and
verification using :
• PIL Block
• Model Block PIL
• Top-Model PIL
Required Hardware
To run this example you will need the following hardware: Texas Instruments C2000
processor based board with serial over USB capabilities
The Texas Instruments controlCard provides serial over USB capabilities. This allows
serial communication from the target to your host computer. We will use this serial
connection in this example to exchange data from Simulink to the target.
Some boards do not provide a FTDI chip and use the FTDI on the docking station and use
the USB serial cable to establish a serial connection between the host computer and the
target hardware. You can also use the COM1 port of your computer to establish an
RS-232 serial connection with the board. See Set Up Serial Communication with Target
Hardware for details on establishing a serial connection between the target and the host
computer.
The Embedded Coder Support Package for Texas Instruments C2000 supports serial
communication interface for PIL over SCI-A.
4-53
4 Examples
After establishing a serial connection, find the COM port associated with the target
hardware.
For more information on how to configure the Virtual COM port refer to this page. Note
the COM port number of the USB Serial Port showing in your Windows Device Manager
under Ports "(COM & LPT)"
• Set the COM Port as obtained above and replace the 'COM1' in the following command
with the correct Serial port corresponding to your controlCARD:
setpref('MathWorks_Embedded_IDE_Link_PIL_Preferences','COMPort','COM1');
• Set the baud rate for PIL communication by entering the baud rate as
setpref('MathWorks_Embedded_IDE_Link_PIL_Preferences','BaudRate',115200);
setpref('MathWorks_Embedded_IDE_Link_PIL_Preferences','enableserial',true);
4-54
Code Verification and Validation with PIL
Task 2 - Verify the generated code for a subsystem using a PIL block
This example shows how to use a PIL block for subsystem code verification. With this
approach:
1. Open the PIL Block model. This model is configured for the TI Piccolo F2806x target.
You can configure the model to run on other TI C2000 processors or TI C2000 Concerto
C28x core by changing the target hardware in the Configuration Parameters > Hardware
Implementation pane. The objective here is to create a PIL block out of the Controller
subsystem that you will run on the Texas Instruments C2000 processor.
4-55
4 Examples
3. Create a PIL block for the Controller subsystem as explained in Verify Generated Code
Using Software-in-the-Loop (SIL) and Processor-in-the-Loop (PIL) Simulation.
4. Place the PIL block created in the model as shown by the comments in the model.
5. Run the PIL simulation as explained in Verify Generated Code Using Software-in-the-
Loop (SIL) and Processor-in-the-Loop (PIL) Simulation.
6. You can switch between the original and PIL block subsystems by double clicking on
the Manual Switch block. Double click on the Numerical Difference block to see the
difference between the simulated Controller subsystem and the PIL block running on the
target processor.
This example shows how to verify the generated code for a referenced model by running a
PIL simulation. With this approach:
4-56
Code Verification and Validation with PIL
1. Open the Model Block PIL model. This model is configured for TI Piccolo F2806x
target. To configure the model to run on other TI C2000 processors you can change the
target hardware in the Configuration Parameters > Hardware Implementation pane. The
model contains two Model blocks that both point at the same referenced model. You will
configure one of the Model blocks to run in PIL simulation mode and the other in normal
mode.
2. Choose a PIL serial communication interface by following the steps in Task 1 above.
3. Configure and run CounterA Model block in PIL simulation as explained in Verify
Generated Code Using Software-in-the-Loop (SIL) and Processor-in-the-Loop (PIL)
Simulation.
4. When the model starts running, Scope1 displays the PIL simulation output running on
the TI Piccolo F2806x processor while Scope2 shows the normal mode simulation output.
4-57
4 Examples
4-58
Code Verification and Validation with PIL
This example shows how to verify the generated code for a model by running a PIL
simulation. With this approach:
1. Open the Top Model PIL model. This model is configured for the TI Piccolo F2806x
target.
2. Choose a PIL serial communication interface by following the steps in Task 1 above.
3. Run the top model PIL simulation as explained in Verify Generated Code Using
Software-in-the-Loop (SIL) and Processor-in-the-Loop (PIL) Simulation.
4. When the PIL simulation is completed, a logsOut variable is created in the base
workspace. The logsOut data contains PIL simulation results. You can access the logged
data for signals count_a and count_b using the following commands:
• count_a = get(logsOut,'count_a');
• count_a.Values.Data
• count_b = get(logsOut,'count_b');
• count_b.Values.Data
Summary
4-59
4 Examples
Required Hardware
• Any of the Texas Instruments C2000 - based controlCARDS with docking station or
Spectrum Digital eZdsp boards that have a serial interface with SCI_A.
Note: F281x based boards do not support parameter tuning over a serial communication
interface. Refer to CAN based parameter tuning for these boards.
• A USB serial cable if your hardware provides serial over USB capabilities, or an
RS-232 cable connected to the COM1 port of your computer.
Model
4-60
Parameter Tuning and Signal Logging with Serial Communication
This example uses Texas Instruments F28335 controlCARD with docking station and USB
serial cable to connect the host computer and the target hardware. You can also use the
COM1 port of your computer to establish an RS-232 serial connection with the board. See
Set Up Serial Communication with Target Hardware for details on establishing a serial
connection between the target and the host computer.
After establishing a serial connection, find the COM port associated with the target
hardware:
4-61
4 Examples
The Example Model is configured for the Texas Instruments F28335 controlCARD with
docking station, but you can follow the procedure for any other hardware board
mentioned in Required Hardware. See also Parameter Tuning over Serial
Communication for Texas Instruments C2000 Processors.
2. Open the Modeling tab and press Ctrl+E to open Configuration Parameters dialog box
and navigate to the Hardware Implementation pane.
3. Select your target hardware from the Hardware board drop-down list.
Note: To run the Example Model on targets with small amounts of RAM such as the
F28027 or F28035, enable the Boot From Flash (stand alone execution) option in
Hardware Implementation > Target Hardware Resources > Build options tab and
increase the heap size as mentioned in the Limitations section.
4-62
Parameter Tuning and Signal Logging with Serial Communication
The default baud rate is 115200. You can increase the baud of the serial over USB of your
Launchpad or controlCARD. On Launchpads and controlCARDs using FTDI 2232H, you
can select any baud less than or equal to 6 Mbps, or exactly 9 or 12 Mbps. On
controlCARDs using FTDI 2232D, you can select any baud less than or equal to 1.5 Mbps,
or exactly 2 or 3 Mbps.
4-63
4 Examples
4-64
Parameter Tuning and Signal Logging with Serial Communication
5. Open the Simulation tab and specify a value in the Stop Time text box. You can
specify the stop time as 'inf' to run the model continuously on the target hardware.
4-65
4 Examples
When you perform Monitor and Tune action for the model, the host computer
communicates with the target, on which the generated executable runs. To perform
Monitor and Tune in the Example Model:
1. Open the Hardware tab and click Monitor & Tune. You can observe from the
Diagnostic Viewer that the code is generated for the model and the host connects to the
target after loading the generated executable.
2. While the model is running, open the Scope connected to the Gain block to monitor its
output.
4-66
Parameter Tuning and Signal Logging with Serial Communication
Parameter Tuning
You can tune parameter values while the generated executable is running on the target
hardware. When the parameter values are changed in the Simulink model, the modified
values are communicated to the target hardware.
1. While the Monitor and Tune action is in progress, double click the Gain block and
change the value of the gain. You can observe that the amplitude of the sine waveform
has changed according to the new gain value. Change the value of the Constant block to 0
to switch the input source and observe the result on the Scope. If the Verbose option is
4-67
4 Examples
To modify more than one parameter and communicate the changes to the target hardware
at once, use the Batch download option in the External Mode Control Panel. To open the
External Mode Control Panel, go to the Hardware tab and click Control Panel. Refer to
Parameter Downloading for details on the Batch Download option.
Data Logging
While the Monitor and Tune action is in progress, you can log data from the model to a
file. You can either make use of the Scope or the To Workspace block. Follow the steps
below to manually trigger data logging or trigger data logging from a signal.
You can use the Arm trigger button on the External Mode Control Panel to trigger data
logging. The Arm when connecting to target option enables the trigger automatically
when the host connects to the target and data uploading begins. Otherwise, to start
uploading the data, you must manually arm the trigger by clicking the Arm trigger
button located in the External Mode Control Panel. Triggers can be useful when the
communication channel speed does not allow live visualization of the desired signals. In
this task, you will learn how to manually trigger data uploading from the target to the
host computer.
1. Open the External Mode Control Panel and click on the Signal & Triggering button,
which opens the External Signal & Triggering dialog box.
a. By default, the Source option is set to manual. Set the Mode to normal to collect
contiguous data samples. External mode allocates sufficient memory to collect data for
the length of the Duration for each signal. Depending on the communication speed and
the processing time given to the External mode engine that is running as a background
task, you may see a continuous data logging stream, or a stream of data containing gaps
corresponding to the time required to send the acquired buffers.
b. Specify the Duration as 15 to collect 15 data samples for a base rate signal. Since the
signal from the Gain block has the same sample rate as that of the model, the number of
samples collected in each data set is 15. Uncheck the Arm when connecting to target
option to enable manual triggering to upload data.
4-68
Parameter Tuning and Signal Logging with Serial Communication
2. To view the sample time of the model, navigate to Display > Sample Time and select
Sample Time Legend. For this example model, the sample time is 0.01 s.
3. Click on the Data Archiving button of the External Mode Control Panel to enable
logging data to a MAT file from the Enable Data Archiving dialog box.
4-69
4 Examples
4. Check the Enable archiving option. Use the File and Directory parameters to specify
the destination of your log file. In normal mode, file name incrementing happens
automatically and new data sets are saved in new MAT files.
5. Open the Scope connected to the Gain block and click on the Configuration
Properties button. Navigate to the Logging tab and check the Log data to workspace
option. Specify a name in Variable name. The logged data is saved in this variable. To
save the time instant and the signal data values, select Structure With Time for Save
format.
4-70
Parameter Tuning and Signal Logging with Serial Communication
Note: If you do not select the Save data to workspace option, the MAT files for data
logging are created, but they will be empty.
6. Click Monitor & Tune. Click the Arm Trigger button on the External Mode Control
Panel to trigger data logging and the Cancel Trigger button to stop logging the data.
Navigate to the folder specified for saving the logged data. Several MAT files are in this
location, each containing a structure with 15 contiguous data samples.
4-71
4 Examples
To collect only a single set of contiguous data samples, select One-shot. In this mode,
check the option Increment file after one-shot in the Enable Data Archiving dialog box
to save new data sets in new MAT files.
In signal trigger mode, Monitor and Tune uses a signal as a trigger to start logging data.
The data uploading begins when the trigger event occurs. To analyze a signal when an
error or fault condition occurs while the model is running, use a signal trigger to log data.
In this task, you will learn how to trigger data logging to a file when certain signal
conditions are met. In signal trigger mode, depending on the Delay specified, you can
choose to log data samples of a signal immediately at trigger, a few seconds after the
occurrence of the trigger, or both before and after the occurrence of the trigger.
1. Open the External Signal & Triggering dialog box from the External Mode Control
Panel.
2. In this dialog box, select the Scope block connected to the Step input and click the
Trigger Signal button to set the selected block signal as the trigger signal.
a. Select signal as the trigger Source. This enables the options in the Trigger signal.
Set the Mode to normal to collect contiguous data samples.
b. Specify the Duration as 15 to collect 15 base rate samples whenever the trigger
conditions are satisfied.
c. Specify the Delay as 5. This causes data logging to begin 5 base rate samples after the
occurrence of the signal trigger. Because the sample time for this model is 0.01 s and the
step input is applied at the time instant 26 s, data logging begins from the time instant
26.05 s , (i.e 5 * 0.01 s after the trigger event at 26 s).
d. In the Trigger signal section, choose rising as the Direction and set Level to 1.
This causes the signal trigger conditions to be met whenever the signal connected to
Scope1 increases in magnitude and crosses the threshold value of 1.
4-72
Parameter Tuning and Signal Logging with Serial Communication
3. Specify a folder and a file name in the Enable Data Archiving dialog box to save the
logged data.
5. The trigger conditions are met at the time instant 26 s, so stop the simulation after,
about 40 s. Navigate to the folder where the data is saved and load the MAT file into
MATLAB workspace by double-clicking on it. If you examine the contents of the MAT file,
the structure member time indicates, that data is logged from the time instant 26.05 s.
If the Delay 0, logging of the signal data begins immediately when the signal trigger
conditions are met. The Delay option can also be used with negative values to center the
data acquisition around the event of interest. To log data samples before the trigger
conditions occur for the Example Model, specify a negative value, -8 for example in the
Delay field. This captures 8 base rate samples before the occurrence of the trigger and
the remaining data samples after the occurrence of trigger.
To collect a data set of base rate samples only when the signal trigger conditions are met
for the first time, choose the Mode as One Shot. This mode is useful for viewing fast-
changing data on a slow communication channel. To achieve this, increase the value of
the Duration and set the signal trigger to acquire relevant data based on an event of
interest, like a fault signal, an over voltage/current signal or a temperature warning
signal.
4-73
4 Examples
Limitations
• Increasing the Duration allows the capture of large real-time buffers. These buffers
use heap section to allocate memory. A high value of Duration may result in Not
enough memory on the target to process the packet warning, and consequently cause
no data to be uploaded from the target to the host computer. To fix this problem,
specify a larger heap size if your target has sufficient memory. To change the heap
size, browse to Configuration Parameters > Code Generation > Build
Configuration > Specify > Linker and modify the value of --heap_size.
• Parameter tuning and signal logging for 8-bit data types is not supported over serial
communication interface for Texas Instruments C2000 processors. See Data Type
Support for details on the data type support for Texas Instruments C2000 processors.
Troubleshooting
• If you observe breaks in the scope, you can try the following to improve logging:
More About
“Parameter Tuning and Signal Logging over Serial Communication” on page 1-48
4-74
Real-Time Code Execution Profiling
Model
Introduction
Sample times specified in a Simulink® model determine the time schedule for running
generated code on target hardware. If the target hardware has sufficient computing
power, the code runs according to specified sample times in real-time.
4-75
4 Examples
You can use real-time execution profiling to check whether generated code meets real-
time performance requirements. Execution Profiling results can also be used to take
actions to enhance design of your system. For example, if the code easily meets the real-
time requirements, you may consider adding more functionality to your system to exploit
available processing power. If, on the other hand, the code does not meet real-time
requirements, you may look for ways to reduce execution time. For example, you can
identify the tasks that require the most time and then investigate whether trade-off
between functionality and speed is possible.
This example introduces a workflow for real-time code execution profiling by showing you
how to:
• Configure the model for code execution profiling, and generate code.
• Run generated code on target hardware.
• Analyze performance through code execution profiling plots and reports.
2. Open the Modeling tab and press CTRL+E to open Configuration Parameters dialog
box. Go to Code Generation > Verification.
3. Select Measure task execution time, and select Measure function execution
times > Detailed (all function call sites) option. These options enable you to profile
execution time for each task and function in generated code. Click OK.
4. Check that Hardware Implementation > Build Options > Build, load and run is
selected. This option must be selected, or the generated executable does not download
into the target.
5. Open the Hardware tab and click Build, Deploy & Start to run the code inside the
target hardware.
6. Run the following code in MATLAB Command Window to get the profiling data into
MATLAB workspace:
codertarget.profile.getData('f28377S_RTProfiler')
4-76
Real-Time Code Execution Profiling
7. Run the following code in MATLAB Command Window to obtain the Profiling Report
for the session you just ran. Analyze the report on different turnaround and execution
times for each task and function. Close the report when you are done.
executionProfile.report
8. Execute the following code in MATLAB Command Window to obtain the Profiling
Timeline for the session you just ran. Analyze the execution timeline of different tasks
4-77
4 Examples
and functions. Notice where the faster task pre-empts the slower one and where different
functions start and end. Close the timeline when you are done.
executionProfile.timeline
Notes
• The code execution profiler uses an on-chip timer. If you use a processor simulator,
select one that can simulate processor timers.
4-78
Real-Time Code Execution Profiling
• The model needs to run long enough to collect sufficient profiling data. This time
depends on the number of profiling samples specified and the sample rates of the
model. If you use a simulator, data collection can take considerably longer than when
you use hardware.
• The shipped target configuration file (ccxml) removes RAM initializations done by the
debugger while connecting to the target. Please make sure of this behavior on using a
custom target configuration file.
• Code execution profiling is currently not supported for models with asynchronously
executed subsystems. For example, subsystems triggered by C28x Interrupt Block is
not supported.
4-79
4 Examples
Introduction
In this example you will learn how to configure and use I2C blocks to:
Required Hardware
Note: Any C2000 (except c281x) controlSTICK or ControlCARD with docking station is
not equipped with I2C EEPROM. You must add I2C EEPROM to this board to run the
model.
Available models:
• c28x_i2c_eeprom.slx
• c28x_i2c_eeprom_interrupt.slx
Available models:
c28x_i2c_sensor.slx
The model writes four bytes to EEPROM and reads back the data from the corresponding
EEPROM address to show successful communication.
4-80
Using the I2C Bus to Access Sensors
You can run the model in External mode, monitor the transmitted and received data using
display blocks. You can change the data in "EEPROM Data" subsystem and see the
changes in the display blocks.
1 Open the c28x_i2c_eeprom model. This model is configured for TI F28335 hardware
board. To configure the model to run on other TI C2000 processors, you can change
the 'Hardware board' parameter in the Configuration Parameters > Hardware
Implementation pane.
2 In the Configuration Parameters window, click Hardware Implementation and
navigate to Target hardware resources > External mode and set the Serial port
parameter to the COM port at Device Manager > Ports (COM & LTP) in Windows.
For more information, see Parameter Tuning and Signal Logging with Serial External
mode.
3 Run the model and observe the "Receive data" and "Transmit data" display blocks.
4 Change the four byte data in "EEPROM Data" subsystem and observe the change
getting reflected in "Receive data" block.
4-81
4 Examples
The model writes four bytes to EEPROM and reads back the data from the corresponding
EEPROM address to show successful communication.
• EEPROM Data: Contains the free-running counter data that is written to the
EEPROM.
• EEPROM Address: Contains the EEPROM address where the data is written to.
• Trigger Logic: Triggers EEPROM Data Write and EEPROM Data Read subsystems
alternatively. The trigger logic consists of the STATVAR data store variable, which is
updated to start a write/read operation in the I2C ISR block when the SCD interrupt is
triggered.
• EEPROM Data Write Subsystem: Consists of the I2C Transmit block, which sends
the EEPROM address and the data along with a stop condition to the EEPROM at the
end of the data write.
4-82
Using the I2C Bus to Access Sensors
• EEPROM Data Read Subsystem: Consists of the I2C Transmit block, which sends
the EEPROM address to the EEPROM to initiate the EEPROM read operation. An
ARDY interrupt is generated when the address is sent to the EEPROM from the TX
FIFO. The I2C Receive block is then used in the interrupt service routine (ISR) to read
the data of specified length along with a stop condition at the end of the data write.
You can run the model in External mode and monitor the transmitted and received data
using display blocks.
4-83
4 Examples
The model configures the registers in Sensor Boosterpack reads the data from the
accelerometer and gyroscope.
4-84
Using the I2C Bus to Access Sensors
• Data Realignment Subsystem: Aligns the data as required before displaying it using
a display block.
You can run the model in External mode and monitor the accelerometer and gyroscope
data in the scope.
1. Open the c28x_i2c_sensor model. This model is configured for TI Delfino F2837xS
hardware board. To configure the model for other TI C2000 processors, you can change
the hardware board in the Configuration Parameters > Hardware Implementation
pane.
3. Ensure that the Sensor Boosterpack is connected to the Launchpad, and select the
corresponding I2C module (A/B) on Tx and Rx blocks. I2C_B module exists only for
F2807xs/F2837xS and F2837xD processors.
4. Select appropriate GPIO pins for SDA and SCL in Hardware Implementation > I2C_A/
I2C_B to communicate with Sensor Boosterpack.
5. Run the model and observe the accelerometer and gyroscope sensor data in the scope.
More About
4-85
4 Examples
By running the models provided in this example on the host computer, you can:
Prerequisites
Before you start with this example, install these MathWorks® products:
• Simscape™
• Simscape™ Electrical™
• Instrument Control Toolbox™
Required Hardware
Available Models
• DCDC_Buck_Sim.slx can be used to simulate the controller for the DC/DC buck
converter.
• f28379D_DCDC_Buck.slx can be used to generate code and load it on the F8379D
LaunchPad.
• f28377s_DCDC_Buck.slx can be used to generate code and load it on the F8377S
LaunchPad.
• c2000_host_read_12M.slx can be run on the host computer to log signals and tune
parameters.
4-86
Modeling a Voltage Controller for the DC/DC Buck Converter
• Controller: The discrete proportional integral (PI) controller minimizes the error
between the reference voltage and the output voltage. The duty cycle of the PI
controller is limited to 60% of the PWM time period.
• DC/DC Buck Converter: Simscape™ blocks are used to model the DC/DC buck
converter circuitry.
• Dashboard Controls: Used to set the reference voltage, switch on/off active load, and
tune proportional and integral gains.
1 Open the f28379D_DCDC_Buck model, and click the Run button to simulate the
model. The initialization file DCDC_Buck_Param.m loads the variables required for
the simulation.
2 Observe the output waveforms on the scope blocks. You can tune the input
parameters using the dashboard controls.
4-87
4 Examples
Note: On the F28379D processor, this example runs on CPU1. Ensure that the program
running on CPU2 is not using the peripherals that are used by CPU1.
1. On the host computer, browse to Device Manager > Ports (COM & LPT) to find the
COM port.
2. Set the COM ports of the following blocks in the c2000_host_read_12M model to match
the COM port of the host computer:
4-88
Modeling a Voltage Controller for the DC/DC Buck Converter
For more information on using the serial connection for your hardware, see http://
processors.wiki.ti.com/index.php/Using_the_serial_adapter_of_XDS100.
While the model runs, you can monitor the following signals on the scope:
• I_FB Current: The real-time current flowing through the inductor (L1). 4095 ADC
counts is equivalent to 6.8333 A inductor current.
• V_FB Voltage: The measured output voltage of the system. 4095 ADC counts is
equivalent to 6.0909 V output voltage.
While the model runs, you can tune parameters using the following dashboard blocks:
• Voltage Request: Change the output voltage demand. This parameter is the main
request for the control loop. The controller algorithm compares the Voltage Request
value with the measured output voltage and adjusts the PWM duty cycle towards
achieving the output voltage.
• Active load: Turn the active load present on the hardware on or off. This parameter
allows you to add an extra load resistor to study the effect of abrupt changes in the
load circuit.
• P Gain: Change the proportional gain of the controller algorithm. You can change this
parameter to study the robustness of the controller. Large, abrupt changes may lead to
instability of the controller; apply changes smoothly.
• I Gain: Change the integral gain of the controller algorithm. You can change this
parameter to study the robustness of the controller. Large, abrupt changes may lead to
instability of the controller; apply changes smoothly.
More About
4-89
4 Examples
Required Hardware
Hardware Connections
The SPI EEPROM uses the following 8-bit opcodes for enable, write data, read data, and
read status.
The hardware connections made are dependent on the EEPROM usage. You can use the
SPI EEPROM provided in the TI Peripheral Explorer or a separate EEPROM chip, such as
CAT25256 256kB SPI EEPROM.
4-90
Using SPI to Read and Write Data to SPI EEPROM
The Counter Limited block sends the counter value to the SPI Master Transfer block as
input, and the output data received is sent to the scope. You can observe the counter
value in the Scope block while running the model in External mode.
4-91
4 Examples
1 Open the c28x_spitest_ert model. This model is configured for the TI F28379D
LaunchPad hardware board. To configure the model to run on other TI C2000
processors, change the Hardware board parameter in the Configuration
Parameters > Hardware Implementation pane.
2 Browse to Hardware Implementation > Target Hardware Resources > SPI_A,
and select Enable loopback. Alternatively, you can connect SIMO and SOMI
physically using GPIO pins to enable external loopback.
3 Select appropriate values for SIMO, SOMI, CLK, and STE pin assignment,
depending on the processor.
4 In the Configuration Parameters window, click Hardware Implementation >
Target hardware resources > External mode and set the Serial port parameter
to the COM port at Device Manager > Ports (COM & LTP) in Windows. For more
information, see “Parameter Tuning and Signal Logging with Serial Communication”
on page 4-60.
5 Open Hardware tab and click Monitor & Tune. Observe the counter values on the
scope.
4-92
Using SPI to Read and Write Data to SPI EEPROM
Read and Write Data to SPI EEPROM Using the Master Transfer Block
The model writes data values of various types to the EEPROM and reads back the data
from the corresponding EEPROM address to show successful communication.
SPI blocks are configured with the Data bits parameter set to 8 to send the 8-bit opcodes
and write/read the 8-bit data. If you select the STE pin provided by the SPI peripheral in
Configuration Parameters, the slave is deselected between data transfers. In this case,
the Explicit GPIO calls option is used to select Slave select pin as GPIO1 to ensure
that the slave is selected continuously for multiple data transfers.
The model consists of a Trigger Subsystem, Write EEPROM Data and Read EEPROM Data
subsystems, and Display blocks. The Read EEPROM Data subsystem is always triggered,
while the Write EEPROM Data subsystem is triggered only if the data read from the
EEPROM does not match the input data to be written to the EEPROM.
The Write EEPROM Data subsystem performs EEPROM write enable operation before
every write cycle. The input data of different types are packed in 8-bit packets using the
4-93
4 Examples
Byte Pack block, and then the data is converted to uint16. The data is then written to the
EEPROM at the address location 0x0020 using the Master Transfer block. After this, the
program waits until the EEPROM write operation is complete by monitoring the status
flag of the EEPROM.
The Read EEPROM Data subsystem reads data back from the memory location 0x0020,
and the 8-bit packet data is unpacked to data of required type using the Byte Unpack
block. This data is then shown using Display blocks.
1 Open the c28x_spi_eeprom model. This model is configured for the TI F28379D
LaunchPad hardware board. To configure the model to run on other TI C2000
processors, change the Hardware board parameter in the Configuration
Parameters > Hardware Implementation pane.
2 Browse to Hardware Implementation > Target Hardware Resources > SPI_A.
3 Enter the value for Desired baud rate in bits/sec as 2000000, and set STE pin
assignment to None.
4 In the Configuration Parameters window, click Hardware Implementation and
go to Target hardware resources > External mode and set the Serial port
parameter to the COM port at Device Manager > Ports (COM & LTP) in Windows.
For more information, see “Parameter Tuning and Signal Logging with Serial
Communication” on page 4-60.
5 Open Hardware tab and click Monitor & Tune. Observe output data in display
blocks.
6 Change the input data values and observe the changes.
SPI Loopback Using the SPI Transmit Block, the SPI Receive Block, and Interrupts
The Counter Limited block sends the counter value to the SPI Transmit block as input.
The receive FIFO is configured to trigger the interrupt for a FIFO length of 4. The output
data of length 4 received from the SPI Receive block is realigned as a single stream and
sent to the scope. You can observe the counter value in the Scope block while running in
external mode.
4-94
Using SPI to Read and Write Data to SPI EEPROM
4-95
4 Examples
Read and Write Data to SPI EEPROM Using the SPI Transmit Block, the SPI
Receive Block, and Interrupts
The model writes data values of various types to EEPROM and reads back data from the
corresponding EEPROM address to show successful communication. This model can be
used only for hardware boards with an SPI FIFO length of 15.
SPI blocks are configured with the Data bits parameter set to 8 to send the 8-bit opcodes
and write/read the 8-bit data. If you select the STE pin provided by the SPI peripheral in
Configuration Parameters, the slave is deselected between data transfers. In this case,
the Explicit GPIO calls option is used to set Slave select pin to GPIO1 to ensure
that the slave is selected continuously for multiple data transfers. The receive FIFO is
configured to trigger the interrupt for a FIFO length of 15.
The model consists of Write EEPROM Data, Transmit Read Command, Read EEPROM
Data, and Data Realignment subsystems along with Display blocks. Write and read data
operations are triggered alternatively using the STATVAR variable.
The Write EEPROM Data subsystem performs the EEPROM write enable operation using
SPI Transmit and SPI Receive blocks. Before every write cycle, block priorities are set to
ensure that SPI Transmit is executed first. The input data of different types are packed in
8-bit packets using the Byte Pack block and converted to uint16. Data is then written to
4-96
Using SPI to Read and Write Data to SPI EEPROM
the EEPROM at the address location 0x0020 using the SPI Transmit block. After this, the
program waits until the receive interrupt is triggered. When the receive interrupt is
triggered, the data from the receive FIFO is read and discarded.
The Transmit Read Command subsystem is then triggered, which sends a read command
and an address with dummy data of the size of the data to be read. After this, the
program waits until the receive interrupt is triggered. When the receive interrupt is
triggered, data from the receive FIFO is read.
The Data Realignment subsystem performs byte reordering to create 8-bit word packets,
which are unpacked to data of required type using the Byte Unpack block. This data is
then shown using display blocks.
More About
4-97
4 Examples
• Send scalar and vector data from CPU1 using IPC Transmit block
• Receive data at CPU2 using IPC Receive block in polling and interrupt modes
Required Hardware
This example is configured for the Texas Instruments F28377D controlCARD with a
docking station. A USB serial cable is used to establish a serial connection between the
host computer and the target hardware. For more information, see “Set Up Serial
Communication with Target Hardware” on page 1-7.
Send Scalar and Vector Data from CPU1 Using IPC Transmit block
This example uses four different channels to transmit data from CPU1 to CPU2. A
maximum of 32 channnels can be used.
Open the c2837xd_ipc_cpu1_tx model, and click Build, Deploy & Start under Hardware
tab or press Ctrl+B to build and download the executable file on CPU1.
4-98
Inter-Processor Communication Using IPC Blocks
Receive Data at CPU2 Using IPC Receive Block in Polling and Interrupt Modes
4-99
4 Examples
3. Observe the output data using display blocks. The data received in CPU2 must match
the data transmitted from CPU1.
Note: The channel number of the IPC Receive block on the reading CPU must match the
channel number of the IPC Transmit block on the writing CPU.
4-100
Inter-Processor Communication Using IPC Blocks
4-101
4 Examples
More About
For inter-processor communication, the first two blocks of the global shared RAM (2x16k)
are used. For larger data transfers using IPC blocks, the memory must be increased using
the linker file. You can access the linker file by browsing to Configuration Parameters >
Hardware Implementation > Target hardware resources > Build Options.
To increase the IPC memory size, allocate more memory for RAMGS_IPCBuffCPU1 and
RAMGS_IPCBuffCPU2. The size of the memory must be the same in both cases.
For dual motor control using IPC blocks, see “Permanent Magnet Synchronous Motor
Field-Oriented Control”. In this example, c28379Dpmsmfocdual_cpu1_ert.slx and
c28379Dpmsmfocdual_cpu2_ert.slx models communicate using IPC.
4-102
Modify Duty Cycle of ePWM Using DMA
You can observe the duty cycle changes by connecting the ePWM pin (GPIO2) to:
The example consists of a model and a callback script. The script runs when the model is
initialized. The callback script (sineTableCalculation.m) generates a sine wave of
500 samples, and then scales the sine wave to the range of zero to the value of the ePWM
period register.
Required Hardware
Available Models
• F2833x: c2833x_dma_epwm.slx
• F2806x: c2806x_dma_epwm.slx
• F2807x, F2837x, and F28004x: c28x7x_c28004x_dma_epwm.slx
Model
4-103
4 Examples
The ePWM block is configured in up-down mode for a period of 0.002 seconds. For more
information, see “General Pane”.
The ePWM block is also configured to generate a start of conversion event for module A
(SOCA). For more information, see “Event Trigger Pane”.
The DMA parameters are configured to transfer 500 sine wave samples from the
duty_cycle_table look-up table to the ePWM compare register. DMA transfers one
sample at a time when triggered by the ePWM2SOCA event. To configure the DMA
parameters, browse to Configuration Parameters > Hardware Implementation >
Target hardware resources > DMA_ch1.
The Memory Copy block provides the value of the ePWM compare register to the scope.
4-104
Modify Duty Cycle of ePWM Using DMA
2. Click SCI_A, and set the Desired baud rate in bits/sec parameter to 1.25e6.
3. Click External mode, and set the Serial port parameter to the COM port at Device
Manager > Ports (COM & LTP) in Windows. For more information, see “Parameter Tuning
and Signal Logging with Serial Communication”.
4. To ensure that enough memory is present to run the model in External mode, click
Code Generation > Optimization in the Configuration Parameters window.
5. Set the Default parameter behavior parameter to Inlined, and click OK.
6. Open Hardware tab and click Monitor & Tune. Observe the sine wave values on the
scope.
More About
C280x/C2802x/C2803x/C2805x/C2806x/C2833x/C2834x/F28M3x/F2807x/F2837xD/
F2837xS/F2838x/F28004x ePWM
4-105
4 Examples
Prerequisites
Before you start with this example, install these MathWorks® products:
• Simscape™ Electrical™
• Instrument Control Toolbox™
Required Hardware
Available Models
• Solar_Inverter_Sim.slx can be used to simulate the plant model and controller for the
PV inverter system.
• c28035solar_inverter.slx can be used to generate code and load it on the F28035
controlCARD.
• c2000_host_solar.slx can be run on the host computer to log signals and tune
parameters.
The simulation model consists of the plant model and the controllers. The plant model
consists of three major components:
4-106
Photovoltaic Inverter with MPPT Using Solar Explorer Kit
• Emulated PV Panel: This module takes the irradiance value as input (in kW/m2) and
simulates the PV emulator implemented on the Texas Instruments Solar Explorer Kit.
• DC-DC Boost Converter: This module boosts up the input voltage based on the duty
cycle of the PWM pulses.
• Single Phase DC-AC Inverter: This module generates a single-phase AC voltage
waveform using the H-bridge topology. An AC load can be connected to the output.
To make a solar panel energy efficient, the panel must be operated at its maximum power
point. However, the maximum power point is not fixed because of the nonlinear nature of
the PV cell and changes in temperature and light intensity. The perturb & observe (P&O)
algorithm is implemented using a Stateflow® chart for calculating the reference voltage
required for maximum power point operation. The reference voltage is achieved with the
4-107
4 Examples
help of the DC-DC boost controller. The DC-DC boost controller implements a PI
controller to track the reference voltage set by the MPPT algorithm. For tracking the
reference voltage, the PV panel voltage (Vpv) is measured.
The DC-DC boost converter is a traditional single-phase converter with a single switching
MOSFET, Q1. The duty cycle of the PWM output that drives Q1 determines the amount of
boost imparted to the controlled parameter.
The DC-DC boost controller is realized using a PI controller. An increase in the duty cycle
of the boost converter loads the panel and results in a panel output voltage drop.
Accordingly, an increase in the output of the controller (duty cycle of the boost converter)
causes an increase in the error input to the controller. To achieve the reference voltage
value, the feedback and the voltage reference inputs of the PI controller are reversed. The
controller operates at a rate of 50 kHz.
The DC-DC boost converter output voltage is not controlled using the DC-DC boost
controller. However, the boost converter output voltage is regulated by the DC-AC
inverter controller, which modulates the current drawn by the DC-AC inverter to keep this
voltage regulated. The DC-AC inverter controller uses nested control loops — an outer
voltage loop and an inner current loop.
The voltage loop generates the reference for the current loop. An increase in the current
loads the DC bus and therefore causes a drop in the DC bus voltage. To achieve the
reference voltage value, the feedback and the outer voltage compensator reference are
reversed. The current reference is then multiplied by the sine reference to get the
instantaneous current reference. The instantaneous current reference is then used by the
current compensator along with the feedback current to provide duty cycle for the DC-AC
inverter. The duty cycle is calculated using the unipolar sine PWM technique.
The input to the PV emulator can be changed to run the simulation for different values of
irradiance. The controller parameters can be tuned to get a refined performance.
The deployment model consists of three real-time interrupt service routines (ISR) used
for:
4-108
Photovoltaic Inverter with MPPT Using Solar Explorer Kit
The F28035 processor receives the irradiance value through serial communications
interface (SCI) and sends it to the F28027 processor (PV emulator on the Solar Explorer
Kit) using serial peripheral interface (SPI) communication. The F28027 processor is
preconfigured to receive the updated irradiance value from the F28035 processor.
The host model receives the data from the kit and plots it to verify the performance of the
MPPT and the control algorithms.
4-109
4 Examples
While the model runs, you can monitor the Actual Panel Power signal on the scope. Actual
Panel Power is the real-time power supplied by the PV emulator.
While the model runs, you can tune parameters using the dashboard blocks:
4-110
Photovoltaic Inverter with MPPT Using Solar Explorer Kit
open-circuit voltage of the panel at the set irradiance, that is, Vref_cmd <=
Irradiance (in kW/m2) * 28.
More About
4-111
4 Examples
Introduction
Signal logging enables you to monitor the signal behavior and to perform any historical
analysis of the data. The data can be saved in any of these formats: Structure, Structure
with time, or Array. You can save the signals using the following blocks:
• To Workspace
• Scope
• Output port
This example provides you with the workflow to enable MAT-file logging and obtain the
MAT-file on a Micro SD card mounted on Texas Instruments™ C2000™ Processors.
Required Hardware
• For the external SD card interface, based on the SPI module selected, the SIMO,
SOMI, CLK and STE pin has to connected to corresponding GPIO pins of C2000
processor.
• Connect VCC and GND pins to appropriate supply and ground.
4-112
MAT-file Logging on SD Card for Texas Instruments C2000 Processors
Step 1 - Prepare the Connection and Configure a Simulink Model for MAT-File
Logging
The MAT-file logging needs to be configured on the Simulink model so that the selected
signals are logged on the Micro SD card on Texas Instruments™ C2000™ Processors.
2. Open the SD Card Logging model. This Simulink model is pre-configured for the TI
Delfino F2837xD with MAT-File logging enabled. In this example, signals from the Scope
block are logged.
open_system('c28x_matfile_logging.slx');
3. In your model window, open the Configuration Parameters dialog box, go to the
Hardware Implementation pane, and select the name of the target hardware from the
Hardware board list. If required, you can change the Hardware board selection other
than pre-configured F2837xD.
4-113
4 Examples
6. Double-click the Scope block in the Simulink model. In the Scope dialog box, click the
gear icon (Configuration Properties).
7. In the Configuration Properties: Scope dialog box, open the Logging tab, and select
Log data to Workspace. Also select Limit data points to last and set a value of 512.
9. On the Modeling tab, enter a value for the stop time. This is the duration for which
the signal is logged. However, the model continues to run on the hardware and it is not
affected by the time specified.
4-114
MAT-file Logging on SD Card for Texas Instruments C2000 Processors
For example, in this demo model (SD Card Logging), the stop time is 10. The signal will
be logged for 10 seconds. If the stop time is Inf, the signal will be logged till the Micro
SD card is full or the board is disconnected.
Step 2 - Deploy the Model on Texas Instruments C2000 Processors and View the
MAT-files
After the Simulink model is configured for MAT-file logging, you can deploy the model on
the connected Texas Instruments C2000 Processors and view the MAT-file(s) created on
the Micro SD card.
Tip: To learn more about logging data, see “Configure Model to Log Signals on SD Card”
on page 2-7.
1. In the Simulink model, go to Hardware tab and click Build, Deploy & Start button.
The build process for the model starts and it is deployed on the Texas Instruments C2000
Processors board. On successful deployment of the model, the LED on the board starts
blinking.
Note: For processor other than F2837xD, you have to replace the Digital Output block
and select the appropriate GPIO pin for LED blinking.
2. To view the logged MAT-files, remove the Micro SD card from the board after the
Simulation time, and insert the card on your computer.
If the deployment of the model was successful, the MAT-files are generated on the Micro
SD card as shown below:
4-115
4 Examples
After importing the MAT-files to your computer, you can use it for further analysis in
MATLAB®.
Because the model running on the hardware creates multiple MAT-files, the logged data
points are distributed across the generated MAT-files. You can create a stitcher function
to combine these MAT-files into a single MAT-file that contains all the logged data points.
To view an example of a MAT-file stitcher and understand its usage, enter the following
command in the MATLAB® command window.
edit('c28x_MAT_stitcher.m');
In this example, a Scope block is used to log signals. However, the signals in a Simulink®
model can also be logged on the SD card using the To Workspace block or by logging
the output(s) of the Simulink® model. Explore the MAT-file logging of a Simulink model
using these two techniques.
4-116
MAT-file Logging on SD Card for Texas Instruments C2000 Processors
Related Topics
4-117
4 Examples
Prerequisites
Required Hardware
Available Models
• PFC_MultiAxisKit_Sim.slx simulates the plant model and controller for the PFC
system.
• c28035pfc.slx generates code and loads it on the F28035 controlCARD.
• c2000_host_pfc.slx runs on the host computer to log signals.
The simulation model consists of the plant model and the controller. The plant model
consists of two major modules:
• AC-DC Rectifier: This module takes 13 to 16V AC input and outputs rectified DC
voltage.
4-118
Power Factor Correction Using Boost Converter
• DC-DC Boost Converter: This module boosts up the input voltage based on the duty
cycle of the pulse width modulation (PWM) output.
open_system('PFC_MultiAxisKit_Sim.slx');
The AC-DC rectification stage uses a traditional uncontrolled H-bridge rectifier. The DC-
DC boost converter on the kit has a two-phase interleaved topology. For simplicity, only
one phase has been used for the boost operation. The duty cycle of the PWM output
determines the amount of boost imparted to the input voltage.
The PFC controller provides current shaping of the AC input and regulates the DC bus.
The outer voltage loop ensures that the output DC voltage is maintained at the set
reference by using a discrete proportional integral PI controller.
4-119
4 Examples
The inner current loop performs the wave shaping of the input AC current to maintain a
high power factor. The reference for the current loop is generated by feed-forward of the
rectified DC voltage as well as the output of outer the voltage loop.
The output of the PFC controller is the PWM duty cycle of the DC-DC boost converter. The
controller operates at a rate of 50 kHz.
1. Open the PFCMultiAxisKitSim model, and click the Run button to simulate the model.
The deployment model has a real-time interrupt service routines (ISR) configured to
trigger PFC control at the rate of 50 kHz.
open_system('c28035pfc.slx');
4-120
Power Factor Correction Using Boost Converter
1. Turn on [M4]SW1 on the kit which turns on the power supply for smooth precharging
of the DC bus.
4. Follow the build process by opening the diagnostic viewer using the link at the bottom
of the model canvas.
The host model receives the data from the hardware kit and plots it to verify the
performance of the PFC controller.
open_system('c2000_host_pfc.slx');
4-121
4 Examples
While the model runs, you can monitor the rectified DC voltage and input boost converter
current to analyze the performance of PFC control.
More About
4-122
Interface LCD Booster Pack with Texas Instruments C2000 Processors
• Configure the Kentec QVGA display through the serial peripheral interface (SPI)
• Display the image through the SPI using direct memory access (DMA)
Required Hardware
• F28379D Launchpad
• BOOSTXL-K350QVG-S1 Kentec QVGA Display Booster Pack
Hardware Connections
Mount the Kentec QVGA Display Booster Pack on the F28379D Launchpad. The display
uses the following pin mapping with the F28379D Launchpad.
4-123
4 Examples
• Disable serial communication interface (SCI) interrupt ensure DMA channel is in halt
state.
• Initialize the display.
open_system('c2837xD_lcd_display.slx');
1. Reset the LCD, turn ON the backlight, select the SCS pin and wait for 1 ms.
2. Configure the following registers: Power parameter, Pixel format, Display orientation,
MCU interface parameter, Display control, Gamma correction and Power control. To
configure Pixel format - Exit sleep mode, wait for 30 ms and then configure the register.
For the image to display on the LCD, the image data must be transferred from the host
computer to the target F28379D Launchpad through the SCI.
Due to low memory constraints on the target F28379D Launchpad, it is not possible to
send the entire image data from the host computer to the target F28379D. Instead, the
4-124
Interface LCD Booster Pack with Texas Instruments C2000 Processors
image data is transferred in chunks from the host computer to the target F28379D
through the SCI. These chunks are stored in a small memory section Image_Array in the
target. Double buffer is used in Image_Array to ensure data integrity between data read
from the host using SCI and data transferred to the LCD display through the SPI
interface. The buffers are referred as ping buffer and pong buffer.
• Runs on the host computer, reads the image, and sets the SCI parameters.
• Sends 16-bit image data for the entire buffer in small chunks to the target F28379D
through the SCI.
• Adds a constant delimiter, of the same size as a chunk, for each buffer to indicate the
beginning of new a buffer.
The following table explains the parameters used with their size.
To send the entire image, buffer transmission must occur 20 times, i.e., Image size/buffer
size. Image Size = 20 x buffer size = 20 x (chunk size x number of SCI transfers)
On the model side of the target, the following sequence of events occurs:
1. The target waits for the SCI interrupt. The SCI interrupt is triggered when the serial
receive buffer receives the chunk size data.
4-125
4 Examples
2. In the serial interrupt service routines (ISR), the data is copied into the ping/pong
buffer of Image_Array. The model uses the serial delimiter to identify the beginning of
the data in the target. This process continues until the buffer transfer is complete.
3. The serial is now switched to the alternate buffer among the ping/pong to fill the data
and enable the SPI event trigger for DMA transfer.
4. The DMA starts pushing the data from the first filled buffer to the SPI Transmit FIFO
buffer. The data is transferred to the display through the SPI, and SPI Transmit triggers
the DMA event when the buffer is empty. This process continues till the first filled buffer
data is fully transferred to the display.
• The DMA is halted, and the start address of DMA is changed to the alternate buffer
• An acknowledgement is sent to the host computer showing the first buffer is empty to
receive new serial data
The above sequence continues until the entire image data is transferred to the display.
2. Go to the Modeling tab and press Ctrl+E to open the Configuration Parameters dialog
box.
5. Go to Hardware Implementation > Target Hardware Resources > SPI_A and set
Desired Baud rate in bits/sec to 16000000 and STE pin to None.
4-126
Interface LCD Booster Pack with Texas Instruments C2000 Processors
4-127
4 Examples
7. Navigate to the Hardware tab and press Ctrl+B. If the LCD turns green, it indicates
that the initialization of the Kentec QVGA display was successful.
8. On the host computer, run the function c2837xD_serial_send. The function takes
two arguments:
• COM port - browse to Device Manager > Ports (COM & LPT) to find the COM port.
• Image name - file name of the image that you want to display.
c2837xD_serial_send('COM2', 'mathworks.jpg');
4-128