Download as pdf or txt
Download as pdf or txt
You are on page 1of 152

1

Simscape Driveline Simscape Blocks


Brakes and Detents
Band Brake Frictional brake with flexible band wrapped around rotating drum

Double-Shoe Brake Frictional brake with two pivoted shoes diametrically positioned
about a rotating drum

Loaded-Contact Loaded-contact friction between two rotating bodies


Rotational Friction

Rotational Detent Double-sided, spring-loaded rotational detent

Loaded-Contact Loaded-contact friction between two sliding bodies


Translational
Friction

Translational Double-sided, spring-loaded translational detent


Detent

Clutches
Cone Clutch Friction clutch with conical plates that engage when normal force
exceeds threshold

Disk Friction Clutch Friction clutch with disk plates that engage when plate pressure
exceeds threshold

Dog Clutch Clutch with toothed plates that engage when plate teeth become
enmeshed

Double-Sided Back-to-back dog-cone clutch pairs assembled symmetrically about


Synchronizer a translational detent to provide smooth gear engagement

Logic-Controlled Friction clutch with binary input control


Clutch
Synchronizer Cone clutch, dog clutch, and translational detent assembled to
provide smooth gear engagement

Unidirectional Clutch that transmits power in a single direction


Clutch

Fundamental Friction clutch with kinetic and static-limit friction torques as inputs
Friction Clutch

Couplings and Drives


Belt Drive Power transmission system with taut belt connecting two pulleys

Belt Pulley Power transmission element with frictional belt wrapped around
pulley circumference

Chain Drive Power transmission system with chain and two sprockets

Flexible Shaft Driveline shaft with torsional compliance

Rope Drum Power transmission system with tightly wound rope around
cylindrical drum

Shock Absorber Mechanism for damping translational vibrations

Torque Converter Viscous fluid coupling between rotating driveline shafts

Torsional Spring- Rotational spring and damper coupling, with Coulomb friction,
Damper locking, and hard stops

Universal Joint Rotational coupling between two driveline shafts

Variable Ratio Dynamic gearbox with variable and controllable gear ratio,
Transmission transmission compliance, and friction losses

Nonlinear Rotational damper based on polynomial or lookup-table


Rotational Damper parameterizations

Nonlinear Torsional spring based on polynomial or lookup table


Rotational Spring parameterizations
Nonlinear Translational damper based on polynomial or lookup table
Translational parameterizations
Damper

Nonlinear Translational spring based on polynomial or lookup table


Translational parameterizations
Spring

Rotational Damper Faultable linear rotational damper

Translational Faultable linear translational damper


Damper

Variable Rotational damper with variable damping coefficient


Rotational Damper

Variable Rotational spring with variable spring stiffness


Rotational Spring

Variable Translational viscous damper with variable damping coefficient


Translational
Damper

Variable Translational spring with variable spring stiffness


Translational
Spring

Engines
Generic Engine Internal combustion engine with throttle and rotational inertia and
time lag

Piston Piston mechanism of reciprocating combustion engine

Piston Engine Reciprocating combustion engine with variable number of pistons

Gears
Compound Planetary gear train with stepped planet gear set
Planetary Gear

Cycloidal Drive High-ratio speed reducer based on cycloidal disk motion


Differential Gear mechanism that allows driven shafts to spin at different speeds

Double-Pinion Planetary gear train with two meshed planet gear sets
Planetary Gear

Harmonic Drive High-ratio speed reducer based on elastic deformation of an elliptical


gear

Limited-Slip Reduce velocity difference between two connected shafts


Differential

Planetary Gear Gear train with sun, planet, and ring gears

Ravigneaux Gear Planetary gear with two sun gears and two planet gear sets

Simple Gear Simple gear of base and follower wheels with adjustable gear ratio
and friction losses

Simple Gear with Gear set with parallel-axis rotation and variable meshing efficiency
Variable
Efficiency

Worm Gear Worm gear with adjustable gear ratio and friction losses

Planet-Planet Planetary gear set of carrier, inner planet, and outer planet wheels
with adjustable gear ratio and friction losses

Ring-Planet Planetary gear set of carrier, planet, and ring wheels with adjustable
gear ratio and friction losses

Sun-Planet Planetary gear set of carrier, planet, and sun wheels with adjustable
gear ratio and friction losses

Sun-Planet Bevel Planetary gear set of carrier, beveled planet, and sun wheels with
adjustable gear ratio, assembly orientation, and friction losses

Sun-Planet Worm Planetary gear set of carrier, worm planet, and sun wheels with
Gear adjustable gear ratio, worm thread type, and friction losses

Leadscrew Leadscrew gear set of threaded rotating screw and translating nut,
with adjustable thread and friction losses
Rack & Pinion Rack and pinion gear coupling translational and rotational motion,
with adjustable pinion radius and friction losses

Inertias and Loads


Variable Inertia Time-varying inertia specified as physical signal input

Variable Mass Time-varying mass specified as physical signal input

Unbalanced Load Load with angle-dependent rotational inertia

Sensors
Rotational Power Mechanical sensor used to measure average or instantaneous rotational power
Sensor

Translational Mechanical sensor used to measure average or instantaneous translational power


Power Sensor

Sources
Force Noise Model zero-mean normally (Gaussian) distributed force
Source

Rotational Velocity Produce zero-mean normally (Gaussian) distributed rotational


Noise Source velocity

Sinusoidal Force Produce sinusoidal force


Source

Sinusoidal Produce sinusoidal rotational velocity


Rotational Velocity
Source

Sinusoidal Torque Produce sinusoidal torque


Source

Sinusoidal Produce sinusoidal translational velocity


Translational
Velocity Source

Torque Noise Model zero-mean normally (Gaussian) distributed torque


Source
Translational Produce zero-mean normally (Gaussian) distributed translational
Velocity Noise velocity
Source

Tires and Vehicles


Tire (Friction Parameterized) Tire with friction parameterized in terms of
static and kinetic coefficients

Tire (Magic Formula) Tire with longitudinal behavior given by magic


formula coefficients

Tire (Simple) No-slip tire model with minimal parameters

Vehicle Body Two-axle vehicle with longitudinal dynamics


and motion and adjustable mass, geometry,
and drag properties

Rolling Resistance Model rolling resistance

Tire-Road Interaction (Magic Formula) Tire-road dynamics given by magic formula


coefficients

Transmissions
4-Speed CR-CR Clutch schedule for a four-speed carrier ring-
carrier ring transmission

4-Speed Ravigneaux Clutch schedule for a four-speed Ravigneaux


transmission

6-Speed Lepelletier Clutch schedule for a six-speed Lepelletier


transmission

7-Speed Lepelletier Clutch schedule for a seven-speed Lepelletier


transmission

8-Speed Clutch schedule for an eight-speed


transmission

9-Speed Clutch schedule for a nine-speed


transmission
Ideal Force Sensor
Force sensor in mechanical translational systems
expand all in page

Library
Mechanical Sensors

Description
The Ideal Force Sensor block represents a device that converts a variable passing through the sensor
into a control signal proportional to the force. The sensor is ideal since it does not account for inertia,
friction, delays, energy consumption, and so on.

Connections R and C are mechanical translational conserving ports that connect the block to the line
where force is being monitored. Connection F is a physical signal port that outputs the measurement
result.

The block positive direction is from port R to port C. This means that positive force applied to port R (the
sensor positive probe) generates a positive output signal.

Ports
The block has the following ports:
R
Mechanical translational conserving port associated with the sensor positive probe.
C
Mechanical translational conserving port associated with the sensor negative (reference) probe.
F
Physical signal output port for force.
Ideal Rotational Motion Sensor
Motion sensor in mechanical rotational systems
expand all in page

Library
Mechanical Sensors

Description
The Ideal Rotational Motion Sensor block represents an ideal mechanical rotational motion sensor, that
is, a device that converts an across variable measured between two mechanical rotational nodes into a
control signal proportional to angular velocity or angle. You can specify the initial angular position (offset)
as a block parameter.

The sensor is ideal since it does not account for inertia, friction, delays, energy consumption, and so on.

Connections R and C are mechanical rotational conserving ports that connect the block to the nodes
whose motion is being monitored. Connections W and A are physical signal output ports for velocity and
angular displacement, respectively.

The block positive direction is from port R to port C. This means that the velocity is measured as ω = ω R –
ωC, where ωR, ωC are the absolute angular velocities at ports R and C, respectively.

Parameters
Initial angle
Sensor initial angle, or offset (rad). The default value is 0.

Ports
The block has the following ports:
R
Mechanical rotational conserving port associated with the sensor positive probe.
C
Mechanical rotational conserving port associated with the sensor negative (reference) probe.
W
Physical signal output port for angular velocity.
A
Physical signal output port for angular displacement.

Ideal Torque Sensor


Torque sensor in mechanical rotational systems
expand all in page
Library
Mechanical Sensors

Description
The Ideal Torque Sensor block represents a device that converts a variable passing through the sensor
into a control signal proportional to the torque. The sensor is ideal because it does not account for inertia,
friction, delays, energy consumption, and so on.

Connections R and C are mechanical rotational conserving ports that connect the block to the line where
torque is being monitored. Connection T is a physical signal port that outputs the measurement result.

The block positive direction is from port R to port C.

Ports
The block has the following ports:
R
Mechanical rotational conserving port associated with the sensor positive probe.
C
Mechanical rotational conserving port associated with the sensor negative (reference) probe.
T
Physical signal output port for torque.
Ideal Translational Motion Sensor
Motion sensor in mechanical translational systems
expand all in page

Library
Mechanical Sensors

Description
The Ideal Translational Motion Sensor block represents a device that converts an across variable
measured between two mechanical translational nodes into a control signal proportional to velocity or
position. You can specify the initial position (offset) as a block parameter.

The sensor is ideal since it does not account for inertia, friction, delays, energy consumption, and so on.

Connections R and C are mechanical translational conserving ports that connect the block to the nodes
whose motion is being monitored. Connections V and P are physical signal output ports for velocity and
position, respectively.

The block positive direction is from port R to port C. This means that the velocity is measured
as v = vR – vC, where vR,vC are the absolute velocities at ports R and C, respectively.

Parameters
Initial position
Sensor initial position, or offset (m). The default value is 0.

Ports
The block has the following ports:
R
Mechanical translational conserving port associated with the sensor positive probe.
C
Mechanical translational conserving port associated with the sensor negative (reference) probe.
V
Physical signal output port for velocity.
P
Physical signal output port for position.

Current Sensor
Current sensor in electrical systems
expand all in page
Library
Electrical Sensors

Description
The Current Sensor block represents an ideal current sensor, that is, a device that converts current
measured in any electrical branch into a physical signal proportional to the current.

Connections + and – are electrical conserving ports through which the sensor is inserted into the circuit.
Connection I is a physical signal port that outputs the measurement result.

Ports
The block has the following ports:
+
Electrical conserving port associated with the sensor positive terminal.
-
Electrical conserving port associated with the sensor negative terminal.
I
Physical signal output port for current.

Voltage Sensor
Voltage sensor in electrical systems
expand all in page

Library
Electrical Sensors

Description
The Voltage Sensor block represents an ideal voltage sensor, that is, a device that converts voltage
measured between two points of an electrical circuit into a physical signal proportional to the voltage.

Connections + and – are electrical conserving ports through which the sensor is connected to the circuit.
Connection V is a physical signal port that outputs the measurement result.

Ports
The block has the following ports:
+
Electrical conserving port associated with the sensor positive terminal.
-
Electrical conserving port associated with the sensor negative terminal.
V
Physical signal output port for voltage.
Cảm biến từ trường - Flux Sensor
Ideal flux sensor
expand all in page

Library
Magnetic Sensors

Description
The Flux Sensor block represents an ideal flux sensor, that is, a device that converts flux measured in
any magnetic branch into a physical signal proportional to the flux.

Connections N and S are conserving magnetic ports through which the sensor is inserted into the circuit.
The physical signal port outputs the value of the flux, which is positive when the flux flows from the N to
the S port.

Ports
The block has the following ports:
N
Magnetic conserving port associated with the sensor North terminal.
S
Magnetic conserving port associated with the sensor South terminal.

The block also has a physical signal output port, which outputs the value of the flux.
MMF Sensor
Ideal magnetomotive force sensor
expand all in page

Library
Magnetic Sensors

Description
The MMF Sensor block represents an ideal magnetomotive force (mmf) sensor, that is, a device that
converts the mmf measured between any magnetic connections into a physical signal proportional to the
mmf.

Connections N and S are conserving magnetic ports through which the sensor is connected to the circuit.
The physical signal port outputs the value of the mmf.

Ports
The block has the following ports:
N
Magnetic conserving port associated with the sensor North terminal.
S
Magnetic conserving port associated with the sensor South terminal.

The block also has a physical signal output port, which outputs the value of the mmf.
Hydraulic Flow Rate Sensor
Ideal flow meter
expand all in page

Library
Hydraulic Sensors

Description
The Hydraulic Flow Rate Sensor block represents an ideal flow meter, that is, a device that converts
volumetric flow rate through a hydraulic line into a control signal proportional to this flow rate. Connection
Q is a physical signal port that outputs the volumetric flow rate value. Connection M is a physical signal
port that outputs the mass flow rate value. The sensor is ideal because it does not account for inertia,
friction, delays, pressure loss, and so on.

Connections A and B are conserving hydraulic ports connecting the sensor to the hydraulic line. The
sensor positive direction is from A to B. This means that the flow rate is positive if it flows from A to B.

Ports
The block has the following ports:
A
Hydraulic conserving port associated with the sensor positive probe.
B
Hydraulic conserving port associated with the sensor negative (reference) probe.
Q
Physical signal port that outputs the volumetric flow rate value.
M
Physical signal port that outputs the mass flow rate value.
Hydraulic Pressure Sensor
Ideal pressure sensing device
expand all in page

Library
Hydraulic Sensors

Description
The Hydraulic Pressure Sensor block represents an ideal hydraulic pressure sensor, that is, a device that
converts hydraulic pressure differential measured between two points into a control signal proportional to
this pressure. The sensor is ideal because it does not account for inertia, friction, delays, pressure loss,
and so on.

Connections A and B are conserving hydraulic ports connecting the sensor to the hydraulic line.
Connection P is a physical signal port that outputs the pressure value. The sensor positive direction is
from A to B. This means that the pressure differential is determined as p=pA−pB.

Ports
The block has the following ports:
A
Hydraulic conserving port associated with the sensor positive probe.
B
Hydraulic conserving port associated with the sensor negative (reference) probe.
P
Physical signal port that outputs the pressure value.
Ideal Heat Flow Sensor
Ideal heat flow meter
expand all in page

Library
Thermal Sensors

Description
The Ideal Heat Flow Sensor block represents an ideal heat flow meter, that is, a device that converts a
heat flow passing through the meter into a control signal proportional to this flow. The meter must be
connected in series with the component whose heat flow is being monitored.

Connections A and B are thermal conserving ports. Port H is a physical signal port that outputs the heat
flow value.

The block positive direction is from port A to port B.

Ports
The block has the following ports:
A
Thermal conserving port associated with the sensor positive probe.
B
Thermal conserving port associated with the sensor negative probe.
H
Physical signal output port for heat flow.
Ideal Temperature Source
Ideal source of thermal energy, characterized by temperature

Library
Thermal Sources

Description
The Ideal Temperature Source block represents an ideal source of thermal energy that is powerful
enough to maintain specified temperature at its outlet regardless of the heat flow consumed by the
system.

