You are on page 1of 123

Introduction: Simulink Modeling

In Simulink, it is very straightforward to represent and then simulate a mathematical model representing a physical system. Models are represented
graphically in Simulink as block diagrams. A wide array of blocks are available to the user in provided libraries for representing various phenomena
and models in a range of formats. One of the primary advantages of employing Simulink (and simulation in general) for the analysis of dynamic
systems is that it allows us to quickly analyze the response of complicated systems that may be prohibitively difficult to analyze analytically.
Simulink is able to numerically approximate the solutions to mathematical models that we are unable to, or don't wish to, solve "by hand."

In general, the mathematical equations representing a given system that serve as the basis for a Simulink model can be derived from physical laws. In
this page we will demonstrate how to derive a mathematical model and then implement that model in Simulink. This model is then employed in the
Introduction: Simulink Control page in order to demonstrate how to employ Simulink to design and simulate the control for a system.

Train system
In this example, we will consider a toy train consisting of an engine and a car. Assuming that the train only travels in one dimension (along the track),
we want to apply control to the train so that it starts and comes to rest smoothly, and so that it can track a constant speed command with minimal
error in steady state.

The mass of the engine and the car will be represented by and , respectively. Furthermore, the engine and car are connected via a coupling with
stiffness . In other words, the coupling is modeled as a spring with a spring constant . The force represents the force generated between the wheels
of the engine and the track, while represents the coefficient of rolling friction.

Free-body diagram and Newton's second law


The first step in deriving the mathematical equations that govern a physical system is to draw the free-body diagram(s) representing the system. This
is done below for our train system.
From Newton's second law, we know that the sum of the forces acting on a body is equal to the product of the mass of the body and its acceleration.
In this case, the forces acting on the engine in the horizontal direction are the spring force, the rolling resistance, and the force generated at the
wheel/track interface. The forces acting on the train car in the horizontal direction are the spring force and the rolling resistance. In the vertical
direction, the weight forces are balanced by the normal forces applied by the ground . Therefore, there will be no acceleration in the vertical
direction.

We will model the spring as generating a force that is linearly proportional to the deformation of the spring, , where and are the
displacements of the engine and car, respectively. Here it is assumed that the spring is undeformed when and equal zero. The rolling resistance
forces are modeled as being linearly proportional to the product of the corresponding velocities and normal forces (which are equal to the weight
forces).

Applying Newton's second law in the horizontal direction based on the above free-body diagrams leads to the following governing equations for the
train system.

(1)

(2)

Constructing the Simulink model


This set of system equations can now be represented graphically without further manipulation. Specifically, we will construct two copies (one for
each mass) of the general expression or . First, open Simulink and open a new model window. Then drag two Sum blocks
(from the Math Operations library) into your model window and place them approximately as shown in the figure below.
The outputs of each of these Sum blocks represents the sum of the forces acting on each mass. Multiplying each output signal by will give us the
corresponding acceleration of each mass. Now drag two Gain blocks (from the Math Operations Library) into your model and attach each one with a
line from the output of one of the Sum blocks. Label these two signals as "Sum_F1" and "Sum_F2" in order to make your model more clear. This is
accomplished by double-clicking in the space above each of the two signal lines and entering the desired label.
These Gain blocks should contain for each of the masses. We will define the variables M1 and M2 in the MATLAB workspace, so we can just
enter the corresponding variable names in each of the Gain blocks. Double-click on the upper Gain block and enter "1/M1" into the Gain field.
Similarly, enter "1/M2" in the Gain field of the second Gain block.

You will notice that the gains did not appear in the image of the Gain blocks, rather the blocks display a value of -K-. This is because the blocks are
too small on the screen to show the full variable name inside the triangle. The blocks can be resized so that the actual gain value can be seen. To
resize a block, select it by clicking on it once. Small squares will appear at the corners. Drag one of these squares to stretch the block. Your model
should appear as below.
The outputs of these gain blocks are the accelerations of each of the masses (the train engine and car). The governing equations we derived above
depend on the velocities and displacements of the masses. Since velocity can be determined by integrating acceleration, and position can be
determined by integrating velocity, we can generate these signals employing integrator blocks. Drag a total of four Integrator blocks from the
Continuous library into your model, two for each of our two accelerations. Connect these blocks and label the signals as shown below. Specifically,
the first inegrator takes the acceleration of mass 1 ("x1_ddot") as an input and generates the velocity of mass 1 ("x1_dot"). The second integrator then
takes this velocity and outputs the displacement of the first mass ("x1"). The same pattern holds for the integrators for the second mass.
Now, drag two Scopes from the Sinks library into your model and connect them to the outputs of these integrators. Label them "x1" and "x2".
Now we are ready to add the forces acting on each mass. First, we need to adjust the inputs on each Sum block to represent the proper number of
forces (we will worry about the signs later). Since there is a total of three forces acting on mass 1, double-click on the corresponding Sum block and
change the List of signs field to "|+++". The symbol "|" serves as a spacer. There are only 2 forces acting on mass 2, therefore, we can leave that Sum
block alone for now.
The first force acting on mass 1 is just the input force, . Drag a Signal Generator block from the Sources library and connect it to the uppermost
input of the corresponding Sum block. Label this signal as "F".
The next force acting on mass 1 is the rolling resistance force. Recall that this force is modeled as follows.

(3)

To generate this force, we can tap off the velocity signal and multiply by an appropriate gain. Drag a Gain block into your model window. Tap off the
"x1_dot" signal and connect it to the input of this new Gain block (draw this line in several steps if necessary). Connect the output of the Gain block
to the second input of the Sum block. Double-click the Gain block and enter "mu*g*M1" into the Gain field. The rolling resistance force, however,
acts in the negative direction. Therefore, change the list of signs of the Sum block to "|+-+". Next, resize the Gain block to display the full gain and
label the output of the Gain block "Frr1". Your model should now appear as follows.
The last force acting on mass 1 is the spring force. Recall that this force is equal to the following.

(4)

Therefore, we need to generate a signal which we can then be multiplied by a gain to create the force. Drag a Subtraction block (or a Sum
block or an Addition block) below the rest of your model. In order to change the direction of this block, right-click on the block and choose Format
> Flip block from the resulting menu. Alternatively, you can select the block then hit Ctrl-I. Now, tap off the "x2" signal and connect it to the
negative input of the Subtract block. Also, tap off the "x1" signal and connect it to the positive input. This will cause signal lines to cross. Lines may
cross, but they are only actually connected where a small block appears (such as at a tap point).
Now, we can multiply this difference by the spring constant to generate the spring force. Drag a Gain block into your model to the left of the
Subtraction block. Change the value of the Gain block to "k" and connect the output of the Subtract block to its input. Then connect the output of the
Gain block to the third input of the Sum block for mass 1 and label the signal "Fs". Since the spring force acts on mass 1 in the negative direction, it
is necessary to again change the list of signs of the Sum block to "|+--". Your model should appear as follows.
We can now apply forces to mass 2. For the first force, we will use the same spring force we just generated, except that it is applied to mass 2 in the
positive direction. Simply tap off the spring force signal "Fs" and connect it to the first input of the Sum block for mass 2.
The last force applied to mass 2 is its rolling resistance force. This force is generated in an analogous manner to the rolling resistance force applied to
mass 1. Tap off the signal "x2_dot" and multiply it by a Gain block with value "mu*g*M2". Then connect the output of the Gain block to the second
input of the corresponding Sum block and label the signal "Frr2". Changing the second input of the Sum block to be negative will lead to the
following model.
Now the model is complete. We simply need to supply the proper input and define the output of interest. The input to the system is the force
generated by the engine. Within the Simulink model, we have already defined the force to be the output of a Signal Generator block. The output of
the system, which we will observe and ultimately try to control, will be the velocity of the train engine. Add another Scope block to your model from
the Sinks library. Tap a line from the "x1_dot" signal and connect it to the Scope block. Label this scope as "x1_dot" and your model should appear as
in the following.
Now, the model is complete and should be saved. You can also download the completed model here.

Running the model


Before running the model, we need to assign numerical values to each of the variables used in the model. For the train system, we will employ the
following values.

= 1 kg

= 0.5 kg
= 1 N/sec

=1N

= 0.02 sec/m

= 9.8 m/s^2

Create a new m-file and enter the following commands.

M1 = 1;
M2 = 0.5;
k = 1;
F = 1;
mu = 0.02;
g = 9.8;

Execute your m-file in the MATLAB command window to define these values. Simulink will recognize these MATLAB variables for use in the
model.

