Sps Ug PDF
Sps Ug PDF
User's Guide
R2019a
How to Contact MathWorks
Phone: 508-647-7000
Getting Started
1
Simscape Electrical Product Description . . . . . . . . . . . . . . . . . 1-2
Key Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
v
Tutorials
2
Build and Simulate Composite and Expanded Three-Phase
Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Select System Component Blocks and Build a Resistive Three-
Phase Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Specify Simulation Parameters . . . . . . . . . . . . . . . . . . . . . . . . 2-5
Load Impedance Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
Specify Display Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
Simulate and Analyze the Resistive Three-Phase Model . . . . . 2-7
Simulate and Analyze a Reactive Three-Phase Model . . . . . . . 2-7
Create an Expanded Balanced Three-Phase Model . . . . . . . . . 2-8
Create an Expanded Unbalanced Three-Phase Model . . . . . . 2-10
Simulate the Expanded Balanced and Unbalanced Models and
Analyze the Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10
vi Contents
Three-Phase Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7
About Three-Phase Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7
Expand and Collapse Three-Phase Ports on a Block . . . . . . . . . 3-8
vii
Electrical Behavior Depending on Temperature . . . . . . . . . . 3-41
Improving Numerical Performance . . . . . . . . . . . . . . . . . . . . 3-42
Modeling Machines
4
Machine Parameterization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
viii Contents
Machine Plotting and Display Options . . . . . . . . . . . . . . . . . . . 4-6
Asynchronous Machine Options . . . . . . . . . . . . . . . . . . . . . . . 4-6
Induction Machine Options . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7
Machine Inertia Block Options . . . . . . . . . . . . . . . . . . . . . . . . 4-7
Customization
5
Build Custom Blocks Using the Three-Phase Electrical Domain
................................................. 5-2
Control
6
Tune an Electric Drive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Cascade Control Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Equations for PI Tuning Using the Pole Placement Method . . . 6-2
Equations for DC Motor Controller Tuning . . . . . . . . . . . . . . . 6-5
Tune the Electric Drive in the Example Model . . . . . . . . . . . . 6-7
ix
Phasor-Mode Simulation Using Simscape Components . . . . . 7-13
Real-Time Simulation
8
Prepare Simscape Electrical Models for Real-Time Simulation
Using Simscape Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
x Contents
Simscape to HDL Workflow
9
Generate HDL Code from Simscape Models . . . . . . . . . . . . . . . 9-2
xi
1
Getting Started
Simscape Electrical helps you develop control systems and test system-level performance.
You can parameterize your models using MATLAB® variables and expressions, and design
control systems for electrical systems in Simulink®. You can integrate mechanical,
hydraulic, thermal, and other physical systems into your model using components from
the Simscape family of products. To deploy models to other simulation environments,
including hardware-in-the-loop (HIL) systems, Simscape Electrical supports C-code
generation.
Key Features
• Libraries of electrical components including sensors, actuators, motors, machines,
passive devices, and semiconductor devices
• Adjustable model fidelity, including nonlinear effects, operational limits, fault
modeling, and temperature-dependent behavior
• SPICE netlist importer for converting SPICE subcircuits of discrete devices to
Simscape models
• Application-specific models, including common AC and DC electric drives, smart grids,
and renewable energy systems
• Ideal switching, discretization, and phasor simulation for faster model execution
• MATLAB based Simscape language for creating custom component models
• Support for C-code generation (with Simulink Coder™)
1-2
Simscape Electrical Block Libraries
These library blocks are written in the Simscape language and are fully compatible with
the Simscape technology, including local solvers, data logging, statistics and variable
viewers, frequency analysis, and component and library customizations. To configure
Simscape Electrical models composed of these library blocks for local-solver simulation,
use the Solver Configuration block. Many of the blocks in these libraries also work with
other Simscape Foundation domains, such as the Mechanical, Magnetic, and Thermal
domains. When working with the Simscape technology compatible library blocks, you can
use these capabilities:
• Partitioning Solver
• Simscape HDL Workflow Advisor
• Simscape Results Explorer
You can create single-line three-phase diagrams by using the three-phase blocks because
the Three-Phase Electrical domain supports signals that contain all three phases as
1-3
1 Getting Started
individual elements in a single vector. You can also model each phase individually, for
example, to inject a single-line-to-ground fault into your circuit, by expanding the three-
phase ports on these blocks into three separate single-phase electrical ports.
The Control library contains Simulink blocks for signal generation, mathematical
transformation, and machine control. You can use these components to develop control
systems for single- and multi-phase electrical power systems.
Through conserving ports of the same domain, you can directly connect the blocks from
these Simscape Electrical libraries to Simscape blocks from:
Through physical signal ports, you can connect the physical blocks from these Simscape
Electrical libraries to:
• Simulink blocks, including blocks from the Control library, by using converter blocks
from the Simscape Utilities library
• Blocks from the Physical Signals library, which is in the Simscape Foundation library.
You can connect Specialized Power Systems blocks to Simulink blocks either:
1-4
Simscape Electrical Block Libraries
To display the Electrical library in the Simulink Library Browser, scroll to the Simscape
node. Expand the Simscape node and then the Electrical node. Alternately, at the
MATLAB command prompt, enter this command.
ee_lib
To access the sublibraries in the twelve top-level Simscape Electrical libraries, further
expand the nodes. Alternately, use the open_system command at the MATLAB command
prompt. For example, to access the sublibraries in the Connectors & References library,
enter the commands:
ee_lib;
open_system('ee_lib/Connectors & References')
1-5
1 Getting Started
When you model and analyze mechatronic systems, analog circuit architectures, or
electrical power systems using Simscape Electrical, your workflow might include the
following tasks:
In most applications, it is most natural to model the physical system using Simscape
Electrical blocks and other Simscape blocks, and then develop the controller or signal
processing algorithm in Simulink.
For more information about modeling the physical system, see “Essential Electrical
Modeling Techniques” on page 3-2.
2 Define component data by specifying electrical or mechanical properties as defined
on a datasheet.
For more information about the settings that most affect the solution of a physical
system, see “Setting Up Solvers for Physical Models” (Simscape).
4 Run the simulation.
1-6
Modeling Analog Circuit Architectures, Mechatronic Systems, and Electrical Power Systems Using Simscape Electrical
• Electrical
• Electrical Three-Phase
• Mechanical Rotational
• Mechanical Translational
Models you create from these templates have the corresponding reference block, the
required Solver Configuration block, and the frequently used Simscape-Simulink
interfacing blocks already in the Simulink canvas. The models also contain links that you
can double-click to access other blocks in the corresponding Simscape libraries.
1 Open the Simulink Start page. In the MATLAB Home tab, select the Simulink button.
Alternatively, at the command line, enter:
simulink
2 In the Simscape section, locate the templates that are preconfigured for modeling
with Simscape Electrical. Selecting a template opens a model in the Simulink Editor.
To save the model, select File > Save As.
1-7
1 Getting Started
Using other options on the Electrical menu, you can plot values in per-unit or display
base parameter values in the MATLAB Command Window. These options enable you to
tune the performance of your three-phase machine quickly.
1-8
See Also
The library contains blocks that use either high level or more detailed models to simulate
components. Simscape Electrical does not have the capability to:
• Perform either layout (physical design) tasks, or the associated implementation tasks
such as layout versus schematic (LVS), design rule checking (DRC), parasitic
extraction, and back annotation.
• Model 3-D parasitic effects that are typically important for high-frequency
applications.
For these types of requirements, you must use an EDA package specifically designed for
the implementation of analog circuits.
See Also
Phase Splitter
More About
• “Simscape Electrical Block Libraries” on page 1-3
• “Essential Electrical Modeling Techniques” on page 3-2
• “Parameterizing Blocks from Datasheets” on page 3-17
• “Setting Up Solvers for Physical Models” (Simscape)
• “Simulating an Electronic, Mechatronic, or Electrical Power System” on page 3-10
1-9
1 Getting Started
For a given quantity (voltage, current, power, impedance, torque, etc.) the per-unit value
is the value related to a base quantity.
quantity expressed in SI units
base value in p.u. =
base value
All other base quantities are derived from these two base quantities. Once the base power
and the base voltage are chosen, the base current and the base impedance are
determined by the natural laws of electrical circuits.
base power
base current =
base voltage
2
base voltage (base voltage)
base impedance = =
base current base power
For a transformer with multiple windings, each having a different nominal voltage, the
same base power is used for all windings (nominal power of the transformer). However,
1-10
Per-Unit System of Units
according to the definitions, there are as many base values as windings for voltages,
currents, and impedances.
When the per-unit system is used to specify the transformer R L parameters, the flux
linkage and current in the saturation characteristic must be also specified in pu. The
corresponding base values are
base instantaneous current = (base rms current) × 2
(base rms voltage) × 2
base flux linkage =
2π × (base frequency)
where current, voltage, and flux linkage are expressed respectively in volts, amperes, and
volt-seconds.
For AC machines, the torque and speed can be also expressed in pu. The following base
quantities are chosen:
base power (3 phases) in VA
base torque =
base speed in radians/second
Instead of specifying the rotor inertia in kg*m2, you would generally give the inertia
constant H defined as
kinetic energy stored in the rotor at synchronous speed in joules
H=
machine nominal power in VA
1
2
× J ⋅ w2
H=
Pnom
The inertia constant is expressed in seconds. For large machines, this constant is around
3–5 seconds. An inertia constant of 3 seconds means that the energy stored in the
rotating part could supply the nominal load during 3 seconds. For small machines, H is
lower. For example, for a 3-HP motor, it can be 0.5–0.7 seconds.
1-11
1 Getting Started
The base values for each single-phase transformer are first calculated:
• For winding 1:
1-12
Per-Unit System of Units
The values of the winding resistances and leakage inductances expressed in SI units are
therefore
For the magnetizing branch, magnetizing losses of 1% resistive and 1% inductive mean a
magnetizing resistance Rm of 100 pu and a magnetizing inductance Lm of 100 pu.
Therefore, the values expressed in SI units referred to winding 1 are
• Rm = 100*2083 = 208.3 kΩ
• Lm = 100*5.525 = 552.5 H
The stator and rotor resistance and inductance referred to stator are
• Rs = 0.435 Ω; Ls = 2 mH
• Rr = 0.816 Ω; Lr = 2 mH
The mutual inductance is Lm = 69.31 mH. The rotor inertia is J = 0.089 kg.m2.
Using the base values, you can compute the values in per-units.
1-13
1 Getting Started
Lm = 69.31/57.35 = 1.208 pu
The inertia is calculated from inertia J, synchronous speed, and nominal power.
1 1 2
2
× J ⋅ w2 2
× 0.089 × (188.5)
H= = = 0.7065 seconds
Pnom 3 × 746
If you open the dialog box of the Asynchronous Machine block in pu units provided in the
Machines library of the Simscape Electrical Specialized Power Systems Fundamental
Blocks library, you find that the parameters in pu are the ones calculated.
• When values are expressed in pu, the comparison of electrical quantities with their
"normal" values is straightforward.
For example, for all transformers in the 3–300 kVA power range, the leakage
reactance varies approximately 0.01–0.03 pu, whereas the winding resistances vary
between 0.01 pu and 0.005 pu, whatever the nominal voltage. For transformers in the
1-14
Per-Unit System of Units
300 kVA to 300 MVA range, the leakage reactance varies approximately 0.03–0.12 pu,
whereas the winding resistances vary between 0.005–0.002 pu.
It means that if you do not know the parameters for a 10-kVA transformer, you are not
making a major error by assuming an average value of 0.02 pu for leakage reactances
and 0.0075 pu for winding resistances.
The calculations using the per-unit system are simplified. When all impedances in a
multivoltage power system are expressed on a common power base and on the nominal
voltages of the different subnetworks, the total impedance in pu seen at one bus is
obtained by simply adding all impedances in pu, without considering the transformer
ratios.
1-15
2
Tutorials
• “Build and Simulate Composite and Expanded Three-Phase Models” on page 2-2
• “DC Motor Model” on page 2-13
• “Triangle Wave Generator Model” on page 2-21
2 Tutorials
In this example, you build and analyze a simple Simscape Electrical model that simulates
the behavior of a three-phase AC voltage source driving a purely resistive three-phase
load. You then modify the load in this model to change it to:
2-2
Build and Simulate Composite and Expanded Three-Phase Models
The model also contains two links that you can double-click to access blocks from
Simscape and Simscape Electrical libraries. For more information on using templates
for modeling with Simscape Electrical, see “Modeling Analog Circuit Architectures,
Mechatronic Systems, and Electrical Power Systems Using Simscape Electrical” on
page 1-6.
3 Delete the Simulink-PS Converter and Line Voltage Sensor (Three-Phase) blocks.
4 Add these blocks to the model.
2-3
2 Tutorials
2-4
Build and Simulate Composite and Expanded Three-Phase Models
8 Remove the on-canvas annotations titled Open Simscape Library and Open Simscape
Electrical Library. Save the model using the name simplethreephasemodel.
The blocks in this model use composite three-phase ports. For more information, see
“Three-Phase Ports” on page 3-7.
1 In the Solver Configuration block, select Use local solver and set Sample time to
0.0001.
2-5
2 Tutorials
If you prefer to use a continuous solver instead of a discrete solver, clear the Use
local solver check box in the Solver Configuration block. The simulation then uses
the Simulink solver specified in the model configuration parameters (Simulation >
Model Configuration Parameters). For Simscape Electrical models, an appropriate
solver choice is the moderately stiff solver ode23t. For a 60 Hz AC system, specify a
value for Max step size in the order of 1e-4. For more information, see “Variable-
Step Continuous Explicit Solvers” (Simulink).
2 In the Simulink Editor, set the simulation Stop time to 0.1.
• Component structure — R.
• Resistance — 1 Ω.
Using the default Component structure value, R, models a three-phase load that is
purely resistive in nature. The resistance in each phase is 1 Ω.
• Set Output signal unit of the PS-Simulink Converter1 block to V. This setting
ensures that the block outputs a signal with the same magnitude as the voltage
signal that enters it.
• Set Output signal unit of the PS-Simulink Converter2 block to A. This setting
ensures that the block outputs a signal with the same magnitude as the current
signal that enters it.
2 Label the input signals to the Scope block. Double-click each line, and type the
appropriate label, Voltages or Currents, as shown in the model graphic.
2-6
Build and Simulate Composite and Expanded Three-Phase Models
You are ready to simulate the model and analyze the results.
In this simulation, the Component structure parameter of the RLC (Three-Phase) block
specifies that the electrical characteristics of the three-phase load are purely resistive.
Therefore, for each phase of the three-phase system, the voltage and current remain in
phase with each other. Because the resistance in each phase is 1 Ω, the magnitude of the
phase voltage is equal to the magnitude of the phase current.
2-7
2 Tutorials
2-8
Build and Simulate Composite and Expanded Three-Phase Models
3 Drag two copies of the Phase Splitter block into the model from the Simscape >
Electrical > Connections & References library.
4 Flip one of the Phase Splitter blocks horizontally. Right-click the block and select
Rotate & Flip > Flip Block > Left-Right.
5 Drag a Resistor element into the model from the Simscape > Foundation Library >
Electrical > Electrical Elements library.
6 To create space for more components, hide the Resistor element label. Right-click the
resistor and select Format > Show Block Name to clear this option.
7 Make two more copies of the Resistor element.
8 Connect the components as shown.
This model name reflects that the load previously modeled by the RLC block is now
expanded into individual phases. The load is still balanced, that is, there is equal
resistance in each phase.
2-9
2 Tutorials
This model name reflects that the three-phase load previously modeled by the RLC
block is expanded into individual phases. The load is unbalanced, that is, the
resistance in one of the phases is higher than in the other two.
2-10
Build and Simulate Composite and Expanded Three-Phase Models
version of the model, the load is expanded into an individual resistive element for
each phase, but the resistance in each phase is unchanged. For each phase of the
three-phase system, the voltage and current remain in phase with each other.
Because the resistance in each phase is 1 Ω, the magnitude of the phase voltage is
equal to the magnitude of the phase current.
Comparing these results with the results for the three-phase resistive model shows
that a block with composite three-phase ports, the RLC (Three-Phase) block in the
original model, produces results with the same fidelity as that of expanded phases.
4 Open the simplethreephasemodel_expanded_unbalanced model.
5 Simulate the model. Autoscale the scope axes.
In this version of the model, the c-phase of the three-phase load has twice the
resistance of the other two. Therefore, half as much current flows in that phase, as
the second plot shows. However, because the load remains purely resistive, the
voltage and current remain in phase with each other.
2-11
2 Tutorials
See Also
Related Examples
• “Modeling Analog Circuit Architectures, Mechatronic Systems, and Electrical Power
Systems Using Simscape Electrical” on page 1-6
• “Essential Electrical Modeling Techniques” on page 3-2
2-12
DC Motor Model
DC Motor Model
In this section...
“Select Blocks to Represent System Components” on page 2-13
“Build the Model” on page 2-14
“Specify Model Parameters” on page 2-15
“Configure the Solver Parameters” on page 2-18
“Run the Simulation and Analyze the Results” on page 2-19
In this example, you model a DC motor driven by a constant input signal that
approximates a pulse-width modulated signal and look at the current and rotational
motion at the motor output.
The following table describes the role of the blocks that represent the system
components.
Block Description
Solver Configuration Defines solver settings that apply to all physical modeling
blocks
PS-Simulink Converter Converts the input physical signal to a Simulink signal
Controlled PWM Generates the signal that approximates a pulse-width
Voltage modulated motor input signal
H-Bridge Drives the DC motor
DC Motor Converts input electrical energy into mechanical motion
Current Sensor Converts the electrical current that drives the motor into a
measurable physical signal proportional to the current
DC Voltage Source Generates a DC voltage
2-13
2 Tutorials
Block Description
Electrical Reference Provides the electrical ground
Mechanical Rotational Provides the mechanical ground
Reference
Ideal Rotational Converts the rotational motion of the motor into a measurable
Motion Sensor physical signal proportional to the motion
Scope Displays motor current and rotational motion
2-14
DC Motor Model
Note You can use the Simscape function ssc_new with domain type electrical to
create a Simscape model that contains these blocks:
• Simulink-PS Converter
• PS-Simulink Converter
• Scope
• Solver Configuration
• Electrical Reference
2-15
2 Tutorials
The following blocks specify model information that is not specific to a particular block:
• Solver Configuration
• Electrical Reference
• Mechanical Rotational Reference
As with Simscape models, you must include a Solver Configuration block in each
topologically distinct physical network. This example has a single physical network, so
use one Solver Configuration block with the default parameter values.
You must include an Electrical Reference block in each Simscape Electrical network. You
must include a Mechanical Rotational Reference block in each network that includes
electromechanical blocks. These blocks do not have any parameters.
For more information about using reference blocks, see “Grounding Rules” (Simscape).
• The DC Voltage Source block (PWM reference voltage) generates a constant signal.
• The Controlled PWM Voltage block generates a pulse-width modulated signal.
• The H-Bridge block drives the motor.
In this example, all input ports of the H-Bridge block except the PWM port are connected
to ground. As a result, the H-Bridge block behaves as follows:
• When the motor is on, the H-Bridge block connects the motor terminals to the power
supply.
• When the motor is off, the H-Bridge block acts as a freewheeling diode to maintain the
motor current.
In this example, you simulate the motor with a constant current whose value is the
average value of the PWM signal. By using this type of signal, you set up a fast simulation
that estimates the motor behavior.
2-16
DC Motor Model
This value tells the block to generate an output signal whose value is the average
value of the PWM signal. Simulating the motor with an averaged signal estimates
the motor behavior in the presence of a PWM signal. To validate this
approximation, use value of PWM for this parameter.
3 Set the H-Bridge block parameters as follows:
This value tells the block to generate an output signal whose value is the average
value of the PWM signal. Simulating the motor with an averaged signal estimates
the motor behavior in the presence of a PWM signal. To validate this
approximation, use value of PWM for this parameter.
Note The simulation mode for both the Controlled PWM Voltage and H-Bridge blocks
must be the same.
Motor Parameters
Set the Motor block parameters as follows, leaving the unit settings at their default values
where applicable:
2-17
2 Tutorials
• Mechanical tab:
Specify the parameters of the blocks that create the motor current display:
Of the three blocks, only the PS-Simulink Converter1 block has parameters. Set the PS-
Simulink Converter1 block Output signal unit parameter to A to indicate that the block
input signal has units of amperes.
Specify the parameters of the blocks that create the motor torque display:
Of the three blocks, only the PS-Simulink Converter block has parameters you need to
configure for this example. Set the PS-Simulink Converter block Output signal unit
parameter to rpm to indicate that the block input signal has units of revolutions per
minute.
Note You must type this parameter value. It is not available in the drop-down list.
2-18
DC Motor Model
For more information about configuring solver parameters, see “Simulating an Electronic,
Mechatronic, or Electrical Power System” on page 3-10.
In the model window, select Simulation > Run to run the simulation.
To view the motor current and torque in the Scope windows, double-click the Scope
blocks. You can do this before or after you run the simulation.
Note By default, the scope displays appear stacked on top of each other on the screen, so
you can only see one of them. Click and drag the windows to reposition them.
Motor Current
2-19
2 Tutorials
Motor RPM
As expected, the motor runs at about 2000 rpm when the applied DC voltage is 2.5 V.
2-20
Triangle Wave Generator Model
In this example, you model a triangle wave generator using Simscape Electrical blocks
and custom Simscape Electrical blocks, and then look at the voltage at the wave
generator output.
To see the completed model, open the Triangle Wave Generator example.
You model the triangle wave generator with a set of physical blocks. The wave generator
consists of:
You have a manufacturer datasheet for the two operational amplifiers you want to model.
Later in the example, you use the datasheet to parameterize the Simscape Electrical
Band-Limited Op-Amp block.
2-21
2 Tutorials
The following table describes the role of the blocks that represent the system
components.
Block Description
Sine Wave Generates a sinusoidal signal that controls the resistance of the
Variable Resistor block
Scope Displays the triangular output wave
Simulink-PS Converts the sinusoidal Simulink signal to a physical signal
Converter
Solver Configuration Defines solver settings that apply to all physical modeling blocks
PS-Simulink Converts the output physical signal to a Simulink signal
Converter
Capacitor Works with an operational amplifier and resistor block to create
the integrator
Resistor Works with the operational amplifier and capacitor blocks to
create the integrator and noninverting amplifier
Variable Resistor Supplies a time-varying resistance that adjusts the gain of the
integrator, which in turn varies the frequency and amplitude of
the generated triangular wave
DC Voltage Source Generates a DC reference signal for the operational amplifier
block of the noninverting amplifier
Voltage Sensor Converts the electrical voltage at the output of the integrator
into a physical signal proportional to the current
Electrical Reference Provides the electrical ground
Band-Limited Op- Works with the capacitor and resistor to create an integrator
Amp and a noninverting amplifier
Diode Limits the output of the Band-Limited Op-Amp block, to make
the output waveform independent of supply voltage
2-22
Triangle Wave Generator Model
2 Add to the model the blocks listed in this table. The Library Path column of the table
specifies the hierarchical path to each block.
Note You can use the Simscape function ssc_new with a domain type of
electrical to create a Simscape model that contains these blocks:
• Simulink-PS Converter
• PS-Simulink Converter
2-23
2 Tutorials
• Scope
• Solver Configuration
• Electrical Reference
3 Rename and connect the blocks as shown in the diagram. The blocks in the triangle
wave generator circuit are organized in two stages. The Comparator Stage contains a
comparator constructed from a Band-Limited Op-Amp block and two Resistor blocks.
The Integrator Stage contains an integrator constructed from another Band-Limited
Op-Amp block, a Resistor, a Capacitor, and Electrical Reference.
These blocks specify model information that is not specific to a particular block:
2-24
Triangle Wave Generator Model
• Solver Configuration
• Electrical Reference
As with Simscape models, you must include a Solver Configuration block in each
topologically distinct physical network. This example has a single physical network, so
use one Solver Configuration block with the default parameter values.
You must include an Electrical Reference block in each Simscape Electrical network. This
block does not have any parameters.
Generate the sinusoidal control signal using the Sine Wave block.
• Amplitude — 0.5e4
• Bias — 1e4
• Frequency — pi/5e-4
Configure the blocks modeling the physical system that generates the triangle wave:
1 Accept the default parameters for the Simulink-PS Converter block. These
parameters establish the units of the physical signal at the block output such that
they match the expected default units of the Variable Resistor block input.
2 Set the two Band-Limited Op-Amp block parameters for the LM7301 device with a +–
20V power supply:
2-25
2 Tutorials
• The datasheet gives input resistance as 39 Mohms. Set Input resistance, Rin to
39e6.
• Set Output resistance, Rout to 0 ohms. The datasheet does not quote a value
for Rout, but the term is insignificant compared to the output resistor that it
drives.
• Set minimum and maximum output voltages to –20 V and +20 V, respectively.
• The datasheet gives the maximum slew rate as 1.25 V/μs. Set the Maximum slew
rate, Vdot parameter to 1.25e6 V/s.
• Set the bandwidth to 4e6.
3 Set the two Diode block parameters for a 4.3 V zener diode. To model a BZX384-
B4V3, set block parameters as follows:
• On the Main tab, set Diode model to Piecewise Linear. This selects a
simplified Zener diode model that is more than adequate to test the correct
operation of this circuit.
• Leave the Forward voltage as 0.6 V — this is a typical value for most diodes.
• The datasheet gives the forward current as 250 mA when the forward voltage is
1V. So that the Diode block matches this, set the On resistance to (1 V – 0.6 V) /
250 mA = 1.6 ohms.
• The datasheet gives the reverse leakage current as 3 μA at a reverse voltage of 1
V. Therefore, set the Off conductance to 3 μA / 1 V = 3e-6 S.
• The datasheet gives the reverse voltage as 4.3 V. On the Breakdown tab, set the
Reverse breakdown voltage Vz to 4.3 V.
• Set the Zener resistance Rz to a suitably small number. The datasheet quotes
the Zener voltage for a reverse current of 5 mA. For the Diode block to be
representative of the real device, the simulated reverse voltage should be close to
4.3V at 5mA. As Rz tends to zero, the reverse breakdown voltage tends to Vz
regardless of current, as the voltage-current gradient becomes infinite. However,
for good numerical properties, Rz must not be made too small. If, say, you allow a
0.01 V error on the Zener voltage at 5 mA, then Rz is 0.01 V / 5 mA = 2 ohms. Set
the Zener resistance parameter to this value.
4 The Voltage Sensor block does not have any parameters.
5 Accept the default parameters for the Variable Resistor block. These parameters
establish the units of the physical signal at the block output such that they match the
expected default units of the Variable Resistor block input.
6 Set the Capacitor block parameters as follows:
2-26
Triangle Wave Generator Model
• Capacitance — 2.5e-9
• Capacitor voltage — 0.08
This value starts the oscillation in the feedback loop. It is found in the Variables
tab.
• Series resistance — 0
7 Set the DC Voltage Source block Constant voltageparameter to 0.
8 Set the Resistor R3 block Resistance parameter to 10000.
9 Set the Resistor R1 block Resistance parameter to 1000.
10 Set the Resistor R2 block Resistance parameter to 10000.
11 Accept the default parameters for the PS-Simulink Converter block. These
parameters establish the units of the physical signal at the block output such that
they match the expected default units of the Scope block input.
Specify the parameters of the Scope block to display the triangular output signal.
Double-click the Scope block and then click the View > Configuration Properties to
open the Scope Configuration Properties dialog box. On the Logging tab, clear the Limit
data points to last check box.
2-27
2 Tutorials
For more information about configuring solver parameters, see “Simulating an Electronic,
Mechatronic, or Electrical Power System” on page 3-10.
In the model window, select Simulation > Run to run the simulation.
To view the triangle wave in the Scope window, double-click the Scope block. You can do
this before or after you run the simulation.
The following plot shows the voltage waveform. As the resistance of the Variable Resistor
block increases, the amplitude of the output waveform increases and the frequency
decreases.
2-28
3
There are two three-phase port types in Simscape Electrical blocks, composite and
expanded. You can connect a composite three-phase port only to another composite
three-phase port. You can connect the individual electrical conserving ports of an
expanded three-phase port only to other electrical conserving ports. For more
information, see “Three-Phase Ports” on page 3-7.
• Electrical and mechanical rotational conserving ports , which connect directly to
Simscape foundation blocks.
Each port type has specific Across and Through variables associated with it. To learn
about the rules to follow when building an electromechanical model, see “Basic
Principles of Modeling Physical Networks” (Simscape).
• Physical signal ports , which connect to Simulink blocks through Simulink-PS
Converter and PS-Simulink Converter blocks from the Simscape Utilities library. These
blocks convert physical signals to and from Simulink mathematical signals.
Keep these rules in mind when using each port type in Simscape Electrical blocks.
• You can connect physical conserving ports only to other conserving ports of the same
type. Electrical conserving ports in Simscape Electrical blocks can connect directly to
3-2
Essential Electrical Modeling Techniques
For each Through variable, the sum of the values flowing into a branch point equals
the sum of the values flowing out.
• You can connect physical signal ports to other physical signal ports using regular
connection lines, similar to Simulink signal connections. These connection lines carry
physical signals between Simscape Electrical blocks.
• You can connect physical signal ports to Simulink ports through converter blocks. Use
the Simulink-PS Converter block to connect Simulink outports to physical signal
inports. Use the PS-Simulink Converter block to connect physical signal outports to
Simulink inports.
• Unlike Simulink signals, physical signals can have units. In Simscape Electrical block
dialog boxes, you can specify the units along with the parameter values, where
appropriate. Use the converter blocks to associate units with an input signal and to
specify the desired output signal units.
Required Blocks
Each topologically distinct physical network in a diagram requires exactly one Solver
Configuration block from the Simscape Utilities library. The Solver Configuration block
specifies global environment information for simulation and provides parameters for the
solver that your model needs for simulation.
Each electrical network requires an Electrical Reference block. This block establishes the
electrical ground for the circuit. Networks with electromechanical blocks also require a
Mechanical Rotational Reference block. For more information about using reference
blocks, see “Grounding Rules” (Simscape).
3-3
3 Modeling and Simulation Basics
Another way to start a new model is to use a Simscape template from theSimulink start
page. The start page includes model templates that provide you with design patterns for
modeling electrical, three-phase electrical, mechanical rotational, and mechanical
translational networks using Simscape Electrical. For more information, see “Modeling
Analog Circuit Architectures, Mechatronic Systems, and Electrical Power Systems Using
Simscape Electrical” on page 1-6.
You can also use the Simscape “Creating A New Circuit” (Simscape) example as a
template for a new electronic circuit model. This example opens a simple electrical model,
prepopulated with some useful blocks, and also opens an Electrical Starter Palette, which
contains links to the most often used electrical components. Open the example by typing
ssc_new_elec in the MATLAB Command Window and use File > Save As to save the
example model under the desired name. Then delete the unwanted blocks and add new
ones from the Electrical Starter Palette and from the block libraries.
Many blocks in the Simulink library generate these zero crossings by default. For
example, the Pulse Generator block produces a discrete-time output by default, and
generates the corresponding zero crossings. To generate zero crossings for all Simulink
blocks that model instantaneous events, in the Solver Configuration Parameters for the
model, expand Solver details and in the Zero crossing options, for the Zero crossing
control option, select Use local settings or Enable all. For more information
about zero crossing control, see “Zero-crossing control” (Simulink).
3-4
Essential Electrical Modeling Techniques
The Simulink Logical Operator block implements the behavioral model of the two-input
NOR gate. Using Simulink in this manner introduces algebraic loops, unless you place a
lag somewhere between the physical signal inputs and outputs. In this case, a first-order
lag is included in the Propagation Delay subsystem to represent the delay due to gate
capacitances. For applications where no lag is required, use blocks from the Physical
3-5
3 Modeling and Simulation Basics
3-6
Three-Phase Ports
Three-Phase Ports
In this section...
“About Three-Phase Ports” on page 3-7
“Expand and Collapse Three-Phase Ports on a Block” on page 3-8
Composite three-phase ports represent three individual electrical conserving ports with a
single block port. You can use composite three-phase ports to build models that
correspond to single-line diagrams of three-phase electrical systems. Instead of explicitly
connecting each phase of the three-phase system between blocks, you connect all three
phases using a single port. You can connect composite three-phase ports only to other
composite three-phase ports.
Composite three-phase ports produce results with the same fidelity as expanded three-
phase ports. Both connection methods consider instantaneous phase voltages and
currents and are suitable for modeling balanced and unbalanced three-phase electrical
power systems. Each electrical conserving port in an expanded three-phase port has a
Through variable of scalar current and an Across variable of scalar voltage. For a
composite three-phase port, the Through variable is a three-element current, and the
Across variable is a three-element voltage.
You can use the Phase Splitter block to expand a composite three-phase port into separate
electrical conserving ports. The separate electrical ports can then connect to Simscape
Electrical electrical components.
The figure shows two simple circuits that contrast the composite and expanded
connection methods. The two circuits produce the same results.
3-7
3 Modeling and Simulation Basics
The top circuit uses a Voltage Source block with a composite three-phase port ~. The
bottom circuit uses a Voltage Source block with expanded electrical conserving ports a, b,
and c. In each circuit, the instantaneous phase voltages and currents are the same.
• Right-click the block. On the Simscape block choices context menu, select
Expanded three-phase ports or Composite three-phase ports.
For blocks with a single composite port ~, the expanded electrical ports are labeled a,
b, and c. For blocks with more than one composite port ~1 and ~2, the expanded
electrical ports are labeled a1, b1, c1 and a2, b2, c2.
3-8
Switch Between Physical Signal and Electrical Ports
To switch a block connection port between an electrical conserving port and a physical
signal port :
3-9
3 Modeling and Simulation Basics
Selecting a Solver
Simscape Electrical software supports all of the continuous-time solvers that Simscape
supports. For more information, see “Setting Up Solvers for Physical Models” (Simscape).
You can select any of the supported solvers for running a simulation of an electronic
model. The variable-step solvers, ode23t and ode15s, are recommended for most
applications because they run faster and work better for systems with a range of both fast
and slow dynamics. The ode23t solver is closest to the solver that SPICE traditionally
uses.
To use Simulink Coder software to generate standalone C or C++ code from your model,
you must use the ode14x solver. For more information about code generation, see “Code
Generation” (Simscape).
In most cases, the default tolerance values produce accurate results without sacrificing
unnecessary simulation time. The parameter value that is most likely to be inappropriate
3-10
Simulating an Electronic, Mechatronic, or Electrical Power System
for your simulation is Max step size, because the default value, auto, depends on the
simulation start and stop times rather than on the amount by which the signals are
changing during the simulation. If you are concerned about the solver missing significant
behavior, change the parameter to prevent the solver from taking too large a step.
The Simulink documentation describes the following parameters in more detail and
provides tips on how to adjust them:
The Solver Configuration block reference page in the Simscape documentation explains
when to adjust the Consistency Tolerance parameter value.
There are a few techniques you can apply to any Simscape Electrical model to overcome
simulation issues:
• Add parasitic capacitors and/or resistors (specifically, junction capacitance and ohmic
resistance) to the circuit to avoid numerical issues. The Astable Oscillator example
uses these devices.
• Adjust the current and voltage sources so they start at zero and ramp up to their final
values rather than starting at nonzero values.
To learn about avoiding simulation errors in the presence of specific Simscape Electrical
model configurations, see “Modeling Instantaneous Events” on page 3-4 and “Using
Simulink Blocks to Model Physical Components” on page 3-5.
3-11
3 Modeling and Simulation Basics
See Also
Solver Configuration
More About
• “How Simscape Simulation Works” (Simscape)
• “Trimming and Linearization” (Simscape)
• “Troubleshooting” (Simscape)
3-12
Selecting the Output Model for Logic Blocks
• Linear — Models the gate output as a voltage source driving a series resistor and
capacitor connected to ground. This is suitable for logic circuit operation under
normal conditions and when the logic gate drives other high-impedance CMOS gates.
The block sets the value of the gate output capacitor such that the resistor-capacitor
time constant equals the Propagation delay parameter value. The linear output
model is shown in the following illustration.
3-13
3 Modeling and Simulation Basics
Use the Output current-voltage relationship parameter on the Outputs tab of the
block dialog box to specify the output model.
For most system models, MathWorks recommends selecting the linear option because it
supports faster simulation. If necessary, you can use the more detailed output model to
validate simulation results obtained from the simpler model.
• Supply voltage — Supply voltage value (Vcc) applied to the gate in your circuit. The
default value is 5 V.
• Measurement voltage — The gate supply voltage for which mask data output
resistances and currents are defined. The default value is 5 V.
• Logic HIGH output resistance at zero current and at I_OH — A row vector
[ R_OH1 R_OH2 ] of two resistance values. The first value R_OH1 is the gradient of the
output voltage-current relationship when the gate is logic HIGH and there is no output
current. The second value R_OH2 is the gradient of the output voltage-current
3-14
Selecting the Output Model for Logic Blocks
relationship when the gate is logic HIGH and the output current is I_OH. The default
value is [ 25 250 ] Ω.
• Logic HIGH output current I_OH when shorted to ground — The resulting
current when the gate is in the logic HIGH state, but the load forces the output
voltage to zero. The default value is 63 mA.
• Logic LOW output resistance at zero current and at I_OL — A row vector
[ R_OL1 R_OL2 ] of two resistance values. The first value R_OL1 is the gradient of the
output voltage-current relationship when the gate is logic LOW and there is no output
current. The second value R_OL2 is the gradient of the output voltage-current
relationship when the gate is logic LOW and the output current is I_OL. The default
value is [ 30 800 ] Ω.
• Logic LOW output current I_OL when shorted to Vcc — The resulting current
when the gate is in the logic LOW state, but the load forces the output voltage to the
supply voltage Vcc. The default value is -45 mA.
• Propagation delay — Time it takes for the output to swing from LOW to HIGH or HIGH
to LOW after the input logic levels change. For quadratic output, it is implemented by
the lagged gate input demand. The default value is 25 ns.
• Protection diode on resistance — The gradient of the voltage-current relationship
for the protection diodes when forward biased. The default value is 5 Ω.
• Protection diode forward voltage — The voltage above which the protection diode
is turned on. The default value is 0.6 V.
The following graphic illustrates the quadratic output model parameterization, using the
default parameter output characteristics for a +5V supply.
3-15
3 Modeling and Simulation Basics
3-16
Parameterizing Blocks from Datasheets
Most of the time, datasheets should be a sufficient source of parameters for Simscape
Electrical blocks (see Examples 1 on page 3-19, 2 on page 3-23, and 4 on page 3-31).
Sometimes, there is need for more information than is available on the datasheet, and
data can be augmented from a manufacturer SPICE netlist. For example, circuit
performance may depend on one or two critical components, and increased accuracy is
needed either for parameter values or the underlying model. Simscape Electrical libraries
contain a SPICE-compatible sublibrary to support this case, and this is illustrated by
Example 3 on page 3-27. If you have many components that need to be modeled to a
high level of accuracy, then Simulink cosimulation with a specialist circuit simulator may
be a better option.
You can also use the SPICE conversion assistant to convert SPICE components into
Simscape equivalents. For more information, see “Converting a SPICE Netlist to
Simscape Blocks” on page 3-69
3-17
3 Modeling and Simulation Basics
creating your own abstracted model using the Simscape language, or using Simulink
blocks. For an example of using Simulink blocks, see the Modeling an Integrated Circuit
example.
When looking for a datasheet, make sure you have the originating manufacturer
datasheet because some resellers abbreviate them.
For additional ways to parameterize and validate your model, see “Additional
Parameterization Workflows” on page 3-33.
3-18
Parameterize a Piecewise Linear Diode Model from a Datasheet
The Phillips Semiconductors datasheet for a BZX384–B4V3 gives the following data:
In the datasheet, the tabulated values for VF are for higher forward currents. This value of
0.7V at 5mA is extracted from the datasheet current-voltage curve, and is chosen as it
matches the zener current used when quoting the working voltage of 4.3V.
To match the datasheet values, the example sets the piecewise linear diode block
parameters as follows:
• Forward voltage. Leave as default value of 0.6V. This is a typical value for most
diodes, and the exact value is not critical. However, it is important that the value set is
taken into account when calculating the On resistance parameter.
• On resistance. This is set using the datasheet information that the forward voltage is
0.7V when the current is 5mA. The voltage to be dropped by the On resistance
parameter is 0.7V minus the Forward voltage parameter, that is 0.1V. Hence the On
resistance is 0.1V / 5mA = 20 Ω.
• Off conductance. This is set using the datasheet information on reverse current. The
reverse current is 3μA for a reverse voltage of 1V. Hence the Off conductance should
be set to 3μA / 1V = 3e-6 S.
• Reverse breakdown voltage. This parameter should be set to the datasheet working
voltage parameter, 4.3V.
3-19
3 Modeling and Simulation Basics
• Zener resistance. This needs to be set to a suitable small number. Too small, and the
voltage-current relationship becomes very steep, and simulation convergence may not
be as efficient. Too large, and the zener voltage will be incorrect. For the Diode block
to be representative of the real device, the simulated reverse voltage should be close
to 4.3V at 5mA (the reverse bias current provided by the circuit). Allowing a 0.01 V
error on the zener voltage at 5mA, the zener resistance RZ will be 0.01V / 5mA = 2 Ω.
• Junction capacitance. This parameter is set to the datasheet diode capacitance
value, 450 pF.
3-20
Parameterize a Piecewise Linear Diode Model from a Datasheet
3-21
3 Modeling and Simulation Basics
3-22
Parameterize an Exponential Diode from a Datasheet
This model either requires two data points from the diode current-voltage relationship, or
values for the underlying equation coefficients, namely the saturation current IS and the
emission coefficient N. The BZX384-B4V3 datasheet only provides values for the former
case. Some datasheets do not give the necessary data for either case, and you must follow
the processes in Example 1 on page 3-19 or Example 3 on page 3-27 instead.
The two data points in the table below are from the BZX384-B4V3 datasheet current-
voltage curve:
A more complex capacitance model is also available for the Diode component with the
exponential equation option. However, the datasheet does not provide the necessary
data. Moreover, the operation of this circuit is not sufficiently sensitive to voltage-
dependent capacitance effects to warrant the extra detail.
3-23
3 Modeling and Simulation Basics
3-24
Parameterize an Exponential Diode from a Datasheet
3-25
3 Modeling and Simulation Basics
3-26
Parameterize an Exponential Diode from SPICE Netlist
The subcircuit data can be used to parameterize the Simscape Electrical Diode block
either in conjunction with the datasheet, or on its own. For example, the Ohmic resistance
is defined in the subcircuit as RS = 0.387, thus providing the missing piece of information
in Example 2 on page 3-23.
Note that where there is a one-to-one correspondence between subcircuit parameters and
datasheet values, the numbers often differ. One reason for this is that datasheet values
are sometimes given for maximum values, whereas subcircuit values are normally for
nominal values. In this example, the CJO value of 271.5 pF differs from the datasheet
capacitance of 450 pF at zero bias for this reason.
3-27
3 Modeling and Simulation Basics
3-28
Parameterize an Exponential Diode from SPICE Netlist
3-29
3 Modeling and Simulation Basics
3-30
Parameterize an Op-Amp from a Datasheet
The Band-Limited Op-Amp and Finite-Gain Op-Amp blocks have been designed to work
from manufacturer datasheets. Implementing detailed op-amp device models, derived
from manufacturer SPICE netlist models, is not recommended, because it provides more
accuracy than is typically warranted and slows down simulations. The simple
parameterization of the Simscape Electrical op-amp blocks allows you to determine the
sensitivity of your circuit to abstracted performance values, such as maximum slew rate
and bandwidth. Because of this behavior-based parameterization, you can determine
which specification of op-amp is required for a given application. A circuit designer can
later match these behavioral parameters, determined from the model, against specific op-
amp devices.
Based on the datasheet values above, set the Band-Limited Op-Amp block parameters as
follows:
Note that these parameters correspond to the values for +-5 volt operation. The
datasheet also gives values for +-2.2V and +-30V operation. It is usually better to pick
values for a supply voltage below what your circuit uses, because performance is worse at
3-31
3 Modeling and Simulation Basics
lower voltages; for example, the gain is less, and the input impedance is less. You can use
the variation in op-amp parameters with supply voltage to suggest a typical range of
parameter values for which you should check the operation of your circuit.
3-32
Additional Parameterization Workflows
In this section...
“Validation Using Data from SPICE Tool” on page 3-33
“Parameter Tuning Against External Data” on page 3-33
“Building an Equivalent Model of a SPICE Netlist” on page 3-33
If the device models you wish to model are complex (hundreds of components), then
cosimulation with an external circuit simulator may be a better approach.
3-33
3 Modeling and Simulation Basics
See Also
SPICE Diode
3-34
Simulating Thermal Effects in Rotational and Translational Actuators
• A DC Motor block can optionally show a single thermal port corresponding to the
armature
• A Shunt Motor block can optionally show two thermal ports, one for the stator winding
and one for the field winding
The thermal port represents copper resistance losses which convert electrical power to
heat. These losses are sometimes referred to as i2R losses. The thermal ports do not
represent iron losses due to, for example, Eddy currents and hysteresis.
The thermal ports are hidden by default. To expose the thermal port on a particular block
instance in your block diagram:
1 Right-click the block where you want to show the thermal port.
2 From the context menu, select Simscape > Block choices > Show thermal port.
When the thermal port is exposed, the block dialog box contains two additional tabs,
Temperature Dependence and Thermal Port. For actuator blocks with single winding,
these tabs always contain the same set of parameters.
3-35
3 Modeling and Simulation Basics
• Thermal mass — Thermal mass of the electrical winding, defined as the energy
required to raise the temperature by one degree. The default value is 100 J/K.
• Initial temperature — The temperature of the thermal port at the start of simulation.
The default value is 25 °C.
For more information on selecting the parameter values, see “Thermal Model for Actuator
Blocks” on page 3-37.
Parameters for actuator blocks with two windings differ, and are described on the
respective block reference pages.
3-36
Simulating Thermal Effects in Rotational and Translational Actuators
R = R0 (1 + α (T – T0 ))
where:
3-37
3 Modeling and Simulation Basics
1 Right-click the block where you want to show the thermal port.
2 From the context menu, select Simscape > Block choices > Show thermal port.
When the thermal port is exposed, the block dialog box contains an additional tab,
Thermal Port. For semiconductor devices, the tab always contains the same set of
parameters.
3-38
Simulating Thermal Effects in Semiconductors
3-39
3 Modeling and Simulation Basics
For more information on selecting the parameter values, see “Thermal Model for
Semiconductor Blocks” on page 3-40 and “Improving Numerical Performance” on page
3-42. For explanation of the relationship between the Thermal Port and Temperature
Dependence tabs in a block dialog box, see “Electrical Behavior Depending on
Temperature” on page 3-41.
The port H in the diagram corresponds to the thermal port H of the block. The two
Thermal Mass blocks represent the thermal mass of the device case and the thermal mass
of the semiconductor junction, respectively. The Controlled Heat Flow Rate Source block
(called Ideal Heat Flow Source in the diagram) inputs heat to the model with value equal
to the electrically generated heat from the device.
The two Conductive Heat Transfer blocks model the thermal resistances. Resistance R_JC
(conductance 1/R_JC) represents the thermal resistance between junction and case.
Because of this resistance, under normal conditions the junction will be hotter than the
case. Resistance R_CA represents the thermal resistance between port H and the device
case. If the device has no heatsink, then in your model you should connect port H to an
Ideal Temperature Source with its temperature set to ambient conditions. If your device
does have an external heatsink, then you must model the heatsink externally to the
device, and connect the heatsink thermal mass directly to port H.
If you wish to keep all or part of the thermal model of the device external to the model,
you can set the necessary block parameters to zero. The following rules apply:
3-40
Simulating Thermal Effects in Semiconductors
The thermal time constants t_J and t_C are defined as follows:
where M_J and M_C are the junction and case thermal masses, respectively, R_JC is the
thermal resistance between junction and case, and R_CA is the thermal resistance
between port H and the device case.
You can determine the case time constant by experimental measurement. If data is not
available for the junction time constant, you can either omit it and set the junction-case
resistance to zero, or you can set the junction time constant to a typical value of one tenth
of the case time constant. The alternative is to estimate thermal masses based on device
dimensions and averaged material specific heats.
• Simulate the generated heat, device temperature, and the effect of temperature on the
electrical equations.
• Simulate the generated heat and device temperature, but do not include effect of
temperature on the electrical equations. Use this option when the impact of
3-41
3 Modeling and Simulation Basics
The thermal port and the Thermal Port tab of the block dialog box let you simulate the
generated heat and device temperature. The Thermal Dependence tab of the block
dialog box lets you model the effect of temperature of the semiconductor junction on the
electrical equations. Therefore:
• To simulate all the temperature effects, show the block’s thermal port and set the
Parameterization parameter on the Thermal Dependence tab to Model
temperature dependence (or, for blocks with a choice of options for modeling
temperature dependence, select one of these options, for example, Use an I-V data
point at second measurement temperature).
• To simulate just the generated heat and device temperature, show the block’s thermal
port but set the Parameterization parameter on the Thermal Dependence tab to
None — Simulate at parameter measurement temperature.
The thermal time constants are generally much slower than electrical time constants, so
the thermal aspects of your model are unlikely to dictate the maximum fixed time step
you can simulate at (for example, for hardware-in-the-loop simulations). However, if you
need to remove detail (for example, to speed up simulation), the junction thermal mass
time constant is typically an order of magnitude faster than the case thermal mass time
constant. You can remove the effect of the junction thermal mass by setting the junction
thermal mass to zero and also setting the junction-case thermal resistance to zero.
3-42
Simulate Thermal Effects Using Simscape Electrical Thermal Blocks
Prerequisite
This example requires a simulation log variable in your MATLAB workspace. The model in
this example is configured to log Simscape data for the whole model for the entire
simulation time.
To learn how to determine if a model is configured to log simulation data, see “Examine
the Simulation Data Logging Configuration of a Model” on page 7-19.
Thermal Variants
Thermal modeling provides data that helps you to estimate cooling requirements for your
system. The nonideal blocks in the Simscape Electrical Semiconductors & Converters
library has thermal variants that allow you to determine device temperatures by
simulating heat generation. For example, the IGBT (Ideal, Switching) block, which models
a three-terminal semiconductor device, has thermal variants that can simulate the heat
generated by switching events and conduction losses. Selecting a thermal variant for a
block adds a thermal port to the block and enables the associated thermal-modeling
parameters.
Thermal Blocks
In the Simscape Electrical Passive library, the Thermal sublibrary contains blocks that
allow you to model heat transfer using thermal variants:
3-43
3 Modeling and Simulation Basics
Thermal Ports
Thermal ports are physical conserving ports in the Simscape thermal domain. Thermal
ports on Simscape Electrical semiconductors are associated with temperature and heat
flow. The figure shows a thermal port on a thermal variant of the IGBT (Ideal, Switching)
block.
Thermal ports are associated with temperature and heat flow which are the Across and
Through variables of the Simscape thermal domain. To measure thermal variables, you
can use one or both of these methods:
1 Log simulation data using a Simscape logging node. View the data using the
sscexplore function.
2 Add a sensor from the Simscape > Foundation Library > Thermal > Thermal
Sensors library to your model. To measure temperature, use a parallel-connected
Ideal Temperature Sensor block. To measure heat flow, use a series-connected Ideal
Heat Flow Sensor block.
There are several advantages to using data logging for desktop simulation. Data logging
is less computationally costly than using a sensor block and it allows you to:
3-44
Simulate Thermal Effects Using Simscape Electrical Thermal Blocks
However, if you use only data logging to measure a variable, you cannot output a
feedback signal for that variable to a control system during simulation as you can when
you use only a sensor to measure the variable. Also, because data logging is not
supported for code generation, you cannot use Simscape data logging when you perform
real-time simulation on target hardware.
Thermal-Modeling Parameters
Thermal-modeling parameters are device-specific characteristics that determine how
much heat a block generates during simulation. When you select a thermal variant for a
Diode, no additional parameters are enabled because the default variant includes all
parameters necessary to model conduction loss. When you select a thermal variant for a
three-terminal semiconductor block, additional thermal-modeling parameters are enabled
because the default variant does not include parameters necessary to model switching
losses.
• Output current
• Switch-on loss
• Switch-off loss
• On-state voltage
If you parameterize thermal losses based on Voltage, current, and temperature, use
vectors to specify the temperature, output current, switching losses, and on-state voltage.
Limitations
Even though simulating thermal losses generates information about the thermal state of a
block, thermal dynamics do not affect the electrical behavior of Simscape Electrical
blocks during simulation.
3-45
3 Modeling and Simulation Basics
ee_rectifier_diodes
The model contains a three-phase rectifier that includes six Diode blocks.
2 Select a thermal variant for the Diode1 block, right-click the block and, from the
context menu, select Simscape > Block choices. Select Show thermal port.
3 Add a Simscape Electrical block that represents heat flow between the diode and the
environment. In the model window, the text on the right, contains links that open the
Simulink Library browser. Click Simscape > Electrical > Pasive > Thermal and
add a Foster Thermal Model block to the model.
4 Modify these Foster Thermal Model block parameters:
a From the Simulink Library browser, open the Simscape > Foundation Library
> Thermal > Thermal Sources library and add an Ideal Temperature Source
block.
b From the Simscape > Foundation Library > Thermal > Thermal Elements
library, add a Thermal Reference block.
c From the Simscape > Foundation Library > Physical Signals > Sources
library, add a PS Constant block. For the Constant parameter, specify a value of
300.
6 Measure and display the temperature of Diode1:
a From the Simulink Library browser, open the Simscape > Foundation Library
> Thermal > Thermal Sensors library, add an Ideal Temperature Sensor block.
3-46
Simulate Thermal Effects Using Simscape Electrical Thermal Blocks
b Make a copy of one of the PS-Simulink Converter blocks in the model window.
For the Output signal unit parameter, select K.
c From the Simulink Library browser, open the Simulink > Sinks library and add
a Scope block.
7 Arrange and connect the blocks as shown in the figure.
8 Label the signal from the PS-Simulink Converter block to the Scope block, double-
click the line between the blocks and at the prompt, enter Temp (K).
9 Simulate the model.
10 To see the temperature data, open the Scope block.
3-47
3 Modeling and Simulation Basics
To see the total heat generated by all the semiconductors in the rectifier, use data logging
and the Simscape Results Explorer.
1 To enable the thermal ports on all the rectifier diodes, select thermal variants for the
Diode2, Diode3, Diode4, Diode5, and Diode6 blocks.
2 To measure heat transfer for each diode, create a Foster thermal model subsystem:
3-48
Simulate Thermal Effects Using Simscape Electrical Thermal Blocks
3-49
3 Modeling and Simulation Basics
c Create a subsystem from the copied blocks and rename the subsystem as
Foster_D2. For information see, “Create a Subsystem” (Simulink).
d Open the Foster_D2 subsystem. For the Conn1 block, for the Port location on
the parent subsystem parameter, select Right.
e Make four copies of the Foster_D2 subsystem. Attach one subsystem to each of
the remaining Diode blocks and rename the subsystems as Foster_D3 through
Foster_D6 to match the Diode3 through Diode6 block names.
3 Simulate the model.
4 View the results using the Simscape Results Explorer:
a In the model window, in the text under Three-Phase Rectifier, click Explore
simulation results.
b To display the temperature data for Diode1, in the Simscape Results Explorer
window, expand the Diode1 > H node and click T.
c To display the DC voltage in a separate plot, expand the Voltage_Sensor node
and CTRL+click V.
d To display the temperature data for all the diodes, expand the Diode2 > H node
and CTRL+click T. Repeat the process for Diode3 through Diode6.
e To overlay the temperature data in single plot, in the Simscape Results Explorer
window, above the tree-node window, click the options button. In the Options
3-50
Simulate Thermal Effects Using Simscape Electrical Thermal Blocks
dialog box, for Plot signals, select Overlay. To accept the change, click OK.
Click and drag the legend down to see the temperature data clearly.
3-51
3 Modeling and Simulation Basics
3-52
See Also
The temperature profile for each diode lags, in succession, behind the temperature
profile of Diode1. For each diode, the temperature also rises and settles along the
same values as the temperature profile for Diode1. The data indicate that, because
of the lagging behavior of the individual diode temperatures, the temperature of the
rectifier rises and settles along the same temperature profile as the diodes, but with
less fluctuation.
References
[1] Schütze, T. AN2008-03: Thermal equivalent circuit models. Application Note. V1.0.
Germany: Infineon Technologies AG, 2008.
See Also
Cauer Thermal Model Element | Diode | Foster Thermal Model | GTO | IGBT (Ideal,
Switching) | MOSFET (Ideal, Switching) | Thermal Resistor | Thyristor (Piecewise Linear)
Related Examples
• “Quantifying IGBT Thermal Losses”
3-53
3 Modeling and Simulation Basics
1 Right-click a battery block in your model and, from the context menu, select
Electrical > Basic characteristics. The software automatically computes a set of
bias conditions, based on the block parameter values, and opens a figure window
containing a plot of no-load voltage versus the state-of-charge (SOC) for the block.
For example, the following plot corresponds to the default parameter values of a
Battery block with infinite charge.
3-54
Plot Basic Characteristics for Battery Blocks
2 If you change the block parameter values and plot the characteristics again, the plot
opens in a new window. This way, you can compare the plots side-by-side and see how
the parameter values affect the resulting voltage-charge characteristics for the block.
For example, if you change the Battery charge capacity parameter value to Finite
and Self-discharge to Enabled, the new plot looks like this.
3-55
3 Modeling and Simulation Basics
See Also
Battery | Battery (Table-Based)
3-56
Plot Basic Characteristics for Semiconductor Blocks
This feature is implemented for nonthermal variants of the following blocks in the
Semiconductors library:
• N-Channel IGBT
• N-Channel MOSFET (both threshold-based and surface-potential-based variants)
• P-Channel MOSFET (both threshold-based and surface-potential-based variants)
• N-Channel LDMOS FET
• P-Channel LDMOS FET
• N-Channel JFET
• P-Channel JFET
• NPN Bipolar Transistor
• PNP Bipolar Transistor
1 Right-click a semiconductor block in your model and, from the context menu, select
Electrical > Basic characteristics. The software automatically computes a set of
bias conditions, based on the block parameter values, and opens a figure window
containing a plot of the DC I-V characteristics for the block.
For example, the following plot corresponds to the default parameter values of a
threshold-based N-Channel MOSFET block.
3-57
3 Modeling and Simulation Basics
2 If you change the block parameter values and plot the characteristics again, the plot
opens in a new window. This way, you can compare the plots side-by-side and see how
the parameter values affect the resulting DC I-V characteristics for the block.
For example, if you change the Gate-source voltage, Vgs, for R_DS(on) parameter
value to 20 V, the new plot looks like this.
3-58
See Also
See Also
More About
• “MOSFET Characteristics Viewer” on page 3-60
3-59
3 Modeling and Simulation Basics
In this section...
“Suggested Workflow” on page 3-60
“Add and Manage Characteristics” on page 3-62
“Choose Parameters and Generate Plots” on page 3-65
“Save the Results” on page 3-67
Suggested Workflow
The Characteristics Viewer tool is available for surface-potential-based N-Channel
MOSFET or P-Channel MOSFET blocks only. To switch to a surface-potential-based
variant when you add an N-Channel MOSFET or P-Channel MOSFET block from the
library, right-click the block in your model and, from the context menu, select Simscape
> Block choices > Surface-potential-based. Then, when you right-click the block
again, the context menu will contain the Electrical option, necessary to start the
parameterization tool.
3-60
MOSFET Characteristics Viewer
3-61
3 Modeling and Simulation Basics
Continue adding more characteristics, as needed. The Replace plot button lets you
replace previously added plots. You can also use the List/Delete characteristics
block, iteratively with Add characteristics, to configure your characteristics set.
3 Double-click Choose parameters and select the parameters of interest.
4 Double-click Generate plots.
5 Iterate between the previous two steps to tune the parameters by matching the
simulation results to the target curves.
6 When satisfied with the results of the parameters tuning, double-click Update
starting block parameters to update the block parameters in your model. Until you
perform this step, the block in the original model is not affected.
7 You can double-click Save data to save the generated characteristics as a MAT-file,
for future reuse in a different model.
3-62
MOSFET Characteristics Viewer
2 Enter Plot number. This number defines the number of the figure that the
characteristic will be plotted on. It allows you to add multiple characteristics to the
same figure, for overlaying characteristics on top of each other. However, the figure
will comprise one xy-axis only.
3 Specify the Characteristic type:
• Target only — The plot will contain data that you specified, in terms of both
input and output values. No simulation will be performed in this case. The data
will simply be added to the appropriate plot.
• Simulated only — The plot will contain data that is a result of a simulation over
the input bias conditions that you specify.
• Target and simulated — The plot will contain both types of data. This option
is useful if you are trying to adjust parameters for the model to fit data that you
have extracted from a datasheet.
3-63
3 Modeling and Simulation Basics
4 Select Sweep type, which defines the x-axis variable for the resultant plot:
3-64
MOSFET Characteristics Viewer
The Replace plot button lets you replace previously added plots. You can also use
the List/Delete characteristics block, iteratively with Add characteristics, to
configure your characteristics set.
3-65
3 Modeling and Simulation Basics
3-66
MOSFET Characteristics Viewer
The Tuner window opens. It contains a series of sliders on different tabs, according to
which feature of the MOSFET characteristics is most impacted by the specific
parameter:
• The VT tab displays parameters that primarily impact the threshold voltage
(gamma and phib2ref).
• The parameters on the DC tab primarily affect the DC characteristics.
• The parameters on the AC tab primarily affect the MOSFET dynamics.
• The parameters on the T tab affect temperature scaling.
• The parameters on the FIXED tab are generally fixed at some particular value
that is not easy to derive from the displayed characteristics, such as the
simulation temperature and the gate resistance (which is often indicated directly
on datasheets).
• The EXTRAS tab contains other parameters, which impact the characteristics in
ways similar to parameters that already appear on other tabs. For example, Rsref
(the series resistance associated with the source) operates similarly to betaref
from the DC tab. As a result, it is not always possible to disentangle these two
effects.
2 Use the sliders on the appropriate tabs of the Tuner dialog.
You can modify the min and max values, as needed, because they simply define the
range over which the various sliders work. These values have no meaning for the
underlying model parameters. Changing a min or max value automatically updates
the slider range, without needing to click OK or Apply.
3 After adjusting the sliders, generate the plots to see how close the simulation data is
to the target data. In the charactericViewer window, double-click Generate
plots.
4 Iterate between tuning the parameters and generating plots until the simulation
results match the target curves.
3-67
3 Modeling and Simulation Basics
Note For this step to work, the original model must stay open while you are tuning
the parameters.
• You can also double-click Save data to save the generated characteristics as a MAT-
file, for future reuse in a different model. Specify the file name for saving the data.
Inside the file, all the data is saved in an object named parameterHelper.
To apply the parameters stored in this object to another MOSFET block, select the
MOSFET block in a model and, in the MATLAB Command Window, type:
parameterHelper.parameters.updateBlockParameters(gcbh)
This command applies the parameter values to the block defined by the handle gcbh.
You can also use a string instead of the block handle, for example:
parameterHelper.parameters.updateBlockParameters(gcb)
See Also
More About
• Interactive Generation of MOSFET Characteristics
• “Plot Basic Characteristics for Semiconductor Blocks” on page 3-57
3-68
Converting a SPICE Netlist to Simscape Blocks
You can convert SPICE components into Simscape equivalents using the SPICE
conversion assistant. Often this conversion is automatic. However, because SPICE is a
rich language, it is not always possible to perform a full conversion without some manual
intervention.
To convert SPICE subcircuits into equivalent Simscape components, follow these steps.
There are many different SPICE simulators with variations in syntax and syntax
interpretation. The conversion assistant uses the same syntax as Cadence® PSpice and,
where such differences exist, complies with PSpice.
Commands
The SPICE conversion assistant supports these commands:
3-69
3 Modeling and Simulation Basics
The conversion assistant implements .FUNC SPICE commands using Simscape functions.
These functions are placed inside a package sublibrary named
+subcircuit_name_simscape_functions, where subcircuit_name is the name of
the subcircuit being converted.
where the r, c, and l values are scaling factors for the value specified on the component
declaration. This behavior complies with PSpice, but is not consistent across all
simulators.
The conversion assistant does not automatically convert initial conditions specified using
the .IC statement. However, you can specify initial conditions for capacitors and
inductors using the syntax IC=<value>. Also, you can manually convert any .IC
statements from the generated Simscape component files.
Because the purpose of the conversion assistant is to help convert SPICE subcircuits into
Simscape blocks, simulation commands, such as .TRAN, are ignored.
Numeric Suffixes
The conversion assistant supports these numeric SPICE suffixes:
3-70
Elementary Math
Mathematical Functions
The conversion assistant supports these basic mathematical functions used in SPICE and
MATLAB.
Elementary Math
Name SPICE Function MATLAB Function
Absolute value abs abs
Smallest element min min
Largest element max max
Sign function sgn sign
Trigonometry
Name SPICE Function MATLAB Function
Sine sin sin
Inverse sine asin asin
Hyperbolic sine sinh sinh
Cosine cos cos
Inverse cosine acos acos
Hyperbolic cosine cosh cosh
3-71
3 Modeling and Simulation Basics
The conversion assistant interprets log() as the natural logarithm rather than the
base-10 logarithm. Not all SPICE simulators are consistent in this regard, so ensure that
this interpretation is congruent with your SPICE model.
Other
In addition, the conversion assistant supports these SPICE functions:
3-72
Sources
Symbols
The conversion assistant recognizes these SPICE symbols:
• + at the start of a line indicates line continuation from the previous line
• * at the start of a line indicates that the entire line is a comment
• ; within a line indicates the beginning of an inline comment
Components
The notation for SPICE commands in this section follows these rules:
This list shows the full set of supported SPICE components, and their supported SPICE
netlist notations. You can specify only the .MODEL parameters that differ from SPICE
default values.
Sources
• Independent voltage source
V<name> <+ node> <- node> [DC] <value>
V<name> <+ node> <- node> exp(<v1> <v2> <td1> <tc1> <td2> <tc2>)
V<name> <+ node> <- node> pulse(<v1> <v2> <td> <tr> <tf> <pw> <per>)
V<name> <+ node> <- node> pwl(<<tj> <vj>>*)
V<name> <+ node> <- node> sffm(<voff> <vampl> <fc> <mod> <fm>)
V<name> <+ node> <- node> sin(<voff> <vampl> <freq> <td> <df>)
3-73
3 Modeling and Simulation Basics
• Behavioral source (The <expression> does not need to appear in braces {})
B<name> <+ node> <- node> V=<expression>
B<name> <+ node> <- node> I=<expression>
Passive Devices
• Resistor
R<name> <+ node> <- node> [model name] <value>
.MODEL <model name> res(r=<value>)
• Capacitor
C<name> <+ node> <- node> [model name] <value> [IC=<value>]
.MODEL <model name> cap(c=<value>)
• Inductor
L<name> <+ node> <- node> [model name] <value> [IC=<value>]
.MODEL <model name> ind(l=<value>)
• Inductor coupling
K<name> <inductor name> <inductor name>* <value>
3-74
Switches
Switches
• Voltage-controlled switch
S<name> <+ node> <- node> <+ control node> <- control node> <model name>
.MODEL <model name> sw(ron=<value>, roff=<value>, vt=<value>, vh=<value>)
• Current-controlled switch
W<name> <+ node> <- node> <voltage source name> <model name>
.MODEL <model name> csw(ron=<value>, roff=<value>, it=<value>, ih=<value>)
Semiconductor Devices
• Diode
D<name> <+ node> <- node> <model name> [area]
.MODEL <model name> d(is=<value>, rs=<value>, n=<value>, cjo=<value>, vj=<value>,
+m=<value>, fc=<value>, tt=<value>, revbrk=<value>, bv=<value>, ibv=<value>,
+xti=<value>, eg=<value>)
NPN
Q<name> <collector node> <base node> <emitter node> [substrate node] <model name> <area>
.MODEL <model name> npn(bf=<value>, br=<value>, cjc=<value>, cje=<value>, cjs=<value>,
+eg=<value>, fc=<value>, ikf=<value>, ikr=<value>, irb=<value>, is=<value>, isc=<value>,
+ise=<value>, itf=<value>, mjc=<value>, mje=<value>, mjs=<value>, nc=<value>, ne=<value>,
+nf=<value>, nr=<value>, rb=<value>, rbm=<value>, rc=<value>, re=<value>, tf=<value>,
+tr=<value>, vaf=<value>, var=<value>, vjc=<value>, vje=<value>, vjs=<value>, vtf=<value>,
+xcjc=<value>, xtb=<value>, xtf=<value>, xti=<value>)
PNP
Q<name> <collector node> <base node> <emitter node> [substrate node] <model name> <area>
.MODEL <model name> pnp(bf=<value>, br=<value>, cjc=<value>, cje=<value>, cjs=<value>,
+eg=<value>, fc=<value>, ikf=<value>, ikr=<value>, irb=<value>, is=<value>, isc=<value>,
+ise=<value>, itf=<value>, mjc=<value>, mje=<value>, mjs=<value>, nc=<value>, ne=<value>,
+nf=<value>, nr=<value>, rb=<value>, rbm=<value>, rc=<value>, re=<value>, tf=<value>,
+tr=<value>, vaf=<value>, var=<value>, vjc=<value>, vje=<value>, vjs=<value>, vtf=<value>,
+xcjc=<value>, xtb=<value>, xtf=<value>, xti=<value>)
N-Channel
J<name> <drain node> <gate node> <source node> <model name> [area]
.MODEL <model name> njf(beta=<value>, cgd=<value>, cgs=<value>, fc=<value>, is=<value>,
+lambda=<value>, m=<value>, n=<value>, rd=<value>, rs=<value>, vto=<value>, xti=<value>)
P-Channel
3-75
3 Modeling and Simulation Basics
J<name> <drain node> <gate node> <source node> <model name> [area]
.MODEL <model name> pjf(beta=<value>, cgd=<value>, cgs=<value>, fc=<value>, is=<value>,
+lambda=<value>, m=<value>, n=<value>, rd=<value>, rs=<value>, vto=<value>, xti=<value>)
Subsystems
• Subcircuit
X<name> [node]* <subcircuit name> [PARAMS: < <name>=<value> >*]
The generated Simscape component file contains all the supported conversions, and this
header, which identifies the temperature coefficients of the resistor for manual
conversion:
component test
% test
3-76
See Also
To complete the conversion, modify the Simscape component file to implement the
missing components. For more information about performing manual conversions and this
particular scenario, see subcircuit2ssc.
Limitations
• The netlist must be written in PSpice format and be syntactically correct. The
conversion assistant does not check for proper PSpice syntax.
• Only a subset of the PSpice netlist language is supported. However, unsupported
PSpice commands are identified at the top of the corresponding Simscape component
file to facilitate manual conversion.
• To build generated Simscape components into Simscape blocks, parameter values
must conform to Simscape constraints. For example, capacitance of a fundamental
capacitor and inductance of a fundamental inductor must be nonzero.
See Also
ssc_build | subcircuit2ssc
More About
• “Building Custom Block Libraries” (Simscape)
• “Composite Components” (Simscape)
3-77
4
Modeling Machines
Machine Parameterization
In Simscape Electrical software, induction machines are parameterized using
fundamental parameters. Each synchronous machine is parameterized using standard or
fundamental parameters.
Machine fundamental parameters include the values of inductances and resistances of the
stator and rotor d- and q-axis equivalent circuits. These parameters fully specify the
electrical characteristics of the machine, but you cannot determine them directly from
machine test responses. Hence, it is more common to parameterize a synchronous
machine using a standard parameter set. You can obtain the standard parameters by
observing responses at the machine terminals with suitable tests scenarios.
You can tell the parameter set a block uses because the block name includes the
parameter set name, e.g. Induction Machine Squirrel Cage. The parameters you can set
in the block dialog box correspond to the parameterization type.
If a machine block has standard and fundamental variants, base your block choice on the
parameters you are most familiar with or you have available. Standard block variants use
classical equations to convert standard parameter values that you enter to fundamental
parameter values for use at run time.
If a machine block has an SI and a per-unit variant, base your block choice on the
parameters you have available. For machine blocks that are SI variants, you enter the
number of pole pairs and the SI values for the nominal voltage, power, and frequency on
the main tab of the dialog box. You also enter SI values for the resistance and reactance
parameters on the impedance tab, and for the magnetic flux linkage parameters on the
initial condition tab. The block uses classical equations to calculate per-unit base values
from the parameters on the main tab. It expresses the resistance, inductance, and
magnetic flux linkage parameters as per-unit ratios of the SI values (resistance,
reactance, and magnetic flux linkage) and the base values for use at run time.
The field circuit and rotational ports of machine blocks use SI units. However, the pu
measurement port of machine blocks outputs a vector of physical signals in per-unit.
4-2
See Also
See Also
More About
• “Per-Unit System of Units” on page 1-10
• “Per-Unit Conversion for Machine Parameters” on page 4-4
4-3
4 Modeling Machines
X(SI)
L=X=
Xbase
where:
where:
4-4
See Also
See Also
More About
• “Per-Unit System of Units” on page 1-10
4-5
4 Modeling Machines
Using other options on the Electrical menu, you can display values in per-unit or display
base parameter values in the MATLAB Command Window. These options enable you to
initialize and tune your three-phase machine quickly.
• Display Base Values — Displays the machine per-unit base values in the MATLAB
Command Window.
• Plot Torque Speed (SI) — Plots torque versus speed, both measured in SI units, in a
MATLAB figure window using the present machine parameters.
• Plot Torque Speed (pu) — Plots torque versus speed, both measured in per-unit, in a
MATLAB figure window using the present machine parameters.
• Plot Open-Circuit Saturation — Plots terminal voltage versus no-load stator
current, both in per-unit, or, for SI blocks, in V and A, respectively, in a MATLAB figure
window. The plot contains three traces:
• Unsaturated
• Saturated
• Derived
• Plot Saturation Factor — Plots saturation factor applied to magnetic inductance
versus magnetic flux linkage in per-unit, or for SI blocks, in Wb, in a MATLAB figure
window.
• Plot Saturated Inductance — Plots magnetizing inductance versus per-unit
magnetic flux linkage, both in per-unit, or, for SI blocks, in H and Wb, respectively, in a
MATLAB figure window.
4-6
Machine Plotting and Display Options
• Display Base Values — Displays the machine per-unit base values in the MATLAB
Command Window
• Display Associated Base Values — Displays the associated per-unit base values in
the MATLAB Command Window.
• Display Associated Initial Conditions — Displays the associated intitial condition
values in the MATLAB Command Window.
• Plot Open-Circuit Saturation (pu) — Plots air-gap voltage, Vag, versus field current,
ifd, both measured in per-unit, in a MATLAB figure window. The plot contains three
traces:
4-7
4 Modeling Machines
1 Calculate the required power and voltage characteristics of your load circuit.
2 In the Initial Conditions tab of the dialog box, set Specify initialization by to
Electrical power and voltage output.
3 Enter the required power and voltage values and click OK.
4 Right-click the machine block and select Electrical > Display Associated Initial
Conditions.
Simscape Electrical Power Systems calculates the field circuit and rotational port
values required to start the machine in steady state and displays them in the
MATLAB Command Window.
5 Use these values to input parameters to the blocks connected to the field circuit and
rotational ports of the synchronous machine.
4-8
5
Customization
• “Build Custom Blocks Using the Three-Phase Electrical Domain” on page 5-2
• “Custom Synchronous Machine” on page 5-4
5 Customization
foundation.electrical.three_phase
You can use these simplified example models to write your own custom component files.
To customize the block for your application, edit the source file and save it under another
name.
For example, you can create a folder called +MyMachines and save the source files for
your customized machines in this folder. Create this folder in your working directory, or in
another directory that is on the MATLAB path. Running the ssc_build command on this
package generates the MyMachines_lib library model. This library contains all your
custom machine blocks and is located in the same directory where you have created the
+MyMachines folder. Open the MyMachines_lib library by double-clicking it or by
typing its name at the MATLAB command prompt.
For more information on packaging and deploying Simscape component files, see
“Building Custom Block Libraries” (Simscape).
5-2
See Also
component MyComponent
• The comment line immediately following the component declaration (that is, the first
line beginning with the % character) defines the name of the block, as it appears in the
custom library next to the block icon and at the top of the block dialog box. If you do
not specify this comment, then the component name serves as the block name. The
block name must be unique within the subpackage (sublibrary) where it resides.
• Additional comments, below the line specifying the block name, are interpreted as the
block description. You do not have to modify them when copying an existing file, but if
you change the way the component works, it makes sense to reflect the change in the
block description. The block description is for informational purposes only.
• When modifying component equations, if you introduce additional terms, make sure to
add the appropriate variables or parameters to the component declaration section. For
example, if you add zero-sequence dynamics to the component equations, declare an
additional parameter for stator zero-sequence inductance, L0, and an additional
variable for the initial stator zero-sequence magnetic flux linkage.
The “Custom Synchronous Machine” on page 5-4 tutorial shows how you can modify
the Synchronous Machine component file and customize it for use in your applications.
For more information on writing customized component files, see “Custom Components”
(Simscape).
See Also
More About
• “Custom Synchronous Machine” on page 5-4
• “Custom Components” (Simscape)
• “Foundation Domains” (Simscape)
5-3
5 Customization
This example shows how you can further simplify the component file and make a custom
machine block that does not account for the stator rate of change of flux.
1 In your working directory, create a folder called +MyMachines. This folder will
contain the source files for your customized machines.
2 To open the library of simplified component examples, at the MATLAB command
prompt, type:
ThreePhaseExamples_lib
5-4
Custom Synchronous Machine
The Simscape source file for this block opens in the MATLAB Editor.
5 Change the name of the component, the name of the block, and the block description
by replacing these lines of the file:
component sm
% Synchronous Machine :1.5
% Synchronous machine (SM) with a round rotor parameterized
% using fundamental per-unit parameters. The defining equations are
% simplified by omitting the zero-sequence dynamics: the model is suitable
% for balanced operation.
% The model contains effect of rate of change of magnetic flux linkages
% on stator voltages, effect of speed variation on stator voltages, one
% damper winding on the d-axis and two damper windings on the q-axis.
5-5
5 Customization
with:
component sm1
% Simplified Synchronous Machine
% This synchronous machine does not include the stator d.psi/dt terms.
6 To remove the stator rate of change of flux terms, scroll down to the equations
section and modify the stator voltage equations from:
to:
ssc_build(MyMachines)
MyMachines_lib
The library contains the Simplified Synchronous Machine block, which you can now
use in your models.
5-6
See Also
See Also
ssc_build
More About
• “Build Custom Blocks Using the Three-Phase Electrical Domain” on page 5-2
• “Custom Components” (Simscape)
• “Customizing the Block Name and Appearance” (Simscape)
• “Component Equations” (Simscape)
5-7
6
Control
6 Control
This example shows how to tune an electric drive using a cascade control structure.
where,
6-2
Tune an Electric Drive
• σ is overshoot.
• ξ is the damping factor.
The response time, tr, depends on the damping and the natural frequency, ωn, such that:
• If ξ < 0.7,
4
tr ≅ .
ωnξ
• If ξ ≥ 0.7,
6ξ
tr ≅ .
ωn
The general workflow for designing a PI controller for a first-order system is:
1 Discretize the plant model using the zero-order hold (ZOH) discretization method.
That is, given that the first-order equation representing the plant is
Km
G(s) = ,
Tms + 1
where,
Setting
1 − z−1
s= ,
z−1Ts
6-3
6 Control
1
GPI(s) = KP + KI ,
s
setting
1 − z−1
s= ,
z−1Ts
Combining the discrete equations for the plant and the controller yields the closed
loop transfer function for the system,
q0b1z−1 + q1b1z−2
G0(z−1) = ,
1 + a1 − 1 + q0b1 z−1 + −a1 + q1b1 z−2
The denominator of the transfer function is the characteristic polynomial. That is,
where,
• α = − 2e−ξωnTscos ω T 1 − ξ 2 .
1 n s
• α = e−2ξωnTs .
2
4 To determine the controller parameters, set the characteristic polynomial for the
system equal to the characteristic polynomial for the required performance. If
Pc0(z−1) = Pcd(z−1),
then
α1 = a1 − 1 + q0b1
6-4
Tune an Electric Drive
and
α2 = − a1 + q1b1 .
α1 − a1 + 1
q0 =
b1
and
α2 + a1
q1 = .
b1
Therefore, the general equations for the proportional and integral control parameters
for the first-order system are
KP = q0
and
q1 + Kp
KI = .
Ts
dia
va = La + Raia + Kbω
dt
and
dω
T e = Jm + Bmω + Tload = Kbia,
dt
where:
6-5
6 Control
To tune the current controller, assume that the model is linear, that is, that the back
electromotive force, as represented by Kbω, is negligible. This assumption allows for an
approximation of the plant model using this first-order Laplace equation:
1
Ra
Gi(s) = La
.
Ra
s+1
Given the system requirements, you can now solve for KP and KI. The requirements for the
current controller in the example model are:
Therefore, the proportional and integral parameters for the current controller are:
• KP = 7.7099.
• KI = 455.1491.
To tune the speed controller, approximate the plant model with a simple model. First
assume that the inner loop is much faster than the outer loop. Also assume that there is
no steady-state error. These assumptions allow for the use a first-order system by
considering a transfer function of 1 for the inner current loop.
To output rotational velocity in revolutions per minute, the transfer function is multiplied
by a factor of 30/π. To take as control input the armature current instead of the motor
torque, the transfer function is multiplied by the proportionality constant, Kb. The
resulting approximation for the outer-loop plant model is
6-6
Tune an Electric Drive
30Kb
πBm
Gn(s) = Jm
.
Bm
s+1
The speed controller has the same sample time and overshoot requirements as the
current controller, but the response time is slower, such that:
Therefore, the proportional and integral parameters for the speed controller are:
• KP = 0.0045
• KI = 0.0405
model = 'ee_dc_motor_control'
open_system(model)
6-7
6 Control
b The Control subsystem contains the model of the cascaded control system built
using blocks from the Simulink library.
sim(model)
3 View the results. Open the Scope block.
6-8
Tune an Electric Drive
The input arguments for the function are the system parameters and the
requirements for the controller:
6-9
6 Control
edit ee_getDCMotorFirstOrderPIParams
b To calculate the controller parameters using the function, save these system
parameters to the workspace:
Ra=4.67; % [Ohm]
La=170e-3; % [H]
Bm=47.3e-6; % [N*m/(rad/s)]
Jm=42.6e-6; % [Kg*m^2]
Kb=14.7e-3; % [V/(rad/s)]
Tsc=1e-3; % [s]
c Calculate the parameters for tuning the current controller as a function of the
parameters and requirements for the inner controller:
• Km = 1/Ra.
• Tm = La/Ra.
• Ts = Tsc.
• sigma = 0.05.
• Tr = 0.11.
Kp_i =
7.7099
Ki_i =
455.1491
The gain parameters for the current controller are saved to the workspace.
d Calculate the parameters for tuning the speed controller based on the
parameters and requirements for the outer controller:
• Km = Kb*(30/pi).
6-10
Tune an Electric Drive
• Tm = Jm/Ra.
• Ts = Tsc.
• sigma = 0.05.
• Tr = 0.5.
[Kp_n, Ki_n] = ee_getDCMotorFirstOrderPIParams((Kb*(30/pi))/Bm,Jm/Bm,Tsc,0.05,0.5)
Kp_n =
0.0045
Ki_n =
0.0405
The gain parameters for the speed controller are saved to the workspace.
5 Simulate the model using the saved gain parameters for the speed and controllers.
sim(model)
6 View the results. Open the Scope block.
6-11
6 Control
There is slightly more overshoot, however, the controller responds much faster to the load
torque change.
See Also
Inertia | Rotational Electromechanical Converter | Rotational Friction
Related Examples
• “DC Motor Control”
6-12
7
• “Optimize Block Settings for Simulating with the Partitioning Solver” on page 7-2
• “Phasor-Mode Simulation Using Simscape Components” on page 7-13
• “Examine the Simulation Data Logging Configuration of a Model” on page 7-19
• “Perform a Power-Loss Analysis” on page 7-21
• “Choose a Simscape Electrical Function for an Offline Harmonic Analysis”
on page 7-30
• “Perform an Online Harmonic Analysis Using the Simscape Spectrum Analyzer Block”
on page 7-34
7 Simulation and Analysis of Power Engineering Systems
The Partitioning solver is a Simscape fixed-step local solver that improves performance
for certain models. However, not all networks can simulate with the Partitioning solver.
Some models that use the Partitioning solver can produce errors and fail to initialize due
to numerical difficulties. To resolve numerical difficulties preventing initialization with
asynchronous, synchronous, and permanent magnet rotor machine blocks, you can
exclude zero-sequence terms. Excluding parasitic conductance resolves numerical
difficulties with the Floating Neutral (Three-Phase) and Neutral Connection block, which
include such conductance by default.
To determine the best solver choice for your model, use the ee_updateSolver helper
function, which is useful for iterating with various solvers. The function updates certain
parameter values for every instance of these blocks in your model:
7-2
Optimize Block Settings for Simulating with the Partitioning Solver
1 Open the model. At the MATLAB command prompt, enter this code.
See Code
model = 'ee_pmsm_drive';
open_system(model)
7-3
7 Simulation and Analysis of Power Engineering Systems
Two blocks that the ee_solverUpdate function can update are the Solver
Configuration block and PMSM block.
2 Save the parameter settings for the two blocks.
See Code
7-4
Optimize Block Settings for Simulating with the Partitioning Solver
• Use local solver — The option to use a local Simscape solver is cleared.
• Solver type — Backward Euler, a Simscape local fixed- cost solver, is specified.
However, if you open the block dialog box, you can see that it is not enabled
because the option to use a local solver is cleared.
• Use fixed-cost runtime consistency iterations — The option to use fixed-cost is
cleared. This option is also disabled when the option to use a local solver is
cleared.
For the machine, the Zero sequence parameter is set to Include. Zero-sequence
equations can cause numerical difficulty when you simulate with the Partitioning
solver.
7-5
7 Simulation and Analysis of Power Engineering Systems
See Code
See Code
% Run a timed simulation using the Baseline solver configuration
out = sim(model);
tBaseline = out.SimulationMetadata.TimingInfo.ExecutionElapsedWallTime;
6 Use ee_updateSolver function to change to the Backward Euler solver
configuration. Save the configuration settings, and compare the settings to the
baseline settings.
See Code
% Configure for Backward Euler solver simulation
ee_updateSolver('Backward Euler',model)
% Save the new parameter settings and compare them to the baseline
% configuration.
7-6
Optimize Block Settings for Simulating with the Partitioning Solver
get_param(solvConfigPath,'UseLocalSolver');
'Solver Configuration','Solver type',...
get_param(solvConfigPath,'LocalSolverChoice');
'Solver Configuration','Sample time',...
get_param(solvConfigPath,'LocalSolverSampleTime');
'Solver Configuration',...
'Use fixed-cost runtime consistency iterations',...
get_param(solvConfigPath,'DoFixedCost');
'Machine','Zero sequence',...
get_param(machinePath,'zero_sequence')};
configDiff =
{'on'}
The option to use the local solver, which is set to Backward Euler by default, and the
option to use fixed-cost runtime consistency iterations are now both selected.
7 Run a timed simulation using the Backward Euler solver.
See Code
out = sim(model);
tBackEuler = out.SimulationMetadata.TimingInfo.ExecutionElapsedWallTime;
8 If you change the local solver to the Partitioning solver and simulate the model now,
an error occurs because of the zero-sequence terms. Use the ee_updateSolver
function to configure the model for simulating with the Partitioning solver without
generating an error. Save the configuration settings, compare the settings to baseline
settings, and run a timed simulation.
7-7
7 Simulation and Analysis of Power Engineering Systems
See Code
% Configure for Partioning solver simulation
ee_updateSolver('Partitioning', model)
configDiff =
{'NE_PARTITIONING_ADVANCER' }
{'ee.enum.park.zerosequence.exclude'}
{'on' }
7-8
Optimize Block Settings for Simulating with the Partitioning Solver
The solver type is now set to the Partitioning solver and the machine is configured to
exclude zero-sequence terms.
The simulation runs without generating an error. It does generate a warning because
initial conditions for nondifferential variables are not supported for the Partitioning
solver.
9 Print tables that show:
See Code
display(compTimeDiffTable);
% Compute and display the percent difference for the simulation times
spdBackEulerVsBaseline = 100*(tBaseline - tBackEuler)/tBaseline;
spdPartitionVsBaseline = 100*(tBaseline - tPartitioning)/tBaseline;
7-9
7 Simulation and Analysis of Power Engineering Systems
'VariableNames', {'Comparison','Percent_Difference'});
display(compPctDiffTable);
3×2 table
Solver Sim_Duration
________________ ____________
'Baseline' [38.0255]
'Backward Euler' [23.4011]
'Partitioning' [ 9.2042]
compPctDiffTable =
2×2 table
Comparison Percent_Difference
________________________________ __________________
Simulation time on your machine may differ because simulation speed depends on
machine processing power and the computational cost of concurrent processes. The
local fixed-step Partitioning and Backward Euler solvers are faster than the baseline
solver, which is a global, variable-step solver. The Partitioning solver is faster than
the Backward Euler solver.
10 To compare the results, open the Simulink Data Inspector.
See Code
% Get Simulink Data Inspector run IDs for
% the last three runs
runIDs = Simulink.sdi.getAllRunIDs;
runBackEuler = runIDs(end - 1);
runPartition = runIDs(end);
compBaselinePartition = Simulink.sdi.compareRuns(runBackEuler,...
runPartition);
7-10
Optimize Block Settings for Simulating with the Partitioning Solver
The first plot shows the overlay of the Backward Euler and Partitioning solver
simulation results. The second plot shows how they differ. The default tolerance for
differences is 0. To determine if the accuracy of the results meets your requirements,
you can adjust the relative, absolute, and time tolerances. For more information, see
“Compare Simulation Data” (Simulink).
7-11
7 Simulation and Analysis of Power Engineering Systems
You can also use the ee_updateSolver function to reset the model for simulation with a
global solver.
See Code
See Also
PMSM | Solver Configuration
Related Examples
• “Increase Simulation Speed Using the Partitioning Solver” (Simscape)
7-12
Phasor-Mode Simulation Using Simscape Components
To measure the time required to run a simulation, open the model ee_sm_control and
create a model callback.
mdl = load_system('ee_sm_control');
open_system(mdl);
set_param(mdl,'StartFcn','tic;');
set_param(mdl,'StopFcn','tsim=toc;');
7-13
7 Simulation and Analysis of Power Engineering Systems
Double-click the Solver Configuration block and apply the following configuration:
• Enable the local solver by checking the Use local solver check box
• Set the Sample time parameter to 1e-3
• Set the Equation formulation parameter to Time
Simulate the model and save the run time and logging variable.
sim(get_param(mdl,'Name'));
tsim_time = round(tsim,2);
simlog_ee_sm_control_time = simlog_ee_sm_control;
7-14
Phasor-Mode Simulation Using Simscape Components
Double-click the Solver Configuration block and apply the following configuration:
• Enable the local solver by checking the Use local solver check box
• Set the Sample time parameter to 1e-2
• Set the Equation formulation parameter to Frequency and time
Simulate the model and save the run time and logging variable.
sim(get_param(mdl,'Name'));
tsim_phasor = round(tsim,2);
simlog_ee_sm_control_phasor = simlog_ee_sm_control;
Compare DC results
Plot the field voltage and rotor speed for both the time and frequency-time simulations.
For each simulation mode, display markers at every 50 data points.
[hTime,hPhasor]=setup_figure(simlog_ee_sm_control_time,simlog_ee_sm_control_phasor,'dc'
legend([hTime,hPhasor],{['Time (t=',num2str(tsim_time),'s)'],['Phasor (t=',num2str(tsim
7-15
7 Simulation and Analysis of Power Engineering Systems
Compare AC results
Plot the a-phase voltage of the synchronous machine over the time period 1s to 1.1s.
Because of the larger time steps in the frequency-time formulation, the resolution of the
AC quantity is too small to make out the sine wave. The points that are available are
undersampled, but still accurate.
7-16
Phasor-Mode Simulation Using Simscape Components
[hTime,hPhasor]=setup_figure(simlog_ee_sm_control_time,simlog_ee_sm_control_phasor,'ac'
legend([hTime,hPhasor],{['Time (t=',num2str(tsim_time),'s)'],['Phasor (t=',num2str(tsim
7-17
7 Simulation and Analysis of Power Engineering Systems
Sometimes there are small phase offsets between time- and frequency-time-generated AC
signals. This difference is caused by the accumulated integration error of a slightly
different signal frequency over time.
See Also
Solver Configuration
More About
• “Frequency and Time Simulation Mode” (Simscape)
7-18
Examine the Simulation Data Logging Configuration of a Model
model = 'ee_rectifier_power_dissipated';
open(model)
2 Open the model configuration parameters and then, in the left pane, select
Simscape. Relevant parameters are:
• Log simulation data — Data logging is enabled for the whole model because this
parameter is set to All so you can calculate the power dissipated by any of the
semiconductors in the model.
• Workspace variable name — This parameter, which is also referred to as the
name of the simulation log variable, is specified as
simlog_ee_rectifier_power_dissipated.
• Limit data points — You can calculate the power dissipated for the entire
simulation time because the option is not selected.
Alternatively, you can determine the Simscape data logging configuration without opening
the model configuration parameters, by using the get_param function. For example, for
the ee_rectifier_power_dissipated model, to determine:
get_param(model,'SimscapeLogType')
ans =
'all'
• The name of the Simscape logging variable
get_param(model,'SimscapeLogName')
7-19
7 Simulation and Analysis of Power Engineering Systems
ans =
'simlog_ee_rectifier_power_dissipated'
• If the option to limit data-points is on or off
get_param(model,'SimscapeLogLimitData')
ans =
'off'
See Also
Functions
get_param
Related Examples
• “Data Logging” (Simscape)
7-20
Perform a Power-Loss Analysis
This example shows how to analyze power loss and how to mitigate transient power
dissipation behavior. Analyzing power loss, with and without transients, is useful for
determining if components are operating within safety and efficiency guidelines.
Prerequisite
This example requires a simulation log variable in your MATLAB workspace. The model in
this example is configured to log Simscape data for the whole model for the entire
simulation time.
To learn how to determine if a model is configured to log simulation data, see “Examine
the Simulation Data Logging Configuration of a Model” on page 7-19.
model = 'ee_rectifier_power_dissipated';
open(model)
7-21
7 Simulation and Analysis of Power Engineering Systems
sim(model)
rectifierLosses =
6×2 table
LoggingNode Power
_______________________________________________________________________ ______
'ee_rectifier_power_dissipated.Rectifier.D6' 52.222
'ee_rectifier_power_dissipated.Rectifier.D3' 52.222
'ee_rectifier_power_dissipated.Rectifier.D4' 52.194
'ee_rectifier_power_dissipated.Rectifier.D5' 52.194
'ee_rectifier_power_dissipated.Rectifier.D1' 52.194
'ee_rectifier_power_dissipated.Rectifier.D2' 52.194
7-22
Perform a Power-Loss Analysis
On average, diodes D3 and D6 dissipate more power than the other diodes in the
rectifier.
sscexplore(simlog_ee_rectifier_power_dissipated)
2 View the instantaneous power dissipated by the diodes.
7-23
7 Simulation and Analysis of Power Engineering Systems
At the beginning of the simulation, there is a difference in the power dissipation for
each diode.
3 Take a closer look at the differences. Overlay the plots and zoom to the beginning of
the simulation.
a
In the Results Explorer window, click the plot options button.
b Enable the Limit time axis option.
7-24
Perform a Power-Loss Analysis
The variation in power dissipation is due to transient behavior at the beginning of the
simulation. The model reaches steady state at simulation time, t ⋍ 0.001 seconds.
4 Determine the average power dissipation for only the diodes during the interval that
contains transient behavior.
7-25
7 Simulation and Analysis of Power Engineering Systems
rectifierLosses = ee_getPowerLossSummary(simlog_ee_rectifier_power_dissipated.Rectifier,0,1e-3)
rectifierLosses =
6×2 table
LoggingNode Power
______________ ________
'Rectifier.D3' 174.88
'Rectifier.D6' 174.88
'Rectifier.D4' 0.27539
'Rectifier.D5' 0.27539
'Rectifier.D1' 0.12482
'Rectifier.D2' 0.032017
The average power dissipated by diodes D3 and D6 exceeds the average for the other
diodes.
5 Output a table of the maximum power dissipation for each diode, for the entire
simulation time.
pd_D1_max = max(simlog_ee_rectifier_power_dissipated.Rectifier.D1.power_dissipated.series.values);
pd_D2_max = max(simlog_ee_rectifier_power_dissipated.Rectifier.D2.power_dissipated.series.values);
pd_D3_max = max(simlog_ee_rectifier_power_dissipated.Rectifier.D3.power_dissipated.series.values);
pd_D4_max = max(simlog_ee_rectifier_power_dissipated.Rectifier.D4.power_dissipated.series.values);
pd_D5_max = max(simlog_ee_rectifier_power_dissipated.Rectifier.D5.power_dissipated.series.values);
pd_D6_max = max(simlog_ee_rectifier_power_dissipated.Rectifier.D6.power_dissipated.series.values);
diodes = {'D1';'D2';'D3';'D4';'D5';'D6'};
PowerMax = [pd_D1_max;pd_D2_max;pd_D3_max;pd_D4_max;pd_D5_max;pd_D6_max];
T = table(PowerMax,'RowNames', diodes)
T =
6×1 table
PowerMax
________
D1 166.45
D2 166.45
D3 339.54
D4 166.45
D5 166.45
D6 339.54
7-26
Perform a Power-Loss Analysis
The maximum instantaneous power dissipation for diodes D3 and D6 is almost double
the maximum instantaneous power dissipation for the other diodes.
• Final States
• Save final operating point
d Click Apply.
2 Run the simulation.
The final state is saved as the variable xFinal in the MATLAB workspace.
3 Configure the model to initialize using xFinal, in the model configuration parameters.
a
Click the Reload logged data button in the Simscape Results Explorer.
b Click OK to confirm that simlog_ee_rectifier_power_dissipated is the
variable name that contains the logged data.
7-27
7 Simulation and Analysis of Power Engineering Systems
c To see the data more clearly, click and drag the legend away from the peak
amplitudes.
The plot shows that the simulation no longer contains the transient.
6 Output a table of the maximum power dissipation for each diode, for the modified
simulation.
pd_D1_max = max(simlog_ee_rectifier_power_dissipated.Rectifier.D1.power_dissipated.series.values);
pd_D2_max = max(simlog_ee_rectifier_power_dissipated.Rectifier.D2.power_dissipated.series.values);
pd_D3_max = max(simlog_ee_rectifier_power_dissipated.Rectifier.D3.power_dissipated.series.values);
7-28
See Also
pd_D4_max = max(simlog_ee_rectifier_power_dissipated.Rectifier.D4.power_dissipated.series.values);
pd_D5_max = max(simlog_ee_rectifier_power_dissipated.Rectifier.D5.power_dissipated.series.values);
pd_D6_max = max(simlog_ee_rectifier_power_dissipated.Rectifier.D6.power_dissipated.series.values);
diodes = {'D1';'D2';'D3';'D4';'D5';'D6'};
PowerMax = [pd_D1_max;pd_D2_max;pd_D3_max;pd_D4_max;pd_D5_max;pd_D6_max];
T = table(PowerMax,'RowNames', diodes)
T =
6×1 table
PowerMax
________
D1 166.45
D2 166.45
D3 166.45
D4 166.45
D5 166.45
D6 166.45
The maximum instantaneous power dissipation for diodes D3 and D6 is the same as
the maximum instantaneous power dissipation for the other diodes.
See Also
Functions
ee_getEfficiency | ee_getPowerLossSummary | ee_getPowerLossTimeSeries
Related Examples
• “Power-Loss Analysis of a Three-Phase Rectifier”
• “Examine the Simulation Data Logging Configuration of a Model” on page 7-19
• “Data Logging” (Simscape)
• “About the Simscape Results Explorer” (Simscape)
7-29
7 Simulation and Analysis of Power Engineering Systems
Harmonic Distortion
Nonlinear loads create power distortion in the form of harmonics, that is, voltages and
currents that are multiples of the fundamental frequency. Harmonic waveforms can result
in energy losses though heat dissipation and in reduced power quality. They can also
cause equipment to malfunction or to become damaged. Standards development
organizations such as the Institute of Electrical and Electronics Engineers (IEEE) and the
International Electrotechnical Commission (IEC) define the recommended limits for
harmonic content in electric power systems.
To decide which functions and workflows to use for your harmonic analysis, consider your
goals. The table cross-references the harmonic functions with common harmonic analysis
according to the data the function outputs and the task requires.
7-30
Choose a Simscape Electrical Function for an Offline Harmonic Analysis
7-31
7 Simulation and Analysis of Power Engineering Systems
a Specify the filter size, in terms of reactive power compensation, and specify the
filter quality.
b Calculate the capacitor reactance at the tuned harmonic order.
c Calculate the filter capacitance.
d Calculate the inductor reactance at the tuned harmonic order.
7-32
See Also
1 To determine the THD in your model, perform an online analysis. For information, see
“Perform an Online Harmonic Analysis Using the Simscape Spectrum Analyzer Block”
on page 7-34.
2 Use the ee_getHarmonics and ee_calculateThdPercent functions to determine
the THD in your model.
3 Compare the THD values for the online and offline analyses. If the results differ,
reconfigure the Spectrum Analyzer block.
See Also
Blocks
Spectrum Analyzer
Functions
ee_calculateThdPercent | ee_getHarmonics | ee_plotHarmonics
Related Examples
• “Harmonic Analysis of a Three-Phase Rectifier”
• “Perform an Online Harmonic Analysis Using the Simscape Spectrum Analyzer
Block” on page 7-34
• “Data Logging” (Simscape)
7-33
7 Simulation and Analysis of Power Engineering Systems
Harmonic Distortion
Nonlinear loads create power distortion in the form of harmonics, that is, voltages and
currents that are multiples of the fundamental frequency. Harmonic waveforms can result
in energy losses through heat dissipation and in reduced power quality. They can also
cause equipment to malfunction or to become damaged. Standards development
organizations such as the Institute of Electrical and Electronics Engineers (IEEE) and the
International Electrotechnical Commission (IEC) define the recommended limits for
harmonic content in electric power systems.
This example shows how to examine harmonic distortion in your model using offline, that
is after simulation, and online, that is during simulation, analyses. The offline analysis
uses the Simscape Electrical harmonic analysis functions and helps you to determine
configuration settings for, and verify the results of, the online analysis. The online analysis
uses the Simscape Spectrum Analyzer block.
Prerequisite
This example requires a simulation log variable in your MATLAB workspace. The model in
this example is configured to log Simscape data for the whole model for the entire
simulation time.
To learn how to determine if a model is configured to log simulation data, see “Examine
the Simulation Data Logging Configuration of a Model” on page 7-19.
7-34
Perform an Online Harmonic Analysis Using the Simscape Spectrum Analyzer Block
model = 'ee_composite_rectifier';
open_system(model)
The example model contains a three-phase rectifier. The model also contains a
Selector block that outputs only the a-phase from three-phase current signal that it
receives from the PS-Simulink Converter block.
2 Simulate the model.
sim(model)
3 View the time-domain results. Open the Scope block.
7-35
7 Simulation and Analysis of Power Engineering Systems
The time domain analysis shows that the rectifier is converting the voltage, but it
does not include any information about the frequencies in the signal.
4 Determine configuration settings and calculate the expected results for an online
harmonic analysis. Perform an offline harmonic analysis.
a The Simscape Electrical harmonic analysis functions require that you use a fixed-
step solver. Determine the solver type and sample time for the model. To turn on
sample-time highlighting, in the Simulink editor menu bar, select Display >
Sample Time > All.
7-36
Perform an Online Harmonic Analysis Using the Simscape Spectrum Analyzer Block
Extract and display the maximum harmonic order and the fundamental
frequency:
disp(['Maximum Harmonic Order = ', num2str(max(harmonicOrder))])
disp(['Fundamental Frequency = ', num2str(fundamentalFrequency)])
harmonicTable =
7-37
7 Simulation and Analysis of Power Engineering Systems
10×4 table
7-38
Perform an Online Harmonic Analysis Using the Simscape Spectrum Analyzer Block
2 Configure the Spectrum Analyzer block using the Spectrum Settings panel.
i Configure the block to display the root mean square (RMS) of the frequency.
From the Type dropdown menu, select RMS.
ii Determine the value to specify for the resolution bandwidth (RBW) using this
equation:
NENBW * f
RBW = ,
N
where,
7-39
7 Simulation and Analysis of Power Engineering Systems
1.5 * 60Hz
RBW = = 9Hz
10
In the Distortion Measurements pane, for Num Harmonics, again enter 30.
3 Simulate the model.
sim(model)
7-40
Perform an Online Harmonic Analysis Using the Simscape Spectrum Analyzer Block
7-41
7 Simulation and Analysis of Power Engineering Systems
The THD percentage is 14.17% and the fundamental peak power is 1375.89 Vrms at
0.06 kHz (60 Hz). These results agree with the results from the offline harmonic
analysis.
See Also
Blocks
PS-Simulink Converter | Selector | Spectrum Analyzer
Functions
ee_calculateThdPercent | ee_getHarmonics | ee_plotHarmonics
Related Examples
• “Harmonic Analysis of a Three-Phase Rectifier”
• “Choose a Simscape Electrical Function for an Offline Harmonic Analysis” on page
7-30
• “Data Logging” (Simscape)
7-42
8
Real-Time Simulation
8 Real-Time Simulation
The checks are organized into folders. You can use the checks in the Simscape checks
folder for all physical models. Subfolders contain checks that target blocks from Simscape
Electrical and other add-on products such as Simscape Driveline and Simscape
Multibody.
Before you run the checks, use the processes described in “Real-Time Model Preparation
Workflow” (Simscape), “Real-Time Simulation Workflow” (Simscape), and “Hardware-In-
The-Loop Simulation Workflow” (Simscape).
1 In the Simulink Editor menu bar, select Analysis > Performance Tools >
Performance Advisor.
2 In the Performance Advisor window, under Activity, select Execute real-time
application.
3 In the left pane, expand the Real-Time folder, and then the Simscape checks folder.
4 Run the top-level Simscape checks and the Simscape Electrical checks. If your model
contains blocks from other add-on products, also run the checks in the subfolder
corresponding to that product.
See Also
More About
• “Model Preparation Objectives” (Simscape)
• “Real-Time Model Preparation Workflow” (Simscape)
8-2
See Also
8-3
9
For HDL code generation, you can design your own Simscape algorithm or choose from a
list of example models that are created in Simscape. The example models include:
• Boost Converter
• Bridge Rectifier
• Buck Converter
• Halfwave Rectifier
• Three Phase Rectifier
• Two Level Converter Ideal
• Two Level Converter Igbt
All examples are prefixed with sschdlex and post fixed with Example. For example, to
open the Boost Converter model, in the MATLAB™ command window, enter:
load_system('sschdlexBoostConverterExample')
open_system('sschdlexBoostConverterExample/Simscape_system')
HDL Coder™ does not support code generation from Simscape networks that contain:
• Events
9-2
Generate HDL Code from Simscape Models
• Mode charts
• Delays
• Runtime parameters
• Periodic sources
• Simscape™ Multibody™ blocks
• Simscape Electrical Specialized Power Systems blocks
1. Create a Simscape model by using switched linear blocks. Add Simulink-PS Converter
blocks at the input ports and PS-Simulink Converter blocks at the output ports.
2. Configure the solver options for HDL code generation by using a Solver Configuration
block. In the block parameters of this block:
3. Enclose the blocks inside a Subsystem and provide the test inputs.
4. Configure the model for HDL code generation by running the hdlsetup function.
hdlsetup configures the solver settings such as using a fixed-step solver, specifies the
simulation start and stop times, and so on. To run the command for your
current_model:
hdlsetup('current_model')
For example: To verify presence of nonlinear blocks in Half Wave Rectifier Model, in the
MATLAB command window, enter:
simscape.findNonlinearBlocks('sschdlexHalfWaveRectifierExample')
To open the half-wave rectifier model, in the MATLAB Command Window, enter:
9-3
9 Simscape to HDL Workflow
open_system('sschdlexHalfWaveRectifierExample')
load_system('HalfWaveRectifier_HDL')
open_system('HalfWaveRectifier_HDL/Simscape_system')
set_param('HalfWaveRectifier_HDL', 'SimulationCommand', 'update');
The Simscape model uses switched linear blocks such as Diode and Resistor to model the
design. The model has Simulink-PS Converter blocks at the input port and PS-Simulink
converter blocks at the output ports. To verify that the solver settings are configured
correctly, open the Solver Configuration block.
At the top level of the model, you see a Simscape_system block that models the half-
wave rectifier algorithm. The model accepts a Sine Wave input, uses a Rate Transition
block to discretize the continuous time input, and has a Scope block that calculates the
output. To see the input stimulus and the output from the model, connect the Sine Wave
input to the Scope block.
open_system('HalfWaveRectifier_HDL')
9-4
Generate HDL Code from Simscape Models
To configure the half-wave rectifier model for HDL compatibility, in the MATLAB
command window, enter:
hdlsetup('HalfWaveRectifier_HDL')
To see the simulation results, simulate the model and then open the Scope block.
sim('HalfWaveRectifier_HDL')
This figure shows simulation results with the sine wave input and the outputs from
Simscape_system.
9-5
9 Simscape to HDL Workflow
To generate an HDL implementation model from which you can generate code, use the
Simscape HDL Workflow Advisor. To open the Advisor, run this command:
sschdladvisor('HalfWaveRectifier_HDL')
This updates the model advisor cache and opens the Simscape HDL Workflow Advisor. To
learn more about the Simscape HDL Workflow Advisor and the various tasks, right-click
that folder or task, and select What's This?.
9-6
Generate HDL Code from Simscape Models
To run the workflow, in the Simscape HDL Workflow Advisor, right-click the Generate
implementation model task and select Run to Selected Task.
In some cases, your Simscape algorithm may not be compatible for generating an
implementation model using the Simscape HDL Workflow Advisor. In such cases, running
certain tasks in the Advisor can result in the task to fail. To learn how you can make it
HDL compatible, see
9-7
9 Simscape to HDL Workflow
To see the implementation model, in the Generate implementation model task, click
the link.
open_system('gmStateSpaceHDL_HalfWaveRectifier_HDL')
The model contains two subsystems. The Subsystem block contains the Simscape
algorithm that you modeled. From and Goto blocks inside this Subsystem provide the
same Sine Wave input to the HDL Subsystem.
The HDL Subsystem models the state-space representation that you generated from the
Simscape model. The ports of this Subsystem use the same name as the Simulink-PS
Converter and PS-Simulink Converter blocks in your original Simscape model. If you
navigate inside this Subsystem, you see several delays, adders, and Matrix Multiply
blocks that model the state-space equations.
open_system('gmStateSpaceHDL_HalfWaveRectifier_HDL/HDL Subsystem/HDL Algorithm')
9-8
Generate HDL Code from Simscape Models
The simulation results from the HDL implementation model matches that of the original
plant model. Therefore, we can verify that the plant simulation model is correctly
transformed into an HDL implementation model.
HDL code is generated for the HDL Subsystem block inside this model.
The HDL model and subsystem parameter settings are saved using this command:
hdlsaveparams('gmStateSpaceHDL_HalfWaveRectifier_HDL');
9-9
9 Simscape to HDL Workflow
The model uses single data types and generates HDL code in native floating-point mode.
Floating-point operators can introduce delays. Because the design contains feedback
loops, for the model transformation advisor to allocate enough delays for the operators
inside the feedback loops, the model uses clock-rate pipelining in conjunction with a large
value for the Oversampling factor. An Oversampling factor of 100 and the clock-rate
pipelining optimization is saved on this model.
• Clock-Rate Pipelining
• Oversampling Factor
• Allocate Sufficient Delays for Floating-Point Operations
Before you generate HDL code, it is recommended to enable generation of the validation
model. The validation model compares the output of the generated model after code
generation and the original model. To learn more, see Generated Model and Validation
Model.
Run these commands to save validation model generation settings on your Simulink
model:
HDLmodelname = 'gmStateSpaceHDL_HalfWaveRectifier_HDL';
hdlset_param(HDLmodelname, 'TargetDirectory', 'C:/Temp/hdlsrc');
hdlset_param(HDLmodelname, 'GenerateValidationModel', 'on');
makehdl('gmStateSpaceHDL_HalfWaveRectifier_HDL/HDL Subsystem');
The generated HDL code and validation model is saved in C:/Temp/hdlsrc directory.
The generated code is saved as HDL_Subsystem_tc.vhd. To open the validation model,
click the link to gm_gmStateSpaceHDL_HalfWaveRectifier_HDL_vnl.slx in the
code generation logs in the Command Window.
Open the Compare block at the output of HDL Subsystem_vnl Subsystem of the
validation model. Then, open the Assert_Out1 block. To see the simulation results after
HDL code generation, open the Compare: Out1 Scope block:
9-10
Generate HDL Code from Simscape Models
The top graph represents the output of our generated model, and the middle graph
represents the output of the implementation model. Since the output generated by both
the models are exactly matching, the error between them is zero, which is represented in
the last graph.
9-11
9 Simscape to HDL Workflow
Optionally, you can deploy the HDL code on a Hardware platform. For more information,
see Deploy Simscape plant models to Speedgoat FPGA IO modules.
See Also
Functions
checkhdl | makehdl
More About
• “Getting Started with Simscape Electrical”
• “Troubleshoot Conversion of Simscape DC Motor Control to HDL-Compatible
Simulink Model” (HDL Coder)
• “Validate HDL Implementation Model to Simscape Algorithm” (HDL Coder)
9-12
Deploy Simscape™ Plant Models to Speedgoat FPGA I/O Modules
1 Develop the Simscape model and convert it into an implementation model by using
the Simscape HDL Workflow Advisor. HDL code is generated from this
implementation model. For more information, see Generate HDL Code from Simscape
Models.
2 Deploy HDL code to a Speedgoat I/O module by using the HDL Workflow Advisor.
You can use the HDL Workflow Advisor to deploy the Simulink™ model to Speedgoat
FPGA I/O modules. Simulating the plant model on the FPGA provides:
9-13
9 Simscape to HDL Workflow
Speedgoat FPGA IO333-325K uses Xilinx Vivado. If it is not already present, install Xilinx
Vivado v2018.2. Then, set the tool path to the installed Xilinx Vivado 2018.2 executable.
To set the tool path, use the hdlsetuptoolpath function.
hdlsetuptoolpath('ToolName','Xilinx Vivado','ToolPath','C:\Xilinx\Vivado\2018.2\bin\viv
To run the simulation of the Simscape plant model in real time on hardware, you must set
up the I/O module. For information on setting up the I/O module, see Xilinx HDL Software
for Speedgoat I/O Hardware.
The HDL Workflow Advisor guides you through the stages of generating HDL code for a
Simulink subsystem and the FPGA design process, such as:
• Checking the model for HDL code generation compatibility and automatically fixing
incompatible settings.
• Generating HDL code, a test bench, and scripts to build and run the code and test
bench.
• Synthesis and timing analysis through integration with third-party synthesis tools.
• Completing the automated workflows for deployment on hardware platforms such as
System-on-Chip(SoC), FPGAs, and Speedgoat I/O modules.
This example shows how to use the HDL Workflow Advisor to deploy HDL code on
Speedgoat IO333-325K module that uses Xilinx Vivado. For example, to open the HDL
Workflow Advisor for a Subsystem inside the model, enter:
load_system('sschdlexTwoLevelConverterIgbtExample')
hdladvisor('sschdlexTwoLevelConverterIgbtExample/Simscape_system')
In the HDL Workflow Advisor, the left pane lists the folders in the hierarchy. Each folder
represents a group or category of related tasks. Expanding the folders shows the
available tasks in each folder. From the left pane, you can select a folder or an individual
task. The HDL Workflow Advisor displays information about the selected folder or task in
the right pane. The contents of the right pane depends on the selected folder or task. For
some tasks, the right pane contains simple controls for running the task and a display
area for status messages and other task results. For other tasks that involve setting code
9-14
Deploy Simscape™ Plant Models to Speedgoat FPGA I/O Modules
or test bench generation parameters, the right pane displays several parameter and
option settings.
To learn more about each individual task, right-click that task, and select What's This?.
For more information, see Getting Started with the HDL Workflow Advisor.
This example uses a Two-Level Ideal converter Simscape plant model. To open this model,
enter:
open_system('sschdlexTwoLevelConverterIdealExample')
open_system('TwoLevelConverter_HDL')
set_param('TwoLevelConverter_HDL','SimulationCommand','update')
9-15
9 Simscape to HDL Workflow
open_system('TwoLevelConverter_HDL/Simscape_system')
9-16
Deploy Simscape™ Plant Models to Speedgoat FPGA I/O Modules
The Simscape subsystem receives six-switch controlling pulses as input. The Simscape
subsystem acts as a generator that uses a two-level, carrier-based PWM method to:
To generate an implementation model, use the Simscape HDL Workflow Advisor. Enter:
sschdladvisor('TwoLevelConverter_HDL')
9-17
9 Simscape to HDL Workflow
To generate the implementation model, in the Simscape HDL Workflow Advisor, keep the
default settings for all the tasks, and then run the tasks. You see a link to the model in the
Generate implementation model task.
• sschdladvisor
• Generate HDL code from Simscape Models
open_system('gmStateSpaceHDL_TwoLevelConverter_HDL')
9-18
Deploy Simscape™ Plant Models to Speedgoat FPGA I/O Modules
The model contains two subsystems. The HDL Subsystem models the state-space
representation that you generated from the Simscape model. The ports of this subsystem
use the same name as the Simulink-PS Converter and PS-Simulink Converter blocks that
you use in your original Simscape model. If you navigate inside this Subsystem, you see
several delays, adders, and Matrix Multiply blocks that model the state-space equations.
From and Goto blocks inside this subsystem provide the same input as that of the original
model to the HDL Subsystem.
This example shows how to deploy the implementation model of Two Level IGBT
Converter to Speedgoat IO333-325K FPGA module by using the HDL Workflow Advisor.
The Speedgoat IO333 FPGA module uses Xilinx Vivado and IP Core Generation
Infrastructure. Before you run the Workflow Advisor, make sure that you have specified
the path to the installed Xilinx Vivado executable.
To open the HDL Workflow Advisor for the Implementation model, enter:
hdladvisor('gmStateSpaceHDL_TwoLevelConverter_HDL/HDL Subsystem')
2. In Set Target Device and Synthesis Tool task, set these parameters and select Run
This Task:
9-19
9 Simscape to HDL Workflow
3. In Set Target Reference Design task, select a value of x4 for the parameter PCIe
lanes, and select Run This Task.
4. In Set Target Interface task, map the Input and Output single data type ports to
PCIe Interface and select Run This Task.
9-20
Deploy Simscape™ Plant Models to Speedgoat FPGA I/O Modules
5. In Set Target Frequency task, select a target frequency that is within the range. If the
target frequency is set to higher values, it results in a failure to generate the bitstream
when you run task Build FPGA Bitstream. This example has Target Frequency set to
50 MHz.
9-21
9 Simscape to HDL Workflow
6. Right-click Generate RTL Code and IP Core task and select Run to Selected Task.
This step generates a warning if the model uses vector data types. Click the link in the
warning, select Scalarize vector ports, and rerun the task.
7. Run the workflow to the Generate Simulink Real-Time interface task. In Create
Project task, you can open the Vivado project and see the implemented design.
8. When the Generate Simulink Real-Time interface task passes, you see a link to
open the Simulink Real-Time Interface Model. Select this link.
9-22
Deploy Simscape™ Plant Models to Speedgoat FPGA I/O Modules
9-23
9 Simscape to HDL Workflow
• Save the HDL Workflow Advisor settings to script and run the script using command
line.
• Import the settings to modify it and rerun it using the HDL Workflow Advisor User
Interface.
The script is a MATLAB® file that you can run from the command line.
The HDL Workflow Advisor updates the tasks with the imported script settings.
This example shows how to configure and run an exported HDL Workflow script.
To generate an HDL Workflow script, configure and run the HDL Workflow Advisor with
your Simulink design, then export the script.
This script is a Simulink Real-Time FPGA I/O workflow script that targets the
Speedgoat IO333-325K module, which uses the Xilinx Vivado synthesis tool.
See Also
Functions
checkhdl | makehdl
9-24
See Also
More About
• “IP Core Generation Workflow for Speedgoat I/O Modules” (HDL Coder)
• “FPGA Programming and Configuration” (HDL Coder)
• “Troubleshoot Conversion of Simscape DC Motor Control to HDL-Compatible
Simulink Model” (HDL Coder)
• “Simscape HDL Workflow Advisor Tasks” (HDL Coder)
• “Validate HDL Implementation Model to Simscape Algorithm” (HDL Coder)
9-25
9 Simscape to HDL Workflow
Introduction
The Simscape plant model is converted to an HDL compatible Simulink model by using
the Simscape HDL Workflow Advisor. To run the Advisor, you invoke the sschdladvisor
function for the model.
The Simscape HDL Workflow Advisor generates an HDL Implementation model from
which you can generate HDL code. Before you generate the implementation model, make
sure make sure that the Simscape plant model is compatible for generation of the
implementation model using the Simscape HDL Workflow Advisor. For more information,
see Generate HDL Code from Simscape Models.
In some cases, the Simscape plant model may not be compatible for generation of the
implementation model using the Simscape HDL Workflow Advisor. For HDL compatibility,
you can modify the Simscape plant model and then run the Simscape HDL Workflow
Advisor.
This example illustrates the DC Motor Control plant model. The model contains a
nonlinear Friction block. You can use the approach in this example to convert Simscape
models with few nonlinear blocks to a HDL-compatible Simulink model.
This is a physical model developed in Simscape. The model contains nonlinear elements
and needs certain modifications for generating the implementation model.
load('dc_motor_control_params.mat')
open_system('ee_dc_motor_control_original')
9-26
Troubleshoot Conversion of Simscape DC Motor Control to HDL-Compatible Simulink Model
To convert Simscape plant models into HDL-compatible implementation model, make sure
that the model does not contain nonlinear components or blocks.
1. Detect presence of nonlinear components or blocks in the model. To verify the presence
of nonlinear blocks in Simscape plant model, enter:
simscape.findNonlinearBlocks('ee_dc_motor_control_original')
9-27
9 Simscape to HDL Workflow
ans =
{'ee_dc_motor_control_original/DC Motor/Friction'}
The Simscape plant model has a nonlinear block, which is the Friction block. For HDL
compatibility, remove the Friction block.
delete_block('ee_dc_motor_control_original/DC Motor/Friction')
2. Reduce the stop time of this model in Model configuration Parameters to 1s.
set_param('ee_dc_motor_control_original','Solver','ode15s','StopTime','1')
3.Excluding the inputs and outputs, enclose all other blocks at the top level of the DC
motor control model inside a subsystem. Attach Rate Transition blocks at the inputs
TLoad and rpmReq. Save the changes into a new model as
ee_dc_motor_control_modif.
load('dc_motor_control_params.mat')
open_system('ee_dc_motor_control_modif')
set_param('ee_dc_motor_control_modif','SimulationCommand','update')
9-28
Troubleshoot Conversion of Simscape DC Motor Control to HDL-Compatible Simulink Model
4. To see the simulation results after you modify the model, run these commands:
sim('ee_dc_motor_control_modif')
open_system('ee_dc_motor_control_modif/Visualization')
9-29
9 Simscape to HDL Workflow
To open the Simscape HDL Workflow Advisor, run the sschdladvisor for your model.
sschdladvisor('ee_dc_motor_control_modif')
9-30
Troubleshoot Conversion of Simscape DC Motor Control to HDL-Compatible Simulink Model
To generate the implementation model, in the Simscape HDL Workflow Advisor, leave all
tasks to the default settings and then run the tasks. You see a link to the model in the
Generate implementation model task. To open the implementation model, enter:
open_system('gmStateSpaceHDL_ee_dc_motor_control_modif')
9-31
9 Simscape to HDL Workflow
The sample time of Implementation model is related to the sample time of modified
Simscape plant model and the number of iterations specified in Simscape HDL Workflow
Advisor. Incorrect setting of sample time can result in failure to simulate the
implementation model. The sample time of modified plant model is Ts, and the number of
iterations are five. So the sample time of Implementation model should be Ts/5. To set the
sample time, enter:
set_param('gmStateSpaceHDL_ee_dc_motor_control_modif','SolverType', ...
'Fixed-step','FixedStep','Ts/5')
To simulate the model, run this command and then open the Scope block to see the
results:
sim('gmStateSpaceHDL_ee_dc_motor_control_modif')
9-32
Troubleshoot Conversion of Simscape DC Motor Control to HDL-Compatible Simulink Model
From the Scope block, you can verify that the output generated by the modified Simscape
plant model matches the output generated by the implementation model.
You can now generate HDL code for the implementation model. Before you can generate
HDL code, you must select the Treat each discrete rate as a separate task check box
and set Single task rate transition to error.
9-33
9 Simscape to HDL Workflow
To save validation model generation settings on your Simulink model, run these
commands:
modelname = 'gmStateSpaceHDL_ee_dc_motor_control_modif';
hdlset_param(modelname, 'TargetDirectory', 'C:/Temp/hdlsrc')
hdlset_param(modelname, 'GenerateValidationModel', 'on');
makehdl('gmStateSpaceHDL_ee_dc_motor_control_modif/HDL Subsystem')
By default, HDL Coder generates VHDL code. To generate Verilog code, run this
command:
The generated HDL code and the validation model is saved in C:/Temp/hdlsrc
directory. The generated code is saved as HDL_Subsystem_tc.vhd.
1 Verify the model generated after HDL code generation by using the validation model.
To open the validation model, click the link to
gm_gmStateSpaceHDL_ee_dc_motor_control_modif_vnl.slx. when you generate code.
2 Deploy the generated HDL code on Speedgoat FPGA I/O boards or other target
platforms. For more information, see Deploy Simscape plant models to Speedgoat
FPGA IO modules.
See Also
Functions
checkhdl | makehdl
9-34
See Also
More About
• “Generate HDL Code from Simscape Models” (HDL Coder)
• “Getting Started with Simscape Electrical”
• “Simscape HDL Workflow Advisor Tasks” (HDL Coder)
• “Validate HDL Implementation Model to Simscape Algorithm” (HDL Coder)
9-35
9 Simscape to HDL Workflow
Introduction
The Simscape HDL Workflow Advisor generates an HDL implementation model from
which you can generate HDL code. Before you generate the implementation model, make
sure that the Simscape plant model is compatible for generation of the implementation
model by using the Simscape HDL Workflow Advisor. For more information, see Generate
HDL Code from Simscape Models.
In some cases, the Simscape plant model might not be compatible for generation of the
implementation model using the Simscape HDL Workflow Advisor. For HDL compatibility,
you can modify the Simscape plant model and then run the Simscape HDL Workflow
Advisor.
This example illustrates how to modify Permanent Magnet Synchronous Motor model in
Simscape for HDL compatibility. The model is nonlinear and not compatible for
generation of implementation model by using the Simscape HDL Workflow Advisor. This
example illustrates how you can modify a continuous-time nonlinear model to a discrete-
time switched linear model. The model becomes compatible for generation of the
implementation model from which you can generate HDL code.
This model is a physical system developed in Simscape. The model contains nonlinear
elements and needs modifications for generating the implementation model. To open the
model. run this command:
open_system('ee_pmsm_drive')
9-36
Troubleshoot Conversion of Simscape™ Permanent Magnet Synchronous Motor to HDL-Compatible Simulink Model
open_system('ee_pmsm_drive_original')
This model shows a Permanent Magnet Synchronous Machine (PMSM) and inverter sized
for use in a typical hybrid vehicle. The inverter is connected directly to the vehicle
battery. You can use the model to design the PMSM controller, selecting architecture and
gains to achieve performance that you want. The Gmin resistor provides a very small
conductance to ground that improves the numerical properties of the model when using a
variable-step solver. To see how the model works, simulate the model.
sim('ee_pmsm_drive_original')
This model is a continuous time system. To work with Simscape HDL Workflow Advisor,
you must convert the model into a discrete system.
9-37
9 Simscape to HDL Workflow
1. Configure the solver options for HDL code generation by using a Solver Configuration
block. In the block parameters of this block:
2. Modify Solver settings in Configuration Parameters dialog box, on the Solver pane:
• On the Display tab, set the Sample Time to All. Review the generated report for any
blocks that have a sample time other than Ts, or which are running on a continuous
time scale.
4. Double-click the Step block in the model and set its Sample time to Ts.
5. For faster simulation, ignore the zero-sequence parameters of the PMSM. Double-click
the Permanent Magnet Synchronous Motor block and set Zero Sequence to Exclude.
The model is now a fixed-step discrete system. Simulate the model and compare signals in
the Simulation Data Inspector.
9-38
Troubleshoot Conversion of Simscape™ Permanent Magnet Synchronous Motor to HDL-Compatible Simulink Model
Some Pulse Width Modulation (PWM) signals transition earlier or later between
simulations, but they are well within the step-size of the controller. The only signals that
differ beyond tolerance are the Torque Demand and Motor Torque, toward the end of
simulation, within acceptable limits.
To make the Simscape plant model HDL-Compatible, identify the presence of any
nonlinear components or blocks in the model. Enter:
simscape.findNonlinearBlocks('ee_pmsm_drive_original')
9-39
9 Simscape to HDL Workflow
ans =
The Simscape plant model has a nonlinear block, which is the PMSM block.
Remove the PMSM block, Encoder block, Gmin resistor, and, Motor & load inertia block.
To delete the Simscape elements and blocks, enter:
For ease of implementation, the Simscape plant model is converted into an HDL Advisor
compatible model by using a two-step process:
1. Implement an initial nonlinear Simulink model by using double-precision data type, and
blocks that are not compatible with HDL coder.
2. Modify this nonlinear model to make it suitable for deployment with HDL Coder by
using single-precision data types and blocks that are compatible with HDL Coder for
more efficient HDL code generation.
Replace the PMSM block, Encoder block, Gmin resistor and, Motor & load inertia block
with Electrical Interface Simulink block and Permanent Magnet Synchronous Motor
Simulink block.
load_system('ee_pmsm_drive_initialSL')
set_param('ee_pmsm_drive_initialSL','SimulationCommand','update')
open_system('ee_pmsm_drive_initialSL/Electrical Interface')
9-40
Troubleshoot Conversion of Simscape™ Permanent Magnet Synchronous Motor to HDL-Compatible Simulink Model
The PMSM Simulink block is implemented by using Electrical Equations and Mechanical
Equations. For more information, see PMSM.
9-41
9 Simscape to HDL Workflow
1. Update Output data type in Signal Attributes tab of Gain and Product blocks to
Single.
load_system('ee_pmsm_drive_singleSL')
set_param('ee_pmsm_drive_singleSL','SimulationCommand','update')
blockconstant=find_system('ee_pmsm_drive_singleSL', 'blocktype', 'Gain')
9-42
Troubleshoot Conversion of Simscape™ Permanent Magnet Synchronous Motor to HDL-Compatible Simulink Model
blockconstant =
The array blockconstant stores the exact location of Gain blocks as variables. There
are two Gain blocks in the Simulink model.
To set the output data type of these Gain blocks to single, enter:
set_param(blockconstant{1},'OutDataTypeStr', 'single')
set_param(blockconstant{2},'OutDataTypeStr', 'single')
ans =
2. The Park Transform and Inverse Park Transform blocks inside the PMSM Simulink
block are modified to eliminate the 6 Sine and 6 Cosine blocks.
9-43
9 Simscape to HDL Workflow
3. Reduce the hardware required for the Park Transform block by adding Clarke
Transform and Clarke to Park Angle Transform blocks.
9-44
Troubleshoot Conversion of Simscape™ Permanent Magnet Synchronous Motor to HDL-Compatible Simulink Model
4. Reduce the hardware required for the Inverse Park Transform block by adding Inverse
Park to Clarke Angle Transform and Inverse Clarke Transform blocks.
5. Replace the Three-Phase Current Sensor Simscape block by feeding the controller with
three-phase currents coming from the PMSM model.
6. Add a Digital Clock with Sample time Ts. Connect the clock to a Display block.
open_system('ee_pmsm_drive_singleSL')
9-45
9 Simscape to HDL Workflow
To open the Simscape HDL Workflow Advisor, run the sschdladvisor for your model.
sschdladvisor('ee_pmsm_drive_singleSL')
9-46
Troubleshoot Conversion of Simscape™ Permanent Magnet Synchronous Motor to HDL-Compatible Simulink Model
To generate the implementation model, in the Simscape HDL Workflow Advisor, leave the
default settings and then run the tasks. You see a link to the model in the Generate
implementation model task. To open the implementation model, enter:
load_system('gmStateSpaceHDL_ee_pmsm_drive_singleSL')
open_system('gmStateSpaceHDL_ee_pmsm_drive_singleSL')
9-47
9 Simscape to HDL Workflow
To execute the implementation model, modify the Fixed-step size to Ts/5 as Number of
Iterations in sschdladvisor are 5.
The single precision implementation model is reconfigured for HDL code generation. To
reconfigure, place the PMSM model within the HDL Subsystem. Save the model as
gmStateSpaceHDL_ee_pmsm_drive_GenerateHDL.
load_system('gmStateSpaceHDL_ee_pmsm_drive_GenerateHDL')
open_system('gmStateSpaceHDL_ee_pmsm_drive_GenerateHDL')
9-48
Troubleshoot Conversion of Simscape™ Permanent Magnet Synchronous Motor to HDL-Compatible Simulink Model
open_system('gmStateSpaceHDL_ee_pmsm_drive_GenerateHDL/HDL Subsystem')
9-49
9 Simscape to HDL Workflow
1 Select the Treat each discrete rate as a separate task check box.
2 Set Single task rate transition to error.
3 Set Multitask rate transition to error.
9-50
See Also
To save validation model generation settings on your Simulink model, run these
commands:
modelname = 'gmStateSpaceHDL_ee_pmsm_drive_GenerateHDL';
hdlset_param(modelname, 'TargetDirectory', 'C:/Temp/hdlsrc')
hdlset_param(modelname, 'GenerateValidationModel', 'on');
makehdl('gmStateSpaceHDL_ee_pmsm_drive_GenerateHDL/HDL Subsystem')
By default, HDL Coder generates VHDL code. To generate Verilog code, run this
command:
The generated HDL code and the validation model is saved in C:\Temp\hdlsrc folder.
The generated code is saved as HDL_Subsystem_tc.vhd.
1 Verify the model generated after HDL code generation by using the validation model.
To open the validation model, click the link to
gmStateSpaceHDL_ee_pmsm_drive_GenerateHDL.slx when you generate code.
2 Deploy the generated HDL code on Speedgoat FPGA I/O boards or other target
platforms. For more information, see Deploy Simscape plant models to Speedgoat
FPGA IO modules.
See Also
Functions
checkhdl | makehdl
More About
• “Generate HDL Code from Simscape Models” (HDL Coder)
9-51
9 Simscape to HDL Workflow
9-52
Validate HDL Implementation Model to Simscape Algorithm
1 Open the bridge rectifier model. To learn how the bridge rectifier is implemented,
open the Simscape_system Subsystem. To open the bridge rectifier model, in the
MATLAB Command Window, enter:
open_system('sschdlexBridgeRectifierExample')
open_system('sschdlexBridgeRectifierExample/Simscape_system')
2 Save a local copy of this model and rename it as BridgeRectifier_HDL to run the
Simscape to HDL workflow. Open the Simscape HDL Workflow Advisor for your
model:
sschdladvisor('BridgeRectifier_HDL')
3 Right-click the Get state-space parameters task and select Run to Selected Task
to run all tasks in the Advisor except for the Generate implementation model task.
9-53
9 Simscape to HDL Workflow
After running this task, you see a link to the generated HDL implementation model.
After you generate the implementation model, do not close the Simscape HDL
Workflow Advisor UI. By keeping this window open, if you have to fix any warnings
generated from the implementation model, you only have to modify the settings in the
Generate implementation model task and then rerun this task. You do not have to
modify or rerun other tasks.
5 Click the link to open the HDL implementation model. You see a Validation
Subsystem that compares the simulation results of the Simscape model to the HDL
implementation model. Simulate the implementation model.
9-54
Validate HDL Implementation Model to Simscape Algorithm
You see that simulating the model generates multiple assertions indicating a mismatch in
the simulation results. If you open the Diagnostic Viewer, you see this message:
Assertion detected in
'gmStateSpaceHDL_BridgeRectifier_HDL_SimMismatch/Validation/Check
Static Range1' at time 0.04186 [4982 similar]
The message indicates that the Simscape™ algorithm does not match the equivalent HDL
implementation. To resolve the validation mismatch, you can modify various settings in
the Generate implementation model task until the HDL implementation model
matches the Simscape algorithm. The settings include Validation logic tolerance,
Number of solver iterations, and Floating-point precision. In most cases, to resolve
the numeric mismatch, you may want to use a combination of these settings.
9-55
9 Simscape to HDL Workflow
includes validation logic. Simulate the model and check whether the simulation displays
any warnings in the Diagnostic Viewer. If the simulation results produce warnings,
proceed to the next step to increase the number of solver iterations.
You can start with an initial value of 20 for the Number of solver iterations. Run the
Generate implementation model task while making sure that you selected Generate
validation logic for the implementation model. Simulate the model and check
whether the simulation displays any warnings in the Diagnostic Viewer. If the simulation
results produce warnings, you can increase the Number of solver iterations by
increments of 20, generate the implementation model, and then simulate the model to see
if it meets the numeric accuracy requirements.
Note When you increase the number of solver iterations, the code generator changes the
sample time of the generated HDL implementation model. A large number of iterations
can increase the simulation time significantly.
If your implementation model does not meet the accuracy requirements after you use a
value of 100 for Number of solver iterations, proceed to the next step to use double-
precision floating-point data types.
9-56
See Also
you use single data types, and then simulate the generated model to see if your design
meets the numeric accuracy requirements. Run the Generate implementation model
task while making sure that you selected Generate validation logic for the
implementation model. Simulate the model and check whether the simulation displays
any warnings in the Diagnostic Viewer.
If the simulation results still produce warnings, proceed to the first step to further
increase the validation logic tolerance. Use a tolerance value of 1e-03 and then simulate
the model to see if the numeric accuracy requirements are met. If you still see warnings
in the Diagnostic Viewer, increase the number of solver iterations. You can continue
iterating between these steps till the HDL implementation model numerically matches the
Simscape algorithm.
For the bridge rectifier model, to resolve the warnings, set the Validation logic
tolerance to 1e-4 and specify the Floating-point precision as double. After you
generate the implementation model with the validation logic, you see that simulating the
model does not display any warnings in the Diagnostic Viewer.
See Also
Functions
simscape.findNonlinearBlocks | sschdladvisor
More About
• “Generate HDL Code from Simscape Models” (HDL Coder)
• “Simscape HDL Workflow Advisor Tasks” (HDL Coder)
• “Deploy Simscape™ Plant Models to Speedgoat FPGA I/O Modules” (HDL Coder)
9-57
9 Simscape to HDL Workflow
Sampling Frequency
When you generate HDL code and deploy the plant model onto an FPGA, you may want to
improve the sampling frequency. The sampling frequency depends on these parameters:
To improve the sampling rate, you want to maximize the FPGA clock frequency, and
minimize the oversampling factor and number of solver iterations. As you improve the
sampling rate, make sure that the updated sampling frequency is equivalent to the fixed
sample time that you specify for your original Simscape model by using the Solver
Configuration block. To learn more about how this block is used in your model before
running the Simscape HDL Workflow Advisor, see “Generate HDL Code from Simscape
Models” (HDL Coder).
The preceding section uses the boost converter model as an example to illustrate how you
can modify the oversampling factor and the number of solver iterations to improve the
sampling rate.
9-58
Improve Sampling Rate of HDL Implementation Model Generated from Simscape Algorithm
1 Open the boost converter model. To learn how the boost converter is implemented,
open the Simscape_system Subsystem. To open the boost converter model, in the
MATLAB Command Window, enter:
open_system('sschdlexBoostConverterExample')
open_system('sschdlexBoostConverterExample/Simscape_system')
You see that the model runs at a sample time 1e-6. The sample time of 200e-9
corresponds to the sample time of the sources that drive the Simscape algorithm.
2 Save a local copy of this model and rename it as BoostConverter_HDL to run the
Simscape to HDL workflow. Open the Simscape HDL Workflow Advisor for your
model:
sschdladvisor('BoostConverter_HDL')
3 Run the workflow to the Generate implementation model task.
After running this task, you see a link to the generated HDL implementation model.
Click the link to open the HDL implementation model. If you simulate the HDL
implementation model and navigate the model to the HDL Algorithm Subsystem,
you see that the model uses single data types, and contains Rate Transition and
Zero Order Hold blocks that run the model at a sample time 200e-9, which is 5 times
faster than the original Simscape model.
9-59
9 Simscape to HDL Workflow
4 Run this command to see the HDL parameter settings that are saved on the model:
hdlsaveparams('gmStateSpaceHDL_BoostConverter_HDL')
The HDL parameters that are saved indicate that the model has the native floating-point
mode enabled and uses an Oversampling factor of 60 and has Latency Strategy set to
MIN. This default combination of HDL parameters that are saved on the model offers an
optimal trade-off between oversampling factor and the target FPGA clock frequency and
improves the sampling frequency. If you want to further improve the sampling frequency,
you can reduce the number of iterations and the oversampling factor as illustrated below.
9-60
Improve Sampling Rate of HDL Implementation Model Generated from Simscape Algorithm
of solver iterations, the HDL implementation model runs at a sample rate that is N times
faster than the original Simscape algorithm. By default, for switched linear models, the
Number of solver iterations is 5. The generated HDL implementation model runs 5
times faster than the original Simscape model.
To improve the sampling rate, you want to reduce the number of solver iterations. The
number of solver iterations depends on various factors such as the complexity of your
design, the number of modes in the design that the workflow must calculate, and so on. In
the Generate implementation model task of the Simscape HDL Workflow Advisor, start
by reducing the Number of solver iterations to a value such as 3, select Generate
validation logic for the implementation model, and then generate the HDL
implementation model. Simulate the HDL implementation model and open the Diagnostic
Viewer to make sure that the model does not display any warnings or assertions.
If you see warnings or assertions, it indicates a simulation mismatch because the number
of solver iterations that you specified is not adequate to compute the required number of
modes in the state-space design. To resolve the warnings, you may want to increase the
Validation logic tolerance to a value such as 1e-4 and then simulate the HDL
implementation model. If you still see warnings, increase the Number of solver
iterations.
To learn more about how you can resolve the simulation mismatch, see “Validate HDL
Implementation Model to Simscape Algorithm” (HDL Coder).
9-61
9 Simscape to HDL Workflow
In the Configuration Parameters dialog box, on the HDL Code Generation > Floating
Point pane, you can specify a Latency Strategy of Min, Max, or Zero on the model. The
oversampling factor and latency strategy of the floating-point operator must be varied in
conjunction. By default, the oversampling factor of 60 and minimum latency strategy
gives an optimal sampling frequency. In most cases, when you use minimum latency
strategy, you can start with an Oversampling factor of 60, generate HDL code, and then
further reduce the oversampling factor until the code generator is unable to allocate
delays for the floating-point operations.
If you specify Max latency, the floating-point operations introduce the maximum number
of delays. To make sure that these delays can be allocated, increase the Oversampling
factor. You may want to increase the Oversampling factor to a value such as 100
depending on the complexity of your HDL design. The maximum latency strategy provides
the maximum FPGA clock frequency that you can achieve. If the increase in FPGA clock
frequency outweighs the increase in oversampling factor, you can use the maximum
latency strategy instead.
For the boost converter model, the default settings of Number of solver iterations set
to 5, Oversampling factor set to 60, and Latency Strategy set to Min provides the
optimal sampling frequency.
See Also
Functions
simscape.findNonlinearBlocks | sschdladvisor
More About
• “Solvers for Real-Time Simulation” (Simscape)
• “Latency Considerations with Native Floating Point” (HDL Coder)
• “Deploy Simscape™ Plant Models to Speedgoat FPGA I/O Modules” (HDL Coder)
9-62