Connections A and B are thermal conserving ports corresponding to the source inlet and outlet,
respectively. Port S is a physical signal port, through which the control signal that drives the source is
applied. You can use the entire variety of Simulink® signal sources to generate the desired heat flow
variation profile. The temperature differential across the source is directly proportional to the signal at the
control port S.

The block positive direction is from port A to port B. This means that the temperature differential is
determined as TB – TA, where TB and TA are the temperatures at source ports.

Ports
The block has the following ports:
A
Thermal conserving port associated with the source inlet.
B
Thermal conserving port associated with the source outlet.
S
Physical signal input port, through which the control signal that drives the source is applied.

Pressure & Temperature Sensor (TL)


Measure pressure and temperature differences

Library
Thermal Liquid/Sensors
Description
The Pressure & Temperature Sensor (TL) block represents an ideal sensor that measures pressure and
temperature differences between two thermal liquid nodes. Because pressure and temperature are
Across variables, the sensor block must connect in parallel with the component being measured.

The relative orientation of ports A and B determines the measurement sign. The sign is positive if the
measured quantity is greater at port A than it is at port B. Switching port connections reverses the
measurement sign.

Ports P and T output the pressure and temperature measurements as physical signals. Connect the ports
to PS-Simulink Converter blocks to transform the output physical signals into Simulink ® signals, e.g., for
plotting or additional data processing.

Assumptions and Limitations


 Sensor inertia is negligible
Ports
The block has the following ports.

A, B Thermal liquid conserving ports

P Physical signal output port for pressure measurement

T Physical signal output port for temperature measurement

Mass & Energy Flow Rate Sensor (TL)


Measure mass and energy flow rates

Library
Thermal Liquid/Sensors

Description
The Mass & Energy Flow Rate Sensor (TL) block represents an ideal sensor that measures mass and
energy flow rates through a thermal liquid node. Because the flow rates are Through variables, the block
must connect in series with the component being measured.

The relative orientation of ports A and B establishes the measurement sign. The sign is positive if flow
occurs from port A to port B. Switching port connections reverses the measurement sign.

Two physical signal ports output the measurement data. Port M outputs the mass flow rate. Port Phi
outputs the thermal energy flow rate. Connect the ports to PS-Simulink Converter blocks to transform the
output physical signals into Simulink® signals, e.g., for plotting or additional data processing.

Assumptions and Limitations


 Sensor inertia is negligible.
Ports
The block has the following ports.

A, B Thermal liquid conserving ports

M Physical signal output port for mass flow rate measurement

Phi Physical signal output port for energy flow rate measurement
Thermodynamic Properties Sensor (TL)
Measure specific internal energy, density, and specific heat at constant pressure
expand all in page

 Library:
 Foundation Library / Thermal Liquid / Sensors

Description
The Thermodynamic Properties Sensor (TL) block represents an ideal sensor that measures specific
internal energy, density, and specific heat at constant pressure in a thermal liquid network. There is no
mass or energy flow through the sensor.

The block measures these thermodynamic properties at the node connected to port A. All measurements
are taken with respect to absolute zero.

Ports
Output
expand all
u — Specific internal energy measurement, kJ/kg
physical signal
rho — Density measurement, kg/m^3
physical signal
cp — Specific heat at constant pressure measurement, kJ/(kg*K)
physical signal
Conserving
expand all
A — Sensor inlet
thermal liquid
Volumetric Flow Rate Sensor (TL)
Measure volumetric flow rate

Library
Thermal Liquid/Sensors

Description
The Volumetric Flow Rate Sensor (TL) block measures the volumetric flow rate through the thermal liquid
branch defined by ports A and B. The flow rate is positive if fluid flows from port A to port B.

Ports
 A — Thermal Liquid conserving port representing source inlet A
 B — Thermal Liquid conserving port representing source inlet B
 V — Physical signal output port for sensing the volumetric flow rate
Hydraulically-Actuated Driveline Clutch
Open Model
This example shows an engine driving an inertial load via a hydraulically-
controlled clutch. It shows how Simscape™ Driveline™ can be used in
conjunction with Foundation Library hydraulic blocks to model hydraulically-
actuated drivelines.
Model

Simulation Results from Simscape Logging


The plot below shows the speeds of an engine and load as a clutch is engaged.
Once the clutch is fully engaged the shafts rotate at the same speed. The clutch
actuator is modeled as a hydraulic system.
CR-CR Four-Speed Transmission
Open Model
This example shows a four-speed transmission with two planetary gears and five
clutches. The test sequence steps through the four forward gear ratios, switches
to neutral, and then applies a brake clutch to the output shaft of the transmission.
To manually select the gear for the transmission, configure the Clutch Control
subsystem to use the Manual variant using the hyperlinks. The Manual control
subsystem has blocks from the Dashboard library that let you select the gear and
apply the brake by clicking on them with the mouse.
Model

Transmission Subsystem
Simulation Results from Simscape Logging
The plot below shows the input and output shaft speeds of the transmission. The
clutch states are also plotted (locked or open), indicating the selected gear of the
transmission.
Five-Speed Transmission
Open Model
This example shows a five-speed transmission with a reverse gear. An engine spins the
layshaft and the six sets of output gears. To engage the selected gear, ideal actuators
move the selector levers connected to the double-sided synchronizers. The position of the
selector levers determines which gears are connected to the output shaft.
Model

Transmission Subsystem
Simulation Results from Simscape Logging
The plot below shows the shaft speeds for the engine, load, and intermediate gears. As
the transmission shifts between the gears, the load speed matches the speed of different
gears in the transmission. When the reverse gear is engaged, the speed of the output shaft
is negative.

The plot below shows the selector lever positions for each of the double-sided
synchronizers. Their positions dictate which of the gears are engaged and determines the
gear ratio for the transmission.
Modeling an Automatic Transmission Controller
Open Model

This example shows how to model an automotive drivetrain with Simulink®. Stateflow®
enhances the Simulink model with its representation of the transmission control logic. Simulink
provides a powerful environment for the modeling and simulation of dynamic systems and
processes. In many systems, though, supervisory functions like changing modes or invoking new
gain schedules must respond to events that may occur and conditions that develop over time. As
a result, the environment requires a language capable of managing these multiple modes and
developing conditions. In the following example, Stateflow shows its strength in this capacity by
performing the function of gear selection in an automatic transmission. This function is
combined with the drivetrain dynamics in a natural and intuitive manner by incorporating a
Stateflow block in the Simulink block diagram.
Analysis and Physics
Figure 1 shows the power flow in a typical automotive drivetrain. Nonlinear ordinary differential
equations model the engine, four-speed automatic transmission, and vehicle. The model
discussed in this example directly implements the blocks from Figure 1 as modular Simulink
subsystems. On the other hand, the logic and decisions made in the Transmission Control Unit
(TCU) do not lend themselves to well-formulated equations. TCU is better suited for a Stateflow
representation. Stateflow monitors the events which correspond to important relationships within
the system and takes the appropriate action as they occur.

Figure 1: Generic block diagram for a drivetrain system


The throttle opening is one of the inputs to the engine. The engine is connected to the impeller of
the torque converter which couples it to the transmission (see Equation 1).
Equation 1
The input-output characteristics of the torque converter can be expressed as functions of the
engine speed and the turbine speed. In this example, the direction of power flow is always
assumed to be from the impeller to the turbine (see Equation 2).
Equation 2

The transmission model is implemented via static gear ratios, assuming small shift times (see
Equation 3).
Equation 3

The final drive, inertia, and a dynamically varying load constitute the vehicle dynamics (see
Equation 4).
Equation 4

The load torque includes both the road load and brake torque. The road load is the sum of
frictional and aerodynamic losses (see Equation 5).
Equation 5
The model programs the shift points for the transmission according to the schedule shown in
Figure 2. For a given throttle in a given gear, there is a unique vehicle speed at which an upshift
takes place. The simulation operates similarly for a downshift.

Figure 2: Shift schedule


Modeling
To open this model type sldemo_autotrans in MATLAB® terminal. Initial conditions are set in
the Model Workspace.
The top-level diagram of the model is shown in Figure 3. To run the simulation, press the Play
button on the toolbar in the model window. Note that the model logs relevant data to MATLAB
Workspace in a data structure called sldemo_autotrans_output. Logged signals have a blue
indicator (see Figure 3). After you run the simulation, you can view the components of the data
structure by typing sldemo_autotrans_output in MATLAB Command Window. Also note that
the units appear on the subsystem icons and signal lines. To learn more about units in Simulink
see Simulink Units.
Figure 3: Model diagram and sample simulation results (passing maneuver)
Modeling
The Simulink model shown in Figure 3 is composed of modules which represent the engine,
transmission, and the vehicle, with an additional shift logic block to control the transmission
ratio. User inputs to the model are in the form of throttle (given in percent) and brake torque
(given in ft-lb). The user inputs throttle and brake torques using the ManeuversGUI interface.
The Engine subsystem consists of a two-dimensional table that interpolates engine torque versus
throttle and engine speed. Figure 4 shows the composite Engine subsystem. Double click on this
subsystem in the model to view its structure.

Figure 4: Engine subsystem


The TorqueConverter and the TransmissionRatio blocks make up the Transmission subsystem,
as shown in Figure 5. Double click on the Transmission subsystem in the model window to view
its components.

Figure 5: Transmission subsystem


The TorqueConverter is a masked subsystem, which implements Equation 2. To open this
subsystem, right click on it and select Mask > Look Under Mask from the drop-down menu. The
mask requires a vector of speed ratios ( Nin/Ne ) and vectors of K-factor (f2) and torque ratio
(f3). Figure 6 shows the implementation of the TorqueConverter subsystem.
Figure 6: Torque converter subsystem
The transmission ratio block determines the ratio shown in Table 1 and computes the
transmission output torque and input speed, as indicated in Equation 3. Figure 7 shows the block
diagram for the subsystem that realizes this ratio in torque and speed.
Table 1: Transmission gear ratios
gear Rtr = Nin/Ne
1 2.393
2 1.450
3 1.000
4 0.677

Figure 7: Transmission gear ratio subsystem


The Stateflow block labeled ShiftLogic implements gear selection for the transmission. Double
click on ShiftLogic in the model window to open the Stateflow diagram. The Model Explorer is
utilized to define the inputs as throttle and vehicle speed and the output as the desired gear
number. Two dashed AND states keep track of the gear state and the state of the gear selection
process. The overall chart is executed as a discrete-time system, sampled every 40 milliseconds.
The Stateflow diagram shown in Figure 8 illustrates the functionality of the block.
Figure 8: Stateflow diagram of the transmission shift logic
The shift logic behavior can be observed during simulation by enabling animation in the
Stateflow debugger. The selection_state (always active) begins by performing the
computations indicated in its during function. The model computes the upshift and downshift
speed thresholds as a function of the instantaneous values of gear and throttle. While in
steady_state, the model compares these values to the present vehicle speed to determine if a shift
is required. If so, it enters one of the confirm states (upshifting ordownshifting), which records
the time of entry.
If the vehicle speed no longer satisfies the shift condition, while in the confirm state, the model
ignores the shift and it transitions back to steady_state. This prevents extraneous shifts due to
noise conditions. If the shift condition remains valid for a duration of TWAIT ticks, the model
transitions through the lower junction and, depending on the current gear, it broadcasts one of the
shift events. Subsequently, the model again activates steady_state after a transition through one
of the central junctions. The shift event, which is broadcast to the gear_selection state, activates
a transition to the appropriate new gear.
For example, if the vehicle is moving along in second gear with 25% throttle, the state second is
active within gear_state, and steady_state is active in the selection_state.
The during function of the latter, finds that an upshift should take place when the vehicle
exceeds 30 mph. At the moment this becomes true, the model enters the upshiftingstate. While
in this state, if the vehicle speed remains above 30 mph for TWAIT ticks, the model satisfies the
transition condition leading down to the lower right junction. This also satisfies the condition
[|gear == 2|] on the transition leading from here to steady_state, so the model now takes the
overall transition from upshifting to steady_state and broadcasts the event UP as a transition
action. Consequently, the transition from second to third is taken in gear_state which completes
the shift logic.
The Vehicle subsystem (Figure 9) uses the net torque to compute the acceleration and integrate it
to compute the vehicle speed, per Equation 4 and Equation 5. The Vehicle subsystem is masked.
To see the structure of the Vehicle block, right click on it and select Mask > Look Under Mask
from the drop-down menu. The parameters entered in the mask menu are the final drive ratio, the
polynomial coefficients for drag friction and aerodynamic drag, the wheel radius, vehicle inertia,
and initial transmission output speed.
Figure 9: Vehicle subsystem (masked)
Results
The engine torque map, and torque converter characteristics used in the simulations are shown in
Figure 10 and Figure 11.

Figure 10: Engine torque map


Figure 11: Torque converter characteristics (see Figure 5 and Equation 2)
The first simulation (passing maneuver) uses the throttle schedule given in Table 2 (this data is
interpolated linearly).
Table 2: Throttle schedule for first simulation (passing maneuver)
Time (sec) Throttle (%)
0 60
14.9 40
15 100
100 0
200 0

