Using Simulink in Engine Model PDF
Using Simulink in Engine Model PDF
Using Simulink in Engine Model PDF
in Automotive Applications
Abstract This book includes nine examples that represent typical design tasks of an automotive engineer. It
shows how The MathWorks modeling and simulation tools, Simulink® and Stateflow, facilitate
TM
the design of automotive control systems. Each example explains the principles of the physical sit-
uation, and presents the equations that represent the system. The examples show how to proceed
from the physical equations to the Simulink block diagram. Once the Simulink model has been
completed, we run the simulation, analyze the results, and draw conclusions from the study.
TABLE OF C ONTENTS
Introduction ....................................................................................................................... 4
Summary Automotive engineers have found simulation to be a vital tool in the timely and cost-effective
development of advanced control systems. As a design tool, Simulink has become the standard for
excellence through its flexible and accurate modeling and simulation capabilities. As a result of its open
architecture, Simulink allows engineers to create custom block libraries so they can leverage each other’s
work. By sharing a common set of tools and libraries, engineers can work together effectively within
individual work groups and throughout the entire engineering department.
In addition to the efficiencies achieved by Simulink, the design process can also benefit from Stateflow, an
interactive design tool that enables the modeling and simulation of complex reactive systems. Tightly
integrated with Simulink, Stateflow allows engineers to design embedded control systems by giving them
an efficient graphical technique to incorporate complex control and supervisory logic within their
Simulink models.
This booklet describes nine automotive design examples that illustrate the strengths of Simulink and
Stateflow in accelerating and facilitating the design process.
Examples The examples cited in this booklet consist of application design tasks typically encountered in
Description the automotive industry. We present a variety of detailed models including the underlying
equations, block diagrams, and simulation results. The material may serve as a starting point for the
new Simulink user or as a reference for the more experienced user. In the models, we propose approaches
for model development, present solutions to challenging problems, and illustrate some of the most
common design uses of Simulink and Stateflow today.
The applications and models described in this booklet include the following examples using Simulink
alone:
I. Engine Model
engine.mdl — open-loop simulation
enginewc.mdl — closed-loop simulation
II. Anti-Lock Braking System
absbrake.mdl
III. Clutch Engagement Model
clutch.mdl
IV. Suspension System
suspn.mdl
V. Hydraulic Systems
hydcyl.mdl — Pump and actuator assembly
Simulink The models used in this book are available via ftp at
Model Files ftp://ftp.mathworks.com/pub/product-info/examples/autobook.zip. This zip file contains the set
of MDL, MAT, and M-files containing Simulink models that users can explore and build upon. The
included files require MATLAB® 5.1, Simulink 2.1, and Stateflow 1.0. Models for these applications can be
opened in Simulink by typing the name of the model at the MATLAB command prompt. MATLAB,
Simulink, and Stateflow are not included with this booklet. To obtain a copy of MATLAB, Simulink, and
Stateflow, or for a diskette containing the model files, please contact your representative at The
MathWorks.
Acknowledgments The engine model is based on published findings by Crossley and Cook (1991)(1). We’d like to thank
Ken Butts and Jeff Cook of the Ford Motor Company for permission to include this model and for
subsequent help in building the model in Simulink.
The clutch and hydraulic cylinder models are based on equations provided by General Motors. We’d like
to thank Eric Gassenfeit of General Motors for permission to include these models.
The vehicle suspension model was written by David MacClay of Cambridge Control Ltd.
The simple three-state engine model and the set of icons that are relevant for automotive modeling were
provided by Modular Systems. A far more detailed engine model may be purchased directly from Modular
Systems.
Contact The MathWorks technical personnel specializing in automotive solutions can be reached via e-mail
Information at the following addresses:
Stan Quinn squinn@mathworks.com
Both Modular Systems and Cambridge Control Ltd. offer consulting services in automotive modeling.
They can be reached as follows:
Summary This example presents a model of a four-cylinder spark ignition engine and demonstrates Simulink’s
capabilities to model an internal combustion engine from the throttle to the crankshaft output. We used
well-defined physical principles supplemented, where appropriate, with empirical relationships that
describe the system’s dynamic behavior without introducing unnecessary complexity.
Overview This example describes the concepts and details surrounding the creation of engine models with emphasis
on important Simulink modeling techniques. The basic model uses the enhanced capabilities of
Simulink 2 to capture time-based events with high fidelity. Within this simulation, a triggered
subsystem models the transfer of the air-fuel mixture from the intake manifold to the cylinders via
discrete valve events. This takes place concurrently with the continuous-time processes of intake flow,
torque generation and acceleration. A second model adds an additional triggered subsystem that provides
closed-loop engine speed control via a throttle actuator.
These models can be used as standalone engine simulations. Or, they can be used within a larger system
model, such as an integrated vehicle and powertrain simulation, in the development of a traction control
system.
Model Description
This model, based on published results by Crossley and Cook (1991), describes the simulation of a four-
cylinder spark ignition internal combustion engine. The Crossley and Cook work also shows how a
simulation based on this model was validated against dynamometer test data.
The ensuing sections (listed below) analyze the key elements of the engine model that were identified by
Crossley and Cook:
• Throttle
• Intake manifold
• Mass flow rate
• Compression stroke
• Torque generation and acceleration
Note: Additional components can be added to the model to provide greater accuracy in simulation and to
more closely replicate the behavior of the system.
Analysis THROTTLE
and Physics The first element of the simulation is the throttle body. Here, the control input is the angle of the throttle
plate. The rate at which the model introduces air into the intake manifold can be expressed as the product
of two functions—one, an empirical function of the throttle plate angle only; and the other, a function of
the atmospheric and manifold pressures. In cases of lower manifold pressure (greater vacuum), the flow
rate through the throttle body is sonic and is only a function of the throttle angle. This model accounts for
m˙ ai = f (θ )g (Pm )
= mass flow rate into manifold (g/s) where,
f (θ ) = 2.821 − 0.05231θ + 0.10299θ 2 − 0.00063θ 3
θ = throttle angle (deg) Equation 1.1
P
1, Pm ≤ amb
2
2 2 P
Pm Pamb − Pm , amb
≤ Pm ≤ Pamb
g (Pm ) = Pamb 2
2 2
− Pm Pamb − Pamb , Pamb ≤ Pm ≤ 2Pamb
m P
−1, Pm ≥ 2Pamb
Pm = manifold pressure (bar)
Pamb = ambient (atmospheric) pressure (bar)
Intake Manifold
The simulation models the intake manifold as a differential equation for the manifold pressure. The
difference in the incoming and outgoing mass flow rates represents the net rate of change of air mass with
respect to time. This quantity, according to the ideal gas law, is proportional to the time derivative of the
manifold pressure. Note that, unlike the model of Crossley and Cook, 1991(1) (see also references 3
through 5), this model doesn’t incorporate exhaust gas recirculation (EGR), although this can easily be
added.
(m˙ ai − m˙ ao )
RT
P˙ m = Equation 1.2
Vm
where,
2
m˙ ao = −0.366 + 0.08979 NPm − 0.0337NPm + 0.0001N 2P m Equation 1.3
To determine the total air charge pumped into the cylinders, the simulation integrates the mass flow rate
from the intake manifold and samples it at the end of each intake stroke event. This determines the total
air mass that is present in each cylinder after the intake stroke and before compression.
Compression Stroke
In an inline four-cylinder four-stroke engine, 180° of crankshaft revolution separate the ignition of each
successive cylinder. This results in each cylinder firing on every other crank revolution. In this model,
the intake, compression, combustion, and exhaust strokes occur simultaneously (at any given time, one
cylinder is in each phase). To account for compression, the combustion of each intake charge is delayed
by 180° of crank rotation from the end of the intake stroke.
The engine torque less the net load torque results in acceleration.
where,
Figure 1.1 shows the top level of the Simulink model. Note that, in general, the major blocks correspond
to the high-level list of functions given in the model description in the preceding summary. Taking
advantage of Simulink’s hierarchical modeling capabilities, most of the blocks in Figure 1.1 are made up
of smaller blocks. The following paragraphs describe these smaller blocks.
edge180 N 1
crank speed
valve timing (rad/sec)
Torque Teng
mass(k+1)
Throttle Ang. 30/pi
N N
trigger
throttle Mass Airflow Rate
(degrees) Tload
1 rad/s Engine
Engine Speed, N Combustion to
Compression Speed
s rpm
Vehicle (rpm)
Throttle & Manifold Dynamics
Load
Intake
Drag Torque throttle deg (purple)
load torque Nm (yellow)
Mux
Throttle/Manifold
Simulink models for the throttle and intake manifold subsystems are shown in Figure 1.2. The throttle
valve behaves in a nonlinear manner and is modeled as a subsystem with three inputs. Simulink
implements the individual equations, given in Equation 1.1 as function blocks. These provide a
convenient way to describe a nonlinear equation of several variables. A Switch block determines whether
the flow is sonic by comparing the pressure ratio to its switch threshold, which is set at one half (Equation
1.1). In the sonic regime, the flow rate is a function of the throttle position only. The direction of flow is
from the higher to lower pressure, as determined by the Sign block. With this in mind, the Min block
ensures that the pressure ratio is always unity or less.
Atmospheric Throttle
Pressure, Pa
(bar)
Engine Speed, N
Intake Manifold
Throttle Angle,
theta (deg) f(theta)
1 2.821 - 0.05231*u + 0.10299*u*u - 0.00063*u*u*u
2
Manifold Pressure, g(pratio)
Pm (bar)
min pratio 2*sqrt(u - u*u)
1
3
1.0 Throttle
Atmospheric Pressure, Flow, mdot
Pa (bar) Sonic Flow (g/s)
flow direction
Consider a complete four-stroke cycle for one cylinder. During the intake stroke, the Intake block
integrates the mass flow rate from the manifold. After 180° of crank rotation, the intake valve closes and
the Unit Delay block in the Compression subsystem samples the integrator state. This value, the
accumulated mass charge, is available at the output of the Compression subsystem 180° later for use in
combustion. During the combustion stroke, the crank accelerates due to the generated torque. The final
180°, the exhaust stroke, ends with a reset of the Intake integrator, prepared for the next complete 720°
cycle of this particular cylinder.
For four cylinders, we could use four Intake blocks, four Compression subsystems, etc., but each would be
idle 75% of the time. We’ve made the implementation more efficient by performing the tasks of all four
cylinders with one set of blocks. This is possible because, at the level of detail we’ve modeled, each function
applies to only one cylinder at a time.
Combustion
Engine torque is a function of four variables. The model uses a Mux block to combine these variables into
a vector that provides input to the Torque Gen block. Here, a function block computes the engine torque,
as described empirically in Equation 1.4. The torque which loads the engine, computed by step functions
in the Drag Torque block, is subtracted in the Vehicle Dynamics subsystem. The difference divided by the
inertia yields the acceleration, which is integrated to arrive at the engine crankshaft speed.
Results We saved the Simulink model in the file engine.mdl which can be opened by typing engine at the
MATLAB prompt. Select Start from the Simulation menu to begin the simulation. Simulink scope
windows show the engine speed, the throttle commands which drive the simulation, and the load torque
which disturbs it. Try adjusting the throttle to compensate for the load torque.
Figure 1.3 shows the simulated engine speed for the default inputs:
8.97, t < 5
Throttle(deg) =
11.93, t ≥ 5
Engine Simulation
3500
3000
2500
engine speed (RPM)
2000
1500
1000
500
0
0 1 2 3 4 5 6 7 8 9 10
time (sec)
Note the behavior as the throttle angle and load torque change.
The Closed-Loop The following enhanced model demonstrates the flexibility and extensibility of Simulink models. In the
Simulation enhanced model, the objective of the controller is to regulate engine speed with a fast throttle actuator,
such that changes in load torque have minimal effect. This is easily accomplished in Simulink by adding
a discrete-time PI controller to the engine model as shown in Figure 1.4.
The model is stored in the file enginewc.mdl, which can be opened by typing enginewc at the MATLAB
command prompt. This represents the same engine model described previously but with closed-loop
control.
edge180 N 1
crank speed
valve timing (rad/sec)
Mux
We chose a control law which uses proportional plus integral (PI) control. The integrator is needed to
adjust the steady-state throttle as the operating point changes, and the proportional term compensates for
phase lag introduced by the integrator.
∫
θ = K p ( N set − N ) + K I ( N set − N ) dt ,
N set = speed set point Equation 1.6
K p = proportional gain
K I = integral gain
A discrete-time controller, suitable for microprocessor implementation, is employed. The integral term in
Equation 1.6 must thus be realized with a discrete-time approximation.
As is typical in the industry, the controller execution is synchronized with the engine’s crankshaft
rotation. The controller is embedded in a triggered subsystem that is triggered by the valve timing signal
described above. The detailed construction of the Controller subsystem is illustrated in Figure 1.5. Of note
is the use of the Discrete-Time Integrator block with its sample time parameter set (internally) at -1. This
indicates that the block should inherit its sample time, in this case executing each time the subsystem is
triggered. The key component that makes this a triggered subsystem is the Trigger block shown at the
bottom of Figure 1.5. Any subsystem can be converted to a triggered subsystem by dragging a copy of this
block into the subsystem diagram from the Simulink Connections library.
1 pi/30
Desired Kp
rpm rpm
to Proportional Gain 1
rad/s Ki T Throttle Setting
limit
z -1 output
Integral Gain
2 N
Discrete Time
0 Integrator
integrator input
enable integration
controller output
prevent windup
Results Typical simulation results are shown in Figure 1.6. The speed set point steps from 2000 to 3000 RPM
at t = 5 sec. The torque disturbances are identical to those used in the previous example. Note the quick
transient response, with zero steady-state error.
Several alternative controller tunings are shown. These can be adjusted by the user at the MATLAB
command line. This allows the engineer to understand the relative effects of parameter variations.
3000
Kp = 0.05, Ki = 0.1
Kp = 0.033, Ki = 0.064
Kp = 0.061, Ki = 0.072
2800
engine speed (RPM)
2600
2400
2200
2000
1800
0 1 2 3 4 5 6 7 8 9 10
time (Sec.)
References
1. P.R. Crossley and J.A. Cook, IEE International Conference ‘Control 91’, Conference Publication 332,
vol. 2, pp. 921-925, 25-28 March, 1991, Edinburgh, U.K.
2. The Simulink Model. Developed by Ken Butts, Ford Motor Company. Modified by Paul Barnard, Ted
Liefeld and Stan Quinn, The MathWorks, Inc., 1994-7.
3. J. J. Moskwa and J. K. Hedrick, "Automotive Engine Modeling for Real Time Control Application,"
Proc.1987 ACC, pp. 341-346.
4. B. K. Powell and J. A. Cook, "Nonlinear Low Frequency Phenomenological Engine Modeling and
Analysis," Proc. 1987 ACC, pp. 332-340.
5. R. W. Weeks and J. J. Moskwa, "Automotive Engine Modeling for Real-Time Control Using
Matlab/Simulink," 1995 SAE Intl. Cong. paper 950417.
The spring/damper subsystem that models the front and rear suspensions is shown in Figure 4.3. The
block is used to model Equation 4.1 through 4.3. The equations are implemented directly in the Simulink
diagram through the straightforward use of Gain and Summation blocks. The differences between front
and rear are accounted for as follows. Because the subsystem is a masked block, a different data set (L, K
and C) can be entered for each instance. Furthermore, L is thought of as the Cartesian coordinate x, being
negative or positive with respect to the origin, or center of gravity. Thus, Kf , Cf and -Lf are used for the
front and Kr, Cr and Lr for the rear.
L 1
L
2*K pitch
MomentArm3 Torque
MomentArm1
stiffness
2
L
Vertical
Force
MomentArm2 2*C
1 em
THETA
THETAdot damping
Z Fz
Zdot
Results To run this model, first set up the required parameters in the MATLAB workspace. Run the following
M-file by typing suspdat, or from the MATLAB command line, enter the data by typing:
To run the simulation, select Start from the Simulink Simulation menu or type the following at the
MATLAB command line:
THETAdot
dθ/dt
0
-5
0.1
dz/dt
Zdot
-0.1
7000
Ff
6000 -3
x 10
15
10
5 road height
h
0
-5
100
moment due to vehicle accel/decel
50
Y
0
0 1 2 3 4 5 6 7 8 9 10
time in seconds
Conclusions The Vehicle Suspension model allows you to simulate the effects of changing the suspension damping
and stiffness, thereby investigating the tradeoff between comfort and performance. In general, a racing
car has very stiff springs with a high damping factor, whereas a passenger vehicle designed for comfort
has softer springs and a more oscillatory response.
Summary This example considers several hydraulic systems. The general concepts apply to suspension, brake,
steering, and transmission systems. We model three variations of systems employing pumps, valves, and
cylinder/piston actuators. The first features a single hydraulic cylinder which we develop, simulate and
save as a library block. In the next model, we use four instances of this block, as in an active suspension
system. In the final model, we model the interconnection of two hydraulic actuators, held together by a
rigid rod which supports a large mass.
In some cases we treat relatively small volumes of fluid as incompressible. This results in a system of
differential-algebraic equations (DAEs). Simulink solvers are well-suited to handle this type of problem
efficiently. The masking and library reference capabilities add extra power and flexibility. The creation of
custom blocks enables the implementation of important subsystems with user-defined parameter sets.
The Simulink library keeps a master version of these blocks so that models using a master block
automatically incorporate any revisions and refinements made to it.
Analysis and Figure 5.1 shows a schematic diagram of the basic model. The model directs the pump flow Q to
Physics supply pressure p1 from which laminar flow q1ex leaks to exhaust. The control valve for the
piston/cylinder assembly is modeled as turbulent flow through a variable-area orifice. Its flow q12 leads to
intermediate pressure p2 which undergoes a subsequent pressure drop in the line connecting it to the
actuator cylinder. The cylinder pressure p3 moves the piston against a spring load, resulting in position x.
control valve
Q p1 p2
q23
q1ex A q12 C1
p3
pump
v3
C2
cylinder x
At the pump output, the flow is split between leakage and flow to the control valve. The leakage, q1ex is
modeled as laminar flow.
We modeled turbulent flow through the control valve with the orifice equation. The sign and absolute
value functions accommodate flow in either direction.
2
q12 = C d A sgn( p1 − p 2 ) p1 − p 2
ρ
C d = orifice discharge coefficient
A = orifice area Equation 5.2
p 2 = pressure downstream of control valve
ρ = fluid density
The fluid within the cylinder pressurizes due to this flow, q12 = q23, less the compliance of the piston
motion. We also modeled fluid compressibility in this case.
β
p˙ 3 =
v3
(q 12 − xA
˙ c )
p 3 = piston pressure
β = fluid bulk modulus
v 3 = fluid volume at p 3 Equation 5.3
=V 30 + Ac x
Ac = cylinder
cylinder cross–sectional
cross – sectional area
area
V 30 = fluid volume at x = 0
We neglected the piston and spring masses due to the large hydraulic forces. Force balance at the piston
gives:
x = p3 Ac / K
Equation 5.4
K = spring rate
x˙ = p˙ 3 A c /K
q23 = q12
= C 1( p 2 − p 3 ) Equation 5.5
p 2 = p 3 + q12 /C 1
C 1 = laminar flow coefficient
Modeling Figure 5.2 shows the basic model, stored in the file hydcyl.mdl. Simulation inputs are the pump
flow and the control valve orifice area. The model is organized as two subsystems — the pump and the
actuator assembly.
Mux
Qout p1 p
p1 pressures
p1 (yellow)
x
p2 (purple)
A p3 (blue)
pump qin piston position
valve/cylinder/piston/spring assembly
control valve
orifice area
Pump
The pump model computes the supply pressure as a function of the pump flow and the load (output) flow
(Figure 5.3). A From Workspace block provides the pump flow data, Qpump. This is specified by a matrix
with column vectors of time points and the corresponding flow rates [T, Q]. The model subtracts the
output flow, using the difference, the leakage flow, to determine the pressure p1, as indicated above in
Equation 5.1. Since Qout = q12 is a direct function of p1 (via the control valve), this forms an algebraic
loop. An estimate of the initial value, p10, enables a more efficient solution.
We mask the subsystem in Simulink to facilitate ready access to the parameters by the user. The
parameters to be specified are T, Q, p10 and the leakage flow coefficient, C2. For easy identification, we then
assigned the masked block the icon shown in Figure 5.2, and saved it in the Simulink library hydlib.mdl.
Actuator Assembly
valve/cylinder/piston/spring assembly
p2, p3
1/C1
p2
xdotAc laminar flow
Ac^2/K pressure drop Mux 1
p
p2
A beta
2 Area q12
1 p3 Ac/K 2
1 p1 s
V30 x
p1 control valve piston
force/spring
flow pressure
cylinder
volume
3
Ac
qin
In Figure 5.4, a system of differential-algebraic equations models the cylinder pressurization with the
pressure p3, which appears as a derivative in Equation 5.3 and is used as the state (integrator). If we
neglect mass, the spring force and piston position are direct multiples of p3 and the velocity is a direct
multiple of ṗ 3 . This latter relationship forms an algebraic loop around the bulk modulus Gain block,
Beta . The intermediate pressure p2 is the sum of p3 and the pressure drop due to the flow from the valve to
the cylinder (Equation 5.5). This relationship also imposes an algebraic constraint through the control
valve and the 1/C1 gain.
The control valve subsystem computes the orifice (equation 5.2), with the upstream and downstream
pressures as inputs, as well as the variable orifice area. A lower level subsystem computes the “signed
square root,” y = sgn(u) u . Three nonlinear functions are used, two of which are discontinuous. In
Cd = 0.61
ρ = 800 kg/m3
C 1 = 2e- 8 m3 /sec/Pa
C 2 = 3e- 9 m3 /sec/Pa
β = 7e8 Pa
Ac = 0.001 m3
K = 5e4 N/m
V30 = 2.5e- 5 m3
sec. m3/sec
0 0.005
0.04 0.005
0.04 0
[T, Q] =
0.05 0
0.05 0.005
0.1 0.005
The system thus initially steps to a pump flow of 0.005 m3/sec = 300 l/min, abruptly steps to zero at t =
0.04, then resumes its initial flow rate at t = 0.05.
The control valve starts with zero orifice area and ramps to 1e-4 m2 during the 0.1 second simulation
time. With the valve closed, all of the pump flow goes to leakage so the initial pump pressure jumps to
As the valve opens, pressures p2 and p3 build up while p1 dips in response to the load increase as shown in
Figure 5.5. When the pump flow cuts off, the spring and piston act like an accumulator and p3, though
decreasing, is continuous. The flow reverses direction, so p2, though relatively close to p 3, falls abruptly.
At the pump itself, all of the backflow goes to leakage and p 1 drops radically. This behavior reverses as the
flow is restored.
16
p1
14 p1
12
8
p2
p
3
p
2
6
4 p3 p
1
0
0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1
time (sec)
The piston position is directly proportional to p3 , where the hydraulic and spring forces balance as shown
in Figure 5.6. Discontinuities in the velocity at 0.04 and 0.05 seconds indicate negligible mass. The model
reaches a steady state when all of the pump flow again goes to leakage, now due to zero pressure drop
across the control valve. That is, p3 = p2 = p1 = p10.
0.03
0.025
piston position (m)
0.02
0.015
0.01
0.005
0
0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1
time (sec)
p
p1
x
A
qin
pump
valve/cylinder/piston assembly 1
p positions
p1
x1 (yellow)
x x2 (purple)
A x3 (blue)
qin x4 (red)
control valve/cylinder/piston assembly 2
Mux
valve
command
p
p1
x
A
qin
valve/cylinder/piston assembly 3
p
p1
x
A
qin
valve/cylinder/piston assembly 4
supply
pressure
p1 load
flow
The pump flow begins at 0.005 m3/sec again for this system, then drops to half that value at t = 0.05 sec.
The parameters C1, C2, Cd, ρ and V30 are identical to the previous model. However, by assigning
The ratio of area/spring rate remains constant, so each case should have the same steady-state output.
The dominant time constant for each subsystem is proportional to Ac 2/K, so we can expect case two to be
somewhat faster than the case one, and case three somewhat slower. In case four, the effective bulk
modulus of the fluid is significantly lower, as would be the case with entrained air. We thus expect this
softer case to respond more sluggishly than case one. The simulation results support these predictions.
0.018
0.016
0.014
piston position (m)
0.012
0.01
x2
0.008
x1
0.006
0.004 x4
0.002
x3
0
0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1
time (sec)
The initial jolt of flow at t = 0 responds like a pressure impulse, as seen by the four actuators (in Figure
5.8). The pump pressure p1 , which is initially high, drops rapidly as all four loads combine to make a
high flow demand. During the initial transient (about four milliseconds), distinctive responses identify
the individual dynamic characteristics of each unit.
The distinctions in behavior are blurred, however, as the pump pressure falls to the level within the
cylinders (in Figure 5.9). The individual responses blend into an overall system response which
maintains the flow balance between the components. At t = 0.05 seconds, the pump flow drops to a level
that is close to equilibrium and the actuator flows are nearly zero. The individual steady-state piston
positions are equal, as predicted by design.
q
3
15
q4
actuator flow rate (m /sec)
10
3
5
q
1
q
2
-5
0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1
time (sec)
Mux
z (purple), za (blue)
& zb (yellow)
theta
(rad)
zb
za
zbdot
theta
zadot
Mechanical
Load
Fext
Fb
Fa
- 9.81*M
F
p
qin
qin
valve/cylider/piston valve/cylider/piston
force assembly 1 force assembly 2
xdot
xdot
p1
p1
A
A
x
x
orifice B orifice A
supply pressure
load
flow pump
The load subsystem shown in Figure 5.11 solves the equations of motion, which we compute directly with
standard Simulink blocks. We assume the rotation angle is small.
Mz˙˙ = F b + F a + F ext
z = displacement at center
M = total mass
F a , F b = piston forces
F ext = external force at center Equation 5.6
L L
Iθ˙˙ = Fb − Fa
2 2
θ = angular displacement, clockwise
I = moment of inertia
L = rod length
L
za = z − θ
2
L
zb =z + θ
2
L ˙
z˙ a = z˙ − θ Equation 5.7
2
L
z˙ b = z˙ + θ˙
2
z a ,z b = piston displacements
Connecting Rod
2
Fext
1 zdot 1
1 1/M 3
s s
Fb z
thetadot zadot 6 z zb 1
zadot zb
velocity
translation theta za 5
za
1 1
L/2 1/I 4
s thetadot s
theta
3
Fa
The parameters used in the simulation are identical to the first model, except:
L = 1.5m
M = 2500 kg
I = 100 kg- m2
Q pump = 0.005 m3 /sec (constant)
C2 = 3e- 10 m3 /sec/Pa
F ext = -9.81M N
Although pump flow is constant in this case, the model controls the valves independently according to the
following schedule in Figure 5.12:
B A
1
0.6
0.4
0.2
0
0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1
time (secs)
Figure 5.13 and Figure 5.14 show the simulation outputs of rod displacement and angle, respectively. The
response of z is typical of a type-one (integrating) system. The relative positions and the angular
movement of the rod illustrate the response of the individual actuators to their out-of-phase control
signals.
10
6
z
z
b
4
-2
0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1
time (sec)
0
load angular displacement (rad)
-2
-4
-6
-8
-10
0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1
time (sec)
Models such as these will ultimately be used as part of overall plant or vehicle systems. The hierarchical
nature of Simulink allows independently developed hydraulic actuators to be placed, as appropriate, in
larger system models, for example, adding controls in the form of sensors or valves. In cases such as
these, tools from the MATLAB Control System Toolbox can analyze and tune the overall closed-loop
system. The MATLAB/Simulink environment can thus support the entire design, analysis, and modeling
cycle.
Summary The following example illustrates 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 Similar to the engine model described earlier in this document, physical and empirical relationships
Physics form the basis for the throttle and intake manifold dynamics of this model. The mass flow rate of air
pumped from the intake manifold, divided by the fuel rate which is injected at the valves, gives the air-fuel
ratio. The ideal, or stoichiometric mixture ratio provides a good compromise between power, fuel
economy, and emissions. A target ratio of 14.6 is assumed in this system.
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 6.1 shows the top level of the Simulink model (fuelsys.mdl). The controller 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]), to simulate failures. Simulink accomplishes this with Manual Switch blocks. Double-
click on the block itself to change the position of the switch. Similarly, the user can induce the failure
condition of a high engine speed by toggling the switch on the far left. A Repeating Table block provides the
throttle angle input and periodically repeats the sequence of data specified in the mask.
throttle
0 throttle
sensor throttle angle MAP
Nominal engine
Speed speed
engine speed
300
700
0 speed
High fuel rate fuel air/fuel ratio
Speed sensor
(rad./Sec.)
EGO
engine
gas
Use this switch
12 dynamics
to force the EGO
engine to sensor
overspeed
MAP
Metered Fuel
To toggle 0 MAP
a switch, sensor fuel rate
double click controller
on its icon. air/fuel
Use these switches to
simulate any combination mixture ratio
of sensor failures
The controller uses the sensor input and feedback signals to adjust the fuel rate to give a stoichiometric
ratio (Figure 6.2). The model uses four subsystems to implement this strategy: control logic, sensor
correction, 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.
1
Sensor correction and
throtle Fault Redundancy
Airflow calculation
Mu Sensors
Corrected sens_in
Failures
Fuel Calculation
2
engine
Failures airflow airflow
speed
control logic fuel rate 1
fuel
mode
throt throtState mode rate
3 speedState
speed Mu
EGO
o2State
Ego
pressState
fuel_mode
4 press
MAP
fuel rate
controller/control logic
Oxygen_Sensor_Mode O2_normal
Pressure_Sensor_Mode
entry: o2State = 0
[t > o2_t_thresh]
[press > max_press | press < min_press]
O2_warmup /Sens_Failure_Counter.INC
entry: o2State = 1 [Ego > max_ego]/
Sens_Failure_Counter.INC press_norm press_fail
entry: pressState = 0 entry: pressState = 1
Throttle_Sensor_Mode
Speed_Sensor_Mode
[throt> max_throt | throt < min_throt]/
Sens_Failure_Counter.INC [speed==0 & press < zero_thresh]/
Sens_Failure_Counter.INC
throt_norm throt_fail
entry: throtState=0 entry: throtState = 1
speed_norm speed_fail
entry: speedState = 0 entry: speedState = 1
Sens_Failure_Counter
MultiFail
INC
INC INC INC
Fueling_Mode
Fuel_Disabled
H [ speed > max_speed ] entry: fuel_mode = DISABLED
Running
Overspeed
Low_Emmisions Rich_Mixture
entry: fuel_mode = LOW H entry: fuel_mode = RICH
[in(FL1)]
Single_Failure [!in(MultiFail)] [in(speed_norm) & ...
Normal
speed < (max_speed - hys)]
[in(FL0)]
enter(MultiFail) [in(MultiFail)]
[in(FL1)]
Warmup Shutdown
[in(O2_normal)]
exit(MultiFail)
Regardless of which sensor fails, the model always generates the directed event broadcast
Sens_Failure_Counter.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,
Sens_Failure_Counter.DEC. The Sens_Failure_Counter state keeps track of the number of failed
sensors. The counter increments on each Sens_Failure_Counter.INC event and decrements on each
Sens_Failure_Counter.DEC event. The model uses a superstate, MultiFail, 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 Normal state is activated at this time.
We easily added a protective overspeed feature 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
The Fault Correction block determines which sensors to use and which to estimate. Figure 6.4 shows the
block diagram for this subsystem. The failures input is a vector of logic signals that trigger the
application of estimates to each particular sensor. When a component of the signal is nonzero, it enables
the appropriate estimation subsystem and causes the switch relating to that signal to send the estimate as
the output. Since the estimation routines are within enabled subsystems, they do not introduce any
computational overhead when they are not needed.
Sensors throtle
Sensors we
speed
1
m Corrected
Sensors map
MAP
throttle
sensor
failure
1
Sensors
2 m speed sensor failure
Failures
The sensors input to the Correction block is the vector of raw sensor values. When there are no faults, the
input simply passes on as the output signal. When a fault exists, the appropriate estimation block uses
this signal to recover the missing component. Figure 6.5 shows an estimation example of the algorithm
for the manifold pressure sensor.
MAP Estimation
speed
1
Sensors
1
map
throttle
Enable
1
est.
engine speed, N air
flow
1 em
sens_in
Pumping Constant
manifold pressure, Pm
Feedforward Control
0.5
Ramp
Rate (Ki)
EGO, residual
exhaust oxygen
e1
<= e0 T e2
2
0.5 z -1
feedback
Oxygen Sensor Integrator correction
Switching Threshold hold
0 integrator
2
O2 fail
Failures (warmup) Feedback Control
NOR
3 enable integration
~=
mode LOW not normal operation
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.
C pump 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 Eqs. 6.2:
e2 = closed–loop correction
e 0, e1, e2 = intermediate error signals
The nonlinear oxygen sensor, modeled with a hyperbolic tangent in the engine gas Mixing and
Combustion subsystem, 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 6.2. If the value 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 Calculation subsystem (Figure 6.7) 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, 1/14.6.
1
est.
air
flow feedforward fuel rate
1/14.6
F/A Norm
1/(14.6*0.8)
F/A Rich mode
0
mode Shutdown fuel rate 1
4 fuel
limit rate
3 Failures output
Failures
2 feedback correction
correction
Switchable
Compensation
The Fuel Calculation subsystem (Figure 6.7) employs adjustable compensation (Figure 6.8) 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.
LOW Mode
1
feedforward
fuel rate
== 1
Fuel Rate
RICH
4
0.25918
feedback
correction z - 0.74082
RICH Mode
Shutoff
Mode
0
Results and Simulation results are shown in Figure 6.9 and Figure 6.10. The simulation is run with a throttle input
Conclusions that ramps from 10 to 20 degrees over a period of two seconds, then 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. To simulate a sensor failure, double-click
on its associated switch (see Figure 6.1). Repeat this operation to toggle the switch back for normal
operation.
Figure 6.9 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. Note, in each case, the nonlinear relationship
between fuel flow and the triangular throttle command (shown qualitatively on its Simulink icon). 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 6.10 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 6.10. 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.
g/sec
1
baseline
0
g/sec
1
throttle sensor failed
0
2
g/sec
1
speed sensor failed
0
2
g/sec
1
EGO sensor failed
0
2
g/sec
1
MAP sensor failed
0
0 1 2 3 4 5 6 7 8
time (sec)
15
baseline
10
15
throttle sensor failed
10
15
speed sensor failed
10
15
EGO sensor failed
10
15
MAP sensor failed
10
0 1 2 3 4 5 6 7 8
time (sec)
14
air/fuel ratio
13
12
11
10
2.5
2
fuel rate (g/sec)
1.5
0.5
0
0 1 2 3 4 5 6 7 8
time (sec)
During simulation, this behavior can also be observed from the Stateflow perspective. By enabling
animation in the Stateflow debugger, the state transitions are highlighted in Figure 6.3 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.
Summary In this example, Simulink is used to model an automotive drivetrain. 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 demonstrates 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.
Transmission
Transmission brake
Control Unit
Figure 7.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 directly
implements these as modular Simulink subsystems. On the other hand, the logic and decisions made in
the transmission controller (TCU) do not lend themselves to well-formulated differential or difference
equations; these are better suited to a Stateflow representation. Stateflow monitors the events which
correspond to important relationships within the system and takes the appropriate action as they occur.
Analysis and The engine receives input in the form of the throttle opening, as commanded by the driver. It is connected
Physics to the impeller of the torque converter which couples it to the transmission
I ei N˙ e = T e − Ti
N e = engine speed
. I ei = engine + impeller moment of inertia Equation 7.1
T e = f1(throttle, N e ) = engine torque
Ti = impeller torque
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 impeller
to turbine.
The transmission model is expressed as static gear ratios, assuming small shift times.
RTR = f 4 ( gear )
T out = RTRTin
N in = RTR N out
Equation 7.3
Tin ,T out = transmission input and output torque
N in , N out = transmission input and output speed
RTR = transmission ratio
The final drive, inertia, and a dynamically varying load constitute the vehicle dynamics.
I v N˙ w = R fd (T out − T load )
I v = vehicle inertia
N w = wheel speed
Equation 7.4
R fd = final drive ratio
T load = load torque
= f 5(Nw )
The load torque includes both the road load and brake torque. The road load is the sum of frictional and
aerodynamic losses.
The model programs the shift points for the transmission according to a schedule, such as is shown in
Figure 7.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.
90 upshift
downshift
80
70 4-3
vehicle speed (mph)
60
3-4
50
40
3-2
2-3
30
20
1-2 2-1
10
0
0 10 20 30 40 50 60 70 80 90 100
throttle (%)
Modeling The Simulink model (sf_car.mdl) is composed of modules which represent the engine, transmission
and vehicle, with an additional shift logic block to control the transmission ratio. User inputs to the
model are in the form of throttle (%) and brake torque (ft-lb). The diagram in Figure 7.3 shows the
overall model.
Mu
The Engine subsystem consists of a two-dimensional table that interpolates engine torque vs. throttle and
engine speed. In accordance with Equation 7.1, the model subtracts the impeller torque, divides the
difference by the inertia and then numerically integrates the quotient to compute the engine speed.
Figure 7.4 shows the composite engine subsystem.
The torque converter and the block which implements the various gear ratios make up the transmission
subsystem, as shown in Figure 7.5.
turbine speed
The torque converter is a masked subsystem, under which the model computes the relationships of
Equation 7.2. The parameters entered into the subsystem are a vector of speed ratios (Nin/Ne ) and vectors
of K-factor (f2) and torque ratio (f3) corresponding to the speed ratio data. Figure 7.6 shows the subsystem
implementation.
1
Ti
Nin
u^2
2
2
impeller Tt
1 turbine
Ne K quotient
speed
ratio factor
Torque
ratio
TORQUE CONVERTER
The transmission ratio block determines the ratio RTR(gear), shown in Table 7.1 and computes the
transmission output torque and input speed, as indicated in Equation 7.3. The ratios used progress from
low to another underdrive ratio, one-to-one and overdrive.
Figure 7.7 shows the block diagram for the subsystem that realizes this ratio in torque and speed.
1
1
Tin
Tout
Product
2
gear
LookUp
Table
2 3
Nin Nout
Product1
The Stateflow block labeled shift_logic implements gear selection for the transmission. The Stateflow
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 mSec. The Stateflow diagram shown
in Figure 7.8 illustrates the functionality of the block.
The shift logic behavior, explained in the following, can be observed during simulation by enabling
animation in the Stateflow debugger. The selection_state, which is 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 (see Figure 7.2).
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 (upshift_confirm or downshift_confirm),
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 Tconfirm, 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.
gear_selection/
gear_state
UPSHIFT34
UPSHIFT12 UPSHIFT23
first/ second/ third/ fourth/
entry: gear = 1; entry: gear = 2; entry: gear = 3; entry: gear = 4;
DOWNSHIFT21
DOWNSHIFT32 DOWNSHIFT43
selection_state/
during: down_threshold = ml(’interp2([1:4],downth, downtab, %g, %g)’, gear, throttle);...
up_threshold = ml(’interp2([1:4],upth, uptab, %g, %g)’, gear, throttle);
[gear == 3]/UPSHIFT34
[gear ==4]/DOWNSHIFT43
[gear == 2]/UPSHIFT23
[gear == 3]/DOWNSHIFT32
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 upshift_confirm state and sets the local variable tup to the current time by its
entry action. While in this state, if the vehicle speed remains above 30 mph until the elapsed time (t -
tup) reaches Tconfirm (0.1 Sec), 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 upshift_confirm to steady_state
and broadcasts the event UPSHIFT23 as a transition action. Consequently, the transition from second to
third is taken in gear_state which completes the shift logic.
The vehicle dynamics (Figure 7.9) use the net torque to compute the acceleration and integrate it to
compute the vehicle speed, per Equation 7.4 and Equation 7.5. In this example, we again use a masked
subsystem for the vehicle submodel. 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.
Results The engine torque map, torque converter characteristics, and road load data used in the simulations are
shown in the three plots which follow (Figure 7.10, Figure 7.11, and Figure 7.12).
300 70%
60%
50%
250
40%
200
engine torque (ft-lb)
30%
150
50
0% throttle
-50
-100
500 1000 1500 2000 2500 3000 3500 4000 4500 5000
engine speed (RPM)
240
220
2.0
200
K-factor (RPM/sqrt(ft-lb))
Torque Ratio
180
160
140 K-factor
120
1.0
100
80
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
speed ratio, N /N
in e
200
torque (ftlb)
150
100
50
80
60
power (HP)
40
20
0
0 10 20 30 40 50 60 70 80 90 100
vehicle speed (mph)
0 60
14.9 40
throttle = 15 100
100 0
200 0
The first column corresponds to time; the second column corresponds to throttle opening in percent. In
this case we do not apply the brake (0 ft-lb). The vehicle speed starts at zero and the engine at 1000 RPM.
Figure 7.13 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 Figs. 7.6 and 7.11).
The vehicle accelerates quickly (no tire slip is modeled) and both the engine and the vehicle gain speed
until about t = 2, 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.
4000
3000
2000
1000
140
vehicle speed (mph) & throttle (%)
120
100
80 vehicle mph
60
throttle %
40
20
0
0 5 10 15 20 25 30
time (sec)
At t = 15, 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 to about 3700 RPM. The
engine torque thus increases somewhat, as well as the mechanical advantage of the transmission. With
Figure 7.14 shows the results of a second simulation. The behavior for the first fifteen seconds is the same
as above, but the throttle subsequently drops to about 5% at 40 seconds. This is followed by a step in brake
torque at t = 50. Again, the large vehicle inertia dominates the dynamics as it eventually slows down to a
crawl. The engine speed downshifts occur at about 72, 80 and 90 seconds, ending in first gear.
4000
2000
150
vehicle speed (mph)
100
50
0
throttle (%) & torque (ftlb)
300
brake
200
throttle
100
0
0 10 20 30 40 50 60 70 80 90 100
time (sec)
Conclusions We 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.
Summary In this example we develop a Simulink model for a hydraulic servomechanism controlled by a pulse-
width modulated (PWM) solenoid. This might represent a motion control system in an industrial or
manufacturing setting, or a subsystem that controls the position of a valve in an automotive or aerospace
application. Nonlinear differential equations are used to model the magnetic, hydraulic and mechanical
components; discrete-time difference equations represent the controller. A behavioral model in Stateflow
implements the electronic circuit which generates the PWM waveforms and regulates the solenoid
current. Although a detailed power electronic model could be developed in Simulink, the Stateflow
description provides the required functionality and speeds development.
Figure 8.1 shows a hydraulic schematic for the mechanism. The objective of the system is to position the
load xp so that it follows commands issued in the form of a time-varying set point rset . An electronic
controller compares these commands to feedback measurements of xp and generates a PWM control
signal at a rate of 50 Hz. The PWM duty cycle is the percentage of the 20 millisecond period for which the
valve directly supplies oil to the control pressure developed in the cylinder behind the piston, pc. For the
remainder of the period, the valve vents pc to exhaust. The composite flow qnet thus controls pc which
develops an actuating force against the piston. This forces the spring-loaded piston to its position xp such
that it follows the reference trajectory rset .
We chose PWM control to regulate the net valve flow with its on/off duty ratio rather than relying on the
strict mechanical tolerances of a continuous valve. This sequentially turns the solenoid completely on or
off , rather than attempting to control it to a precise intermediate position. The tradeoff is that a
disturbance is introduced into the system at the PWM frequency. As a result, we must take care that this
is adequately attenuated by the low-pass response of the mechanical system. We can evaluate this
requirement by constructing a simulation at the design phase rather than waiting for experimental parts.
Physics The model of the solenoid-controlled PWM valve includes three parts:
Magnetic circuit
Armature motion
Valve flows
flux path
supply
pre ssure
pole armature Ps
air gap
exh
control
coil pc pressure
Consider first the magnetic circuit. Faraday’s law determines the flux. We assume that fringing and
leakage flux are negligible, as are eddy currents.
φ˙ = (vsol − iR )/ N ,
φ = flux
vsol = solenoid voltage
i = current
R = winding resistance
N = number of turns
The magnetomotive force required to develop this flux is broken up into components for the steel and the
air gap. Although the majority of the circuit’s reluctance is concentrated at the air gap, the nonlinear
properties of the steel components, such as saturation and hysteresis, can limit performance.
Within the steel, the flux density, B, is a nonlinear function of H, dependent upon the material properties.
We also assume that the area, A, which relates φ and B at the air gap, applies uniformly for the steel path.
B = φ /A
= flux density
= f(Hsteel )
= µ0 H air
A = cross- sectional area at air gap
µ0 = permeability of air
F sol = 0.5B 2 A / µ 0
i = MMF / N
The armature responds to the solenoid force, as well as the hydraulic and spring forces.
The net oil flow directed from the valve to the actuator, qnet , is the supply flow less the exhaust flow.
q net = q s − q ex
K A sgn(P − p ) P − p , x > 0
qs = o o s c s c
0, x =0
K A p , x < balltravel
q ex = o o c Equation 8.3
0, x = balltravel
p c = control pressure
K o = flow coefficient
β
(
p˙ c = q net − x˙ p Ap ,
V
)
β = fluid bulk modulus
V = x p Ap Equation 8.4
= fluid volume
x p = piston position
Ap = actuator (piston) area
The actuator’s equation of motion, dominated by the relatively large hydraulic and spring forces, is
simply:
M p x˙˙p = p c Ap − K sp x p ,
M p = net actuator mass Equation 8.5
K sp = spring rate
Electronic Controls
We employ a discrete-time PI (proportional + integral) control law to
1. Achieve zero steady-state error to step changes in the position set point, and
2. Compensate for the low-frequency actuator dynamics to improve response speed.
K
dutycycle = K p + I (rset − x p ) Equation 8.6
z − 1
The integral term is essential because the null duty cycle, or equilibrium control input, is subject to
uncertainty and will change with the system’s operating point. The proportional part contributes phase
lead at low frequency which is essential for stability.
Equation 8.6 computes the PWM duty cycle as a function of position error. The duty cycle is applied to a
50 Hz pulse train and the power electronics convert the pulse signal to solenoid current. Digital and
analog integrated circuits are available to perform these functions, so we use a behavioral model, rather
than a highly detailed physical model. The behavior is best described in terms of the circuit’s reaction to
the commands it receives and the response of its load. Figure 8.3 shows an idealized example.
At the beginning of each 20 millisecond period, the PWM pulse turns on and must pull the solenoid
armature up against the pole piece to open the valve to supply pressure. Hence, the driver circuit applies
the full supply voltage to achieve the fastest initial rise in current. The solenoid maintains this condition
until the current has risen to the level at which the magnetic and hydraulic forces overcome the spring
and move the armature.
At the end of each pulse, the armature releases so that the ball returns to its original position and the
valve opens to exhaust. We achieve this by opening the solenoid circuit so that the magnetic field
collapses quickly. Typically, we employ a zener diode to limit the large negative EMF while still allowing
a fast decay. The current then remains at zero for the duration of the “off” time until the next cycle
begins.
In this way, we divide the “on” portion of each pulse into two phases: “pull-in” and “hold.” The “off”
portion is characterized by the initial rapid decay, followed by zero voltage and current. The diagram in
Figure 8.3 illustrates this scenario.
vol tage
Vs Ipull
current
Ihold
20 mSec
Modeling Figure 8.4 shows the top-level system block diagram (sf_electrohydraulic.mdl). The set point block
consists of a signal generator and a step function which are added to give wide flexibility to the user in
specifying the set point. The controller is a straightforward discrete-time subsystem. We implemented the
PWM driver circuit in Stateflow, but it functions just like the other subsystems at the block diagram level.
We refined the solenoid valve into three parts, as described above. The actuator model, consisting of the
cylinder pressurization and piston motion subsystems, completes the overall system model.
solenoid
current (A)
electrohydraulic servomechanism
Figure 8.4: Servo model using Simulink and Stateflow
Controller
The controller samples the position error and generates a new solenoid duty cycle every 20 milliseconds.
The duty cycle consists of a component that is proportional to the error plus a component that is
proportional to the integral of the error. The model realizes the integration in the z domain with feedback
around a 1/z block that places a pole at z = 1. The integral gain, as labeled in the diagram, (Figure 8.5) is
fixed with respect to the proportional gain. An overall loop gain, Ka, adjusts both while keeping their
ratio, hence the transfer function zero, constant. While in the linear operating range:
duty cycle KI
= K a 1 +
error z − 1 Equation 8.7
z − (1 − K I )
= Ka
z −1
The model limits the computed duty cycle so that it never falls below the minimum time to open the
valve, nor exceeds the time at which the valve remains continuously open. Whenever it reaches either of
these limits, the integrator holds constant (zero input) until the error is of the appropriate sign to pull it
away from the limit.
1
Ka
set point
proportional + integral control
sampled
loop 1
error
gain
0.1332 duty cycle
1 Saturation
2 feedback z
0 integral
gain
dc
nothold
e1
prevent
windup
controller
PWM_driver_ckt
/ton = 0; energize_solenoid
/toff = ton + duty_cycle*Tpwm/100;
pull_in_current/
entry : v = Vs;
[i >= Ipull]
[t >= ton]
solenoid_off/
entry : v = -(i > 0)*Vz; regulate_hold_current
during: v = -(i > 0)*Vz; [t > toff]/ton += Tpwm;
freewheel/
entry: v = -(i > 0)*Vd;
during: v = -(i > 0)*Vd;
hold/
entry : v = Vs;
Each PWM cycle begins with the local variable ton equal to the current simulation time. The
unconditional transition which begins the cycle computes toff, the time at which the “on” portion of the
pulse ends.
Tpwm is a MATLAB workspace variable representing the pulse period. The system enters the
energize_solenoid state and, by default, the pull_in_current state. As described above, the driver
circuit connects the supply voltage to the output for this phase of the pulse. Once the current reaches
Ipull, the worst-case current required to pull in the armature, it enters the regulate_hold_current
state. A diode in the freewheel state shunts the coil which clamps the solenoid voltage at -Vd. When the
current falls to the hold level, the system alternates between the hold and freewheel states to regulate it to
Ihold ± deltai.
When the time reaches t = toff, it exits the energize_solenoid state, regardless of which of the pull-in,
freewheel or hold states is currently active. This is achieved by drawing the transition directly from the
superstate boundary to the solenoid_off state. The value of ton, the beginning of the next cycle, is updated
at this time. While in the solenoid_off state, the coil connects to the zener voltage, -Vz, until the field
collapses and the current falls to zero, as described in the entry and during actions.
2 0.5*A/mu0
u 1
Fsol
force
magnetic circuit
The model computes the solenoid current by determining the magnetomotive force. In the air gap, Hair =
B/µ0 is multiplied by the gap length to give MMFair . The gap length is computed by subtracting the
armature position from the maximum gap. A small additional gap is added to model additional air in
the circuit, at the armature bearing surface, for example. The MMF required to produce the flux density in
the steel is computed by putting the material characteristics, H vs. B, in a 2-D lookup table. Since this
curve has significant hysteresis, two curves are placed in the table, one for increasing and one for
decreasing flux. The appropriate curve for H steel = f ( B ) is selected according to the sign of φ̇ . Hsteel Lsteel
is added to MMFair and the sum is divided by N to determine the solenoid current.
Armature Motion
The model solves the equation of motion for the armature directly, as shown in Figure 8.8. The sum and
gains use standard blocks , and the subsystem Double Integrator computes the velocity and position of
the armature based on its acceleration. The position x = 0 corresponds to the maximum air gap, gmax.
net force
Cv
Fs0 damping
spring preload
Ks
spring rate
armature motion
In the double integrator subsystem (Figure 8.9), the model limits the position integrator by physical stops
at x = 0 and at x = gmax - gmin (a shim typically limits the minimum gap). When these limits are
reached, it is essential that the velocity becomes zero and remains zero while at the stops. The model
achieves this by feeding the position saturation port back to the velocity reset trigger. In addition, the
derivative input of the velocity integrator switches to zero as long as xdotdot (force/mass) holds the
armature against the stop. The velocity thus remains zero until the force reverses direction.
2
xdot
0
1 1 1
1
s s x
xdotdot Switch
>
0 AND
OR
AND
<
0 <=
0
>=
gmax-gmin
Valve Flows
Simulink models the turbulent flow through the valve orifices with the following subsystem, shown in
Figure 8.10. The inputs pup and pdown are the upstream and downstream pressures and q is the flow
from pup to pdown. The square root of the absolute value of the pressure drop, multiplied by the sign of the
pressure drop and KoAo (defined in Equation 8.3) yields the flow.
pup
1
2 Ko*Ao 1
pdown |u| sqrt
q
source flow
Ps pup
q
pdown
armature position
2
>
0 source
open
0
1
net
>= flow
balltravel exhaust
closed
1 pup
control pressure q
0 pdown
exhaust flow
Cylinder Pressurization
The model for cylinder pressurization is a direct realization of Equation 8.4 in the actuator dynamics
section (see Figure 8.12). Oil volume is the product of the piston position and its cross-sectional area. The
division operator uses a function block within a masked subsystem and the other blocks are standard
gains, a sum, and an integrator.
bulk
modulus
1
beta
qnet 1
1
effective s
flow pc
pressure
3 Ap
xpdot
dVolume/dt
2 Ap
xp
Volume
cylinder pressurization
Figure 8.12: Hydraulic c ylinder subsystem
spring
Ksp
xp
x 1
Ap 1/Mp xdotdot
1
pc
xdot 2
area mass xpdot
double integrator
piston motion
Results Figure 8.14 below shows the set point and piston position for a baseline simulation. During the first 0.1
second, and again from 1.0 to 1.1 seconds, the output is slew rate limited by the maximum flow available
to the actuator. At other times, the 3 Hz sinusoid is tracked closely. Although the solenoid goes through a
complete on/off cycle each PWM period, the 50 Hz dither superimposed on the actuator position is
relatively small.
0.016
set point
0.014
0.012
0.008
0.006
0.004
0.002
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
time (sec)
Figure 8.15 below depicts the solenoid current control, under the authority of the Stateflow model. The
diagram shows two cycles with about 47% and about 55% duty cycle, respectively. During the pull-in
phase, as the flux builds and the current approaches its 2.5A target, the current drops abruptly at about t =
2 milliseconds. This is the instant at which the armature is pulled in. This pull-in generates so much
back EMF that the current drops appreciably. The notch in current is so distinct that it is often used in the
laboratory to measure solenoid response time.
When the current reaches the conservative 2.5A target, more than enough to achieve armature pull-in,
the solenoid enters the hold phase of its energized state. The model regulates the average current to 1A by
chopping the voltage as described in the Stateflow diagram. The chopping takes place at a rate somewhat
higher than 1 kHz in order to regulate the current within ±0.1 A. The freewheel state uses a value of Vd =
0.5 V to slow the decay of energy in the magnetic field. When the completion of each energized state turns
off the solenoid, the negative voltage is limited by Vz = 50 V. The model achieves a rapid decay in current
without subjecting the semiconductor devices to extreme voltages.
2.5
0.5
0
0.94 0.945 0.95 0.955 0.96 0.965 0.97 0.975
time (sec)
Conclusions Simulink and Stateflow combine to provide a powerful modeling environment for dynamic systems. In
this case, Simulink enables the direct construction of block diagram subsystems which represent the
nonlinear differential equations of the physical system and the difference equations of its discrete-time
controller. A Stateflow model captures the behavior of the electronic PWM driver circuit, without
resorting to the complexity of a detailed circuit model. The clear and natural logic of Stateflow facilitates
rapid model development and debugging. The overall model develops in a structured, hierarchical
manner, amenable to careful documentation
Summary The model in this example consists of a block sliding along a surface and compressing a spring under the
influence of a user-designated input force. In the absence of friction, this behaves like a classical spring-
mass system with the steady-state block position proportional to the applied force. When friction is taken
into account, the model becomes considerably more complicated. Friction between the block and surface
tends to resist motion; however, the friction force changes with velocity and tends to be greatest when
stationary. This results in motion which alternately “sticks” and “slips” as the overall force balance
requires. This “stiction” phenomenon is common in many mechanical systems.
In this simulation, Stateflow is used to represent some of the physical states of the system. As noted above,
the friction force between two surfaces is intrinsically tied to their instantaneous relative velocity. The
continuous trajectory of velocity and position is subject to abrupt changes in acceleration, however,
corresponding to transitions between the discrete states of “stuck” and “sliding.” Simulink provides a
powerful tool for modeling the continuous dynamics, and Stateflow is a natural and intuitive setting for
modeling the discrete physical states.
Analysis and The diagram in Figure 9.1 shows the mechanical system.
Physics
Fin K
M
The model for the linear spring (of negligible mass) is:
F friction =
()
sgn x˙ µF n , Fstationary > µF n
Fstationary , otherwise, at x˙ = 0
x˙ = velocity
()
µ = µ x˙ = coefficient of friction Equation 9.3
F n = normal force
Fstationary = instantaneous force such that x˙ = 0
In many applications the friction capacity is described by its static and kinetic magnitudes. This
approach is used in the present model, also assuming a constant normal force.
µ static Fn = F static , x˙ = 0
µFn = Equation 9.4
µkinetic Fn = F sliding , x˙ ≠ 0
The following logic determines Fstationary . Whenever the velocity is nonzero, an impulsive force would be
needed to make it zero instantaneously. This always exceeds the capacity, Fsliding , so the latter magnitude is
used. When the velocity is already zero, however, Fstationary is the force which maintains this condition by
making the acceleration zero.
F stationary = F in − F spring
Equation 9.5
= F sum
sgn(x˙ )F x˙ ≠ 0
sliding ,
F friction = F sum , x˙ = 0 , F sum < F static Equation 9.6
sgn(F sum )F static , x˙ = 0 , F sum ≥ F static
Modeling Figure 9.2 illustrates a Simulink model that demonstrates this behavior (sf_stickslip.mdl). The two
main components are the block labeled Mechanical Motion and the block labeled state_logic . The former is
composed of conventional hierarchical Simulink subsystems and the latter is implemented in Stateflow.
Simulink is ideal for solving ordinary differential equations and the associated linear and nonlinear
signal flow calculations. Stateflow demonstrates its power in its ability to recognize system events which
require changes in the mode of operation.
Mu force and
position
The input force linearly compresses vs. time
the spring, but friction resists this Mux
movement. The magnitude of position
friction depends on the state of motion. vs.
force
position
Fin zero threshold
mechanical state_logic
motion
Timekeeping
As described in Equation 9.2, the model implements the fundamental equation of motion, in the
Mechanical Motion block. Double-clicking on this block shows the underlying subsystem, pictured in
Figure 9.3. The sum of the forces divided by the mass determines the block acceleration. The acceleration
is integrated twice to compute the velocity and position.
Fsum
3
2
1
velocity
Fin 1/M 1 1
1
Fsum s s
position
xdot Ffriction
stuck
friction force
2
stuck
spring
Mechanical Motion
The friction force subsystem shown in Figure 9.4 performs a number of nonlinear operations on the
signals in order to model the relationships of Equation 9.6. Standard Simulink blocks implement the
1
Sign1
Fsum |u|
Abs fstatic
min
Fstatic
MinMax
3 1
stuck Ffriction
Fsliding
fsliding
2
xdot
friction forces
Figure 9.4: Friction Subsystem
The Stateflow diagram in Figure 9.5 below describes the behavior of the system states. The block input
signals are Fsum and novelocity. Fsum as defined in Figure 9.4 and novelocity is a binary signal that
becomes one the instant the velocity crosses through zero. The Stateflow block output is the control signal
stuck, as described above. The parameter Fstatic is taken from the MATLAB workspace.
state_logic
state_of_motion
stuck/ sliding/
entry: stuck = 1; entry: stuck = 0;
The output signal of the machine, stuck, is a binary representation of the state. The entry function of the
stuck state sets it to one, and the entry function of the sliding state clears it to zero. It can then be used as
a control signal in the other Simulink blocks, as indicated above. The ultimate value of the state machine
in this example is to model the state transitions of the system in accordance with physical laws while
using the appropriate frictional force in the acceleration computations at each instant.
The input force ramps linearly from zero to 5 N and back to zero, with a period of 5 seconds. Two
noteworthy characteristics of the parameters are:
ω n = K / M = 31.6 rad/sec
is much higher than that of the excitation (2π/10 rad/sec). As is typical in the laboratory, the model
employs a very low excitation frequency in order to determine the static response characteristics of the
system.
Figure 9.6 and Figure 9.7 show plots of the simulation results. Figure 9.6 shows the time histories of the
input force and the resulting position. The input force must exceed that of the static friction in order to
begin motion at t = 1. From 1 < t < 5, the position tracks the spring force less the kinetic friction force, with
small oscillations showing changes in velocity at the natural frequency ω n . The input force then begins
to decrease. The mass immediately comes to a halt and sticks until t = 7, when the net force again exceeds
the static friction force, now in the reverse direction.
Force
4.5
3.5
2.5
Position
2
1.5
0.5
0
0 2 4 6 8 10 12 14 16 18 20
time (sec)
Similar behavior follows as the input force decreases to zero and repeats another cycle. Figure 9.7 shows
the input-output characteristics of the system, position vs. force. The plot forms a hysteresis loop as the
position lags the force. The static input-output characteristics cannot be represented by a single-valued
function because the system has memory.
Friction Characteristics
5
3
position (m)
-1
-1 0 1 2 3 4 5 6
force (N)
The static behavior relies, not only on the spring rate (force vs. position), but also on the position and
velocity at the instant of the last state transition. While in the stuck state, the position will remain
constant at the point where it entered the state. In the sliding state, the position depends on the spring
characteristics, the direction of the velocity, and the position of the mass at the moment it began to slide.
This behavior is captured in a natural and intuitive way in the Stateflow model.
We can illustrate the dynamic behavior of “stiction,” or stick-slip friction, even more dramatically by
changing the system parameters as follows.
M = 0.1 kg
F sliding = 0.1 N
Stiction Nonlinearity
6
4
force (N) and position (m)
Force
2
Position
0
-1
0 2 4 6 8 10 12 14 16 18 20
time (sec)
With kinetic friction lower in magnitude than static friction, abrupt discontinuities in acceleration occur
at the stuck-to-sliding and sliding-to-stuck state transitions. As the velocity reaches zero, the
acceleration is often nonzero. If the stuck state is entered, however, the acceleration becomes zero
Conclusions We can greatly simplify the modeling and simulation task by inserting a Stateflow block into the
mechanical system. Conceptually, Stateflow captures the complex dynamic nonlinear behavior in a
graphical diagram with straightforward, easy-to-read functionality. We can insert this diagram directly
into the Simulink diagram, and the tasks of code generation, compiling, and linking are seamlessly
automated to provide a powerful simulation environment.
Internet services:
www.mathworks.com The MathWorks home page
ftp.mathworks.com FTP server
Other resources:
comp.soft-sys.matlab Usenet newsgroup 24 Prime Park Way
Natick, MA 01760-1500 USA
© 1998 by The MathWorks, Inc. All rights reserved. MATLAB, Simulink, Handle Graphics, and Real-Time Workshop are registered trademarks, and Stateflow and
Target Language Compiler are trademarks of The MathWorks, Inc. Other product or brand names are trademarks or registered trademarks of their respective holders.
9521v00 2/98