Now, we need to give an appropriate input to the engine. Double-click on the Signal Generator block (outputs "F"). Select square from the Wave
form drop-down menu and set the Frequency field to equal "0.001". You may leave the Units as the default Hertz. Also enter "-1" into the
Amplitude field (positive amplitude steps negative before stepping positive).
The last step before running the simulation is to select an appropriate simulation time. To view one cycle of the 0.001 Hz square wave, we should
simulate the model for 1000 seconds. Select Parameters from the Simulation menu at the top of the model window and change the Stop Time field
to "1000". Close the dialog box.

Now, run the simulation and open the "x1_dot" scope to examine the velocity output (hit autoscale). The input was a square wave with two steps, one
positive and one negative. Physically, this means that the engine first went forward, then backward. The velocity output reflects this.
In this page we derived the mathematical model for the train system from first principles and then represented the derived equations within Simulink.
An alternative option that is now available is to represent a dynamic system employing the physical modeling tool Simscape. Simscape is an addition
to Simulink that allows a user to model a system employing blocks that represent physical quantities (and objects) such as inertias and joints, or
resistances and inductors. Employing Simscape allows the user to simulate a physical system without deriving the governing mathematical equations.

Continuing on to the Introduction: Simulink Control page, we will employ the model derived in this page to demonstrate how to use Simulink to
design the control for our train system.

Effects

Tips

TIPS
ABOUT

BASICS

HARDWARE

INDEX

NEXT

INTRODUCTION

CRUISE CONTROL

MOTOR SPEED

MOTOR POSITION

SUSPENSION

INVERTED PENDULUM

AIRCRAFT PITCH

BALL & BEAM

Introduction: Simulink Control


Related Tutorial Links

Temperature Control Activity

Motor Speed Control Activity

Simulink Interaction with MATLAB

Related External Links

Modeling Challenges Video

Contents
The open-loop plant model

Implementing a PID controller in Simulink

Running the closed-loop model

Extracting a model into MATLAB

Controller design within Simulink

The open-loop plant model


In the Introduction: Simulink Modeling page we demonstrated how Simulink can be employed to simulate a physical system. More generally,
Simulink can also simulate the complete control system, including the control algorithm in addition to the physical plant. As mentioned previously,
Simulink is especially useful for generating the approximate solutions of mathematical models that may be prohibitively difficult to solve "by hand."
For example, consider that you have a nonlinear plant. A common approach is to generate a linear approximation of the plant and then use the
linearized model to design a controller using analytical techniques. Simulink can then be employed to simulate the performance of your controller
when applied to the full nonlinear model. Simulink can be employed for generating the linearized model and MATLAB can be employed for
designing the controller as described in the other Introduction pages. Various control design facilities of MATLAB can also be accessed directly from
within Simulink. We will demonstrate both approaches in this page.

Recall the Simulink model of the toy train system derived in the Introduction: Simulink Modeling page and pictured below.
You can generate this model yourself, or you can download the completed model here. Assuming that the train only travels in one dimension (along
the track), we want to apply control to the train engine so that it starts and comes to rest smoothly, and so that it can track a constant speed command
with minimal error in steady state.

Implementing a PID controller in Simulink


Let us first create the structure for simulating the train system in unity feedback with a PID controller. In order to make our Simulink model more
understandable, we will first save the train model into its own subsystem block. To accomplish this, delete the three scope blocks and replace each
one by an Out1 block from the Sinks library. Label each Out1 block with the corresponding variable name, "x1_dot", "x1", and "x2". Then delete the
Signal Generator block and replace it with an In1 block from the Sources library. Label this input "F" for the force generated between the train engine
and the railroad track. Your model should now appear as follows.
Next select all of the blocks in your model (Ctrl A) and select Create Subsystem from the Edit menu at the top of the model window. With a little
rearranging and relabeling, your model will appear as shown below.

Now we can add a controller to our system. We will employ a PID controller which can be implemented using a PID Controller block from the
Continuous library. Placing this block in series with the train subsystem, your model will appear as follows. In the following, we model the controller
as generating the force "F" directly. This neglects the dynamics with which the train engine generates the torque applied to the wheels, and
subsequently neglects the dynamics of how the force is generated at the wheel/track interface. This simplified approach is taken at this point since we
only wish to introduce the basic functionality of Simulink for controller design and analysis.
Double-clicking on the PID Controller block, we will initially set the Integral (I) gain field equal to 0 and will leave the Proportional (P) and
Derivative (D) gains as their defaults of 1 and 0, respectively. Next add a Sum block from the Math Operations library. Double-click on this block
and modify the List of signs field to "|+-". Since we wish to control the velocity of the toy train engine, we will feedback the engine's velocity. This is
accomplished by 4ring a line off of the "x1_dot" signal and connecting it to the negative sign of the Sum block. The output of the Sum block will be
the velocity error for the train engine and should be connected to the input of the PID Controller block. Connecting the blocks as described and
adding labels, your model should appear as follows.
Next add a Signal Builder block from the Sources library to represent the velocity commanded to the train. Since we wish to design a controller to
bring the train smoothly up to speed and smoothly to rest, we will test the system with a velocity command that steps up to 1 m/s followed by a step
back down to 0 m/s (recall that our system is a toy train). To generate this type of command signal, double-click on the Signal Builder block. Then
choose Change time range from the Axes menu at the top of the block's dialog window. Set the Max time field to "300" seconds. Next, set the step
up to occur at 10 seconds and the step down to occur at 150 seconds. This is accomplished by clicking on the corresponding portions of the signal
graph (left and right vertical lines) and either dragging the line to the desired position, or entering the desired time in the T field at the bottom of the
window. When done, your signal should appear as follows.
Also add a Scope block from the Sinks library and use it to replace the Out1 block for the train's velocity. Relabeling the blocks, your model will
appear as follows.
We are now ready to run the closed-loop simulation. If you wish to skip the above steps, you may download the completed model with control here.

Running the closed-loop model


Before running the model, we need to assign numerical values to each of the variables used in the model. For the train system, we will employ the
following values.

= 1 kg

= 0.5 kg
= 1 N/sec

=1N

= 0.02 sec/m

= 9.8 m/s^2

Create a new m-file and enter the following commands.

M1 = 1;
M2 = 0.5;
k = 1;
F = 1;
mu = 0.02;
g = 9.8;

Execute your m-file in the MATLAB command window to define these values. Simulink will recognize these MATLAB variables for use in the
model. Next we need to set the time for which our simulation will run to match the time range of the command from the Signal Builder block. This is
accomplished by selecting Parameters from the Simulation menu at the top of the model window and changing the Stop Time field to "300". Now,
run the simulation and open the "x1_dot" scope to examine the velocity output (hit autoscale). The result as shown below demonstrates that the
closed-loop system is unstable for this controller.
Since the performance achieved above is unsatisfactory, we need to redesign our controller. We will first demonstrate how to extract a model from
Simulink into MATLAB for analysis and design. Then we will demonstrate how to design the control from directly within Simulink.

Extracting a model into MATLAB


The Simulink Control Design toolbox offers the functionality to extract a model from Simulink into the MATLAB workspace. This is especially
useful for complicated, or nonlinear simulation models. This is also useful for generating discrete-time (sampled) models. For this example, let us
extract a continous-time model of our train subsystem. First we need to identify the inputs and outputs of the model we wish to extract. The input to
the train system is the force . We can designate this fact by right-clicking on the signal representing "F" (output of the PID block) and choosing
Linearization Points > Input Point from the resulting menu. Likewise, we can designate the output of the train system by right-clicking on the
"x1_dot" signal and choosing Linearization Points > Output Point from the resulting menu. These inputs and outputs will now be indicated by
small arrow symbols as shown in the following figure. Since we wish to extract a model of the train by itself, without control, we need to further
delete the feedback signal, otherwise we will extract the closed-loop model from to . Your model should now appear as follows.
We can now extract the model by opening the Linear Analysis Tool. This is accomplished by selecting Control Design > Linear Analysis from
under the Tools menu at the top of the model window. Following these steps will open the window shown below.
This tool generates an LTI object from a (possibly nonlinear) Simulink model and allows you to specify the point about which the linearization is
performed. Since our Simulink model is already linear, our choice of operating point will have no effect and we can leave it as the default Model
Initial Condition. In order to generate the linearized model, select the Linearize button in the above figure, which is indicated by the green
triangle. The Linear Analysis Tool window should now appear as shown below.
Inspecting the above, the step response of the linearized model was automatically generated. Comparing this step response to the one generated by
the simulation of the open-loop train system in the Introduction: Simulink Modeling page, you can see that the responses are identical. This makes
sense since the simulation model was already linear. Additionally, the linearization process generated the object linsys1 shown in the Linear
Analysis Workspace above. This LTI object can be exported for use within MATLAB by simply dragging the object into the MATLAB Workspace
window.