The first column corresponds to time; the second column corresponds to throttle opening in
percent. In this case no brake is applied (brake torque is zero). The vehicle speed starts at zero
and the engine at 1000 RPM. Figure 12 shows the plot for the baseline results, using the default
parameters. As the driver steps to 60% throttle at t=0, the engine immediately responds by more
than doubling its speed. This brings about a low speed ratio across the torque converter and,
hence, a large torque ratio (see Figure 6 and Figure 11. The vehicle accelerates quickly (no tire
slip is modeled) and both the engine and the vehicle gain speed until about t = 2 sec, at which
time a 1-2 upshift occurs. The engine speed characteristically drops abruptly, then resumes its
acceleration. The 2-3 and 3-4 upshifts take place at about four and eight seconds, respectively.
Notice that the vehicle speed remains much smoother due to its large inertia.

Figure 12: Passing maneuver simulation time history


At t=15sec, the driver steps the throttle to 100% as might be typical of a passing maneuver. The
transmission downshifts to third gear and the engine jumps from about 2600 RPM to about 3700
RPM. The engine torque thus increases somewhat, as well as the mechanical advantage of the
transmission. With continued heavy throttle, the vehicle accelerates to about 100 mph and then
shifts into overdrive at about t = 21 sec. The vehicle cruises along in fourth gear for the
remainder of the simulation. Double click on the ManeuversGUI block and use the graphical
interface to vary the throttle and brake history.
Closing the Model
Close the model, clear generated data.
Conclusions
One can easily enhance this basic system in a modular manner, for example, by replacing the
engine or transmission with a more complex model. We can thus build up large systems within
this structure via step-wise refinement. The seamless integration of Stateflow control logic with
Simulink signal processing enables the construction of a model which is both efficient and
visually intuitive.
Generic Engine
Internal combustion engine with throttle and rotational inertia and time lag
Library
Engines

Description
The block represents a general internal combustion engine. Engine types include
spark-ignition and diesel. Speed-power and speed-torque parameterizations are
provided. A throttle physical signal input specifies the normalized engine torque.
Optional dynamic parameters include crankshaft inertia and response time lag. A
physical signal port outputs engine fuel consumption rate based on choice of fuel
consumption model. An optional speed controller prevents engine stall and
enables cruise control. See Generic Engine Model.

Parameters
Engine Torque
Model parameterization
Select how to model the engine. The default is Normalized 3rd-order
polynomial matched to peak power.
 Normalized 3rd-order polynomial matched to peak power —
Parametrize the engine with a power function controlled by power and
speed characteristics.
Normalized Engine Power Polynomial
 Tabulated torque data — Engine is parametrized by speed–torque
table that you specify. If you select this option, the panel changes from its
default.
Tabulated Torque Data
 Tabulated power data — Engine is parametrized by speed-power table
that you specify. If you select this option, the panel changes from its
default.
Tabulated Power Data
Dynamics
Inertia
Select how to model the rotational inertia of the engine block. The default
is No inertia.
 No inertia — Engine crankshaft is modeled with no inertia.
 Specify inertia and initial velocity — Engine crankshaft is
modeled with rotational inertia and initial angular velocity. If you select this
option, the panel changes from its default.
Rotational Inertia and Initial Velocity
Engine time constant
Select how to model the time lag of the engine response. The default is No
time constant — Suitable for HIL simulation.
 No time constant — Suitable for HIL simulation — Engine reacts
with no time lag.
 Specify engine time constant and initial throttle — Engine
reacts with a time lag. If you select this option, the panel changes from its
default.
Engine Time Constant and Initial Throttle
Limits
Speed threshold
Width of the speed range over which the engine torque is blended to zero
as Ω approaches the stall speed. The default is 100.
From the drop-down list, choose units. The default is revolutions per
minute (rpm).
Fuel Consumption
Fuel consumption model
Select model to specify engine fuel consumption. Models range from
simple to advanced parameterizations compatible with standard industrial
data. The default model isConstant per revolution.
Constant per revolution
Fuel consumption by speed and torque
Brake specific fuel consumption by speed and torque
Brake specific fuel consumption by speed and brake mean effective
pressure
Speed Control
Idle speed control
Select speed control model. Options include No idle speed
controller and Enable idle speed controller.
 No idle speed controller — Omit idle speed controller. Throttle input
is used directly.
 Enable idle speed controller — Include idle speed controller to
prevent engine stalling. For more information, see Idle Speed Controller
Model.
Idle speed reference
Enter the value of the speed reference below which speed increases, and
above which speed decreases. The default value is 1000. The default unit
is rpm.
Controller time constant
Enter the value of the time constant associated with an increase or
decrease of the controlled throttle. The constant value must be positive.
The default value is 1. The default unit is s.
Controller threshold speed
Parameter used to smooth the controlled throttle value when the engine's
rotational speed crosses the idle speed reference. For more information,
see Idle Speed Controller Model. Large values decrease controller
responsiveness. Small values increase computational cost. This parameter
must be positive. The default value is 1. The default unit is rpm.
Generic Engine Model
By default, the Generic Engine model uses a programmed relationship between
torque and speed, modulated by the throttle signal.
Engine Speed, Throttle, Power, and Torque
The engine model is specified by an engine power demand function g(Ω). The
function provides the maximum power available for a given engine speed Ω.
The block parameters (maximum power, speed at maximum power, and
maximum speed) normalize this function to physical maximum torque and
speed values.
The normalized throttle input signal T specifies the actual engine power. The
power is delivered as a fraction of the maximum power possible in a steady
state at a fixed engine speed. It modulates the actual power delivered, P, from
the engine: P(Ω,T) = T·g(Ω). The engine torque is τ = P/Ω.
Engine Power Demand
The engine power is nonzero when the speed is limited to the operating
range, Ωmin ≤ Ω ≤ Ωmax. The absolute maximum engine power Pmax defines
Ω0 such that Pmax = g(Ω0). Define w≡ Ω/Ω0 and g(Ω) ≡ Pmax·p(w). Then p(1) =
1 and dp(1)/dw = 0. The torque function is:
τ = (Pmax/Ω0)·[p(w)/w] .
You can derive forms for p(w) from engine data and models. Generic Engine
uses a third-order polynomial form:
p(w) = p1·w + p2·w2 – p3·w3
satisfying
p1 + p2– p3 = 1 , p1 + 2p2– 3p3 = 0 .
In typical engines, the pi are positive. This polynomial has three zeros, one
at w = 0, and a conjugate pair. One of the pair is positive and physical; the
other is negative and unphysical:

Typical Engine Power Demand Function


Restrictions on Engine Speed and Power
 For the engine power polynomial, there are restrictions, as shown, on the
polynomial coefficients pi, to achieve a valid power-speed curve.
 If you use tabulated power or torque data, corresponding restrictions on P(Ω)
remain.
Set w = Ω/Ω0 and p = P(Ω)/P0, and wmin = Ωmin/Ω0 and wmax = Ωmax/Ω0. Then:
 The engine speed is restricted to a positive range above the minimum speed
and below the maximum speed: 0 ≤ wmin ≤ w ≤ wmax.
 The engine power at minimum speed must be nonnegative: p(wmin) ≥ 0. If you
use the polynomial form, this condition is a restriction on the pi:
p(wmin) = p1·wmin + p2·w2min – p3·w3min ≥ 0 .
 The engine power at maximum speed must be nonnegative: p(wmax) ≥ 0. If you
use the polynomial form, this condition is a restriction on wmax: wmax ≤ w+.
Engine Power Forms for Different Engine Types
For the default parametrization, Generic Engine provides two choices of internal
combustion engine types, each with different engine power demand
parameters.

Power Demand Engine Type:


Coefficient Spark-Ignition Diesel
p1 1 0.6526
p2 1 1.6948
p3 1 1.3474
Idle Speed Controller Model
The idle speed controller adjusts the throttle signal to increase engine rotation
below a reference speed according to the following expressions:
Π=max(Πi,Πc)
( ( ))
=
d(Πc)dt 0.5⋅ 1−tanh 4⋅ω−ωrωt −Πcτ
where:
 Π — Engine throttle
 Πi — Input throttle (port T)
 Πc — Controller throttle
 ω — Engine speed
 ωe — Idle speed reference
 ωt — Controller speed threshold
 τ — Controller time constant
The controlled throttle increases with a first-order lag from zero to one when
engine speed falls below the reference speed. When the engine speed rises
above the reference speed, the controlled throttle decreases from one to zero.
When the difference between engine velocity and reference speed is smaller
than the controller speed threshold, the tanh function smooths the time
derivative of the controlled throttle. The controlled throttle is limited to the range
0–1. The engine uses the larger of the input and controlled throttle values. If
engine time lag is included, the controller changes the input before the lag is
computed.
Limitations
This block contains an engine time lag limitation.
Engine Time Lag
Engines lag in their response to changing speed and throttle. The Generic
Engine block optionally supports lag due to a changing throttle only. Time lag
simulation increases model fidelity but reduces simulation performance.
Ports

Port Description
B Rotational conserving port representing the engine block
F Rotational Conserving port representing the engine crankshaft
T Physical signal input port specifying the normalized engine
throttle level
P Physical signal output port reporting the instantaneous engine
power
FC Physical signal output port reporting the fuel consumption rate
Port T accepts a signal with values in the range 0–1. The signal specifies the
engine torque as a fraction of the maximum torque possible in steady state at
fixed engine speed. The signal saturates at zero and one. Values below zero
are interpreted as zero. Values above one are interpreted as one.
Piston Engine

Reciprocating combustion engine with variable number of pistons


Library
Engines
Description
This block represents a reciprocating combustion engine with multiple cylinders.
The piston model accounts for the instantaneous torque transmitted to the engine
drive shaft. The instantaneous torque enables you to model vibrations in the
drivetrain due to piston revolution. To model just the piston mechanism of a
combustion engine, use the Piston block.
Port B represents the translating piston and port F the rotating crankshaft. The
piston force follows from the cylinder pressure and cross-sectional area. The
block obtains the combustion pressure from a lookup table parameterized in
terms of the crank angle and, optionally, the crank angular velocity and engine
throttle level.
The crank torque follows from the piston force and crank angle as well as the
crank and connecting rod lengths. In terms of these inputs, the ratio of the piston
force and crank torque is

=−c sin(θ)+ G −sin2(θ) ,


F B TF rc
sin(2θ)2
 
where:
 FB is the instantaneous piston force associated with the base port.
 TF is the instantaneous crank torque associated with the follower port.
 c is the crank length.
 θ is the instantaneous crank angle.
 r is the connecting rod length.
Piston Dimensions

Physical signal port T lets you specify the engine throttle level as a fraction
between 0 and 1. This fraction corresponds to the percentage of full power
generated. The block uses the physical signal input whenever the pressure
lookup table in the block dialog box is parameterized only in terms of the crank
angle.
Parameters
Pistons
Number of pistons
Number of pistons in the combustion engine. The default number is 4.
Offset angle vector
Vector of piston offset angles. The offset angle specifies the point in the engine
cycle when the piston reaches top dead center. The engine cycle spans in angle
from -S*180 to+S*180 degrees, where S is the number of strokes per cycle.
The vector size must be the same as the number of pistons. The default vector
is [0.0, 180.0, 360.0, -180.0], corresponding to a four-stroke, four-piston
engine.
Cylinder bore
Internal diameter of the engine cylinder that the piston travels in. The default
value is 0.10 m.
Piston stroke
Distance between the top dead center and bottom dead center piston positions.
The default value is 0.06 m.
Piston rod length
Length of the connecting rod located between the engine piston and the
crankshaft. The default value is 0.10 m.
Number of strokes per cycle
Number of strokes required to complete one engine cycle. One stroke
corresponds to a full extension or retraction of the engine piston. A typical
automobile engine is based on a four-stroke cycle with induction, compression,
power, and exhaust stages. The default value is 4
Pressure parameterization
Engine variables that the cylinder pressure depends on. Options include By
crank angle, By crank angle and throttle, By crank angle, throttle,
and crank velocity. The default setting is By crank angle.
Crank angle vector
M-element vector of crank angles at which to specify the cylinder pressure. A
zero angle corresponds to a piston at top dead center. The vector must range
from -S*180 to +S*180degrees, where S is the number of strokes per cycle. The
default vector is an eight-element vector ranging in value from -360 to +360 deg,
corresponding to a four-stroke cycle.
Throttle vector
N-element vector of engine throttle settings at which to specify the cylinder
pressure. A value of 0 corresponds to no throttle and a value of 1 to full throttle.
This parameter is active only when Pressure parameterization is set to By
crank angle and throttle and By crank angle, throttle, and crank
velocity. The default vector is [0.0, 0.3, 0.8, 1.0].
Crank velocity vector
L-element vector of crankshaft angular velocities at which to specify the cylinder
pressure. This parameter is active only when Pressure parameterization is set
to By crank angle, throttle, and crank velocity. The default vector
is [0.0, 1000.0, 6000.0] rpm.
Pressure vector
M-element vector of cylinder pressures corresponding to the crank angles
specified in the Crank angle vector parameter. This parameter is active only
when Pressure parameterization is set to By crank angle.
Pressure matrix (gauge)
M-by-N matrix of cylinder pressures corresponding to the crank angles and
throttle settings specified in the Crank angle vector and Throttle
vector parameters. This parameter is active only when Pressure
parameterization is set to By crank angle and throttle. The default matrix
is an 8–by-4 matrix ranging in value from 0 to 50 bar.
Pressure matrix 3D (gauge)
M-by-N-by-L matrix of cylinder pressures corresponding to the crank angles,
throttle settings, and crank angular velocity values specified in the Crank angle
vector, Throttle vector, and Crank velocity vector parameters. This parameter
is active only when Pressure parameterization is set to By crank angle,
throttle, and crank velocity. The default matrix is an 8–by-4–by-3 matrix
ranging in value from 0 to 50 bar.
Crankshaft
Shaft dynamics
Optional shaft dynamics parameters. Options include No shaft dynamics —
Suitable for HIL simulation and Specify shaft stiffness, damping,
and inertia
Stiffness
Stiffness coefficient of the engine crankshaft. This parameter accounts for
resistance to shaft deformation. This parameter is active only when the Shaft
dynamics parameter is set to Specify shaft stiffness, damping, and
inertia. The default value is 1e6 N*m/rad.
Damping
Damping coefficients of the engine crankshaft. This parameter accounts for
energy dissipation due to shaft deformation. This parameter is active only when
the Shaft dynamicsparameter is set to Specify shaft stiffness, damping,
and inertia. The default value is 1000 N*m/(rad/s).
Inertia
Moment of inertia of the crankshaft about its rotational axis. This parameter
accounts for resistance to sudden changes in motion. This parameter is active
only when the Shaft dynamics parameter is set to Specify shaft stiffness,
damping, and inertia. The default value is 0.02 kg*m^2.
Initial angular deflection
Deflection angle between the base and follower ends of the crankshaft at time
zero. The deflection angle measures the angular deformation of the crankshaft
due to torsion. This parameter is active only when the Shaft
dynamics parameter is set to Specify shaft stiffness, damping, and
inertia. The default value is 0 deg.
Initial angular velocity
Angular velocity of the crankshaft at time zero. This parameter is active only
when the Shaft dynamics parameter is set to Specify shaft stiffness,
damping, and inertia. The default value is 0 rpm.
Base and follower bearing viscous friction coefficients
Two-element vector with the viscous friction coefficients of the base and follower
shaft bearings. The block uses viscous friction to account for energy losses
between the base and follower shafts. The default vector is [0.0,
0.0] N*m/(rad/s), corresponding to zero damping.
Initial crank angle
Crank angle at time zero relative to a top dead center position. The default value
is 90 deg.
Ports
 B — Conserving rotational port representing the engine block
 F — Conserving rotational port representing the engine crankshaft
 T — Physical signal input port for specifying the engine throttle setting
Engine Cooling System
Open Model
This example shows how to model a basic engine cooling system using custom thermal liquid blocks. A
fixed-displacement pump drives water through the cooling circuit. Heat from the engine is absorbed by
the water coolant and dissipated through the radiator. The system temperature is regulated by the
thermostat, which diverts flow to the radiator only when the temperature is above a threshold.

The custom thermal liquid blocks include the Fixed-Displacement Pump, the Fluid Jacket, the Radiator,
and the Thermostat. Click on the source code link on the block dialog to inspect the code and see how
existing Thermal Liquid Library blocks can be modified to suit a specific application.

The Fluid Jacket and the Radiator are modifications of the Pipe (TL) block. These components represent
an internal volume of liquid to model the effects of dynamic compressibility and thermal capacity using the
mass and energy conservation equations. Default priorities for the pressure and temperature are set to
high to provide initial conditions for the liquid state.

The Fixed-Displacement Pump is a modification of the Mass Flow Rate Source (TL) block. The
Thermostat is a modification of the Local Restriction (TL) block. Both components are assumed to contain
negligible volume of liquid. Therefore, they are assumed quasi-steady.

All four components inherit from foundation.thermal_liquid.two_port_dynamic or


foundation.thermal_liquid.two_port_steady base classes, which implements common equations to
calculate the energy flow rate based on a smoothed upwind method. This method allows energy to be
convected downstream, enabling the proper propagation of information throughout the thermal liquid
network.

Model
Engine Subsystem

Simulation Results from Simscape Logging


These plots show the effect of opening the thermostat in the engine cooling system. The temperature of
the piston climbs steadily until the thermostat opens. At that point, the flow of coolant through the radiator
climbs sharply and the flow of coolant through the bypass hose decreases. Because coolant passing
through the radiator releases heat to the atmosphere, the piston temperature rises more slowly.

This plot shows the density of the coolant at different locations in the cooling system over time. The
density of the coolant varies throughout the network based on the local temperature and pressure.
Fluid Properties
Modeling a Fault-Tolerant Fuel Control System
Open Model
This example shows how to combine Stateflow® with Simulink® to efficiently model hybrid systems. This
type of modeling is particularly useful for systems that have numerous possible operational modes based
on discrete events. Traditional signal flow is handled in Simulink while changes in control configuration
are implemented in Stateflow. The model described below represents a fuel control system for a gasoline
engine. The system is highly robust in that individual sensor failures are detected and the control system
is dynamically reconfigured for uninterrupted operation.

Analysis and Physics


Physical and empirical relationships form the basis for the throttle and intake manifold dynamics of this
model. The air-fuel ratio is computed by dividing the air mass flow rate (pumped from the intake manifold)
by the fuel mass flow rate (injected at the valves). The ideal (i.e. stoichiometric) mixture ratio provides a
good compromise between power, fuel economy, and emissions. The target air-fuel ratio for this system
is 14.6. Typically, a sensor determines the amount of residual oxygen present in the exhaust gas (EGO).
This gives a good indication of the mixture ratio and provides a feedback measurement for closed-loop
control. If the sensor indicates a high oxygen level, the control law increases the fuel rate. When the
sensor detects a fuel-rich mixture, corresponding to a very low level of residual oxygen, the controller
decreases the fuel rate.

Modeling
Figure 1 shows the top level of the Simulink model. To open the model, type sldemo_fuelsys in
MATLAB® Command Window. Press the Play button in the model window toolbar to run the simulation.
The model loads necessary data into the model workspace from sldemo_fuelsys_data.m. The model
logs relevant data to MATLAB workspace in a data structure called sldemo_fuelsys_output and
streams the data to the Simulation Data Inspector. Logged signals are marked with a blue indicator while
streaming signals are marked with the light blue badge(see Figure 1).

Note that loading initial conditions into the model workspace keeps simulation data isolated from data in
other open models that you may have open. This also helps avoid MATLAB workspace cluttering. To
view the contents of the model workspace select View > Model Explorer > Model Explorer, and click on
Model Workspace from the Model Hierarchy list.

Notice that units are visible on the model and subsystem icons and signal lines. Units are specified on the
ports and on the bus object. To learn more about units in Simulink seeSimulink Units.
Figure 1: Top-level diagram for the fuel control system model

The Dashboard subsystem (shown in Figure 2) allows the user to interact with the model during
simulation. The Fault Injection switches can be moved from the Normal to Fail position to simulate sensor
failures, while the Engine Speed selector switch can be toggled to change the engine speed. The fuel and
air/fuel ratio signals are visualized using the dashboard gauges and scopes to provide visual feedback
during a simulation run.

Figure 2: Dashboard subsystem for the fuel control system model


The fuel_rate_control uses signals from the system's sensors to determine the fuel rate which gives a
stoichiometric mixture. The fuel rate combines with the actual air flow in the engine gas dynamics model
to determine the resulting mixture ratio as sensed at the exhaust.

The user can selectively disable each of the four sensors (throttle angle, speed, EGO and manifold
absolute pressure [MAP]) by using the slider switches in the dashboard subsystem, to simulate failures.
Simulink accomplishes this by binding slider switches to the value parameter of the constant block.
Double-click on the dashboard subsystem to open the control dashboard to change the position of the
switch. Similarly, the user can induce the failure condition of a high engine speed by toggling the engine
speed switch on the dashboard subsystem. A Repeating Table block provides the throttle angle input and
periodically repeats the sequence of data specified in the mask.

The fuel_rate_control block, shown in Figure 3, uses the sensor input and feedback signals to adjust the
fuel rate to give a stoichiometric ratio. The model uses three subsystems to implement this strategy:
control logic, airflow calculation, and fuel calculation. Under normal operation, the model estimates the
airflow rate and multiplies the estimate by the reciprocal of the desired ratio to give the fuel rate.
Feedback from the oxygen sensor provides a closed-loop adjustment of the rate estimation in order to
maintain the ideal mixture ratio.

Figure 3: Fuel rate controller subsystem

Control Logic
A single Stateflow chart, consisting of a set of six parallel states, implements the control logic in its
entirety. The four parallel states shown at the top of Figure 4 correspond to the four individual sensors.
The remaining two parallel states at the bottom consider the status of the four sensors simultaneously
and determine the overall system operating mode. The model synchronously calls the entire Stateflow
diagram at a regular sample time interval of 0.01 sec. This permits the conditions for transitions to the
correct mode to be tested on a timely basis.

To open the control_logic Stateflow chart, double click on it in the fuel_rate_control subsystem.
Figure 4: The control logic chart

When execution begins, all of the states start in their normal mode with the exception of the oxygen
sensor (EGO). The O2_warmup state is entered initially until the warmup period is complete. The system
detects throttle and pressure sensor failures when their measured values fall outside their nominal
ranges. A manifold vacuum in the absence of a speed signal indicates a speed sensor failure. The
oxygen sensor also has a nominal range for failure conditions but, because zero is both the minimum
signal level and the bottom of the range, failure can be detected only when it exceeds the upper limit.

Regardless of which sensor fails, the model always generates the directed event broadcast Fail.INC. In
this way the triggering of the universal sensor failure logic is independent of the sensor. The model also
uses a corresponding sensor recovery event, Fail.DEC. The Fail state keeps track of the number of
failed sensors. The counter increments on eachFail.INC event and decrements on each Fail.DEC event.
The model uses a superstate, Multi, to group all cases where more than one sensor has failed.

The bottom parallel state represents the fueling mode of the engine. If a single sensor fails, operation
continues but the air/fuel mixture is richer to allow smoother running at the cost of higher emissions. If
more than one sensor has failed, the engine shuts down as a safety measure, since the air/fuel ratio
cannot be controlled reliably.

During the oxygen sensor warm-up, the model maintains the mixture at normal levels. If this is
unsatisfactory, the user can change the design by moving the warm-up state to within
the Rich_Mixture superstate. If a sensor failure occurs during the warm-up period,
the Single_Failure state is entered after the warm-up time elapses. Otherwise, the Normalstate is
activated at this time.

A protective overspeed feature has been added to the model by creating a new state in
the Fuel_Disabled superstate. Through the use of history junctions, we assured that the chart returns to
the appropriate state when the model exits the overspeed state. As the safety requirements for the engine
become better specified, we can add additional shutdown states to the Fuel_Disabled superstate.

Sensor Correction
When a sensor fails, an estimate of the sensor is computed. For example, open the pressure sensor
calculation. Under normal sensor operation the value of the pressure sensor is used. Otherwise, the value
is estimated.
ans =

logical

The estimate of manifold pressure is computed as a function of engine speed and throttle position. The
value is computed conveniently using a Simulink function inside Stateflow.

Airflow Calculation
The Airflow Calculation block (shown in Figure 6) is the location for the central control laws. This block is
found inside the fuel_rate_control subsystem (open this block). The block estimates the intake air flow to
determine the fuel rate which gives the appropriate air/fuel ratio. Closed-loop control adjusts the
estimation according to the residual oxygen feedback in order to maintain the mixture ratio precisely.
Even when a sensor failure mandates open-loop operation, the most recent closed-loop adjustment is
retained to best meet the control objectives.
Figure 6: Airflow estimation and correction

Equation 1

The engine's intake air flow can be formulated as the product of the engine speed, the manifold pressure
and a time-varying scale factor.

Cpump is computed by a lookup table and multiplied by the speed and pressure to form the initial flow
estimate. During transients, the throttle rate, with the derivative approximated by a high-pass filter,
corrects the air flow for filling dynamics. The control algorithm provides additional correction according to
Equation 2.

Equation 2
Figure 7: Engine Gas Dynamics subsystem

Figure 8: Mixing & Combustion block within the Engine Gas Dynamics subsystem

The nonlinear oxygen sensor (EGO Sensor block) is found inside the Mixing & Combustion block (see
Figure 8) within the Engine Gas Dynamics subsystem (see Figure 7). EGO Sensor is modeled as a
hyperbolic tangent function, and it provides a meaningful signal when in the vicinity of 0.5 volt. The raw
error in the feedback loop is thus detected with a switching threshold, as indicated in Equation 2. If the
air-fuel ratio is low (the mixture is lean), the original air estimate is too small and needs to be increased.
Conversely, when the oxygen sensor output is high, the air estimate is too large and needs to be
decreased. Integral control is utilized so that the correction term achieves a level that brings about zero
steady-state error in the mixture ratio.

The normal closed-loop operation mode, LOW, adjusts the integrator dynamically to minimize the error.
The integration is performed in discrete time, with updates every 10 milliseconds. When operating open-
loop however, in the RICH or O2 failure modes, the feedback error is ignored and the integrator is held.
This gives the best correction based on the most recent valid feedback.

Fuel Calculation
The fuel_calc subsystem (within the fuel_rate_control subsystem, see Figure 9) sets the injector signal to
match the given airflow calculation and fault status. The first input is the computed airflow estimation. This
is multiplied with the target fuel/air ratio to get the commanded fuel rate. Normally the target is
stoichiometric, i.e. equals the optimal air to fuel ratio of 14.6. When a sensor fault occurs, the Stateflow
control logic sets the mode input to a value of 2 or 3 (RICH or DISABLED) so that the mixture is either
slightly rich of stoichiometric or is shut down completely.
Figure 9: fuel_calc subsystem

The fuel_calc subsystem (Figure 9) employs adjustable compensation (Figure 10) in order to achieve
different purposes in different modes. In normal operation, phase lead compensation of the feedback
correction signal adds to the closed-loop stability margin. In RICH mode and during EGO sensor failure
(open loop), however, the composite fuel signal is low-pass filtered to attenuate noise introduced in the
estimation process. The end result is a signal representing the fuel flow rate which, in an actual system,
would be translated to injector pulse times.

Figure 10: Switchable compensation subsystem

Results and Conclusions


Simulation results are shown in Figure 11 and Figure 12. The simulation is run with a throttle input that
ramps from 10 to 20 degrees over a period of two seconds, then goes back to 10 degrees over the next
two seconds. This cycle repeats continuously while the engine is held at a constant speed so that the
user can experiment with different fault conditions and failure modes. Click on a sensor fault switch in the
dashboard subsystem to simulate the failure of the associated sensor. Repeat this operation to slide the
switch back for normal operation.

Figure 11: Comparing the fuel flow rate for different sensor failures

Figure 11 compares the fuel flow rate under fault-free conditions (baseline) with the rate applied in the
presence of a single failure in each sensor individually. In each case note the nonlinear relationship
between fuel flow and the triangular throttle command (shown in Figure 13). In the baseline case, the fuel
rate is regulated tightly, exhibiting a small ripple due to the switching nature of the EGO sensor's input
circuitry. In the other four cases the system operates open loop. The control strategy is proven effective in
maintaining the correct fuel profile in the single-failure mode. In each of the fault conditions, the fuel rate
is essentially 125% of the baseline flow, fulfilling the design objective of 80% rich.

Figure 12: Comparing the air-fuel ratio for different sensor failures

Figure 12 plots the corresponding air/fuel ratio for each case. The baseline plot shows the effects of
closed-loop operation. The mixture ratio is regulated very tightly to the stoichiometric objective of 14.6.
The rich mixture ratio is shown in the bottom four plots of Figure 12. Although they are not tightly
regulated, as in the closed-loop case, they approximate the objective of air/fuel (0.8*14.6=11.7).
Figure 13: Throttle command

The transient behavior of the system is shown in Figure 14. With a constant 12 degree throttle angle and
the system in steady-state, a throttle failure is introduced at t = 2 and corrected at t = 5. At the onset of
the failure, the fuel rate increases immediately. The effects are seen at the exhaust as the rich ratio
propagates through the system. The steady-state condition is then quickly recovered when closed-loop
operation is restored.

Figure 14: Transient response to fault detection

Remarks
With animation enabled in the Stateflow debugger, the state transitions are highlighted in the Stateflow
diagram (see Figure 4) as the various states are activated. The sequence of activation is indicated by
changing colors. This closely coupled synergy between Stateflow and Simulink fosters the modeling and
development of complete control systems. An engineer's concepts can develop in a natural and
structured fashion with immediate visual feedback reinforcing each step.
Related Examples
Refer to other examples related to sldemo_fuelsys:

 Fixed-point design: fxpdemo_fuelsys


 Production C/C++ code generation: Air-Fuel Ratio Control System with Stateflow Charts (Simulink Coder)
 Fixed-point production C/C++ code generation: Air-Fuel Ratio Control System with Fixed-Point
Data (Simulink Coder)
MIMO Control of Diesel Engine
This example also uses:

 Simulink Control Design


Open Script

This example uses systune to design and tune a MIMO controller for a Diesel engine. The
controller is tuned in discrete time for a single operating condition.
Diesel Engine Model
Modern Diesel engines use a variable geometry turbocharger (VGT) and exhaust gas
recirculation (EGR) to reduce emissions. Tight control of the VGT boost pressure and EGR
massflow is necessary to meet strict emission targets. This example shows how to design and
tune a MIMO controller that regulates these two variables when the engine operates at 2100 rpm
with a fuel mass of 12 mg per injection-cylinder.
open_system('rct_diesel')

The VGT/EGR control system is modeled in Simulink. The controller adjusts the
positions EGRLIFT and VGTPOS of the EGR and VGT valves. It has access to the boost pressure
and EGR massflow targets and measured values, as well as fuel mass and engine speed
measurements. Both valves have rate and saturation limits. The plant model is sampled every 0.1
seconds and the control signals EGRLIFT and VGTPOS are refreshed every 0.2 seconds. This
example considers step changes of +10 KPa in boost pressure and +3 g/s in EGR massflow, and
disturbances of +5 mg in fuel mass and -200 rpm in speed.
For the operating condition under consideration, we used System Identification to derive a linear
model of the engine from experimental data. The frequency response from the manipulated
variables EGRLIFT and VGTPOS to the controlled variables BOOST and EGR MF appears below. Note
that the plant is ill conditioned at low frequency which makes independent control of boost
pressure and EGR massflow difficult.
sigma(Plant(:,1:2)), grid
title('Frequency response of the linearized engine dynamics')

Control Objectives
There are two main control objectives:
1. Respond to step changes in boost pressure and EGR massflow in about 5 seconds with
minimum cross-coupling
2. Be insensitive to (small) variations in speed and fuel mass.
Use a tracking requirement for the first objective. Specify the amplitudes of the step changes to
ensure that cross-couplings are small relative to these changes.
% 5-second response time, steady-state error less than 5%
TR = TuningGoal.Tracking({'BOOST REF';'EGRMF REF'},{'BOOST';'EGRMF'},5,0.05);
TR.Name = 'Setpoint tracking';
TR.InputScaling = [10 3];
For the second objective, treat the speed and fuel mass variations as step disturbances and
specify the peak amplitude and settling time of the resulting variations in boost pressure and
EGR massflow. Also specify the signal amplitudes to properly reflect the relative contribution of
each disturbance.
% Peak<0.5, settling time<5
DR = TuningGoal.StepRejection({'FUELMASS';'SPEED'},{'BOOST';'EGRMF'},0.5,5);
DR.Name = 'Disturbance rejection';
DR.InputScaling = [5 200];
DR.OutputScaling = [10 3];
To provide adequate robustness to unmodeled dynamics and aliasing, limit the control bandwidth
and impose sufficient stability margins at both the plant inputs and outputs. Because we are
dealing with a 2-by-2 MIMO feedback loops, these stability margins are interpreted as disk
margins (see loopmargin and TuningGoal.Margins for details).
% Roll off of -20 dB/dec past 1 rad/s
RO = TuningGoal.MaxLoopGain({'EGRLIFT','VGTPOS'},1,1);
RO.LoopScaling = 'off';
RO.Name = 'Roll-off';

% 7 dB of gain margin and 45 degrees of phase margin


M1 = TuningGoal.Margins({'EGRLIFT','VGTPOS'},7,45);
M1.Name = 'Plant input';
M2 = TuningGoal.Margins('DIESEL ENGINE',7,45);
M2.Name = 'Plant output';
Tuning of Blackbox MIMO Controller
Without a-priori knowledge of a suitable control structure, first try "blackbox" state-space
controllers of various orders. The plant model has four states, so try a controller of order four or
less. Here we tune a second-order controller since the "SS2" block in the Simulink model has
two states.
Figure 1: Second-order blackbox controller.
Use the slTuner interface to configure the Simulink model for tuning. Mark the block "SS2" as
tunable, register the locations where to assess margins and loop shapes, and specify that
linearization and tuning should be performed at the controller sampling rate.
ST0 = slTuner('rct_diesel','SS2');
ST0.Ts = 0.2;
addPoint(ST0,{'EGRLIFT','VGTPOS','DIESEL ENGINE'})
Now use systune to tune the state-space controller subject to our control objectives. Treat the
stability margins and roll-off target as hard constraints and try to best meet the remaining
objectives (soft goals). Randomize the starting point to reduce exposure to undesirable local
minima.
Opt = systuneOptions('RandomStart',2);
rng(0), ST1 = systune(ST0,[TR DR],[M1 M2 RO],Opt);
Final: Soft = 1.05, Hard = 0.98598, Iterations = 576
Final: Soft = 1.05, Hard = 0.97199, Iterations = 389
Final: Soft = 1.05, Hard = 0.87771, Iterations = 417
All requirements are nearly met (a requirement is satisfied when its normalized value is less than
1). Verify this graphically.
figure('Position',[10,10,1071,714])
viewSpec([TR DR RO M1 M2],ST1)
Plot the setpoint tracking and disturbance rejection responses. Scale by the signal amplitudes to
show normalized effects (boost pressure changes by +10 KPa, EGR massflow by +3 g/s, fuel
mass by +5 mg, and speed by -200 rpm).
figure('Position',[100,100,560,500])
T1 = getIOTransfer(ST1,{'BOOST REF';'EGRMF
REF'},{'BOOST','EGRMF','EGRLIFT','VGTPOS'});
T1 = diag([1/10 1/3 1 1]) * T1 * diag([10 3]);
subplot(211), step(T1(1:2,:),15), title('Setpoint tracking')
subplot(212), step(T1(3:4,:),15), title('Control effort')

D1 = getIOTransfer(ST1,{'FUELMASS';'SPEED'},{'BOOST','EGRMF','EGRLIFT','VGTPOS'});
D1 = diag([1/10 1/3 1 1]) * D1 * diag([5 -200]);
subplot(211), step(D1(1:2,:),15), title('Disturbance rejection')
subplot(212), step(D1(3:4,:),15), title('Control effort')
The controller responds in less than 5 seconds with minimum cross-coupling between
the BOOST and EGRMF variables.
Tuning of Simplified Control Structure
The state-space controller could be implemented as is, but it is often desirable to boil it down to a
simpler, more familiar structure. To do this, get the tuned controller and inspect its frequency
response
C = getBlockValue(ST1,'SS2');

clf
bode(C(:,1:2),C(:,3:4),{.02 20}), grid
legend('REF to U','Y to U')
bodemag(C(:,5:6)), grid
title('Bode response from FUELMASS/SPEED to EGRLIFT/VGTPOS')
The first plot suggests that the controller essentially behaves like a PI controller acting on REF-Y
(the difference between the target and actual values of the controlled variables). The second plot
suggests that the transfer from measured disturbance to manipulated variables could be replaced
by a gain in series with a lag network. Altogether this suggests the following simplified control
structure consisting of a MIMO PI controller with a first-order disturbance feedforward.
Figure 2: Simplified control structure.
Using variant subsystems, you can implement both control structures in the same Simulink
model and use a variable to switch between them. Here setting MODE=2 selects the MIMO PI
structure. As before, use systune to tune the three 2-by-2 gain matrices Kp, Ki, Kff in the
simplified control structure.
% Select "MIMO PI" variant in "CONTROLLER" block
MODE = 2;

% Configure tuning interface


ST0 = slTuner('rct_diesel',{'Kp','Ki','Kff'});
ST0.Ts = 0.2;
addPoint(ST0,{'EGRLIFT','VGTPOS','DIESEL ENGINE'})

% Tune MIMO PI controller.


ST2 = systune(ST0,[TR DR],[M1 M2 RO]);
Final: Soft = 1.09, Hard = 0.99972, Iterations = 222
Again all requirements are nearly met. Plot the closed-loop responses and compare with the
state-space design.
clf
T2 = getIOTransfer(ST2,{'BOOST REF';'EGRMF
REF'},{'BOOST','EGRMF','EGRLIFT','VGTPOS'});
T2 = diag([1/10 1/3 1 1]) * T2 * diag([10 3]);
subplot(211), step(T1(1:2,:),T2(1:2,:),15), title('Setpoint tracking')
legend('SS2','PI+FF')
subplot(212), step(T1(3:4,:),T2(3:4,:),15), title('Control effort')
D2 = getIOTransfer(ST2,{'FUELMASS';'SPEED'},{'BOOST','EGRMF','EGRLIFT','VGTPOS'});
D2 = diag([1/10 1/3 1 1]) * D2 * diag([5 -200]);
subplot(211), step(D1(1:2,:),D2(1:2,:),15), title('Disturbance rejection')
legend('SS2','PI+FF')
subplot(212), step(D1(3:4,:),D2(3:4,:),15), title('Control effort')
The blackbox and simplified control structures deliver similar performance. Inspect the tuned
values of the PI and feedforward gains.
showTunable(ST2)
Block 1: rct_diesel/CONTROLLER/MIMO PID/Kp =

D =
u1 u2
y1 -0.007961 -0.0007802
y2 -0.02036 0.01463

Name: Kp
Static gain.

-----------------------------------

Block 2: rct_diesel/CONTROLLER/MIMO PID/Ki =

D =
u1 u2
y1 -0.01052 -0.01425
y2 -0.03017 0.04636

Name: Ki
Static gain.

-----------------------------------

Block 3: rct_diesel/CONTROLLER/MIMO PID/Kff =

D =
u1 u2
y1 0.01208 -8.608e-05
y2 0.04208 -0.001504

Name: Kff
Static gain.

Nonlinear Validation
To validate the MIMO PI controller in the Simulink model, push the tuned controller parameters
to Simulink and run the simulation.
writeBlockValue(ST2)
The simulation results are shown below and confirm that the controller adequately tracks
setpoint changes in boost pressure and EGR massflow and quickly rejects changes in fuel mass
(at t=90) and in speed (at t=110).

Figure 3: Simulation results with simplified controller.


Double-Shoe Brake
Frictional brake with two pivoted shoes diametrically positioned about a rotating drum

Library
Brakes & Detents/Rotational

Description
The block represents a frictional brake with two pivoted rigid shoes that press against a rotating drum to
produce a braking action. The rigid shoes sit inside or outside the rotating drum in a diametrically
opposed configuration. A positive actuating force causes the rigid shoes to press against the rotating
drum. Viscous and contact friction between the drum and the rigid shoe surfaces cause the rotating drum
to decelerate. Double-shoe brakes provide high braking torque with small actuator deflections in
applications that include motor vehicles and some heavy machinery. The model employs a simple
parameterization with readily accessible brake geometry and friction parameters.

In this schematic, a) represents an internal double-shoe brake, and b) represents an external double-
shoe brake. In both configurations, a positive actuation force F brings the shoe and drum friction surfaces
into contact. The result is a friction torque that causes deceleration of the rotating drum. Zero and
negative forces do not bring the shoe and drum friction surfaces into contact and produce zero braking
torque.

The model uses the long-shoe approximation. Contact angles smaller than 45° produce less accurate
results. The following formulas provide the friction torque the leading and trailing shoes develop,
respectively:
( )
TLS= a D2
μ⋅p ⋅r cosθsb−cosθs sinθa
( )
TTS= b D2
μ⋅p ⋅r cosθ −cosθ sinθa
sb s

In the formulas, the parameters have the following meaning:

Parameter Description

TLS Brake torque the leading shoe develops

TTS Brake torque the trailing shoe develops

μ Effective contact friction coefficient

pa Maximum linear pressure in the leading shoe-drum contact

pb Maximum linear pressure in the trailing shoe-drum contact

rD Drum radius

θsb Shoe beginning angle

θs Shoe span angle

θa Angle from hinge pin to maximum pressure point

/ / /
θa= θsπ if  0if  θs≤θs≤π ≥π   
2 2 2

The model assumes that only Coulomb friction acts at the shoe-drum surface contact. Zero relative
velocity between the drum and the shoes produces zero Coulomb friction. To avoid discontinuity at zero
relative velocity, the friction coefficient formula employs the following hyperbolic function:

( )
μ=μCoulomb⋅tanh
4ωshaftωthreshold
In the formula, the parameters have the following meaning:

Parameter Description

μ Effective contact friction coefficient

μCoulomb Contact friction coefficient

ωshaft Shaft velocity

ωthreshold Angular velocity threshold

Balancing the moments that act on each shoe with respect to the pin yields the pressure acting at the
shoe-drum surface contact. The following formula provides the balance of moments for the leading shoe.

F= N F
M −M c
In the formula, the parameters have the following meaning:

Parameter Description

F Actuation Force

MN Moment acting on the leading shoe due to normal force

MF Moment acting on the leading shoe due to friction force

c Arm length of the cylinder force with respect to the hinge pin

The following equations give MN, MF, and c, respectively.

( )
[ ] [ ]
MN= a p D θ −θ − sin2θs−sin2θsb
p r r sinθa 12 s sb 14
( )
[ ] [ ]
MF= a D r cosθsb−cosθs + p cos2θs−cos2θsb
μp r sinθa D r4
c=ra+rpcosθp

The parameters have the following meaning:

Parameter Description

pa Maximum linear pressure at the shoe-drum contact surface

rp Pin location radius

θp Hinge pin location angle

ra Actuator location radius

The model does not simulate self-locking brakes. If brake geometry and friction parameters cause a self-
locking condition, the model produces a simulation error. A brake self-locks if the friction moment exceeds
the moment due to normal forces:

MF>MN

The following formula provides the balance of moments for the trailing shoe.

F= N F
M +M c
Formulas and parameters for MN, MF, and c share the definition in the leading shoe section.

The net braking torque has the formula:

T=TLS+TTS+μvisc
In the formula, parameter μvisc is the viscous friction coefficient.

Variables
Use the Variables tab to set the priority and initial target values for the block variables before simulating.
For more information, see Set Priority and Initial Target for Block Variables(Simscape).
Unlike block parameters, variables do not have conditional visibility. The Variables tab lists all the
existing block variables. If a variable is not used in the set of equations corresponding to the selected
block configuration, the values specified for this variable are ignored.

Assumptions and Limitations


 The brake uses the long-shoe approximation.
 The brake geometry does not self-lock.
 The model does not account for actuator flow consumption.
Modeling Thermal Effects
You can model the effects of heat flow and temperature change through an optional thermal conserving
port. By default, the thermal port is hidden. To expose the thermal port, right-click the block in your model
and, from the context menu, select Simscape > Block choices. Select a variant that includes a thermal
port. Specify the associated thermal parameters for the component.

Ports
F
Physical signal port that represents the brake actuating force
S
Rotational conserving port that represents the rotating drum shaft
H
Thermal conserving port. The thermal port is optional and is hidden by default. To expose the
port, select a variant that includes a thermal port.

Parameters
Geometry
Drum radius
Radius of the drum contact surface. The parameter must be greater than zero. The default value
is 150 mm.
Actuator location radius
Distance between the drum center and the force line of action. The parameter must be greater
than zero. The default value is 100 mm.
Pin location radius
Distance between the hinge pin and drum centers. The parameter must be greater than zero. The
default value is 125 mm.
Pin location angle
Angular coordinate of the hinge pin location from the brake symmetry axis. The parameter must
be greater than or equal to zero. The default value is 15 deg.
Shoe beginning angle
Angle between the hinge pin and the beginning of the friction material linen of the shoe. The
value of the parameter must be in the range 0 ≤ θsb ≤ (π-pin location angle). The default value
is 5 deg.
Shoe span angle
Angle between the beginning and the end of the friction material linen on the shoe. The value of
the parameter must be in the range 0 < θsb ≤ (π -pin location angle - shoe beginning angle). The
default value is 120 deg.

Friction
Viscous friction coefficient
Value of the viscous friction coefficient at the contact surface. The parameter must be greater
than or equal to zero. The default value is .01 n*m/(rad/s).
Temperature
Array of temperatures used to construct a 1-D temperature-efficiency lookup table. The array
values must increase left to right. The default value is [280.0, 300.0, 320.0] K.
This parameter is visible only when you select a block variant that includes a thermal port.
Contact friction coefficient
Value of the Coulomb friction coefficient at the belt-drum contact surface. The value is greater
than zero. Unless you select a block variant that includes a thermal port, the default value is 0.3.
If you select a block variant that includes a thermal port, you specify this parameter as array. The
array is the same size as the array for the Temperature parameter and the values increase left to
right. The default value for the thermal variant is [0.1, 0.05, 0.03].
Angular velocity threshold
Angular velocity at which the contact friction coefficient practically reaches its steady-state value.
The parameter must be greater than zero. the default value is 0.01 rad/s.

Thermal Port
Thermal mass
Thermal energy required to change the component temperature by a single degree. The greater
the thermal mass, the more resistant the component is to temperature change. This parameter is
enabled only if you select a block variant that includes a thermal port. The default value
is 50 kJ/K.

Modeling an Anti-Lock Braking System


Open Model

This example shows how to model a simple model for an Anti-Lock Braking System (ABS). It
simulates the dynamic behavior of a vehicle under hard braking conditions. The model represents
a single wheel, which may be replicated a number of times to create a model for a multi-wheel
vehicle.
This model uses the signal logging feature in Simulink®. The model logs signals to the
MATLAB® workspace where you can analyze and view them. You can view the
code insldemo_absbrakeplots.m to see how this is done.
In this model, the wheel speed is calculated in a separate model
named sldemo_wheelspeed_absbrake. This component is then referenced using a 'Model' block.
Note that both the top model and the referenced model use a variable step solver, so Simulink
will track zero-crossings in the referenced model.
Analysis and Physics
The wheel rotates with an initial angular speed that corresponds to the vehicle speed before
the brakes are applied. We used separate integrators to compute wheel angular speed and vehicle
speed. We use two speeds to calculate slip, which is determined by Equation 1. Note that we
introduce vehicle speed expressed as an angular velocity (see below).

Equation 1

From these expressions, we see that slip is zero when wheel speed and vehicle speed are equal,
and slip equals one when the wheel is locked. A desirable slip value is 0.2, which means that the
number of wheel revolutions equals 0.8 times the number of revolutions under non-braking
conditions with the same vehicle velocity. This maximizes the adhesion between the tire and
road and minimizes the stopping distance with the available friction.
Modeling
The friction coefficient between the tire and the road surface, mu, is an empirical function of slip,
known as the mu-slip curve. We created mu-slip curves by passing MATLAB variables into the
block diagram using a Simulink lookup table. The model multiplies the friction coefficient, mu,
by the weight on the wheel, W, to yield the frictional force, Ff, acting on the circumference of the
tire. Ff is divided by the vehicle mass to produce the vehicle deceleration, which the model
integrates to obtain vehicle velocity.
In this model, we used an ideal anti-lock braking controller, that uses 'bang-bang' control based
upon the error between actual slip and desired slip. We set the desired slip to the value of slip at
which the mu-slip curve reaches a peak value, this being the optimum value for minimum
braking distance (see note below.).
 Note: In an actual vehicle, the slip cannot be measured directly, so this control algorithm is not
practical. It is used in this example to illustrate the conceptual construction of such a simulation
model. The real engineering value of a simulation like this is to show the potential of the control
concept prior to addressing the specific issues of implementation.
Creating a Temporary Directory for the Example
During this example, Simulink generates files in the current working directory. If you do not
want to generate files in this directory, change the working directory to a suitable directory:
origdir = cd(tempdir);

Opening the Model


To open this model type sldemo_absbrake in MATLAB terminal (or click on the hyperlink if you
are using MATLAB Help).

Figure 1: Anti-Lock Braking (ABS) Model


Double click on the 'Wheel Speed' subsystem in the model window to open it. Given the wheel
slip, the desired wheel slip, and the tire torque, this subsystem calculates the wheel angular
speed.

Figure 2: Wheel Speed subsystem


To control the rate of change of brake pressure, the model subtracts actual slip from the desired
slip and feeds this signal into a bang-bang control (+1 or -1, depending on the sign of the error,
see Figure 2). This on/off rate passes through a first-order lag that represents the delay associated
with the hydraulic lines of the brake system. The model then integrates the filtered rate to yield
the actual brake pressure. The resulting signal, multiplied by the piston area and radius with
respect to the wheel (Kf), is the brake torque applied to the wheel.
The model multiplies the frictional force on the wheel by the wheel radius (Rr) to give the
accelerating torque of the road surface on the wheel. The brake torque is subtracted to give the
net torque on the wheel. Dividing the net torque by the wheel rotational inertia, I, yields the
wheel acceleration, which is then integrated to provide wheel velocity. In order to keep the wheel
speed and vehicle speed positive, limited integrators are used in this model.
Running the Simulation in ABS Mode
Press the "Play" button on the model toolbar to run the simulation. You can also run the
simulation by executing the sim('sldemo_absbrake') command in MATLAB. ABS is turned on
during this simulation.

Figure 3: Baseline Simulation Results


 Note: The model logs relevant data to MATLAB workspace in a structure
called sldemo_absbrake_output. Logged signals have a blue indicator. In this
case yout and slp are logged (see the model). Read more about Signal Logging in Simulink
Help.
Figure 3 visualizes the ABS simulation results (for default parameters). The first plot in Figure 3
shows the wheel angular velocity and corresponding vehicle angular velocity. This plot shows
that the wheel speed stays below vehicle speed without locking up, with vehicle speed going to
zero in less than 15 seconds.
Running the Simulation Without ABS
For more meaningful results, consider the vehicle behavior without ABS. At the MATLAB
command line, set the model variable ctrl = 0. This disconnects the slip feedback from the
controller (see Figure 1), resulting in maximum braking. The results are shown in Figure 4.
ctrl = 0;

Now run the simulation again. This will model braking without ABS.

Figure 4: Maximum braking simulation results (braking without ABS)


Braking With ABS Versus Braking Without ABS
In the upper plot of Figure 4, observe that the wheel locks up in about seven seconds. The
braking, from that point on, is applied in a less-than-optimal part of the slip curve. That is,
when slip = 1, as seen in the lower plot of Figure 4, the tire is skidding so much on the
pavement that the friction force has dropped off.
This is, perhaps, more meaningful in terms of the comparison shown in Figure 5. The distance
traveled by the vehicle is plotted for the two cases. Without ABS, the vehicle skids about an
extra 100 feet, taking about three seconds longer to come to a stop.

Figure 5: Stopping distance for hard braking with and without ABS
Closing the Model
Close the model. Close the 'Wheel Speed' subsystem. Clear logged data. Change back to the
original directory.
cd(origdir);

Conclusions
This model shows how you can use Simulink to simulate a braking system under the action of an
ABS controller. The controller in this example is idealized, but you can use any proposed control
algorithm in its place to evaluate the system's performance. You can also use the Simulink®
Coder™ with Simulink as a valuable tool for rapid prototyping of the proposed algorithm. C
code is generated and compiled for the controller hardware to test the concept in a vehicle. This
significantly reduces the time needed to prove new ideas by enabling actual testing early in the
development cycle.
For a hardware-in-the-loop braking system simulation, you can remove the 'bang-bang' controller
and run the equations of motion on real-time hardware to emulate the wheel and vehicle
dynamics. You can do this by generating real-time C code for this model using the Simulink
Coder. You can then test an actual ABS controller by interfacing it to the real-time hardware,
which runs the generated code. In this scenario, the real-time model would send the wheel speed
to the controller, and the controller would send brake action to the model.
Suspension System Comparison
Open Model
This example shows a testbed containing three sets of springs and dampers excited by the same
oscillating velocity source. The first uses the Shock Absorber block and includes linear stiffness and
damping. Optional friction and hard stops are not used. The second shock absorber uses a Nonlinear
Translational Spring and a Nonlinear Translational Damper specified by symmetric polynomials. The third
uses a Variable Translational Spring and Variable Translational Damper. The spring constant is varied
during the simulation using open loop control and the damping coefficient adjusts to ensure critical
damping is achieved. Closed loop control can be added to simulate an adaptive suspension system.

Model

Simulation Results from Simscape Logging


The plot below shows the position of the sprung masses in three different suspension models that are
subjected to the same test.
Power Spectral Density
Vehicle in Simscape Driveline and Simulink
Open Model
This model shows two equivalent simplified vehicles modeled in Simscape™ Driveline™ and Simulink®.
The simulation results are identical, and the Simscape Driveline model is easily extensible to include
different effects and a higher level of modeling fidelity. Meshing losses in the gears and more detailed tire
modeling can be added without introducing algebraic loops.

Model

Simulation Results from Simscape Logging


The plot below compares the results of the Simscape Driveline and Simulink models. When the models
are equivalent, the results are identical. Meshing losses and physical effects can be easily added to the
Simscape Driveline model by enabling them in the block dialog boxes.
Limited Slip Differential with Clutches
Open Model
This example shows a comparison between the behavior of an open differential and a limited slip
differential with clutch packs. The limited slip differential is modeled using components from the Gears
library and Clutches library in Simscape Driveline. Wheel slip is limited by clutches that engage when the
torque applied to the input of the differential exceeds a threshold. The clutches lock the differential so that
the output shafts of the differential spin at the same speed.

The test surface includes an icy patch under the left wheel. This effect is introduced using the variable-
friction coefficient variant of the Tire (Magic Formula) block. Comparing the two differentials on the same
test surface shows that the limited slip differential locks up under the split surface road condition.

Model

Limited Slip Differential Subsystem


Tires Limited Slip Differential Subsystem

Simulation Results from Simscape Logging


The plot below shows the performance of an open and a limited slip differential on a split surface (ice and
tarmac). The limited slip differential locks when the left wheel encounters the icy patch, and the left and
right wheel speeds remain the same. The open differential does not lock and applies the same torque to
both shafts. The result is that the left wheel loses traction on the icy patch and slips.

The plot below shows the performance of open and a limited slip differential on a split surface (ice and
tarmac). The limited slip differential locks instantly when the left wheel encounters the icy patch. As a
result, the wheels turn at the same speed and more torque is applied to the wheel on the high friction
surface. The open differential does not lock. The same torque is applied to both wheels, resulting in the
left wheel slipping extensively on the icy patch.
Vehicle Electrical and Climate Control Systems
This example also uses:

 Simscape Power Systems


Open Model
This example shows how to interface the vehicle climate control system with a model of the electrical
system to examine the loading effects of the climate control system on the entire electrical system of the
car.

Figure 1: Vehicle Electrical and Climate Control System

The Climate Control System


Double clicking on the ClimateControlSystem subsystem will open the model of the climate control
system. Here the user can enter the temperature value they would like the air in the car to reach by
double clicking on the USER SETPOINT IN CELSIUS Block and entering the value into the dialog box.
The EXTERNAL TEMPERATURE IN CELSIUS can also be set by the user in a similar way. The
numerical display on the right hand side of the model shows the reading of a temperature sensor placed
behind the driver's head. This is the temperature that the driver should be feeling. When the model is run
and the climate control is active, it is this display box whose value changes showing the change of
temperature in the car.
Figure 2: The automatic climate control system.

The Stateflow® Controller


The control of the system is implemented in Stateflow®. Double clicking on the Stateflow chart will show
how this supervisory control logic has been formulated.

The Heater_AC state shows that when the user enters a setpoint temperature which greater than the
current temperature in the car by at least 0.5 deg C, the heater system will be switched on. The heater
will remain active until the current temperature in the car reaches to within 0.5 deg of the setpoint
temperature. Similarly, when the user enters a setpoint which is 0.5 deg C (or more) lower than the
current car temperature, the Air Conditioner is turned on and stays active until the temperature of
the air in the car reaches to within 0.5 deg C of the setpoint temperature. After which, the system will
switches off. The dead band of 0.5 deg has been implemented to avoid the problem of continuous
switching.

In the Blower State, the larger the difference between the setpoint temperature and the current
temperature, the harder the fan blows. This ensures that the temperature will reach the required value in
a reasonable amount of time, despite the temperature difference. Once again, when the temperature of
the air in the car reaches to within 0.5 deg C of the setpoint temperature, the system will switches off.

The Air Distribution(AirDist) and Recycling Air States(Recyc_Air) are controlled by the two switches that
trigger the Stateflow chart. An internal transition has been implemented within these two states to
facilitate effective defrosting of the windows when required. When the defrost state is activated, the
recycling air is turned off.
Figure 3: The supervisory control logic in Stateflow.

Heater and Air Conditioner Models


The heater model was built from the equation for a heater exchanger shown below:
Tout = Ts - (Ts-Tin)e^[(-pi*D*L*hc)/(m_dot*Cp)]

Where:

 Ts = constant (radiator wall temperature)


 D = 0.004m (channel diameter)
 L = 0.05m (radiator thickness)
 N = 30000 (Number of channels)
 k = 0.026 W/mK = constant (thermal conductivity of air)
 Cp = 1007 J/kgK = constant (specific heat of air)
 Laminar flow (hc = 3.66(k/D) = 23.8 W/m2K )
In addition, the effect of the heater flap is taken into account. Similar to the operation of the blower, the
greater the temperature difference between the required setpoint temperature and the current
temperature in the car, the more the heater flap is opened and the greater the heating effect.

The Air Conditioner system is one of the two places where the climate control model interfaces with the
car's electrical system model. The compressor loads the engine of the car when the A/C system is active.
The final temperature to exit from the A/c is calculated as follows:

y*(w*Tcomp) = m_dot*(h4-h1)

Where:

 y = efficiency
 m_dot = mass flow rate
 w = speed of the engine
 Tcomp = compressor torque
 h4, h1 = enthalpy
Here we have bang-bang control of the A/C system where the temperature of the air that exits the A/C is
determined by the engine speed and compressor torque.
Figure 4: Heater control subsystem.

Figure 5: A/C control subsystem.

Heat Transfer in the Cabin


The temperature of the air felt by the driver is affected by all of these factors:

 The temperature of the air exiting the vents


 The temperature of the outside air
 The number of people in the car
These factors are inputs into the thermodynamic model of the interior of the cabin. We take into account
the temperature of the air exiting the vents by calculating the difference between the vent air temperature
and the current temperature inside the car and multiplying it by the fan speed proportion (mass flow rate).
Then 100W of energy is added per person in the car. Lastly, the difference between the temperature of
the outside air and the interior air temperature is multiplied by a lesser mass flow rate to account for
the air radiating into the car from the outside.

The output of the interior dynamics model is fed to the display block as a measure of the temperature
read by a sensor placed behind the driver's head.

The Electrical System


This electrical system models the car at idle speed. The PID controllers ensure that the car's alternator
(modeled by a simplified synchronous machine which has its field current regulated to control the output
voltage) is also operating at the required speed. The output of voltage is then fed through a three phase 6
pulse diode bridge to supply the voltage needed to charge the battery which supplies the voltage for the
car's DC bus.

The fan used in the climate control system is fed off this DC bus as are the windscreen wipers, radio etc.
As the difference between the setpoint temperature and the current temperature in the car drops, so does
the fan speed and therefore so does the loading on the DC bus. The inclusion of feedback in the electrical
system ensures that regardless of the load, the voltage on the bus remains at a constant 12V.

The additional model of the car's electrical system allows for the changing of the input voltage to the
engine - modeled as a DC machine. Changing the input voltage shows how the speed of the engine
changes without effecting the voltage on the DC bus.
Figure 6: The electrical system

Modeling a Vehicle Dynamics System


Open Script
This example shows nonlinear grey-box modeling of vehicle dynamics. Many new vehicle features
(like Electronic Stability Programs (ESP), indirect Tire Pressure Monitoring Systems (TPMS), road-tire
friction monitoring systems, and so forth) rely on models of the underlying vehicle dynamics. The so-
called bicycle vehicle model is a rather simple model structure that is frequently being used in the vehicle
dynamics literature. In this example we will start-off with this model structure and try to estimate the
longitudinal and the lateral stiffness of a tire. The actual modeling work was originally carried out by Erik
Narby in his MSc work at NIRA Dynamics AB, Sweden.

Vehicle Dynamics Modeling


The following figure illustrates the vehicle modeling situation to be considered.

Figure 1: Schematic view of a vehicle dynamics system.

By the use of Newton's law of motion and some basic geometric relationships, the longitudinal velocity
v_x(t), the lateral velocity v_y(t) and the yaw rate r(t) measured around the Center Of Gravity (COG) of
the vehicle can be described by the following three differential equations:
d
-- v_x(t) = v_y(t)*r(t) + 1/m*( (F_x,FL(t)+F_x,FR(t))*cos(delta(t))
dt - (F_y,FL(t)+F_y,FR(t))*sin(delta(t))
+ F_x,RL(t)+F_x,RR(t)
- C_A*v_x(t)^2)
d
-- v_y(t) = -v_x(t)*r(t) + 1/m*( (F_x,FL(t)+F_x,FR(t))*sin(delta(t))
dt + (F_y,FL(t)+F_y,FR(t))*cos(delta(t))
+ F_y,RL(t)+F_y,RR(t))
d
-- r(t) = 1/J*( a*( (F_x,FL(t)+F_x,FR(t))*sin(delta(t))
dt + (F_y,FL(t)+F_y,FR(t))*cos(delta(t)))
- b*(F_y,RL(t)+F_y,RR(t)))

where subscript x is used to denote that a force F acts in the longitudinal direction and y that it acts in the
lateral direction. The abbreviations FL, FR, RL and RR label the tires: Front Left, Front Right, Rear Left
and Rear Right, respectively. The first equation describing the longitudinal acceleration also contains an
air resistance term that is assumed to be a quadratic function of the longitudinal vehicle velocity v_x(t). In
addition, delta(t) (an input) is the steering angle, J a moment of inertia, and a and b the distances from the
center of gravity to the front and rear axles, respectively.

Let us assume that the tire forces can be modeled through the following linear approximations:
F_x,i(t) = C_x*s_i(t)
F_y,i(t) = C_y*alpha_i(t) for i = {FL, FR, RL, RR}

where C_x and C_y are the longitudinal and lateral tire stiffness, respectively. Here we have assumed
that these stiffness parameters are the same for all 4 tires. s_i(t) is the so-called (longitudinal) slip of tire i
and alpha_i(t) a tire slip angle. For a front-wheel driven vehicle (as considered here), the slips s_FL(t) and
s_FR(t) are derived from the individual wheel speeds (measured) by assuming that the rear wheels do
not show any slip (i.e., s_RL(t) = s_RR(t) = 0). Hence the slips are inputs to our model structure. For the
front wheels, the tire slip angels alpha_Fj(t) can be approximated by (when v_x(t) > 0)
alpha_Fj(t) = delta(t) - arctan((v_y(t) + a*r(t))/v_x(t))
~ delta(t) - (v_y(t) + a*r(t))/v_x(t) for j = {L, R}

For the rear wheels, the tire slip angels alpha_Rj(t) are similarly derived and computed as
alpha_Rj(t) = - arctan((v_y(t) - b*r(t))/v_x(t))
~ - (v_y(t) - b*r(t))/v_x(t) for j = {L, R}

With J = 1/((0.5*(a+b))^2*m) we can next set up a state-space structure describing the vehicle dynamics.
Introduce the states:
x1(t) = v_x(t) Longitudinal velocity [m/s].
x2(t) = v_y(t) Lateral velocity [m/s].
x3(t) = r(t) Yaw rate [rad/s].

the five measured or derived input signals


u1(t) = s_FL(t) Slip of Front Left tire [ratio].
u2(t) = s_FR(t) Slip of Front Right tire [ratio].
u3(t) = s_RL(t) Slip of Rear Left tire [ratio].
u4(t) = s_RR(t) Slip of Rear Right tire [ratio].
u5(t) = delta(t) Steering angle [rad].

and the model parameters:


m Mass of the vehicle [kg].
a Distance from front axle to COG [m].
b Distance from rear axle to COG [m].
Cx Longitudinal tire stiffness [N].
Cy Lateral tire stiffness [N/rad].
CA Air resistance coefficient [1/m].

The outputs of the system are the longitudinal vehicle velocity y1(t) = x1(t), the lateral vehicle acceleration
(measured by an accelerometer):
y2(t) = a_y(t) = 1/m*( (F_x,FL(t) + F_x,FR(t))*sin(delta(t))
+ (F_y,FL(t) + F_y,FR(t))*cos(delta(t))
+ F_y,RL(t) + F_y,RR(t))

and the yaw rate y3(t) = r(t) (measured by a gyro).

Put together, we arrive at the following state-space model structure:


d
-- x1(t) = x2(t)*x3(t) + 1/m*( Cx*(u1(t)+u2(t))*cos(u5(t))
dt - 2*Cy*(u5(t)-(x2(t)+a*x3(t))/x1(t))*sin(u5(t))
+ Cx*(u3(t)+u4(t))
- CA*x1(t)^2)
d
-- x2(t) = -x1(t)*x3(t) + 1/m*( Cx*(u1(t)+u2(t))*sin(u5(t))
dt + 2*Cy*(u5(t)-(x2(t)+a*x3(t))/x1(t))*cos(u5(t))
+ 2*Cy*(b*x3(t)-x2(t))/x1(t))
d
-- x3(t) = 1/((0.5*(a+b))^2)*m)*( a*( Cx*(u1(t)+u2(t)*sin(u5(t))
dt + 2*Cy*(u5(t) -
(x2(t)+a*x3(t))/x1(t))*cos(u5(t)))
- 2*b*Cy*(b*x3(t)-x2(t))/x1(t))
y1(t) = x1(t)
y2(t) = 1/m*( Cx*(u1(t)+u2(t))*sin(u5(t))
+ 2*Cy*(u5(t)-(x2(t)+a*x3(t))/x1(t))*cos(u5(t))
+ 2*Cy*(b*x3(t)-x2(t))/x1(t))
y3(t) = x3(t)

IDNLGREY Vehicle Model


As a basis for our vehicle identification experiments we first need to create an IDNLGREY model file
describing these vehicle equations. Here we rely on C-MEX modeling and create a vehicle_c.c model file,
in which NY is set to 3. The state and output update functions of vehicle_c.c, compute_dx and
compute_y, are somewhat involved and includes several standard C-defined mathematical functions, like
cos(.) and sin(.) as well as pow(.) for computing the power of its argument.

The state update function compute_dx returns dx (argument 1) and uses 3 input arguments: the state
vector x, the input vector u, and the six scalar parameters encoded in p (t and auxvar of the template C-
MEX model file have been removed here):
/* State equations. */
void compute_dx(double *dx, double *x, double *u, double **p)
{
/* Retrieve model parameters. */
double *m, *a, *b, *Cx, *Cy, *CA;
m = p[0]; /* Vehicle mass. */
a = p[1]; /* Distance from front axle to COG. */
b = p[2]; /* Distance from rear axle to COG. */
Cx = p[3]; /* Longitudinal tire stiffness. */
Cy = p[4]; /* Lateral tire stiffness. */
CA = p[5]; /* Air resistance coefficient. */
/* x[0]: Longitudinal vehicle velocity. */
/* x[1]: Lateral vehicle velocity. */
/* x[2]: Yaw rate. */
dx[0] = x[1]*x[2]+1/m[0]*(Cx[0]*(u[0]+u[1])*cos(u[4])
-2*Cy[0]*(u[4]-(x[1]+a[0]*x[2])/x[0])*sin(u[4])
+Cx[0]*(u[2]+u[3])-CA[0]*pow(x[0],2));
dx[1] = -x[0]*x[2]+1/m[0]*(Cx[0]*(u[0]+u[1])*sin(u[4])
+2*Cy[0]*(u[4]-(x[1]+a[0]*x[2])/x[0])*cos(u[4])
+2*Cy[0]*(b[0]*x[2]-x[1])/x[0]);
dx[2] = 1/(pow(((a[0]+b[0])/2),2)*m[0])
*(a[0]*(Cx[0]*(u[0]+u[1])*sin(u[4])
+2*Cy[0]*(u[4]-(x[1]+a[0]*x[2])/x[0])*cos(u[4]))
-2*b[0]*Cy[0]*(b[0]*x[2]-x[1])/x[0]);
}
The output update function compute_y returns y (argument 1) and uses 3 input arguments: the state
vector x, the input vector u, and five of the six parameters (the air resistance CA is not needed) encoded
in p:
/* Output equations. */
void compute_y(double *y, double *x, double *u, double **p)
{
/* Retrieve model parameters. */
double *m = p[0]; /* Vehicle mass. */
double *a = p[1]; /* Distance from front axle to COG. */
double *b = p[2]; /* Distance from rear axle to COG. */
double *Cx = p[3]; /* Longitudinal tire stiffness. */
double *Cy = p[4]; /* Lateral tire stiffness. */
/* y[0]: Longitudinal vehicle velocity. */
/* y[1]: Lateral vehicle acceleration. */
/* y[2]: Yaw rate. */
y[0] = x[0];
y[1] = 1/m[0]*(Cx[0]*(u[0]+u[1])*sin(u[4])
+2*Cy[0]*(u[4]-(x[1]+a[0]*x[2])/x[0])*cos(u[4])
+2*Cy[0]*(b[0]*x[2]-x[1])/x[0]);
y[2] = x[2];
}

Having a proper model structure file, the next step is to create an IDNLGREY object reflecting the
modeling situation. For ease of bookkeeping, we also specify the names and units of the inputs and
outputs.
FileName = 'vehicle_c'; % File describing the model
structure.
Order = [3 5 3]; % Model orders [ny nx nu].
Parameters = [1700; 1.5; 1.5; 1.5e5; 4e4; 0.5]; % Initial parameters.
InitialStates = [1; 0; 0]; % Initial initial states.
Ts = 0; % Time-continuous system.
nlgr = idnlgrey(FileName, Order, Parameters, InitialStates, Ts, ...
'Name', 'Bicycle vehicle model', 'TimeUnit', 's');
nlgr.InputName = {'Slip on front left tire'; ... % u(1).
'Slip on front right tire'; ... % u(2).
'Slip on rear left tire'; ... % u(3).
'Slip on rear right tire'; ... % u(4).
'Steering angle'}; ... % u(5).
nlgr.InputUnit = {'ratio'; 'ratio'; 'ratio'; 'ratio'; 'rad'};

nlgr.OutputName = {'Long. velocity'; ... % y(1); Longitudinal vehicle


velocity
'Lat. accel.'; ... % y(2); Lateral vehicle
acceleration
'Yaw rate'}; ... % y(3).
nlgr.OutputUnit = {'m/s'; 'm/s^2'; 'rad/s'};
The names and the units of the (initial) states and the model parameters are specified via SETINIT. We
also use this command to specify that the first initial state (the longitudinal velocity) ought to be strictly
positive for the model to be valid and to specify that all model parameters should be strictly positive.
These constraints will subsequently be honored when performing initial state and/or model parameter
estimation.
nlgr = setinit(nlgr, 'Name', {'Longitudinal vehicle velocity' ... % x(1).
'Lateral vehicle velocity' ... % x(2).
'Yaw rate'}); ... % x(3).
nlgr = setinit(nlgr, 'Unit', {'m/s'; 'm/s'; 'rad/s'});
nlgr.InitialStates(1).Minimum = eps(0); % Longitudinal velocity > 0 for the model
to be valid.
nlgr = setpar(nlgr, 'Name', {'Vehicle mass'; ... % m.
'Distance from front axle to COG'; ... % a
'Distance from rear axle to COG'; ... % b.
'Longitudinal tire stiffness'; ... % Cx.
'Lateral tire stiffness'; ... % Cy.
'Air resistance coefficient'}); ... % CA.
nlgr = setpar(nlgr, 'Unit', {'kg'; 'm'; 'm'; 'N'; 'N/rad'; '1/m'});
nlgr = setpar(nlgr, 'Minimum', num2cell(eps(0)*ones(6, 1))); % All parameters > 0!
Four of the six parameters of this model structure can readily be obtained through the data sheet of the
vehicle in question:
m = 1700 kg
a = 1.5 m
b = 1.5 m
CA = 0.5 or 0.7 1/m (see below)

Hence we will not estimate these parameters:


nlgr.Parameters(1).Fixed = true;
nlgr.Parameters(2).Fixed = true;
nlgr.Parameters(3).Fixed = true;
nlgr.Parameters(6).Fixed = true;
With this, a textual summary of the entered IDNLGREY model structure is obtained through PRESENT as
follows.
present(nlgr);

nlgr =
Continuous-time nonlinear grey-box model defined by 'vehicle_c' (MEX-file):

dx/dt = F(t, u(t), x(t), p1, ..., p6)


y(t) = H(t, u(t), x(t), p1, ..., p6) + e(t)

with 5 inputs, 3 states, 3 outputs, and 2 free parameters (out of 6).

Inputs:
u(1) Slip on front left tire(t) [ratio]
u(2) Slip on front right tire(t) [ratio]
u(3) Slip on rear left tire(t) [ratio]
u(4) Slip on rear right tire(t) [ratio]
u(5) Steering angle(t) [rad]
States: initial value
x(1) Longitudinal vehicle velocity(t) [m/s] xinit@exp1 1 (fix) in ]0, Inf]
x(2) Lateral vehicle velocity(t) [m/s] xinit@exp1 0 (fix) in [-Inf,
Inf]
x(3) Yaw rate(t) [rad/s] xinit@exp1 0 (fix) in [-Inf,
Inf]
Outputs:
y(1) Long. velocity(t) [m/s]
y(2) Lat. accel.(t) [m/s^2]
y(3) Yaw rate(t) [rad/s]
Parameters: value
p1 Vehicle mass [kg] 1700 (fix) in ]0, Inf]
p2 Distance from front axle to COG [m] 1.5 (fix) in ]0, Inf]
p3 Distance from rear axle to COG [m] 1.5 (fix) in ]0, Inf]
p4 Longitudinal tire stiffness [N] 150000 (est) in ]0, Inf]
p5 Lateral tire stiffness [N/rad] 40000 (est) in ]0, Inf]
p6 Air resistance coefficient [1/m] 0.5 (fix) in ]0, Inf]

Name: Bicycle vehicle model

Status:
Created by direct construction or transformation. Not estimated.
More information in model's "Report" property.
Input-Output Data
At this point, we load the available input-output data. This file contains data from three different
experiments:
A. Simulated data with high stiffness tires [y1 u1].
B. Simulated data with low stiffness tires [y2 u2].
C. Measured data from a Volvo V70 [y3 u3].

In all cases, the sample time Ts = 0.1 seconds.


load(fullfile(matlabroot, 'toolbox', 'ident', 'iddemos', 'data', 'vehicledata'));
A. System Identification Using Simulated High Tire Stiffness Data
In our first vehicle identification experiment we consider simulated high tire stiffness data. A copy of the
model structure nlgr and an IDDATA object z1 reflecting this particular modeling situation is first created.
The 5 input signals are stored in u1 and the 3 output signals in y1. The slip inputs (generated from the
wheel speed signals) for the front wheels were chosen to be sinusoidal with a constant offset; the yaw
rate was also sinusoidal but with a different amplitude and frequency. In reality, this is a somewhat
artificial situation, because one rarely excites the vehicle so much in the lateral direction.
nlgr1 = nlgr;
nlgr1.Name = 'Bicycle vehicle model with high tire stiffness';
z1 = iddata(y1, u1, 0.1, 'Name', 'Simulated high tire stiffness vehicle data');
z1.InputName = nlgr1.InputName;
z1.InputUnit = nlgr1.InputUnit;
z1.OutputName = nlgr1.OutputName;
z1.OutputUnit = nlgr1.OutputUnit;
z1.Tstart = 0;
z1.TimeUnit = 's';
The inputs and outputs are shown in two plot figures.
h_gcf = gcf;
set(h_gcf,'DefaultLegendLocation','southeast');
h_gcf.Position = [100 100 795 634];
for i = 1:z1.Nu
subplot(z1.Nu, 1, i);
plot(z1.SamplingInstants, z1.InputData(:,i));
title(['Input #' num2str(i) ': ' z1.InputName{i}]);
xlabel('');
axis tight;
end
xlabel([z1.Domain ' (' z1.TimeUnit ')']);
Figure 2: Inputs to a vehicle system with high tire stiffness.
for i = 1:z1.Ny
subplot(z1.Ny, 1, i);
plot(z1.SamplingInstants, z1.OutputData(:,i));
title(['Output #' num2str(i) ': ' z1.OutputName{i}]);
xlabel('');
axis tight;
end
xlabel([z1.Domain ' (' z1.TimeUnit ')']);