Having extracted this model, we can now employ all of the facilities that MATLAB offers for controller design. For example, let us employ the
following commands to generate and analyze the closed-loop system reflecting the Simulink model created above.

sys_cl = feedback(linsys1,1);
pole(sys_cl)

ans =

-1.5261
0.0000
0.0670 + 1.1977i
0.0670 - 1.1977i

Examination of the above demonstrates that the closed-loop system in its current state has poles with positive real part and, therefore, is unstable.
This agrees with the result of our closed-loop simulation from above. We can then employ MATLAB to design a new controller. Instead, we will
demonstrate how to access some of MATLAB's functionality from directly within Simulink.

Controller design within Simulink


Rather than performing the controller design in MATLAB, we can also launch interactive tools to tune our controller from within Simulink. One
manner in which this can be done is to double-click on the PID Controller in the model and select the Tune button to launch the PID Tuner GUI.
Rather than do this, will launch the more general Simulink Control Design GUI by selecting Linear Analysis > Compensator Design from under the
Tools menu located at the top of the model window. Following these steps will open the Control and Estimation Tools Manager window shown
below.
The first thing that needs to be done is to identify the controller block that is to be tuned. This is accomplished by first clicking on the Select Blocks
button, and then selecting the PID Controller block from the resulting window as shown below. Next click the OK button. Note that controllers
represented in other types of blocks (Transfer Function, State Space, etc.) can also be tuned.
Before we proceed to tune our controller, we must first identify the inputs and outputs of the closed-loop system we wish to analyze. This is done in
the same manner we did when extracting a model into MATLAB. Specifically, right-click on the velocity command signal (output of the Signal
Builder block) and choose Linearization Points > Input Point from the resulting menu to identify the input of our closed-loop system. Similarly,
right-click on the train engine velocity signal ("x1_dot") and select Linearization Points > Output Point from the menu to choose the output of our
system. Your model should now appear as follows where the small arrow symbols identify the input and output of the model.
Now that we have identified the block to tune and our input and output signals, we can now commence with tuning the controller. Select the Tune
Blocks button in the Control and Estimation Tools Manager window. This will open the Design Configuration Window shown below which
provides some introduction on how to employ the interactive design tool. In essence, this GUI is the SISO Design Tool that is available from within
MATLAB as well.
Clicking the Next button, we will choose the design plots we wish to employ for designing our controller. In this example, we will employ a root
locus design approach and hence will choose a Plot Type of Root Locus for Plot 1 as shown below. Since the root locus approach to design employs
a plot from the open-loop system for placing the closed-loop poles, we will leave the choice of Open/Closed Loops as Open Loop 1 (this is our only
choice!).
Clicking the Next button again will allow us to choose our analysis plots. We use the step response plot to assess how well we are able to meet our
goal of bringing the train up to speed smoothly with minimal steady-state error to a constant speed command. Therefore, we will choose a Plot Type
of Step from the drop-down menu under Plot 1 as shown below. We will also select Plot 1 under the Plot Contents portion of the window for the
only system that is defined. There is only one system available because we have defined only a single input and single output for our system.
Selecting the Next Button will then open the SISO Design Tool with a root locus plot and a step response plot. The root locus plot shown below
displays the closed-loop pole locations of the train system plant under simple proportional control. Examining the plot, one can see that many values
of loop gain will place closed-loop poles in the right-half plane leading to an unstable response.
If we decrease the loop gain sufficiently, we can move the closed-loop poles into the left-half plane and we can stabilize our system. This can be
accomplished graphically by "grabbing" the pink boxes marking the closed-loop pole locations and dragging them toward the open-loop pole
locations (marked by x's). A loop gain of approximately 0.1 will stabilize the system. Examining the corresponding step response, which will change
automatically in response to the gain change if the Real-Time Update box is checked in the LTI Viewer window, you can see that while the
response is stable its steady-state error is quite large.
Recall that adding integral control is one way to reduce the steady-state error for a system. In this case, adding an integrator via the controller will
make the system type 1, where type 1 systems can track step references with zero steady-state error. Recall the following form of a PI controller.

(1)

Therefore, a PI controller will add an integrator and a zero to our open-loop system. The integrator can be added to the system by right-clicking in the
field of the root locus plot and selecting Add Pole/Zero > Integrator from the resulting menu. Similarly, the zero can be added by right-clicking on
the root locus plot and selecting Add Pole/Zero > Real zero from the resulting menu. Then click where along the real axis you wish to place the
zero. We will place the zero just to the right of the plant pole on the real axis. You can move the zero by clicking on it and dragging it to a new
location. Once you have placed the zero, then grab the pink boxes representing the closed-loop poles and attempt to line the three dominant poles up
so that they have the same real part. There also will be a real closed-loop pole to the left that is "faster" than the rest, and a closed-loop pole at the
origin that is cancelled by a closed-loop zero at the origin. The resulting root locus plot is shown below.
The compensator can also be edited by directly typing in pole and zero locations. This can be done by choosing Edit Compensator from the Design
menu located at the top of the SISO Design Task window. The window that opens is shown below. We will more precisely place the zero at -0.15
and will choose a loop gain equal to 0.01.
The resulting closed-loop step response plot is shown below demonstrating that the train engine is brought to speed smoothly and with zero steady-
state error for a constant speed command.

The control gains that have been chosen can then be applied to the Simulink model by clicking the Update Simulink Block Parameters button
under the Compensator Editor tab of the Control and Estimation Tools Manager window (see above). The simulation can then be run with this
newly tuned controller. Clicking on the Scope block for the train engine's velocity and selecting autoscale will produce a plot like the one shown
below.
Overall this response seems to meet our goals of bringing the train up to speed and to rest smoothly, while maintaining minimal steady-state error.
This response matches the result generated with the SISO Design Tool above because that analysis and the Simulink model used the exact same
linear model.
Cruise Control: Simulink Modeling
Contents
Physical setup and system equations

Building the model

Open-loop response

Physical setup and system equations


The model of the cruise control system is relatively simple. If it is assumed that rolling resistance and air drag are proportional to the car's speed, then
the problem is reduced to the simple mass and damper system shown below.

Using Newton's 2nd law, the governing equation for this system becomes:

(1)

where u is the force generated between the road/tire interface and can be controlled directly. For this example, let's assume that

m = 1000 kg
b = 50 N.sec/m
u = 500 N
Building the model
This system will be modeled by summing the forces acting on the mass and integrating the acceleration to give the velocity. Open Simulink and open
a new model window. First, we will model the integral of acceleration.

(2)

Insert an Integrator Block (from the Continuous library) and draw lines to and from its input and output terminals.

Label the input line "vdot" and the output line "v" as shown below. To add such a label, double click in the empty space just above the line.

Since the acceleration (dv/dt) is equal to the sum of the forces divided by mass, we will divide the incoming signal by the mass.
Insert a Gain block (from the Math Operations library) connected to the Integrator block input line and draw a line leading to the input of the
Gain block.

Edit the Gain block by double-clicking on it and change its value to "1/m".

Change the label of the Gain block to "inertia" by clicking on the word "Gain" underneath the block.

Now, we will add in the forces which are represented in Equation (1). First, we will add in the damping force.

Attach a Sum block (from the Math Operations library) to the line leading to the inertia Gain block.

Change the signs of the Sum block to "+-".

Insert a Gain block below the Inertia block, select it by single-clicking on it, and select Flip from the Format menu (or type Ctrl-F) to flip it
left-to-right.
Set the block's value to "b" and rename this block to "damping".

Tap a line (hold Ctrl while drawing) off the Integrator block's output and connect it to the input of the damping Gain block.

Draw a line from the damping Gain block output to the negative input of the Sum Block.

The second force acting on the mass is the control input, u. We will apply a step input.

Insert a Step block (from the Sources library) and connect it with a line to the positive input of the Sum Block.

To view the output velocity, insert a Scope block (from the Sinks library) connected to the output of the Integrator.
To provide an appropriate step input of 500 at time equal zero, double-click the Step block and set the Step Time to "0" and the Final Value to
"u".
You can download a model file for the complete system here, ccmodel.mdl.

Open-loop response
To simulate this system, first, an appropriate simulation time must be set.

Select Parameters from the Simulation menu and enter "120" in the Stop Time field. 120 seconds is long enough to view the open-loop
response.
The physical parameters must now be set. Run the following commands at the MATLAB prompt:

m = 1000;
b = 50;
u = 500;

Run the simulation (hit Ctrl-T or select Start from the Simulation menu). When the simulation is finished, double-click on the Scope and hit its
autoscale button. You should see the following output.

Observing the above, we would like to improve the response of the cruise control system. The model created here will be employed for controller
design and analysis within Simulink in the Cruise Control: Simulink Controller Design page.

Cruise Control: Simulink Controller Design


Contents
Extracting a linear model into MATLAB

Implementing PI control

Closed-loop response
In the Cruise Control: Simulink Modeling page we created a Simulink model of the cruise control system. You can recreate the model or download it
here. In this section, we will show how to implement a feedback controller in Simulink to meet the performance specifications for the system.

Extracting a linear model into MATLAB


A linear model of the system (in state space or transfer function form) can be extracted from a Simulink model into MATLAB. This is done through
the use of In1 and Out1 blocks and the MATLAB function linmod.

Replace the Step Block and Scope Block with an In1 and an Out1 block, respectively (these blocks can be found in the Ports & Subsystems
library). This defines the input and output of the system for the extraction process.

Save your file as "ccmodel.mdl" (select Save As from the File menu). MATLAB will extract the linear model from the saved model file, not from the
open model window. At the MATLAB prompt, enter the following commands:

m = 1000;
b = 50;
u = 500;
[A,B,C,D] = linmod('ccmodel')
cruise_ss = ss(A,B,C,D);
A =
-0.0500
B =
1.0000e-03
C =
1
D =
0

To verify the model extraction, we will generate an open-loop step response of the extracted transfer function in MATLAB. We will multiply the
numerator by 500 to simulate a step input of 500 N. Enter the following command in MATLAB.

step(u*cruise_ss)
Implementing PI control
In the Cruise Control: PID Control page a PI controller was designed with Kp = 800 and Ki = 40 to give the desired response. We will implement this
in Simulink by first containing the open-loop system from earlier in this page in a Subsystem block.

Create a new model window.

Drag a Subsystem block from the Ports & Subsystems library into your new model window.

Double-click on this block. You will see a blank window representing the contents of the subsystem (which is currently empty).

Open your previously saved model of the cruise control system, ccmodel.mdl.

Select Select All from the Edit menu (or Ctrl-A), and select Copy from the Edit menu (or Ctrl-C).
Select the blank subsystem window from your new model and select Paste from the Edit menu (or Ctrl-V). You should see your original
system in this new subsystem window. Close this window.

You should now see input and output terminals on the Subsystem block. Name this block "plant model".

Now, we will build a PI controller around the plant model. First, we will feed back the plant output.

Draw a line extending from the plant output.

Insert a Sum block and assign "+-" to it's inputs.

Tap a line of the output line and draw it to the negative input of the Sum block.
The output of the Sum block will provide the error signal. From this, we will generate proportional and integral components.

Insert an Integrator block after the Sum block and connect them with a line.

Insert and connect a Gain block after the Integrator block to provide the integral gain.

Label this Integrator "Ki" and assign it a value of "Ki".

Insert a new Gain block and connect it with a line tapped off the output of the Sum block.

Label this gain "Kp" and assign it a value of "Kp".


Now we will add the proportional and integral components and apply the sum to the plant.

Insert a Sum block between the Ki block and the plant model and connect the outputs of the two Gain blocks to the Sum block inputs.

Connect the Sum block output to the input of the plant block.
Finally, we will apply a step input and view the output with a Scope block.

Attach a Step block to the free input of the feedback Sum block.

Attach a Scope block to the plant output.

Double-click the Step block and set the Step Time to "0" and the Final Value to "u". This allows the input magnitude to be changed outside of
Simulink.
You can download our version of the closed-loop system model here.

In this example, we constructed a PI controller from fundamental blocks. As an alternative, we could have used a Transfer Function block (from the
Continuous library) to implement this in one step, as shown below.
You can download this model here.

Closed-loop response
To simulate this system, first, an appropriate simulation time must be set. Select Parameters from the Simulation menu and enter "10" in the Stop
Time field. The design requirements included a rise time of less than 5 sec, so we simulate for 10 seconds to view the output. The physical parameters
must now be set. Run the following commands at the MATLAB prompt:

m = 1000;
b = 50;
u = 10;
Kp = 800;
Ki = 40;

Run the simulation (hit Ctrl-T or select Start from the Simulation menu). When the simulation is finished, double-click on the scope and hit its
autoscale button. You should see the following output.
DC Motor Speed: Simulink Modeling
Contents
Physical setup

Building the model with Simulink

Building the model with Simscape

Physical setup
A common actuator in control systems is the DC motor. It directly provides rotary motion and, coupled with wheels or drums and cables, can provide
translational motion. The electric circuit of the armature and the free-body diagram of the rotor are shown in the following figure:

For this example, we will assume that the input of the system is the voltage source (V) applied to the motor's armature, while the output is the
rotational speed of the shaft d(theta)/dt. The rotor and shaft are assumed to be rigid. We further assume a viscous friction model, that is, the friction
torque is proportional to shaft angular velocity.
The physical parameters for our example are:

(J) moment of inertia of the rotor 0.01 kg.m^2


(b) motor viscous friction constant 0.1 N.m.s
(Ke) electromotive force constant 0.01 V/rad/sec
(Kt) motor torque constant 0.01 N.m/Amp
(R) electric resistance 1 Ohm
(L) electric inductance 0.5 H

In general, the torque generated by a DC motor is proportional to the armature current and the strength of the magnetic field. In this example we will
assume that the magnetic field is constant and, therefore, that the motor torque is proportional to only the armature current i by a constant factor Kt as
shown in the equation below. This is referred to as an armature-controlled motor.

(1)

The back emf, e, is proportional to the angular velocity of the shaft by a constant factor Ke.

(2)

In SI units, the motor torque and back emf constants are equal, that is, Kt = Ke; therefore, we will use K to represent both the motor torque constant
and the back emf constant.

Building the model with Simulink


This system will be modeled by summing the torques acting on the rotor inertia and integrating the acceleration to give velocity. Also, Kirchoff's laws
will be applied to the armature circuit. First, we will model the integrals of the rotational acceleration and of the rate of change of the armature
current.

(3)

(4)

To build the simulation model, open Simulink and open a new model window. Then follow the steps listed below.

Insert an Integrator block from the Simulink/Continuous library and draw lines to and from its input and output terminals.
Label the input line "d2/dt2(theta)" and the output line "d/dt(theta)" as shown below. To add such a label, double-click in the empty space just
below the line.

Insert another Integrator block above the previous one and draw lines to and from its input and output terminals.

Label the input line "d/dt(i)" and the output line "i".

Next, we will apply Newton's law and Kirchoff's law to the motor system to generate the following equations:

(5)

(6)
The angular acceleration is equal to 1 / J multiplied by the sum of two terms (one positive, one negative). Similarly, the derivative of current is equal
to 1 / L multiplied by the sum of three terms (one positive, two negative). Continuing to model these equations in Simulink, follow the steps given
below.

Insert two Gain blocks from the Simulink/Math Operations library, one attached to each of the integrators.

Edit the Gain block corresponding to angular acceleration by double-clicking it and changing its value to "1/J".

Change the label of this Gain block to "Inertia" by clicking on the word "Gain" underneath the block.

Similarly, edit the other Gain's value to "1/L" and its label to "Inductance".

Insert two Add blocks from the Simulink/Math Operations library, one attached by a line to each of the Gain blocks.

Edit the signs of the Add block corresponding to rotation to "+-" since one term is positive and one is negative.

Edit the signs of the other Add block to "-+-" to represent the signs of the terms in the electrical equation.
Now, we will add in the torques which are represented in the rotational equation. First, we will add in the damping torque.

Insert a Gain block below the "Inertia" block. Next right-click on the block and select Format > Flip Block from the resulting menu to flip
the block from left to right. You can also flip a selected block by holding down Ctrl-I.

Set the Gain value to "b" and rename this block to "Damping".

Tap a line (hold Ctrl while drawing or right-click on the line) off the rotational Integrator's output and connect it to the input of the
"Damping" block.

Draw a line from the "Damping" block output to the negative input of the rotational Add block.

Next, we will add in the torque from the armature.

Insert a Gain block attached to the positive input of the rotational Add block with a line.
Edit its value to "K" to represent the motor constant and Label it "Kt".

Continue drawing the line leading from the current Integrator and connect it to the "Kt" block.

Now, we will add in the voltage terms which are represented in the electrical equation. First, we will add in the voltage drop across the armature
resistance.

Insert a Gain block above the "Inductance" block and flip it from left to right.

Set the Gain value to "R" and rename this block to "Resistance".

Tap a line off the current Integrator's output and connect it to the input of the "Resistance" block.

Draw a line from the "Resistance" block's output to the upper negative input of the current equation Add block.

Next, we will add in the back emf from the motor.


Insert a Gain block attached to the other negative input of the current Add block with a line.

Edit it's value to "K" to represent the motor back emf constant and Label it "Ke".

Tap a line off the rotational Integrator's output and connect it to the "Ke" block.

Add In1 and Out1 blocks from the Simulink/Ports & Subsystems library and respectively label them "Voltage" and "Speed".

The final design should look like the example shown in the figure below.

In order to save all of these components as a single subsystem block, first select all of the blocks, then select Create Subsystem from the Edit menu.
Name the subsystem "DC Motor" and then save the model. Your model should appear as follows. You can also download the file for this system here,
Motor_Model.mdl. We use this model in the DC Motor Speed: Simulink Controller Design section.
Building the model with Simscape
In this section, we alternatively show how to build the DC Motor model using the physical modeling blocks of the Simscape extension to Simulink.
The blocks in the Simscape library represent actual physical components; therefore, complex multi-domain models can be built without the need to
build mathematical equations from physical principles as was done above by applying Newton's laws and Kirchoff's laws.

Open a new Simulink model and insert the following blocks to represent the electrical and mechanical elements of the DC motor.

Resistor, Inductor and Rotational Electromechanical Converter blocks from the Simscape/Foundation Library/Electrical/Electrical Elements
library

Rotational Damper and Inertia blocks from the Simscape/Foundation Library/Mechanical/Rotational Elements library

Four Connection Port blocks from the Simscape/Utilities library

Double-click on the Connection Port blocks to make the location of ports 1 and 2 from the Left and the location of ports 3 and 4 from the Right.
Connect and label the components as shown in the following figure. You can rotate a block in a similar manner to the way you flipped blocks, that is,
by right-clicking on the block then selecting Rotate Block from the Format menu.

Complete the design of the DC motor Simscape model by assigning values to the physical parameters of each of the blocks to match our assumed
values. To assign the necessary values, double-click on the Resistor, Inductor, Inertia, Rotational Damper, and Rotational Electromechanical
Converter blocks and enter the following parameters and associated units:

Resistance = R [Ohm]
Inductance = L [H]
Inertia = J [kg*m^2]
Constant of Proportionality = K [V/(rad/s)]
Damping coefficient = b [N*m/(rad/s)]

The Rotational Damper block serves to model the viscous friction of the motor. This type of friction model was chosen because it is linear. In most
cases real friction is more complicated than this. If you wish to employ a more complicated friction model, for instance to add Coulomb friction to
the model, then you may use the Rotational Friction block from the Simscape/Foundation Library/Mechanical/Rotational Elements library.
Also note that in the above you generated a DC Motor model from the individual mechanical and electrical aspects of the motor. The Simscape
library also includes a DC Motor block under the Simscape/SimElectronics/Actuators library. This block is used in the DC Motor Position: Simulink
Modeling section.

The physical parameters must now be set. Enter the following commands at the MATLAB prompt.

J = 0.01;
b = 0.1;
K = 0.01;
R = 1;
L = 0.5;

These values are the same ones listed in the physical setup section.

You can then save these components in a single subsystem. Select all of the blocks and then choose Create Subsystem from the Edit menu. You can
also change the subsystem block color by right-clicking on the block and choosing Format > Background Color from the resulting menu. This
subsystem block can then be used to simulate the DC motor.
In order to simulate the response of this system it is further necessary to add sensor blocks to the model to simulate the measurement of various
physical parameters and a voltage source to provide excitation to the motor. Furthermore, blocks are needed to interface Simscape blocks with
tradtional Simulink blocks since the Simscape signals represent physical quantities with units, while the Simulink signals are dimensionless numbers.
Add the following blocks to the model you just built to address these functions.

Current Sensor block from the Simscape/Foundation Library/Electrical/Electrical Sensors library

Controlled Voltage Source block from the Simscape/Foundation Library/Electrical/Electrical Sources library

Two PS-Simulink Converter blocks and a Solver Configuration block from the Simscape/Utilities library

Electrical Reference block from the Simscape/Foundation Library/Electrical/Electrical Elements library

Ideal Rotational Motion Sensor block from the Simscape/Foundation Library/Mechanical/Mechanical Sensors library

Mechanical Rotational Reference block from the Simscape/Foundation Library/Mechanical/Rotational Elements library

Three Out1 blocks and one In1 block from the Simulink/Ports & Subsystems library

The Ideal Rotational Motion Sensor block represents a device that measures the difference in angular position and angular velocity between two
nodes. In this case, we employ the block to measure the position and velocity of the motor shaft as compared to a fixed reference represented by the
Mechanical Rotational Reference block. You can leave the Initial angle of the Rotational Motion Sensor block as the default 0 radians.

The Current Sensor block represents another sensor, specifically it measures the current drawn by the motor. The ground for the electrical portion of
our system is defined by the Electrical Reference block.

The Controlled Voltage Source block serves as the power source for the motor where you can externally define the voltage signal by connecting an
input to the block.

The PS-Simulink blocks convert physical signals to Simulink output signals, while the Simulink-PS block conversely converts a Simulink input
signal to a physical signal. These blocks can be employed to convert the Simscape signals, which represent physical quantities with units, to Simulink
signals, which don't explicitly have units attached to them. These blocks, in essence, can perform a units conversion between the physical signals and
the Simulink signals. In our case, we can leave the units undefined since the input and output of each of the conversion blocks have the same units. In
general, the Simscape blockset is employed to model the physical plant, while the Simulink blockset is employed to model the controller.

The Solver Configuration block is employed for defining the details of the numerical solver employed in running the Simscape simulation. We will
use the default settings for this block.
Next, connect and label the components so that they appear as in the figure below. Double-click on the lines which are connected to the Out1 blocks
and label them "Current", "Position", and "Speed". Also double-click on the In1 block and label it "Voltage".

You can save these components in a single subsystem with one input and three outputs. Select all of the blocks and then choose Create Subsystem
from the Edit menu. Also label the subsystem and signals as shown in the following figure.
You can download the complete model file here, Motor_Model_Simscape.mdl, but note that you will need the Simscape addition to Simulink in order
to run the file.

Note that the two models generated above will behave equivalently as long as they are built using the same parameter values. The difference between
them is then only the ease with which they are built and interfaced with, and how transparent they are in presenting information to the user.

If you would like to actually run the models developed above and use them to simulate and develop control algorithms, you may continue on to the
DC Motor Speed: Simulink Control page.
DC Motor Speed: Simulink Controller Design
Contents
Extracting a linear model into MATLAB

Open-loop response

Closed-loop response with lag compensator

Closed-loop response with lead compensator

From the DC Motor Speed: Simulink Modeling page we generated two different DC motor models in Simulink. We will now employ these models
within Simulink to simulate the system response and design different approaches to control.

Extracting a linear model into MATLAB


A linear model of the system can be extracted from the Simulink model into the MATLAB workspace. This can accomplished employing the
MATLAB command linmod or from directly within Simulink as we will do here. We will specifically use the base Simulink model developed from
first principles shown below. You can download this model here, or you can refer to the DC Motor Speed: Simulink Modeling page to recreate the
model yourself.
Recall that the physical parameters have to be set if they have not previously been defined in the workspace.

J = 0.01;
b = 0.1;
K = 0.01;
R = 1;
L = 0.5;

We then need to identify the inputs and outputs of the model we wish to extract. First right-click on the signal representing the Voltage input in the
Simulink model. Then choose Linearization > Input Point from the resulting menu. Similarly, right-click on the signal representing the Speed
output and select Linearization > Output Point from the resulting menu. The input and output signals should now be identified on your model by
arrow symbols as shown in the figure below.
In order to perform the extraction, select from the menus at the top of the model window Tools > Control Design > Linear Analysis. This will cause
the Linear Analysis Tool to open. Within the Linear Analysis Tool window, the Operating Point to be linearized about can remain the default,
Model Initial Condition. In order to perform the linearization, next click the Linearize button identified by the green triangle. The result of this
linearization is the linsys1 object which now appears in the Linear Analysis Workspace as shown below. Furthermore, the open-loop step response
of the linearized system was also generated automatically.
The open-loop step response above is consistent with the response generated in the DC Motor Speed: System Analysis page The reason the responses
match so closely is because this Simulink model uses only linear components. Note that this process can be used extract linear approximations of
models with nonlinear elements too.

We will further verify the model extraction by looking at the model itself. The linearized model can be exported by simply dragging the object into
the MATLAB Workspace. This object can then be used within MATLAB in the same manner as an object created directly from the MATLAB
command line. Specifically, entering the command zpk(linsys1) in the MATLAB command window demonstrates that the resulting model has the
following form.

(1)

This model matches the one generated in the DC Motor Speed: System Modeling page. This can be seen by repeating the MATLAB commands given
below.

s = tf('s');
P_motor = K/((J*s+b)*(L*s+R)+K^2);
zpk(P_motor)
ans =

2
-------------------
(s+9.997) (s+2.003)

Continuous-time zero/pole/gain model.

Open-loop response
The open-loop step response can also be generated directly within Simulink, without extracting any models to the MATLAB workspace. In order to
simulate the step response, the details of the simulation must first be set. This can be accomplished by selecting Configuration Parameters from the
Simulation menu. Within the resulting menu, define the length for which the simulation is to run in the Stop time field. We will enter "3" since 3
seconds will be long enough for the step response to reach steady state. Within this window you can also specify various aspects of the numerical
solver, but we will just use the default values for this example.

Next we need to add an input signal and a means for displaying the output of our simulation. This is done by doing the following:

Remove the In1 and Out1 blocks.


Insert a Step block from the Simulink/Sources library and connect it with a line to the Voltage input of the motor subsystem.

To view the Speed output, insert a Scope from the Simulink/Sinks library and connect it to the Speed output of the motor subsystem.

To provide a appropriate unit step input at t=0, double-click the Step block and set the Step time to "0".

The final model should appear as shown in the following figure.

Then run the simulation (press Ctrl-T or select Start from the Simulation menu). When the simulation is finished, double-click on the scope and hit
its autoscale button. You should see the following output.
This response is identical to that obtained by MATLAB above using the extracted model. This is again to be expected because this Simulink model
includes only linear blocks.

Closed-loop response with lag compensator


In the DC Motor Speed: Root Locus Controller Design page a lag compensator was designed with the following transfer function.

(2)

To generate the closed-loop step response with this compensator in Simulink, we will begin with the "Motor_Model.mdl" file described above. We
will then put the lag compensator in series with the motor subsystem and will feed back the motor's speed for comparison to a desired reference.

More specifically, follow the steps given below:

Remove the Input and Output ports of the model.

Insert a Sum block from the Simulink/Math Operations library. Then double-click on the block and enter "|+-" for its List of signs where the
symbol "|" serves as a spacer between ports of the block.
Insert a Transfer Function block from the Simulink/Continuous library. Then double-click on the block and edit the Numerator coefficients
field to "[44 44]" and the Denominator coefficients field to "[1 0.01]".

Insert a Step block from the Simulink/Sources library. Then double-click on the block and set the Step time to "0".

Insert a Scope block from the Simulink/Sinks library.

Then connect and label the components as shown in the following figure

You can download our version of the closed-loop system model here, Motor_Model_lag.mdl.

Then run the simulation (press Ctrl-T or select Start from the Simulation menu). When the simulation is finished, double-click on the scope and hit
its autoscale button. You should see the following output.
This step response matches exactly the closed-loop performance observed in the DC Motor Speed: Root Locus Controller Design page where the lag
compensator was originally designed. Note that while we used the physics-based Simulink model developed in the DC Motor Speed: Simulink
Modeling page for simulating the closed-loop system, we could have equivalently used the Simscape version of the DC motor model.

Closed-loop response with lead compensator


We have shown in the above and in other pages of this example that the lag compensator we have designed meets all of the given design
requirements. Instead of a lag compensator, we could have also designed a lead compensator to meet the given requirements. More specifically, we
could have designed a lead compensator to achieve a similar DC gain and phase margin to that achieved by the lag compensator, but with a larger
gain crossover frequency. You can refer back to the DC Motor Speed: Frequency Domain Methods for Controller Design page for more details on the
design of the lag compensator, but the fact that the DC gains and phase margins are similar indicate that the responses under lag and lead control
would have similar amounts of error in steady state and similar amounts of overshoot. The difference in response would come in that the larger gain
crossover frequency provided by the lead compensator would make the system response faster than with the lag compensator. We will specifically
use the following lead compensator.

(3)

To see the precise effect of the lead compensator as compared to our lag compensator, let's modify our Simulink model from above as follows:

Disconnect the Step block and Scope block from the rest of the model.
Copy the blocks forming the closed-loop of the model: the Sum block, the Transfer Function block, and the DC Motor subsystem. Then paste
a copy of this loop below the original blocks.

Double-click on the Transfer Function block and edit the Numerator coefficients field to "[160000 5.6e6]" and the Denominator
coefficients field to "[1 1035]".

Insert a Mux block from the Simulink\Signal Routing library and connect the outputs of the two Motor subsystem blocks to the inputs of the
Mux and connect the output of the Mux to the Scope.

Connect the Step block to the Sum block of the original feedback system. Then branch off from this line and connect it to the Sum block of
the lead compensated system as well.

The Mux block serves to bundle the two signals into a single line, this way the Scope will plot both speed signals on the same set of axes. When you
are done, your model should appear as follows.
Running the simulation and observing the output produced by the scope, you will see that both responses have a steady-state error that approaches
zero. Zooming in on the graphs you can generate a figure like the one shown below. Comparing the two graphs, the purple response belonging to the
lead compensated system has a much smaller settle time and slightly larger, but similar, overshoot as compared to the yellow response produced by
the lag compensated system.
It is generally preferred that a system respond to a command quickly. Why then might we prefer to use the lag compensator even though it is slower
than the lead compensator? The advantage of the lag compensator in this case is that by responding more slowly it requires less control effort than the
lead compensator. Less control effort means that less power is consumed and that the various components can be sized smaller since they do not have
to supply as much energy or withstand the higher voltages and current required of the lead compensator.

We will now modify our simulation to explicitly observe the control effort requirements of our two feedback systems. We will do this by sending our
various signals to the workspace for plotting and further manipulation if desired. Specifically, delete the Scope and Mux blocks from your Simulink
model. Then insert four To Workspace blocks from the Simulink\Sinks library. Double-click on each of the blocks and change their Save format
from Structure to Array. Also provide a Variable name within each block that will make sense to you. You can then connect the blocks to the
existing model and label them as shown below. You can download our version of this Simulink model here, Motor_Model_leadlag.mdl.
Then change the simulation stop time to 1 second and run the model. The act of running the simulation will send to the MATLAB workspace a series
of arrays corresponding to the variables set-up in your model with the To Workspace blocks. Furthermore, the time vector used by that run of the
simulation is stored in the default variable tout. You can now plot the results of your simulation from the workspace. Enter the following code to see
how to specifically plot the control effort variables.

subplot(2,1,1)
plot(tout,ulag);
xlabel('time (seconds)')
ylabel('control effort (volts)')
title('Control Effort Under Lag Compensation')
subplot(2,1,2)
plot(tout,ulead);
xlabel('time (seconds)')
ylabel('control effort (volts)')
title('Control Effort Under Lead Compensation')

Examination of the above shows that the control effort required by the lead compensator is above 150,000 Volts, which is well above anything that
could be supplied or withstood by a typical DC motor. This exemplifies the tradeoff inherent between achieving small tracking error and keeping the
amount of control effort required small. Optimal control techniques have been developed to achieve an optimal balance between competing goals.
One such technique is explored in the Aircraft Pitch: State Space Methods for Controller Design page.
DC Motor Position: Simulink Modeling
Contents
Physical setup

Building the model with Simulink

Building the model with Simscape

Building the model through its LTI representation

Physical setup
A common actuator in control systems is the DC motor. It directly provides rotary motion and, coupled with wheels or drums and cables, can provide
translational motion. The electric circuit of the armature and the free-body diagram of the rotor are shown in the following figure:

The input to the system is the voltage applied to the motor's armature (V), while the output is the angular position of the shaft (theta).
The physical parameters for our example are:

(J) moment of inertia of the rotor 3.2284E-6 kg.m^2


(b) motor viscous friction constant 3.5077E-6 Nms
(Ke) electromotive force constant 0.0274 V/rad/sec
(Kt) motor torque constant 0.0274 Nm/Amp
(R) electric resistance 4 ohm
(L) electric inductance 2.75E-6H

The motor torque is proportional to the armature current i by a constant factor Kt as shown in the relation below.

(1)

The back emf, e, is proportional to the angular velocity of the shaft by a constant factor Kb.

(2)

In SI units, the motor torque and back emf constants are equal, that is, K = Kt = Ke.

Building the model with Simulink


This system will be modeled by summing the torques acting on the rotor inertia and integrating the rotor's angular acceleration to give the velocity,
and integrating the velocity to get position. Also, Kirchoff's laws will be applied to the armature circuit. First, we will model the integrals of the rotor
acceleration and of the rate of change of armature current shown below.

(3)

(4)

To build the simulation model, open Simulink and open a new model window. Then follow the steps listed below.

Insert an Integrator block from the Simulink/Continous library and draw lines to and from its input and output terminals.

Label the input line "d2/dt2(theta)" and the output line "d/dt(theta)" as shown below. To add such a label, double-click in the empty space just
above the line.
Insert another Integrator block attached to the output of the previous one and draw a line from its output terminal.

Label the output line "theta".

Insert a third Integrator block above the first one and draw lines to and from its input and output terminals.

Label the input line "d/dt(i)" and the output line "i".

Next, we will apply Newton's law and Kirchoff's law to the motor system to generate the following equations.

(5)

(6)
The angular acceleration is equal to 1 / J multiplied by the sum of two terms (one positive, one negative). Similarly, the derivative of current is equal
to 1 / L multiplied by the sum of three terms (one positive, two negative). Continuing to model these equations in Simulink, follow the steps given
below.

Insert two Gain blocks from the Simulink/Math Operations library, one attached to each of the leftmost integrators.

Edit the Gain block corresponding to angular acceleration by double-clicking on it and changing its value to "1/J".

Change the label of this Gain block to "Inertia" by clicking on the word "Gain" underneath the block.

Similarly, edit the other Gain's value to "1/L" and it's label to "Inductance".

Insert two Add blocks from the Simulink/Math Operations library, one attached by a line to each of the Gain blocks.

Edit the signs of the Add block corresponding to rotation to "+-" since one term is positive and one is negative.

Edit the signs of the other Add block to "-+-" to represent the signs of the terms in Kirchoff's equation.
Now, we will add in the torques which are represented in Newton's equation. First, we will add in the damping torque.

Insert a Gain block below the "Inertia" block, then select it by single-clicking on it. Next select Flip Block from the Format menu (reached
by right-clicking) to flip the block from left to right. You can also flip the selected block by holding Ctrl-I.

Set the Gain value to "b" and rename the block "damping".

Tap a line (hold Ctrl while drawing or right-click) off the first rotational Integrator's output (d/dt(theta)) and connect it to the input of the
damping Gain block.

Draw a line from the damping Gain output to the negative input of the rotational Add block.

Next, we will add in the torque from the armature.

Insert a Gain block attached to the positive input of the rotational Add block with a line.
Edit it's value to "K" to represent the motor constant and label it "Kt".

Continue drawing the line leading from the current Integrator and connect it to the Kt Gain block.

Now, we will add in the voltage terms which are represented in Kirchoff's equation. First, we will add in the voltage drop across the armature
resistance.

Insert a Gain block above the Inductance block and flip it left to right.

Set the Gain value to "R" and rename this block "Resistance".

Tap a line off the current Integrator's output and connect it to the input of the Resistance Gain block.

Draw a line from the Resistance Gain output to the upper negative input of the current equation Add block.

Next, we will add in the back emf from the motor.


Insert a Gain block and attach it to the other negative input of the current Add block with a line.

Edit it's value to "K" to represent the motor back emf constant and label it "Ke".

Tap a line off the first rotational Integrator's output (d/dt(theta)) and connect it to the Ke Gain block.

Now the model is built and we just need to add the voltage input and monitor the position output. We will insert In1 and Out1 ports from the
Simulink/Ports & Subsystems library as shown in the following figure so that we may save the motor model as a subsystem.
In order to save all of these components as a single subsystem block, first select all of the blocks, then select Create Subsystem from the Edit menu.
Name the subsystem "Motor_pos" and then save the model. Your model should appear as follows. You can also download the file for this system
here, Motor_Pos.mdl. We use this model in the DC Motor Position: Simulink Controller Design page
Building the model with Simscape
In this section, we alternatively show how to build the DC Motor model using the physical modeling blocks of the Simscape extension to Simulink.
The blocks in the Simscape library represent actual physical components; therefore, complex multi-domain models can be built without the need to
build mathematical equations from physical principles as was done above by applying Newton's laws and Kirchoff's laws.

Open a new Simulink model and insert the following list of blocks.

DC Motor block from the Simscape/SimElectronics/Actuators library

Current Sensor block from the Simscape/Foundation Library/Electrical/Electrical Sensors library

Controlled Voltage Source block from the Simscape/Foundation Library/Electrical/Electrical Sources library

Three PS-Simulink Converter blocks, one Simulink-PS Converter, and a Solver Configuration block from the Simscape/Utilities library
Electrical Reference block from the Simscape/Foundation Library/Electrical/Electrical Elements library

Ideal Rotational Motion Sensor block from the Simscape/Foundation Library/Mechanical/Mechanical Sensors library

Mechanical Rotational Reference block from the Simscape/Foundation Library/Mechanical/Rotational Elements library

Three Out1 blocks and one In1 block from the Simulink/Ports & Subsystems library

The DC Motor block models both the electrical and mechanical characteristics of the motor. Double-click on the block in order to assign numerical
values to the motor's physical parameters. We will specifically define the motor By equivalent circuit parameters as chosen from the Motor
Parameterization drop-down menu. Assign the various parameters the following variables and units. We will eventually define these variables at the
command line of the MATLAB workspace. Note that since the motor torque constant and the back emf constant are equal if the units are consistent,
we only need to define one of the two.

Armature resistance = R [Ohm]


Armature inductance = L [H]
Back emf constant = K [V/(rad/s)]
Rotor inertia = J [kg*m^2]
Rotor damping = b [N*m/(rad/s)]

The Ideal Rotational Motion Sensor block represents a device that measures the difference in angular position and angular velocity between two
nodes. In this case, we employ the block to measure the position and velocity of the motor shaft as compared to a fixed reference represented by the
Mechanical Rotational Reference block.

The Current Sensor block represents another sensor, specifically it measures the current drawn by the motor.

The PS-Simulink blocks convert physical signals to Simulink output signals, while the Simulink-PS block conversely converts a Simulink input
signal to a physical signal. These blocks can be employed to convert the Simscape signals, which represent physical quantities with units, to Simulink
signals, which don't explicitly have units attached to them. These blocks, in essence, can perform a units conversion between the physical signals and
the Simulink signals. In our case, we can leave the units undefined since the input and output of each of the conversion blocks have the same units. In
general, the Simscape blockset is employed to model the physical plant, while the Simulink blockset is employed to model the controller.

The Solver Configuration block is employed for defining the details of the numerical solver employed in running the Simscape simulation. We will
use the default settings for this block.

Next, connect and label the components so that they appear as in the figure below. Double-click on the lines which are connected to the Out1 blocks
and label them "Current", "Position", and "Speed". Also click on the In1 block and label it "Voltage".
We now need to define the parameters used in our simulation. Type the following commands at the prompt of the MATLAB command window.

R = 4;
L = 2.75E-6;
K = 0.0274;
J = 3.2284E-6;
b = 3.5077E-6;

You can save these components in a single subsystem with one input and three outputs. Select all of the blocks and then choose Create Subsystem
from the Edit menu. Also label the subsystem and signals as shown in the following figure.
You can download the complete model file here, Motor_Pos_Simscape.mdl, but note that you will need the Simscape addition to Simulink in order to
run the file.

Building the model through its LTI representation


You can also build the DC motor model in Simulink by importing one of the models we created in MATLAB in the DC Motor Position: System
Modeling page. In this page we specifically created a transfer function model and a state-space model, both of which may be imported. A zero-pole-
gain format model can also be imported. Recall the following commands used to build a state-space model of the DC motor in MATLAB.

A = [0 1 0
0 -b/J K/J
0 -K/L -R/L];
B = [0 ; 0 ; 1/L];
C = [1 0 0];
D = 0;

This model can then be imported using the LTI System block from the Control System Toolbox library as shown below. This figure demonstrates
how the model is defined by entering "ss(A,B,C,D)" into the LTI system variable cell, though the tf and zpk commands could also be employed.
Adding In1 and Out1 ports from the Ports & Subsystems library then creates the model shown below.
Note that all three of the models generated above will behave equivalently as long as they are built using the same parameter values. The difference
between them is then only the ease with which they are built and interfaced with, and how transparent they are in presenting information to the user.

DC Motor Position: Simulink Controller Design


Contents
Open-loop response

Extracting a linear sampled model into MATLAB

Implementing digital control in Simulink

Converting a continuous-time model to discrete-time within Simulink


In the DC Motor Position: Simulink Modeling section, we developed a Simulink model of the DC motor system using three different methods. You
can download one of these models here, Motor_Pos.mdl. In this section, we will employ this model within Simulink to simulate and design different
approaches to control. Specifically, we will explore the design of a digital control system.

Open-loop response

Begin with the above model saved as a subsystem and follow the steps given below.

Remove the In and Out ports.

Insert a Step block from the Simulink/Sources library and connect it with a line to the Voltage input.

To view the output position, insert a Scope from the Simulink/Sinks library and connect it to the Position output.

To provide an appropriate unit step input at t=0, double-click the Step block and set the Step time to "0".
The system should now appear as in the following figure.

In order to simulate this system, the details of the simulation must first be set. This can be accomplished by selecting Configuration Parameters
from the Simulation menu. Within the resulting menu, define the length for which the simulation is to run in the Stop time field. We will enter "0.2"
since 0.2 seconds will be long enough for the step response to reach steady state. Also in the Configuration Parameters dialog box, the numerical
solver employed in the simulation can be specified. Go ahead and change the Solver field from the default ode45 (Dormand-Prince) to the ode15s
(stiff/NDF) solver. Since the time scales in this example are very small, this stiff system integration method is more efficient than the default
integration method.
The physical parameters must now be set. Enter the following commands at in the MATLAB command window.
J = 3.2284E-6;
b = 3.5077E-6;
K = 0.0274;
R = 4;
L = 2.75E-6;

Then run the simulation (press Ctrl-T or select Start from the Simulation menu). When the simulation is finished, double-click on the scope and hit
its autoscale button. You should see the following output which goes unstable and obviously does not meet our design requirements. Note that this
response is consistent with the results we achieved from the MATLAB command line in the DC Motor Position: System Analysis page.

Extracting a linear sampled model into MATLAB


We will now extract a linear sampled version of this continuous-time model into the MATLAB workspace. The extraction of a sampled model can be
performed from the MATLAB command line using the command dlinmod, though it is preferrable to perform the extraction from directly within
Simulink as we will demonstrate here. We will use the model from above.

The first thing that we need to do is to identify the inputs and outputs of the model we wish to extract. First right-click on the signal representing the
Voltage input in the Simulink model. Then choose Linearization > Input Point from the resulting menu. Similarly, right-click on the signal
representing the Position output and select Linearization > Output Point from the resulting menu. The input and output signals should now be
identified on your model by arrow symbols as shown in the figure below.
In order to perform the extraction, select from the menus at the top of the model window Tools > Control Design > Linear Analysis. This will cause
the Linear Analysis Tool to open. Next follow the steps given below.

From the Linear Analysis Tool window, click the Options button. From the resulting window, change the sample time to "0.001" as shown
in the figure below. The rate conversion method can remain the default Zero-Order Hold.
Within the Linear Analysis Tool window, the Operating Point to be linearized about can remain the default, Model Initial Condition. In
order to perform the linearization/discretization, next click the Linearize button identified by the green triangle.

The result of this linearization/discretization is the linsys1 object which now appears in the Linear Analysis Workspace. This model can be
exported by simply dragging the object into the MATLAB Workspace.

This object can then be used within MATLAB in the same manner as an object created directly from the MATLAB command line. Specifically,
entering the command zpk(linsys1) in the MATLAB command window demonstrates that the resulting model has the following form.

(1)

Note that this model is identical to the model generated from the conversion performed in DC Motor Position: Digital Controller Design page. This
makes sense since the same sample time and discretization method were used, and because the original model was already linear.

To further verify the validity of the model extraction, we will generate an open-loop step response of the discrete-time transfer function in MATLAB.
Enter the following commands at the prompt of the MATLAB command window. You should see the following plot which is in agreement with the
output from the continous Simulink model evaluated above.

t = 0:0.001:0.2;
step(linsys1,t);
grid
The extracted discrete models can then be used within MATLAB for various analysis and controller design tasks. In the following, we directly
employ the Simulink model from above to simulate the implementation of a digital controller without explicitly discretizing the continuous-time
plant model.

Implementing digital control in Simulink


In the DC Motor Position: Digital Controller Design page a digital controller was designed with the following transfer function.

(2)
We can use this compensator to simulate the associated closed-loop digital control system in Simulink. Starting from the Simulink model we used
above for extraction, delete the Input and Output ports and add the following:

Two Zero Order Hold blocks from the Simulink/Discrete library

Discrete Zero Pole block from the Simulink/Discrete library

Sum block from Simulink/Math Operations library

Place one Zero Order Hold block on the input of the Motor_pos subsystem which is a continuous model of the plant. This Zero Order Hold blocks
converts a discrete-time signal to a stepwise-constant continuous signal. The other Zero Order Hold block is placed on the output of the Motor_pos
subsystem and serves to take discrete samples of the output signal of the plant. Edit the Zero Order Hold blocks such that the Sample time fields are
set to "0.001" (this is fast compared to the desired step response in the MATLAB tutorial).

Next edit the Discrete Zero Pole block to model the discrete controller transfer function described above. Specifically, edit the Zeros field to "[0.95
0.80 0.80]", the Poles field to "[-0.98 0.6 1]", the Gain field to "800", and the Sample time field to "0.001". Then label the block "Controller" and
resize it to view its entire contents.