Figure 3: Outputs from a vehicle system with high tire stiffness.


The next step is to investigate the performance of the initial model and for this we perform a simulation.
Notice that the initial state has been fixed to a non-zero value as the first state (the longitudinal vehicle
velocity) is used as denominator in the model structure. A comparison between the true and the simulated
outputs (with the initial model) is shown in a plot window.
clf
compare(z1, nlgr1, [], compareOptions('InitialCondition', 'model'));

Figure 4: Comparison between true outputs and the simulated outputs of the initial vehicle model with
high tire stiffness.
In order to improve the model fit, the two tire stiffness parameters Cx and Cy are next estimated, and a
new simulation with the estimated model is carried out.
nlgr1 = nlgreyest(z1, nlgr1);
A comparison between the true and the simulated outputs (with the estimated model) is shown in a plot
window.
compare(z1, nlgr1, [], compareOptions('InitialCondition', 'model'));

Figure 5: Comparison between true outputs and the simulated outputs of the estimated vehicle model
with high tire stiffness.
The simulation performance of the estimated model is quite good. The estimated stiffness parameters are
also close to the ones used in Simulink® to generate the true output data:
disp(' True Estimated');
fprintf('Longitudinal stiffness: %6.0f %6.0f\n', 2e5, nlgr1.Parameters(4).Value);
fprintf('Lateral stiffness : %6.0f %6.0f\n', 5e4, nlgr1.Parameters(5).Value);
True Estimated
Longitudinal stiffness: 200000 198517
Lateral stiffness : 50000 53752
B. System Identification Using Simulated Low Tire Stiffness Data
In the second experiment we repeat the modeling from the first experiment, but now with simulated low
tire stiffness data.
nlgr2 = nlgr;
nlgr2.Name = 'Bicycle vehicle model with low tire stiffness';
z2 = iddata(y2, u2, 0.1, 'Name', 'Simulated low tire stiffness vehicle data');
z2.InputName = nlgr2.InputName;
z2.InputUnit = nlgr2.InputUnit;
z2.OutputName = nlgr2.OutputName;
z2.OutputUnit = nlgr2.OutputUnit;
z2.Tstart = 0;
z2.TimeUnit = 's';
The inputs and outputs are shown in two plot figures.
clf
for i = 1:z2.Nu
subplot(z2.Nu, 1, i);
plot(z2.SamplingInstants, z2.InputData(:,i));
title(['Input #' num2str(i) ': ' z2.InputName{i}]);
xlabel('');
axis tight;
end
xlabel([z2.Domain ' (' z2.TimeUnit ')']);
Figure 6: Inputs to a vehicle system with low tire stiffness.
clf
for i = 1:z2.Ny
subplot(z2.Ny, 1, i);
plot(z2.SamplingInstants, z2.OutputData(:,i));
title(['Output #' num2str(i) ': ' z2.OutputName{i}]);
xlabel('');
axis tight;
end
xlabel([z2.Domain ' (' z2.TimeUnit ')']);
Figure 7: Outputs from a vehicle system with low tire stiffness.

Next we investigate the performance of the initial model (which has the same parameters as the initial
high tire stiffness model). A comparison between the true and the simulated outputs (with the initial
model) is shown in a plot window.
clf
compare(z2, nlgr2, [], compareOptions('InitialCondition', 'model'));

Figure 8: Comparison between true outputs and the simulated outputs of the initial vehicle model with
low tire stiffness.
The two stiffness parameters are next estimated.
nlgr2 = nlgreyest(z2, nlgr2);
A comparison between the true and the simulated outputs (with the estimated model) is shown in a plot
window.
compare(z2, nlgr2, [], compareOptions('InitialCondition', 'model'));
Figure 9: Comparison betweentrue outputs and the simulated outputs of the estimated vehicle model
with low tire stiffness.
The simulation performance of the estimated model is again really good. Even with the same parameter
starting point as was used in the high tire stiffness case, the estimated stiffness parameters are also here
close to the ones used in Simulink to generate the true output data:
disp(' True Estimated');
fprintf('Longitudinal stiffness: %6.0f %6.0f\n', 1e5, nlgr2.Parameters(4).Value);
fprintf('Lateral stiffness : %6.0f %6.0f\n', 2.5e4,
nlgr2.Parameters(5).Value);
True Estimated
Longitudinal stiffness: 100000 99573
Lateral stiffness : 25000 26117
C. System Identification Using Measured Volvo V70 Data
In the final experiment we consider data collected in a Volvo V70. As above, we make a copy of the
generic vehicle model object nlgr and create a new IDDATA object containing the measured data. Here
we have also increased the air resistance coefficient from 0.50 to 0.70 to better reflect the Volvo V70
situation.
nlgr3 = nlgr;
nlgr3.Name = 'Volvo V70 vehicle model';
nlgr3.Parameters(6).Value = 0.70; % Use another initial CA for the Volvo data.
z3 = iddata(y3, u3, 0.1, 'Name', 'Volvo V70 data');
z3.InputName = nlgr3.InputName;
z3.InputUnit = nlgr3.InputUnit;
z3.OutputName = nlgr3.OutputName;
z3.OutputUnit = nlgr3.OutputUnit;
z3.Tstart = 0;
z3.TimeUnit = 's';
The inputs and outputs are shown in two plot figures. As can be seen, the measured data is rather noisy.
clf
for i = 1:z3.Nu
subplot(z3.Nu, 1, i);
plot(z3.SamplingInstants, z3.InputData(:,i));
title(['Input #' num2str(i) ': ' z3.InputName{i}]);
xlabel('');
axis tight;
end
xlabel([z3.Domain ' (' z3.TimeUnit ')']);
Figure 10: Measured inputs from a Volvo V70 vehicle.
clf
for i = 1:z3.Ny
subplot(z3.Ny, 1, i);
plot(z3.SamplingInstants, z3.OutputData(:,i));
title(['Output #' num2str(i) ': ' z3.OutputName{i}]);
xlabel('');
axis tight;
end
xlabel([z3.Domain ' (' z3.TimeUnit ')']);
Figure 11: Measured outputs from a Volvo V70 vehicle.