Next, enter "|+-" to the List of signs field of the Sum block. The character "|" serves as a spacer between input ports. Now we need to set up the
simulation to observe the motor's position for a step input.

Attach a Step block to the positve input of the Sum block and attach a Scope block to the plant output.

Double-click the Step block and set the Step time to "0".

Finally, connect the blocks as shown below.


Before we can simulate the closed-loop system, we again need to set an appropriate simulation time. Select Configuration Parameters... from the
Simulation menu and enter "0.08" in the Stop time field. We choose this stop time in order to observe the system long enough to see if it satisfies the
0.04 seconds settling time requirement. If you have started a new session of MATLAB or skipped the open-loop response part of this example, then
the physical parameters for the simulation must be set again. Run the following commands at the MATLAB prompt if necessary.

J = 3.2284E-6;
b = 3.5077E-6;
K = 0.0274;
R = 4;
L = 2.75E-6;

Now the simulation can finally be run. Recall that this can be accomplished by pressing Ctrl-T or selecting Start from the Simulation menu. When
the simulation is finished, double-click on the scope and hit its autoscale button. You should see the following output.
From the above figure, it appears that the overshoot is less than 16% and the settling time is less than 0.04 seconds as required. This is consistent with
the analysis employed in designing the digital controller. We have not, however, assessed the response of the system with a disturbance present. A
step disturbance can be added in a similar manner to the way that the step reference was added as shown in the following figure. Sum the disturbance
between the controller and plant following the Zero Order Hold block since the disturbance signal is continous.
Within the model, set the disturbance Step time to occur at "0.03" seconds. Then re-run the simulation and observe the scope output as described
above. The resulting position graph should appear as shown below.
From inspection of the above, you can see that there is a slight bump beginning at 0.03 seconds due to the disturbance, but the system is able to reject
its effect and the steady-state error still goes to zero as required.