Next we investigate the performance of the initial model with the initial states being estimated. A
comparison between the true and the simulated outputs (with the initial model) is shown in a plot window.
nlgr3 = setinit(nlgr3, 'Value', {18.7; 0; 0}); % Initial initial states.
clf
compare(z3, nlgr3);
Figure 12: Comparison between measured outputs and the simulated outputs of the initial Volvo V70
vehicle model.

The tire stiffness parameters Cx and Cy are next estimated, in this case using the Levenberg-Marquardt
search method, whereupon a new simulation with the estimated model is performed. In addition, we here
estimate the initial value of the longitudinal velocity, whereas the initial values of the lateral velocity and
the yaw rate are kept fixed.
nlgr3 = setinit(nlgr3, 'Fixed', {false; true; true});
nlgr3 = nlgreyest(z3, nlgr3, nlgreyestOptions('SearchMethod', 'lm'));
A comparison between the true and the simulated outputs (with the estimated model) is shown in a plot
window.
compare(z3, nlgr3);
Figure 13: Comparison between measured outputs and the simulated outputs of the first estimated Volvo
V70 vehicle model.

The estimated stiffness parameters of the final Volvo V70 model are reasonable, yet it is here unknown
what their real values are.
disp(' Estimated');
fprintf('Longitudinal stiffness: %6.0f\n', nlgr3.Parameters(4).Value);
fprintf('Lateral stiffness : %6.0f\n', nlgr3.Parameters(5).Value);
Estimated
Longitudinal stiffness: 108873
Lateral stiffness : 29964
Further information about the estimated Volvo V70 vehicle model is obtained through PRESENT. It is
here interesting to note that the uncertainty related to the estimated lateral tire stiffness is quite high (and
significantly higher than for the longitudinal tire stiffness). This uncertainty originates partly from that the
lateral acceleration is varied so little during the test drive.
present(nlgr3);

nlgr3 =
Continuous-time nonlinear grey-box model defined by 'vehicle_c' (MEX-file):

dx/dt = F(t, u(t), x(t), p1, ..., p6)


y(t) = H(t, u(t), x(t), p1, ..., p6) + e(t)

with 5 inputs, 3 states, 3 outputs, and 2 free parameters (out of 6).

Inputs:
u(1) Slip on front left tire(t) [ratio]
u(2) Slip on front right tire(t) [ratio]
u(3) Slip on rear left tire(t) [ratio]
u(4) Slip on rear right tire(t) [ratio]
u(5) Steering angle(t) [rad]
States: initial value
x(1) Longitudinal vehicle velocity(t) [m/s] xinit@exp1 17.6049 (est) in
]0, Inf]
x(2) Lateral vehicle velocity(t) [m/s] xinit@exp1 0 (fix) in [-
Inf, Inf]
x(3) Yaw rate(t) [rad/s] xinit@exp1 0 (fix) in [-
Inf, Inf]
Outputs:
y(1) Long. velocity(t) [m/s]
y(2) Lat. accel.(t) [m/s^2]
y(3) Yaw rate(t) [rad/s]
Parameters: value standard dev
p1 Vehicle mass [kg] 1700 0 (fix) in ]0, Inf]
p2 Distance from front axle to COG [m] 1.5 0 (fix) in ]0, Inf]
p3 Distance from rear axle to COG [m] 1.5 0 (fix) in ]0, Inf]
p4 Longitudinal tire stiffness [N] 108873 26.8501 (est) in ]0, Inf]
p5 Lateral tire stiffness [N/rad] 29963.5 217.877 (est) in ]0, Inf]
p6 Air resistance coefficient [1/m] 0.7 0 (fix) in ]0, Inf]

Name: Volvo V70 vehicle model

Status:
Termination condition: Maximum number of iterations reached.
Number of iterations: 20, Number of function evaluations: 41

Estimated using Solver: ode45; Search: lm on time domain data "Volvo V70 data".
Fit to estimation data: [-374.2;29.74;34.46]%
FPE: 2.362e-07, MSE: 0.3106
More information in model's "Report" property.
Concluding Remarks
Estimating the tire stiffness parameters is in practice a rather intricate problem. First, the approximations
introduced in the model structure above are valid for a rather narrow operation region, and data during
high accelerations, braking, etc., cannot be used. The stiffness also varies with the environmental
condition, e.g., the surrounding temperature, the temperature in the tires and the road surface conditions,
which are not accounted for in the used model structure. Secondly, the estimation of the stiffness
parameters relies heavily on the driving style. When mostly going straight ahead as in the third
identification experiment, it becomes hard to estimate the stiffness parameters (especially the lateral
one), or put another way, the parameter uncertainties become rather high.

Additional Information
For more information on identification of dynamic systems with System Identification Toolbox™ visit
the System Identification Toolbox product information page.
Power-Assisted Steering Mechanism
Open Model
This example shows a simplified version of a power-assisted steering mechanism. The hydraulic
actuation system includes a double-acting hydraulic cylinder, 4-way valve, fixed-displacement pump,
and a pressure-relief valve. The steering rack acts against a load modeled by a spring and damper.

The valve opens based on the amount of twist of a torsion bar installed between the steering wheel and
the pinion of a rack-and-pinion mechanism. The rotation of the steering wheel causes the torsion bar to
twist relative to the pinion. The deformation of the bar is transformed into opening of the 4-way valve,
which connects the chambers of the cylinder to pressure or return lines depending upon the direction of
rotation. The PS Gain block Valve Opening converts torsion bar twist to the amount of opening for the 4-
way valve. Setting the Gain parameter of this block to 0 disables the power steering.

If the torsion bar deformation exceeds 9 degrees the wheel is connected directly to the pinion through the
hard stops installed in parallel with the torsion bar. The cylinder moves thesteering rack which twists the
torsion rod in the opposite direction until the valve is in the neutral position.

Model

4 Way Valve Subsystem


Simulation Results from Simscape Logging
The plots below show the amount of assistance the power steering system provides to the driver as the
wheel is turned. The greater the difference in the cylinder chamber presssures, the more assistance that
is provided.

The plots below compare the amount of effort required when the power steering is turned on and turned
off. For the same steering sequence, the amount of torqure required when the power steering is turned off
is much higher. The power steering is turned off by setting the gain in Valve Opening to 0.
Electric Power Assisted Steering
This example also uses:

 Stateflow
Open Model
This example shows how to use a Permanent Magnet Synchronous Motor (PMSM) to amplify driver-
applied force in a power-assisted automobile steering system.

The steering wheel angular velocity represents the input from the driver. The inputs to the PMSM
controller are the angular difference from one end of the steering column to the other and the velocity and
angular displacement of the steering load.

The PMSM Inverter is idealized. You can see voltage and current waveforms on the Inverter Voltages &
Currents Scope. You can see torque waveforms on the Mechanical Torque Scope.

Within the PMSM Driver, the PMSM Controller is a Model Reference block. If you have a Simulink®
Coder™ or Embedded Coder® license, you can generate code directly from the PMSM Controller
referenced model.
Vehicle with Four-Speed Transmission

Open Model
This example shows a complete vehicle with Simscape™ Driveline™
components, including the engine, drivetrain, four-speed transmission, tires, and
longitudinal vehicle dynamics. The transmission controller is implemented as a
state machine in Stateflow, selecting the gear based on throttle and vehicle
speed.
Model

Transmission Subsystem
Clutch Schedule Subsystem

Shift Logic Subsystem


Vehicle Body Subsystem

Simulation Results from Simscape Logging


The plot below shows the input and output shaft speeds of the transmission as
well as the vehicle speed. The clutch states are also plotted (locked or open),
indicating the selected gear of the transmission.
Vehicle with Manual Transmission
Open Model
This example shows a vehicle that has a four-speed manual transmission. The key elements of the
transmission are four synchronizers. By engaging or disengaging these synchronizers and associated
dog clutches, the transmission provides four ratios 3.581, 2.022, 1.384, and 1, respectively. The
synchronizers are modeled using the Cone Clutch and Dog Clutch blocks.

The model also provides an abstracted representation of the gearbox that is significantly less complex
and thus simulates much faster. It uses simply a variable ratio gear to represent the various gear ratios in
the detailed transmission, plus a clutch to represent neutral. By eliminating nearly all of the
discontinuities, it is designed for hardware-in-the-loop simulation. To select this variant, use the hyperlinks
in the model.

Model
Clutch Pedal Linkage Subsystem

Abstract Transmission Variant


This is the simplified version of the transmission. Using a variable ratio gear that accepts the gear ratio as
an input signal, we remove nearly all of the discontinuities. When properly tuned, it can match the results
of the detailed variant.

Detailed Transmission Variant


This is the detailed version of the transmission. It contains all the gears plus the dog clutches and cone
clutches. This variant provides very accurate results and is perfect for tuning control algorithms and
estimating fuel economy.
Synchronizer 1 Subsystem
This subsystem implements a customized model of a synchronizer. Here, the structure of the
synchronizer can be seen and modified. Simscape Driveline also provides pre-built single and double-
synchronizer blocks.

Vehicle Body Subsystem


This subsystem implements the longitudinal vehicle dynamics and the tire model. It is sufficient for
running drive cycles to estimate fuel economy and to tune transmission control algorithms.

Simulation Results from Simscape Logging


The plots below show the driver inputs to the engine and transmission. The top plot shows the forces
applied to the synchronizers to select the active gear, and the bottom plot shows the inputs to the throttle
and clutch.
The plot below show the speeds of various shafts in the drivetrain. The output shaft speed is equal to the
speed of the gear whose synchronizer is engaged. The engine stays in appropriate speed speed range
even though the vehicle is accelerating because of the chosen gear.
The plot below show the behavior of the abstract models and the detailed model. The results are very
similar, indicating that the abstract models can be used without a significant loss of accuracy.
Vehicle with Four-Wheel Drive
Open Model
This model shows a four-wheel drive vehicle starting from rest and ascending a 15 degree incline. Initially
the vehicle rolls backwards until the engine develops sufficient torque to counter the slope. The tire
compliance dynamics can be seen as the vehicle starts to accelerate. The model variant chosen for all of
the tires can be set to the Simple, Friction Parameterized, or Magic Formula tire model using the
hyperlinks in the model.

Model

Simulation Results from Simscape Logging


The plots below show the engine and vehicle speed. As the vehicle is starting at rest on an incline, it rolls
backwards until the torque of the engine is enough to push the vehicle up the hill.

You might also like