If you have not done so already, save your Simulink model. You can also download our version of this model here, Motor_Pos_cl.mdl.

Converting a continuous-time model to discrete-time within Simulink


In the above, we extracted a linear sampled model of our plant from our Simulink model into the MATLAB workspace using the Linear Analysis
Tool. We also, in effect, discretized the plant for the purposes of simulation using Zero Order Hold blocks within Simulink. In this section, we will
generate a discrete-time model of our plant without the use of the Zero Order Hold blocks. This approach offers a wider array of discretization
techniques than can be achieved through Simulink blocks, which are limited to Zero Order and First Order Hold. This is especially useful in
generating a digital controller from a continous design.

So far we have chosen to employ the first principles simulink model but we could have just as easily used the Simscape model or the LTI System
model. One thing to be careful of, however, is that if you were to use the Simscape model of the plant in the above, the physical Simscape signals
would need to be converted to dimensionless Simulink signals in order to interface with the Simulink blocks we employed. This process is described
in the DC Motor Position: Simulink Modeling page.

In the following, we will discretize the LTI System model which can be downloaded here, Motor_Pos_LTI.mdl, or you can create it yourself as DC
Motor Position: Simulink Modeling page.
Recall that the LTI System block imports a model from the MATLAB workspace. Therefore, you need to enter the following commands at the
command line where it is presumed that values have already been entered for the various physical parameters.

A = [0 1 0
0 -b/J K/J
0 -K/L -R/L];
B = [0 ; 0 ; 1/L];
C = [1 0 0];
D = 0;

Your model should appear as follows.

To discretize this model:

Remove the In1 and Out1 ports.

Click on Tools > Control Design > Model Discretizer and the LTI System block will turn red.
Enter a Sample time of 0.001 and leave the Transform method as Zero-order hold.

Then choose Discretize selected blocks from the Discretize menu.

The LTI model now is converted to discrete. Let's add a digital controller and simulate the closed-loop response of this model. Employ the same
controller we used above. The final model should appear as follows.
Simulate the model as we have done previously. The resulting position response should appear as follows.
Note the agreement with the closed-loop simulation results we found previously. This makes sense since the first principles model and the LTI
System block model are equivalent and both Simulink models used a zero-order hold type sampling to discretize the plant.

You can download our version of this model here, Motor_Pos_LTI_cl.mdl.

You might also like