Introduction To MBSD - Notes
Introduction To MBSD - Notes
Introduction To MBSD - Notes
Introduction to Model-Based
System Design
Lecture 1
2
MBD
• Model-Based-System Design re-engineers the
traditional development process from one which
is paper-based to one that uses an executable
model that is the repository for all information
about the concept, design, and implementation.
The model is used throughout the four stages of
development: Research, Design,
Implementation, and Verification & Validation. At
each stage of development the model is updated
and elaborated ensuring continuity and
traceability throughout the evolution of the
design.
3
What is Model-Based-System Design?
• In its most basic form, Model-Based-
System Design is the use of models to
describe the specifications
specifications, operation
operation, and
performance of a component or a system
of components.
• Instead of listing specification in a text
document, a model is used that
implements the specifications,
f operation,
and performance of components.
4
What is Model-Based-System Design?
• Models can be shared with other
engineers:
– Engineers do not have to generate their own
models from text specifications.
– Same model can be used by several
engineers at several different levels in the
design process.
– Component models can be used in larger
systems.
– Models supplied by manufacturers accurately
reflect the performance of their components.
5
Old Method – Text Documents
• Text documents are used to describe the
performance of a component.
• Example: 12V to 5 V DC-DC
DC DC Converter
– 12 V power is readily available in vehicle
environments.
– 5V supplies are needed to power the
Navigation/Infotainment system.
– Power conversion is less that 100% % efficient.
ff
6
Old Method – Text Documents
• Electrical Specifications
– Input Voltage: 9V to 18 V
– Output Voltage: 5V
– Output Ripple: 50 mV
– Output Current: 0A to 8A
– Efficiency: ≥ 86%
– Derating:
7
Old Method – Text Documents
• Thermal Specifications
– Case to Ambient Thermal Resistance:
1ОC/Watt
– Case to Sink Thermal Resistance
0.03ОC/Watt
– Heat Capacity: 300 J/ОC
– Heat Sink Thermal Resistance:
• 0.91
0 91 ОC/Watt (Natural Convection)
• 0.150 ОC/Watt (50 CFM Forced Air Convection)
• 0.105 ОC/Watt (100 CFM Forced Air Convection)
• 0.068 ОC/Watt (200 CFM Forced Air Convection)
8
Model-Based-System Design
• Create a model that implements all of
these specifications:
9
Model-Based-System Design
• This model can:
– Contain much more detail than written
specifications.
– Contain behavioral characteristics such as:
• Voltage cutback during over current event.
• Thermal cutback and power derating.
– Can be shared among engineers working in
different areas and at different levels of the
design process.
10
What is Model-Based-System Design?
• Model-Based-System Design allows us to
uses models throughout the entire design
process:
– Simulation using Simulink (SIL)
• Not real-time
• Develop detailed plant model.
• Develop a system controller.
11
What is Model-Based-System Design?
• Real-Time Simulations
– Determine how the systems responds in real-
time.
– Good for human-system interaction.
– Additional debugging.
12
What is Model-Based-System Design?
• Targeting
– Implement the controller developed and debugged in
SIL and Real-Time simulations on a hardware target
(embedded controller)
controller).
• Most logic errors have been removed.
• Errors occur if model is inaccurate.
– Use automatic Code Generation (Skip the computer
engineering guy!)
• Still need to know something about digital systems and
c oco t o e s
microcontrollers.
• Eliminates the errors introduced when involving an engineer
to manually program the controller.
• Allows the engineers with the physical understanding of the
system to do the logic development and “programming.”
13
What is Model-Based-System Design?
• Hardware in the Loop (HIL) Simulations
– Real-time.
– Controller implemented on our Target
Target.
– Plant implemented on a real-time system.
14
What is Model-Based-System Design?
• Hardware in the Loop (HIL) Simulations
– Same physical interface as in actual system.
– Smoke-free testing of the controller
controller.
– Tests:
• Controller logic.
• Controller speed and processing power.
• Physical interface.
15
What is Model-Based-System Design?
• Controller deployment
– Given accurate models and a consistent
interface, we can just plug in the controller to
our plant.
– It should work perfectly the first time. (Not)
– It should work reasonable well, but we will
notice that the plant model may have
inaccuracies.
inaccuracies
– Typically we will need to modify the plant and
controller to account for the differences.
16
What is Model-Based-System Design?
• Verification and Validation
– SIL, HIL, PIL are forms of V&V
– Design a set of repeatable tests
tests.
• Run tests, measure results.
• Determine pass/fail status.
• Collect Data
• Improve models.
– Repeat the same tests each time we make a
change to the controller or plant.
Introduction to Model-Based
Systems Design
Model-Based
Model Based Design of a
Motor-Generator System
18
19
20
Proportional Feedback
21
Model-Based Design Solution
• Create Plant and Controller Models
– Motor and Generator Models
– P and PI Controllers
• Simulate with Simulink
• Real-Time Simulations with xPC
• Implement Controller on Freescale
MPC55xx Real-Time Target
• Test
• Improve Model and Controller
• Repeat
22
Goal: Design
Embedded
Controller for
the System
Freescale
MPC55xx
Development
Board
Simulation Fallacy
• Simple system models are worthless
• You must start with:
– All component nonlinearities and limitations
– Every function the model will perform
Simulation Fallacy
• The first time we run a simulation of this
type the following will occur:
– It does not work
• Users have no idea why
– It has convergence errors, logic errors, or
improper component behavior
• Users have no idea why
– It runs but the output is obviously wrong
• Users
U h
have no id
idea why
h
27
Course Overview
• Model-Based Design for a small system
• Simulink Simulations
• Real-time simulations with xPC
• Implement controller on MPC5553 or MPC5554 target
• Hardware In The Loop Real-Time Simulations
• Test controller on real system
• Model Verification and Validation
• Design of Experiments to Collect Experimental Data on
Motor and Generator
• Model Refinement and Re-Verification
• Further Exploration of Alternate Control Methods as
Time Permits
Introduction to Model-Based
Systems Design
Lecture 2 : Model Building with Simulink
2
Presentation Outline
• Intro to Simulink via Unit Converter
• Model-Based System Design
• M d l Hierarchy
Model Hi h
• Plant Model – Motor
• Plant Model – Generator
• Plant Model – Shaft Encoder
3
Intro to SimXYZ
• Simulink is an extensive collection of
libraries which enable you to link specific
blocks to develop simulations
• Libraries include
– Mathematical operations
– Differential equations
– Continuous/discrete functions
– Scopes
– Many more!
4
Intro to SimXYZ
5
Intro to SimXYZ
• Click on the
Create New
Model Icon
• You should get a
new model
window.
• Save it as
unit_convert.mdl You might not
have these
Model name files
specified
here.
6
Intro to SimXYZ
7
Intro to SimXYZ
• Place mouse
over the
Constant output
port (>)
(>), left
click, and drag Constant Gain In
to the Gain input Out
port (>)
• A wire with an
arrow will link
th ttwo bl
the blocksk
• Link the Gain
and Display
blocks using the
same method.
8
Intro to SimXYZ
• Click on the
text Constant
and change it
to rpm
• Change the text
Gain to
rpm -> rad/s
• Right click on
the text
Display, select
Format, and
Hide Name
9
Intro to SimXYZ
10
Intro to SimXYZ * indicates changes to the
model since it was last saved.
• The value of the
gain is now K Æ the
block is not big
enoughg to display
p y
the actual value.
• Left click on the
block, then grab a
handle and drag it to
make the block
larger.
• Save your file.
• Note that the
asterisk on the
filename goes away
when it is saved.
* no longer here, indicating that
file was saved.
11
Intro to SimXYZ
12
Lecture 2 Exercise 1a
• Design a converter that converts a speed of 60 miles per hour to kilometers per hour.
Make the following format changes to your blocks:
• All text should be displayed in bold.
• Constant Block Properties:
– Block text changed to “Speed (mph)”
– Font: Arial 16
16.
– Text and block outline color is blue.
– The block has a drop shadow.
– Block fill color is yellow.
• Gain block properties
– Block text changed to “mph Æ kph”
– Font: Arial 12.
– Text and block outline color is red.
– Block fill color is light blue.
• Display block properties:
Demo___________
– Block text changed to “Speed (kph)”
– Font: Arial 18.
• You solution should look as shown:
•
13
Lecture 2 Exercise 1b
• Use Simulink to calculate how far a vehicle moving at 60
mph would travel in 100 seconds. Provide an answer in
both miles and in kilometers.
Demo___________
14
High-Level System
15
High Level System
Plant
Controller
Input Plant
Input
16
17
18
19
Generator
20
MBSD
• Before we tackle the plant, let’s build the
top-level model found on slide 15
• Ope
Open a newe model
ode file
eaand
d sa
save e it as
Lecture2_Model1.mdl
21
System Model Toggle the model
browser to show
the subsystems
22
System Model
• From Commonly Used Blocks, drag two
Subsystem Blocks into your model
• Rename
R th
the one subsystem
b t “C
“Controller,”
t ll ”
and the other “Plant”
23
System Model
Left-click here.
24
Plant Model
• Our plant is not very exciting – it has an
input and an output with nothing in
between
• Delete the arrow connecting the input and
output and add three more subsystems to
represent the generator, motor, and shaft
encoder
• Make your model look like the next slide
25
Plant Model Right click
Select Format
Select Flip Name
• Fantastic
Fantastic, you have got the pieces to build
the plant
• Let’s build a simple motor – left click on
Motor in the Model Browser
26
Motor
• The motor we are modeling is a Pacific
Scientific model 4VM62-020-4 with the
following name plate specs:
– Torque Constant: 30 Oz-in per Amp
– Max Current: 8 Amps
• Our driver will limit the motor to about 4
amps maximum.
• The max torque our motor will produce is
120 Oz-in.
27
Motor
• SimDriveline uses MKS units so we need
to convert our torque to Nm.
• The conversion factor is one Oz-In
Oz In =
0.007062 Nm.
• Note that the maximum torque of our
motor is 120 Oz-in = 0.85 Nm.
28
Plant Model - Motor
• Our motor will operate by
– Receiving a 0-100% max torque request from
the controller
– Multiplying this request with the motor’s max
rated torque (0.85 Nm)
• Drag a gain into the motor subsystem
– Rename the In1 to Torque Request
29
Plant Model - Motor
• We have created an ideal motor with
– Variable torque from 0 to max rated value.
– No rpm limits
limits.
– No energy conversion inefficiencies.
– No frictional losses.
– Torque is independent of rpm.
• This is a terriblyy inaccurate model, but it is
an easy to understand first step.
30
Plant Model - Motor
• Now we need to apply
the motor torque to a
drive line.
• Use
U Si SimDriveline
D i li
– A Simulink physical library
set for modeling dynamics
– Kinetics and kinematics
are built in
– Plug & Play!
• From the Simscape
library, go to
SimDriveline / Sensors
& Actuators and select
Torque Actuator
31
Plant Model - Motor
• Drag a Torque Actuator into the motor
model
– It converts a Simulink signal to a SimDriveline
signal
• Link the output of the Available Current
gain block to the input of the Torque
Actuator
SimDriveline Port –
can ONLY be used
with SimDriveline
blocks
32
Plant Model - Motor
• Since the SimDriveline port
can only be used with
SimDriveline blocks
– Delete the Out1 port in the
Motor subsystem
– Drag in a Connection Port
from the
SimDriveline/Utilities
library
– Right click on the Port,
select Format, and then
Flip Block
– Connect the Actuator to the
Port
– Rename the Port to Motor
Output
33
Plant Model - Motor
34
Plant Model - Motor
• Our motor model is done!
35
Lecture 2 Exercise 2
Modify the motor model to use the name
plate specifications for the motors and
generators used in the lab.
lab Use the
following items listed on the nameplate:
• Torque constant.
• Rotor Inertia.
• Max motor current is 6.3 amps. (Due to
current limits on the DC power supply.)
Demo___________
36
Plant Model
That’s inconvenient!
Having the port on the
right would be way
better
37
Plant Model - Motor
• Use the Model Browser to return to the Motor
subsystem and double click on the Connection Port
(Motor Output)
• Change the Port Location from left to right
• Return to the Plant subsystem and resize the Motor
subsystem block
38
39
40
41
Plant Model - Generator
• Effectively, the generator is a mechanical load to
the motor that is controlled by the electrical load.
• Since:
– The generator voltage is proportional to speed, and
– The resistor current is proportional to voltage, and
– The generator torque is proportional to current
• ÆThe generator mechanical load is proportional
to the g
generator speed.
42
Plant Model - Generator
• Our first generator model will model the
generator as a mechanical load that is
proportional to speed
speed.
• We will model the generator so that it
achieves a maximum load torque of 1 Nm
at 3000 rpm.
• There will be no user input for the load
torque. We will assume that a fixed
number of bulbs are turned on.
43
44
45
46
47
Inertia same as
the motor.
48
Lecture 2 Exercise 3
• Verify the operation of your
generator model.
• Copy the Generator
subsystem to a new model
model. Demo
Demo___________
49
50
Plant Model - Encoder
• Our final step is to read the shaft speed through
a shaft encoder
• We will use the SimDriveline Motion Sensor to
convertt the
th SimDriveline
Si D i li signal
i l tto a Si
Simulink
li k
signal
• Save your model
• Resave your model as Lecture2_Model3.mdl
• Click on the Shaft Encoder in the Model Browser
– Drag in a Connection Port
– Drag in the Motion Sensor from the Sensors &
Actuators library
51
Plant Model - Encoder
52
Plant Model - Encoder
53
Plant Model - Encoder
• Delete the In1 port
• Rename the Connection Port to Shaft
Input
• Drag in a Gain to convert rad/s to rpm
• Rename the Out1 port to Encoder Output
• Link everything together
54
Plant Model - Encoder
55
56
57
58
Environment
• We are just about ready to go but are
missing one thing
– Driveline Environment
• This enables Simulink to utilize the
SimDriveline blocks
• In the SimDriveline Solvers & Inertias
library,
y drag
g a Driveline Environment
block into your plant and connect to the
driveline
59
Environment
Necessary for all
SimDriveline models
Any Questions?
Introduction to Model-Based
Systems Design
Lecture 3: Controller Design and Testing
2
Presentation Outline
• Proportional Control
• System Diagnostics
• T ti
Testing
• Understand the operation of a proportional
controller
3
Proportional Control
4
Proportional Control
Amplifier error signal. Gain ≥ 0.
Error – Difference between
desired and actual response.
5
Getting Started
• It’s time to do a version switch
• Save your model.
• Save
S your model
d l again
i as
– Lecture3_Model1.mdl
6
Getting Started
7
Control Strategy
• Our plan is to implement a proportional (P)
controller based on system speed
– We would like the motor rpm to be held
constant relatively independent of the
mechanical load.
– This will be done by modifying the amount of
torque produced by the motor based on the
difference between the desired and actual
motor speed.
8
Whole System
• At the top level of your model, drag in a
Constant from the Commonly Used
Blocks library
– It will be the desired system speed
• Double click and set its value to 1800 rpm
• This will be a user input in the physical realization
(a knob).
9
Controller
• Open the Controller subsystem within the
Model Browser
– Rename Out1 to “Torque
q Signal”
g
– Rename In1 to “Desired rpm”
– Add a second In1 and rename it “Actual rpm”
– From Commonly Used Blocks, drag in a
• Sum
• Gain
• Saturation
10
Controller
11
Controller
12
Controller
• Double click on the
Saturation block
• Change the Upper and
Change to 1
L
Lower li it tto 1 and
limits d0
respectively
– This allows our torque Change to 0
request to go from zero
Make the second + a -
to max positive torque
– Our motor cannot
produce a negative
torque.
• Click OK
13
Controller
14
Controller
• The last thing to do is estimate the value
for the Gain block
– Usually classic control theory tells us this
• We’re not going to do this here.
– In many systems where we use Model-Based-
System Design, the systems are so
complicated that we do not have sufficient
models to do the classical analysis.
ÎUse common sense, then tune
15
Controller
• We are looking at the difference in between
desired and actual rpm
• For a gain of 1, if we are below the desired rpm
by 1 rpm, the controller will ask the motor for full
t
torque.
– That’s a bit excessive!
• For a gain of 1, if we are slightly above the
desired rpm, the torque will drop to zero.
– That’s a bit excessive!
– Could yield oscillations and broken shafts!
• As
A a starting
t ti point,
i t let’s
l t’ sett the
th gain
i to
t 0.01.
0 01
Î The rpm must be off by 100 rpm to get a full
torque signal
16
Top-Level Block Diagram
• Go back to the top level of your model and
connect everything.
17
Initial Condition
• We are just about ready to run our model.
• Left click on the Plant in the model browser
• Drag in an Initial Condition block from the
SimDriveline / Sensors & Actuators library
• Connect it to the driveline.
• Double click and give it a value of 0 rad/s (0 rpm)
• Click OK
• Note that without this block the initial speed
always start at zero. Using this initial condition
allows us to start the motor at a high rpm and then
see how it settles down to the desired rpm.
18
Initial Condition
19
System Diagnostics
• Before we run our model, we may want to
review the results in graph form.
• We will utilize a scope
• Process:
– Name all signals of interest
– Attach them to the scope
• Preliminary signals of interest
– Desired and actual rpm
20
Scope
• In the Model Browser, left click on the
Controller
• Right click on the signal line which
connects the Desired rpm port to the sum
• Select Signal Properties from the menu.
• Change the Signal Name to Desired_rpm
• Click the OK button.
button
21
Scope
22
Scope
• Repeat for the Actual rpm signal line,
renaming it Actual_rpm
23
Scope
• Now we need to create a viewer and
attach the signals.
• Right
g cclick
c oon the
e Desired
es ed_rpm
p ssignal
g a line.
e
• (1) Select Create & Connect Viewer, (2)
select Simulink, then (3) select Scope,
from the menus.
• Congratulations – you have created a
scope that display a single signal
signal,
Desired_rpm.
24
Scope Right-click on this
signal line.
25
Scope
• Now we need to display the actual rpm on
the same scope and on the same axis.
• Right click on the Actual_rpm
Actual rpm signal line
and select Connect to Existing Viewer,
then select Scope, then select Axis1.
26
Scope
27
Scope
• You will notice little glasses on your
model.
• These glasses indicate that the associated
signal is being display on a scope.
28
Scope
• Typically a scope will only display the last
7500 points of a simulation.
• We are not sure how many points our
simulation will have, so we will change this
setting.
• Click on the Parameters button in the
scope window as shown next.
• Select the History tab and uncheck the
option as shown.
29
Scope
History tab selected.
30
Execution
• We can now run our model.
• Before doing so, how should our system
respond?
p
– When the rpm is well below 1800 rpm, the
motor should apply a large torque to the
system.
• The motor should quickly approach 1800 rpm.
– At close to 1800, the motor torque is reduced
and the rpm should hold close to 1800 rpm.
– Let’s see if our simple system and simple
controller behave as expected.
31
Execution
• Click the Start Simulation button
Start Simulation button
32
Execution
Actual rpm never
• Observe the Scope… reaches Desired rpm.
Click on
binoculars
BAM!
33
Model Problems
• The motor speeds up very quickly. Why?
• The motor speed never reaches the
desired rpm
rpm. Why?
34
Lecture 3 Exercise 1
The motor cannot reach the desired speed of 1800 rpm.
We would like to find out why.
1. Change
g the scopep yy-axis so that the range
g is 0 to 2000
by default.
2. Modify the scope so that it displays 4 plots in the same
window
3. Display following signals:
1. Desired and actual rpm (already done).
2
2. Controller torque requested
requested.
Demo___________
3. Motor Torque
4. Generator Torque
4. Determine why the motor cannot reach the desired
speed and fix it.
35
System Observations
• The system goes from 0 to 1800 rpm in
about 6 ms.
36
System Observations
• A 6 ms step response seems quite fast for
this system.
• The motors are specified as ultra-low
ultra low
inertia motors, so this might be
reasonable.
• We should figure out a way to measure
the inertia.
• Such a small inertia will make the system
hard to control.
37
Motor Step Response
•0 to 99% takes about 6
ms (Δx = 6.080 ms)
⎛ 1000rpm ⎞
Δrpm = Δy⎜⎜ ⎟⎟
Δy
⎝ 2.5V ⎠
⎛ 1000rpm ⎞
= (7.18 V )⎜⎜ ⎟⎟ Δx
⎝ 2. 5 V ⎠
= 2872 rpm
With this fast step response, the response of the motor on slide 34 seems
reasonable.
38
Model Testing and System
Comprehension
• Observe the step response… Approaches
Click on desired rpm
binoculars
BAM!
Starts at IC
39
Issues
• Note that we have but approached the desired
rpm but we don’t seem to achieve it – why?
• Because this is a p
proportional
p control method
and the error signal times the gain yields the
torque necessary to drive the motor!
• Also note that 4 seconds of simulation time is
not needed.
g the simulation end time to 0.05 seconds
• Change
as shown next:
40
Simulation Time
Changed to 0.05 seconds.
41
Simulation Time
• Rerun the simulation and observe the
results:
42
Verification
• Let’s now make sure our system behaves
as expected
• Perform the following tests
tests, write down
what you think should happen, and verify
that it does
43
44
45
Lecture 3 Demo 1
Verification – Controller Gain
• Test 3 - Set controller gain to 0.001
– Steady state error (rpm) __________________
– Steady state stability __________________
• Test 4 – Set controller gain to 0.01
– Steady state error (rpm) __________________
– Steady state stability __________________
• Test 5 – Set controller gain to 0.1
– Steady state error (rpm) __________________ Demo
Demo___________
– Steady state stability __________________
• Test 6 – Set controller gain to 1
– Steady state error (rpm) __________________
– Steady state stability __________________
46
47
Proportional Control
Amplifier error signal. Gain ≥ 0.
Error – Difference between
desired and actual response.
48
Verification – Controller Gain
Gain = 1
Gain = 0.1
49
Verification – Controller Gain
Gain = 0.001
Gain = 0.01
Gain = 0.1
Gain = 1
50
51
MBSD
• This is why we do MBSD
– Understand a complex system using simple
components
– Understand effect of controller and
components / loads on system response
– Size components to within the ballpark
– Identify model shortcomings for future
improvement
• Good job!
53
Outline
• Motor
– Torque will be a function of rpm
• Generator
– L
Loadd ttorque can be
b changed
h d by
b changing
h i the
th number
b off light
li ht
bulbs.
• Friction
– Will be added via a clutch
• MPC555x
– Signals will be scaled accordingly
54
Getting Started
• It’s time to do a version switch.
• Save your model.
• Save
S your model
d l again
i as
– Lecture3_Model2.mdl
55
Improved Motor
• We will improve the motor model by making the
motor torque a function of motor rpm.
• Use the same method used p previouslyy to
measure the motor rpm.
• Use a lookup table to implement the rpm
dependence of the motor.
• Obtain a lookup table from the manufacturer.
• Later on we will design an experiment and
measure the actual torque curve of the motor.
56
Improved Motor Model
• The following torque curve was obtained
from the manufacturer. (Not really, but
we’llll pretend
we pretend.))
Rpm Torque (Nm)
0 0.4
1000 0.4
2000 0.3
3000 0.2
4000 0
57
Motor Model
• Now that we have our motor torque curve
data, we can use it in our model.
• We will use a 1
1-D
D look up table
table.
• Our motor model presently has a constant
torque curve:
58
59
60
61
Motor Model
• When you click the OK button, the torque
curve will be displayed on the lookup table
block
block.
62
Motor Model
• We need to measure the motor speed and
convert the units from rad/sec to rpm.
• We have already done this with a shaft
encoder subsystem.
• We can copy the shaft encoder subsystem
and then paste it inside the motor model.
• Finally, we will feedback the rpm value to
the table.
63
Motor Model
64
Lecture 3 Exercise 2
• Verify the operation of Demo___________
your motor model.
• Copy the Motor
subsystem to a new
model.
• Generate a plot of
motor torque versus
shaft rpm.
• You should obtain a plot
as shown:
• You may need to add a
part called SimDriveline
Env to get your
simulation to run.
65
Verification - Motor
• We have made a simple change to our
model – let’s make sure it operates as we
expected
expected.
• Run the following experiments and
observe the behavior. We should see
similar results as in the previous
simulation.
• Set the shaft rpm initial condition back to
zero.
66
Verification - Motor
• To verify the motor, we should really
observe the torque versus speed.
• We need to add a torque sensor and then
plot it on our graph.
• We will create a new scope with two plots.
• To create a new scope, we use the same
procedure we used earlier
67
Adding a Scope
• In the first plot, we wish to display the desired
and actual rpm.
• To create a new scope, p , right
g click on the signal
g
you display (Desired_rpm), and then select
Create & Connect Viewer, then Simulink, and
then Scope from the menu. This will display
signal Desired_rpm on the scope.
• To add a second trace to the graph, right click
on the second signal you wish to display
(Actual_rpm), select Connect to Existing
Viewer, then Scope1, then Axis1 from the
menus.
68
Verification - Motor
• We now have two scopes for our model
called “Scope” and “Scope 1.”
• “Scope”
Scope has 4 plots (probably) that we
created in exercise 1.
• “Scope1” has a single plot. We would like
to add a second plot.
• Click on the Parameters button in the
Scope1 window as shown next.
• Select the General tab and set the
number of axes to 2.
69
Scope Settings
Number of axes
specified as 2.
70
Motor Model
• We must now add a torque sensor.
• Find a part called Torque Sensor located
in the Simscape / SimDriveline / Sensors
& Actuators library.
• Use a terminator block as shown (Simulink
/ Commonly Used Blocks library) to
terminate the signal.
• Label the Signal as “Motor Torque”
71
Motor Model
72
Motor Model
• We now want to add this trace to Axis 2 of
Scope1.
• Right-click
Right click on the Motor Torque signal line
and select Connect to Existing Viewer,
Scope1, and then Axis 2.
73
Motor Model
• One last improvement we
will make is to guarantee
that the motor cannot
output a negative torque.
(Because our DC motor
controller does not have a
brake.)
• Add a saturation part as
shown and set its limits to
0 and inf.
74
Motor Model
Saturation part
added here.
75
Motor Model
• We now have a slightly better motor model
than before.
• This motor follows a torque curve and
cannot output a negative torque.
• If we had more time, we would continue to
make improvements to the model, but not
here.
• We will now test the model to make sure
the improvements we have made work as
expected.
76
Motor Testing
• When we run a simulation, we should see
the torque fall off as the motor speeds up.
• Run the following g
tests.
• Compare to previous
results.
• See if our model
behaves as expected.
expected
• For all tests, set the
feedback gain to
0.01.
77
Verification – Motor IC
• Test 1 - Set IC to 0 rad/s, all else constant
– Old Model _rpm starts below, ramps up___
– New Model __________________________
• Test 2 – Set IC to 250 rad/s, all else constant
– Old Model __ rpm starts above, ramps down_
– New Model __________________________
• Make sure you observe the torque and see
that the motor behaves correctly.
• Observe that the motor torque is zero if the
motor speed is to high.
78
79
Lecture 3 Demo 2
Verification – Feedback Gain
• Test 4 - Set controller gain to 0.001 Old Model New Model
– Steady state error (rpm) ___________ ___________
– Torque Signal ___________ ___________
– Steady state stability ___________ ___________
• Test 5 – Set controller gain to 0.01
– Steady state error (rpm) ___________ ___________
– Torque Signal ___________ ___________
– Steady state stability ___________ ___________
• Test 6 – Set controller gain to 0.1
– Steady state error (rpm) ___________ ___________
– Torque Signal ___________ ___________
– Steady state stability ___________ ___________
• Test 7 – Set controller gain to 1
– Steady state error (rpm) ___________ ___________
– Torque Signal ___________ ___________
– Steady state stability ___________ ___________
Demo___________
80
Verification - Motor
• Our model seems to be operating as
expected (or else do not contuinue)
– When we observe the torque signal
signal, it is easy
to see that the system oscillates at high gain!
81
82
Improved Generator
Product added to multiply
by the number of bulbs. Original value was 1. Changed
to 1/6 for same load as before
Bulb load. Can range from when we have 6 bulbs.
0 to 6 bulbs.
83
Improved Generator
Part added so that we can only
Saturation part with limits have integer values of the
set from 0 to 6. number of bulbs. Part name
Rounding Function. Library
Simulink / Math Operations.
84
Improved Generator
• Since we added a new Simulink port to the
generator model, we will need to add a
port to the plant model as well.
85
Improved Generator
• At the top level we need to add a constant
that will be used to specify the number of
bulbs.
86
Verification - Generator
• We have made a simple change to our model –
let’s make sure it operates as we expected
• Run the followingg experiments
p and ensure that
we get the same results as with our previous
motor improvement
• Set the light bulb load to 6 bulbs. This should be
the same as our previous experiments.
• Set the desired rpmp is 1800 and the
proportional gain to 0.01.
87
Lecture 3 Demo 3
Verification – Generator IC
• Test 1 - Set IC to 0 rad/s, all else constant
– Old Model __________________________
– New Model __________________________
• Test 2 – Set IC to 250 rad/s, all else constant
– Old Model __________________________
– New Model __________________________
• Th
These results
lt should
h ld matcht h our previous
i
simulations since 6 bulbs is equivalent to
what we did previously.
Demo___________
88
89
Lecture 3 Demo 4
Verification – Feedback Gain
• Test 4 - Set controller gain to 0.001 Old Model New Model
– Steady state error (rpm) ___________ ___________
– Torque Signal ___________ ___________
– Steady state stability ___________ ___________
• Test 5 – Set controller gain to 0.01
– Steady state error (rpm) ___________ ___________
– Torque Signal ___________ ___________
– Steady state stability ___________ ___________
• Test 6 – Set controller gain to 0.1
– Steady state error (rpm) ___________ ___________
– Torque Signal ___________ ___________
– Steady state stability ___________ ___________
• Test 7 – Set controller gain to 1
– Steady state error (rpm) ___________ ___________
– Torque Signal ___________ ___________
– Steady state stability ___________ ___________
Demo___________
90
Verification
• Our generator model works as expected
for 6 bulbs. (If not, fix it.)
• Since we have a variable load load, we can
now observe the affect of changing the
load on the simulation.
• Next, we will run some tests while varying
the load.
• For all tests set the gain to 0.01, the
desired rpm to 1800, and the initial
condition for the rpm to 0.
91
Lecture 3 Demo 5
Verification – Feedback Gain
• Test 1 - Set number of bulbs to 0
– Steady state error (rpm) ___________________________
– Torque Signal ___________________________
• Test 2 - Set number of bulbs to 1
– Steady state error (rpm) ___________________________
– Torque Signal ___________________________
• Test 3 - Set number of bulbs to 2
– Steady state error (rpm) ___________________________
– Torque Signal ___________________________
• Test 4 - Set number of bulbs to 3
– Steady state error (rpm) ___________________________
– Torque Signal ___________________________
• Test 5 - Set number of bulbs to 4
– Steady state error (rpm) ___________________________
– Torque Signal ___________________________
Demo___________
92
Lecture 3 Demo 6
Verification – Feedback Gain
• Test 1 - Set number of bulbs to 5
– Steady state error (rpm) ___________________________
– Torque Signal ___________________________
• Test 2 - Set number of bulbs to 6
– Steady state error (rpm) ___________________________
– Torque Signal ___________________________
Demo___________
93
Improved Model - Generator
• Right now our generator is pretty much a black
box that creates a load torque that is
proportional to motor rpm.
• Lets try to do a similar model that relates a bit
more to the physical components in our system.
– The generator produces a voltage that is proportional
to the generator speed.
– This voltage is applied to the light bulbs, and the
bulbs draw current proportional to the voltage applied
across them (Ohm’s Law).
– The current is supplied by the generator.
– To supply the current, the generator produces a
torque that opposes its direction of motion.
94
Improved Generator Model
• This model is actually a combination of
many of the previous models we have
already built
built.
• Before continuing:
– Save your model.
– Save your model again as
Lecture3_Model4.mdl
95
Improved Generator Model
96
Improved Generator Model
Overall bulb
resistance. When we have equal resistors in parallel, the overall
resistance is the resistance of a single element divided by
the number of elements.
97
Improved Generator Model
Generator voltage
is 24 V when the
rpm is 3500 .
98
Improved Generator Model
Apply torque to
Convert the torque oppose the
from Oz-in to Nm. direction of rotation.
99
Improved Generator Model
This generator model has a bad flaw. Can you find it and fix it.
You might not notice until you run a few simulations.
100
101
Lecture 3 Demo 7
Verification – Feedback Gain
• Test 1 - Set number of bulbs to 0
– Steady state error (rpm) ___________________________
– Torque Signal ___________________________
• Test 2 - Set number of bulbs to 1
– Steady state error (rpm) ___________________________
– Torque Signal ___________________________
• Test 3 - Set number of bulbs to 2
– Steady state error (rpm) ___________________________
– Torque Signal ___________________________
• Test 4 - Set number of bulbs to 3
– Steady state error (rpm) ___________________________
– Torque Signal ___________________________
• Test 5 - Set number of bulbs to 4
– Steady state error (rpm) ___________________________
– Torque Signal ___________________________
Demo___________
102
Lecture 3 Demo 8
Verification – Feedback Gain
• Test 1 - Set number of bulbs to 5
– Steady state error (rpm) ___________________________
– Torque Signal ___________________________
• Test 2 - Set number of bulbs to 6
– Steady state error (rpm) ___________________________
– Torque Signal ___________________________
Demo___________
103
Verification - Generator
• Conclusions
– We have slowly improved the models to make
them more physically realistic.
– Simple models can produce good results and
help us understand our physical system and
help control strategy development.
104
Lecture 3 Problem 1
• Measure the step response of the motor so that we can
verify the quick response of the motor. You should obtain
a plot similar to the one shown below.
Complete___________
p ___________
105
Lecture 3 Problem 2
• Capacitor Car – Description on next page.
Grade___________
___________
One of the systems we will be modeling in this course is a capacitor-powered electric car. (We
may also look at a spring powered car as well.) In this homework, we will begin developing the
models for the capacitor and the electric motor. Create models for the following components:
Capacitor:
The amount of charge that a capacitor stores in coulombs is q. The equation that governs the
amount of charge stored by the capacitor is q = CV, where C is the capacitance in Farads, and V
is the capacitor voltage. We add or remove charge from the capacitor with electric current. If the
current is positive, we will add charge to the capacitor and increase the stored charge and the
capacitor voltage. If the current is negative, we remove charge and decrease the stored charge
and capacitor voltage. The charge added or removed, Δq, is equal to the integral of the current,
∆ . Your model should have the following parameters:
Inputs: Capacitor current.
Outputs: Capacitor voltage.
Parameters: Initial capacitor voltage, capacitance in farads. (Constants)
Test your model by showing that the capacitor obeys the equation using a sine wave
input current of 1 amp amplitude and a 1 Farad capacitor.
Electric Motor:
A lossless DC electric motor obeys the following equations.
• The torque is equal to the torque constant K times the motor current, where the
torque is in Newton-meters, the current is in amps, and the torque constant has units of
Nm/amp.
• The motor back emf (voltage) is equal to the motor speed ω in rad/sec times the back emf
constant K which has units volts/(rad/sec), Vemf .
Note that if the value of K has the same numerical value in both equations, we obtain the
equation for a lossless electromechanical energy converter, , where electrical power
equals mechanical power. To calculate the motor current, we take the applied voltage minus the
back emf, and divide it by the motor winding resistance, .
Test your motor model by applying a constant voltage of 24 V and no mechanical load (you will
still need the ENV part from the SimDriveline libraries. You should observe a spike of current at
startup when the motor speed is zero. As the motor speeds up, you will see the current go to zero
as the motor reaches steady state. Use the following motor parameters.
K=0.01 V/(rad/sec) = 0.01 Nm/Amp.
Inerita=1.5e-3 kg·m2
Winding resistance=2 Ohms.
Applied Voltage = 24 V
You should see the current spike up to 12 Amps and the motor should speed up to
System test: Hook up your capacitor model to your motor model. Give the capacitor an initial
voltage of 12 V. Use the SimDriveline clutch to apply a constant frictional force to the motor.
Run the system until the capacitor discharges to zero. Show that the energy stored in the
capacitor equals the energy dissipated by the friction clutch plus the energy dissipated by the
series resistance. Use the controllable friction clutch in the SimDriveLine libraries. Specify a
clutch pressure of 1 and use the settings below for the clutch:
Introduction to Model-Based
Systems Design
Lecture 3A: Step Response,
Response Data
Collection, and xPC
2
System Observations
• In Lecture 3, we noticed that the motor had a 0%
to 99% step response time of about 6 ms.
• This will cause us difficulties in the future.
• Problem
P bl 1:
1
– It will require a small integration step size during
Simulink simulations. You may have noticed this
already.
– A small step size will take more time to complete a
simulation.
– For us, this is not that great of a limitation because
our model is fairly simple.
3
System Observations
• Problem 2:
– When we simulate a fast system in real time,
a small fixed integration step size is required.
– Even though we have a simple model, it will
require such a small fixed step size that our
real-time targets are not fast enough to run
the model.
4
System Observations
• Problem 3:
– The system responds so quickly to a step change,
y
that we can not observe system behavior visually.
y
– This is mostly an educational restriction because
we want you to see overshoot, undershoot, and
ringing as the controller gains are changed.
– If the system responds in 6 ms, students will not
y
be able to see the system’s dynamic
y response.
p It
would be possible to see the response with a
scope, but we want to see the response on our
real-time system.
5
System Observations
• Problem 4:
– It will be difficult to control a plant that
responds this quickly with the MPC555x
microcontrollers available in the lab.
– Our controllers are limited to a minimum fixed
step size of 1 ms.
ÎIt is difficult to control a plant that has a time
constant of about 2 ms with a controller that
has a response time of 1 ms.
– This is our greatest limitation.
6
System Limitations
• If the motors do indeed respond as fast as
our simulations indicate, the controller
hardware available in the lab will not be
fast enough ton the feedback control
method.
• We will either need to modify the plant or
purchase new and more expensive
microcontroller targets.
• Both of these solutions are expensive and
time consuming.
7
System Limitations
• Before we go to the expense of modifying the plant
or purchasing new equipment, we will verify that the
motors do indeed have this fast of a response.
• We will measure the step response of the motors.
• In lecture 3, we presented a slide that showed the
step response measured using an oscilloscope.
• We never actually set up and ran this experiment.
Some one jjust told us they
y measured the stepp
response and the results were presented.
8
System Limitations
• Here we will set up an experiment to:
– Send the motor a step input.
– Measure the system step response using a
real-time computer system running xPC.
– Write a Matlab post processing function to
calculate the time constant from the
measured data.
– Determine a course of action to mitigate the
problem.
9
Lecture Outline
• Review system step response and observe
problems in the model.
• Setup a real
real-time
time target using xpcexplr
• Learn how to run xPC on a real-time target.
• Setup A/D and D/A blocks using xPC on a
Speedgoat real-time target.
• Run the Step response and collect data
data.
• Transfer the data to the host PC and analyze
the data.
10
Model Review
• We will start with the last model generated in
lecture 3. This has been provided to you as
Lecture3A Model0 mdl
Lecture3A_Model0.mdl.
• Save the model as Lecture3A_Model1.mdl.
• The model is shown below:
11
Model Review
• The controller has a feedback gain of 0.01:
12
Model Review
• We see that we are using a variable step
solver and the maximum step size is set to
Auto:
Variable-step size solver selected.
Solver selected.
13
Solvers
• A variable step solver uses a variable size time step
to perform the integration and solve the differential
equations.
• When the system response changes slowly with
time, a variable-step size solver increases the
integration step size so that fewer integration steps
are required to complete the simulation.
– This requires less computation and allows the simulation to
run faster.
f t
• When the system encounters an area where things
change quickly, the solver reduces the time step so
that faster dynamics are simulated accurately.
14
Solvers
• Our motor-generator system is a good application for a
variable-step solver.
• Usually we change the speed or number of bulbs infrequently.
• During the times when the speed does not change or the bulb
load is not changed, the solver can take a large tikme step.
• When we change the requested speed or the bulb load, we
usually ask for a step change. Î When we change the
number of bulbs, we introduce a step change in the load. We
cannot gradually increase the number of bulbs from say 1 to 2
because we must turn on the bulbs in discrete amounts
amounts. (We
cannot turn on 1.5 bulbs.)
• A step change in the request speed or bulb load introduces a
step change into the system. The variable step solver will
reduce the time step to accurately simulate the system.
15
Solvers
• We also note that the simulation parameters
specify that the max time step is set to auto.
• This means the solver can increase the time step p
to as large a value as it desires.
• We will see later that the discrete intervals at
which a microcontroller can change its output
effectively adds phase delay into the system. This
delay can cause the system to oscillate.
• The larger the simulation time step, the larger the
delay.
16
Solvers
• We also note that the simulation parameters specify that
the min time step is set to auto.
• This means that the solver can make the time step as
small as it wants to
to.
• This could result in very long simulation times.
• When the step size becomes small, you will notice:
– The simulation appears to hang at a certain spot because the time
step is so small. The simulation is still running, but the time step is
so small that the simulation appears to not be making any progress.
– Simulink will stop and indicate that the minimum time step had
been reached and that there is a convergence error.
• A small time step is a result of a system that changes its
properties over a very short time.
17
Solvers
• Examples of systems that require small time
steps are:
– Clutches – during the locked or unlocked state, the
system is easy to solve. However, when the system
transitions between the locked and unlocked state, an
extremely small time step is required to determine just
when the mode switches between the locked and
unlocked states.
• Power-electronic switches – a switch goes from a high
impedance state to a low impedance state in a matter of
microseconds. This transition take a small time step to
simulate accurately.
18
System Simulation
• Run the simulation with the max time step set to
auto, the feedback gain set to 0.01, and the desired
rpm set to 1800. We see the results below:
19
System Simulation
• If you zoom in on the rpm and the torque
signals, you will notice an oscillation:
20
System Simulation
• The oscillation could be a result of the feedback gain being too
high, the simulation time step being too large, or a combination
of the two.
• We will fix the p
problem by
y setting
g the max time stepp to 0.0001
seconds:
21
System Simulation
• A max simulation time step of 0.001
seconds did not eliminate the oscillation.
• A max time step of 0 0.0001
0001 was needed
needed.
• The smallest time step we can run our
controller at is 1 ms, meaning that this
physical system is too fast to be controlled
by out microcontroller targets.
22
System Simulation
• Zooming in at the beginning of the simulation, we
see that the system step response reaches steady
state in about 6 ms:
23
System Response
• This is indeed a very fast response.
• If the motor does respond at this fast of a
rate we will need to slow the system down
rate,
or choose new controller targets.
• Before we take one of these drastic steps
to correct the problem, we will measure
the actual step response of the motors to
verify that they are indeed this fast.
• We will use xPC and a real-time target to
run a step response and collect the data.
24
Lecture 3A Exercise 1
• Use the fixed-step ode3 (Bokacki-Shampine) solver and
determine the largest fixed step size that can be used to
simulate the system with out yielding an oscillation in the motor
torque or plant rpm.
• The desired rpm should be set to 1800, number of bulbs to 3,
and the feedback gain to 0.01 (same as used in the previous
slides.)
• Note that when we deploy the controller on the MPC555x
target, a fixed step size will be used. Thus, this is a good test to
determine the required
q stepp size needed for our controller.
• Find the max step size to the nearest 100 µs.
Demo___________
25
xPC
• We will be using real-time target computers from Speedgoat.
• These targets are industrial strength personal computers
designed to survive in rugged environments.
• They
Th are preconfigured
fi d with
i h xPC
PC anddhhave analog
l and d di
digital
i l
I/O capabilities.
• In Lecture 8, we will show how to setup and use an old
personal computer as a real-time computer using xPC target.
• Since these targets are preconfigured, we will just go through
the steps necessary to communicate with and run models on
the target.
• In Lectures 8 and 10, we will show more detail on using
xpcexplr and target setup.
26
xPC Explorer
• From the Matlab prompt, type the
command >>xpcexplr
• We will use xpcexplr to:
– specify settings to allow us to communicate
with the target.
– Specify a compiler to allow us to build models.
27
Visual Studio Compiler
• First, we will select the compiler. We will
assume that you are using the Microsoft
Visual Studio 2005
2005.
• We will assume that you have already
installed the Microsoft compiler and that it is
installed in directory C:\Program
Files\Microsoft Visual Studio 8.
28
Visual Studio Compiler Setup
• The compiler is specified using the xPC
Explorer.
Select VisualC here.
here
29
Visual Studio Compiler Setup
• If you have Microsoft Visual Studio 2005
installed, your settings will be as shown:
Select VisualC here.
here
Compiler Configuration
specified. Specify the directory where
the Visual C compiler is
installed.
Click apply when done.
30
31
32
Communication tab
selected.
33
xPC Setup
• We will be communicating with our target
through the network.
• Select the TCP/IP connection
Select communication
settings here.
34
xPC Setup
• Specify the IP addresses for your target
system.
35
xPC Target
• We will be using targets preconfigured with xPC.
• These targets have an IP address specified in their
p file/configuration.
setup g
• When you boot up this target, a screen will appear
showing you the IP address.
• This is a static address. The address is specified in
xpcexplr in the configuration section we are currently
workingg on.
• When you specify an IP address in xpcexplr, you need
to make sure that no other computer is using that IP
address.
36
xPC Target
• When you boot up the xPC target, if a monitor is
connected, it should display status information about
the target, including its IP address.
37
xPC Setup
• Select the driver/chip set for your Ethernet
card: Select Ethernet card chip
set here. For the
Speedgoat targets, select
I82559.
38
xPC Setup
• Select the type of bus into which the
Ethernet card is plugged:
39
xPC Setup
• Next, select Settings.
• Since our model is small, we will use the
default settings for model size:
40
•Right-click here.
•Select Connect from the menus.
41
No red x here.
42
xPC Setup
• Communication with our target is now complete.
• We are now ready to create a model to run on the xPC
target computer.
43
Step Response
• We will now use the Speedgoat target to run a test on
the motor and collect data.
• To generate a step, we will use an analog output
channel to generate a 0 to 5 V step
step.
– A 5 V input to the motor driver will tell the driver to run the motor
at full power.
• We will then measure the motor rpm using an analog
input channel from the Speedgoat target.
• We will write the data to a file on the target machine.
• We
W willill then
th run a Matlab
M tl b script
i t on the
th host
h t computer
t to
t
read the data file, perform some data conversion, and
then determine the step response.
44
Speedgoat Target
• The Speedgoat real-time target has a PMC730
Multi-function I/O target installed.
• This card has the following facilities:
– 32 Analog input channels with 16-bit resolution.
• Can be configured as 32 single-ended input channels
(single input referenced to ground).
• Can be configured as 16 differential input channels
(signal difference between the two inputs).
– 8 Single-ended analog output channels with 16-bit
resolution.
45
PMC730 Multi-function I/O Card
• 16 Digital I/O Channels.
– Input/output function configured in groups of
8-channels
8 channels
• One 32-bit counter/timer
• A data sheet for the PMC730 is available
on-line in the DataSheets section of the
MBSD1 website.
46
Speed Goat target.
• Create a new Simulink model and name it
Lecture3A_xPC1.mdl.
• We must first configure the hardware on
the PCM730 board.
• Place a Simulink block named PMC730 5
located in the xPC Target: Speedgoat I/O
Driver Library / IO101 library in your
model.
47
PMC730 Acromag Setup
• This single block is used to setup all functions of
the PMC730 card.
• Onlyy 1 copy
py of this block is needed to set up p the
analog I/O and digital I/O facilities of the card.
• Double-click on the block to open it.
• Note that the block will appear differently
depending on the parameter group selected.
• The screen captures on the next page show the
same block with different Parameter groups
selected.
48
49
PMC730 5 Acromag setup block
• We notice that the module identifier in all of the
screen captures on the previous slide was set to 1.
• If a Speedgoat target has more than one PMC730
target, we can use this card to address each PMC730
individually.
• Our targets have a single PMC730 installed, so the
module identifier will be specified as 1.
• We will now set the parameters on this block to have
a single analog input and a single analog output.
50
PMC730 5 Acromag setup block
• We fist must specify the Module setup.
• Since we only have a single PMC730 module, we can
specify that xPC automatically determine in which slot
th PMC730 is
the i installed.
i t ll d If we had
h d more than
th one
PMC730 installed, we would specify the slot
manually:
Module 1 specified.
Module setup
p specified.
p
51
PMC730 5 Acromag setup block
• We need to specify one channel for analog input:
Module 1 specified.
52
PMC730 5 Acromag setup block
• We need to specify one channel for analog output:
Module 1 specified.
53
Analog Output
• Next, we will add an analog output block to
provide a 0 to 5 V step to the motor controller.
• Place a block called PMC730 2 located in the
xPC Target: Speedgoat I/O Driver Library /
IO101 library in your model.
• Connect a Step block from the Simulink /
Sources library to the Analog output block:
54
Analog Output
• The settings for the analog output block are:
55
Step Block
• The settings for the step block are:
56
Analog Input
• We will use an analog input channel to measure the
rpm.
• Place a block called PMC730 1 located in the xPC
Target: Speedgoat I/O Driver Library / IO101
library in your model.
• Add a Mux from the Simulink / Commonly Used
Blocks library and connect as shown:
57
Analog Input
• The properties of the analog input block
are:
58
Simulink xPC Target Library
• Next, we need to place some xPC scopes
in our model.
• xPC Scopes can be used to generate plots
or to save data in a file.
• Open the Simulink Library Browser by
selecting View and then Library Browser
from the Simulink menus or clicking the
Library Browser button
• Expand the xPC Target library near the
bottom of the list:
59
Simulink xPC Target Library
• We are looking for the xPC Scope which is
in the Misc library:
•These
These blocks will
ill
display a trace on
the target PC
screen or can be
used to record data
in a file.
•Place a scope in
your model as
shown.
60
Model Changes
• We want to record the applied step signal
and the measured rpm.
• Modify the model as shown:
61
Model Changes
• Next, double-click on
the Target Scope
block and make the
changes below.
Specify the Scope type as File. This
will save the input signals to a file.
62
Model Changes
• Next, double-click on
the Target Scope
block and make the
changes below.
Record every data point.
63
Model Changes
• Click the OK button to save the changes. The
complete model is:
64
Simulation Parameter Setup
• Next, we need to set up the simulation
parameters.
• Select Simulation and then Configuration
Parameters from the Simulink menus
65
Simulation Parameter Setup
• There are a number of parameters we
need to change.
• Select the Solver tab and specify the
following parameters
– Stop time: 0.02
– Type: Fixed-step
– Solver: Discrete (no continuous states)
– Fixed-Step Size: Ts
• These selections are shown on the
following slide.
Solver selected.
67
Simulation Parameter Setup
Next, select the Real-Time Workshop tab:
Real-Time Workshop
selected.
68
Simulation Parameter Setup
• We need to specify
that we will be using
a xPC target as our
target system.
• Click the Browse
button, select the
file named
xpctarget.tlc, and
then select OK.
69
Simulation Parameter Setup
• Your dialog box should look as shown.
70
Simulation Parameter Setup
• We do not need to make any other
changes.
• However,
However we will look at the xPC Target
options tab to see some other options that
control behavior we will see.
• Select the xPC Target options tab.
71
72
Simulink xPC Target Library
• The Configuration Parameters are now
complete so click the OK button to accept
the settings
settings.
• Next, we need to define the value of the
sample time, Ts.
• You can do this at the Matlab prompt or as
part of the initialization process of the
model, which is ho we will do it.
• Select File and then Model Properties
from the Simulink menus:
73
Model Properties
74
Model Properties
• Select the Callbacks tab and select the
InitFnc tab.
• Commands in
this window will
be executed
every time the
model is run,
prior to the model
execution.
75
Model Properties
• We can place any Matlab commands in
this pane.
• We will define the sample time here as
100 microseconds:
76
Model Wiring
• The last thing we need to do before running the
model is to connect the real-time system to the
system under test.
test
• Pin connections for the PMC730 are defined in
the users manual located on the website for
MBSD1.
• We are using Analog Output 1.
• We need to also find the ground reference for
this output.
• The data sheet is shown on the next slide:
77
Analog Output Pin Connection
78
Analog Output Pin Connection
We specified the first analog output
channel. Thus, our output is pin 12.
79
Analog Input Pin Connection
We can use any of the common connections specified in
the previous slide as our ground reference.
80
81
82
83
Model Execution
• If you were successful, your model should
be downloaded to your target PC.
• If you have a monitor on your PC,
PC you
should see the following screen.
84
85
Model Execution
• We are now ready to run the model on our
Speedgoat target.
• We must specify that the model should run
on a an external target.
• Select Simulation and then External from
the Simulink Menus.
• The tool bar should show that you have
selected an external target.
86
87
Model Execution
• Note that a new button has appeared.
• This button means connect to external
target
target.
• Next, we must connect to the external
target.
• Click on the button, or select
Simulation and then Connect to Target
from the Simulink menus.
88
Model Execution
• You might ask, how does Matlab know
which target to connect to.
• In the Simulation Parameters setup
setup, on the
xPC tab we specified to automatically
download the model after building, and we
specified that it should use the default
target.
• In the xPC Explorer, we specified
TargetPC1 as the default target.
• Thus, our model will run on TargetPC1.
89
Model Execution
• After connecting to the target, the play
button should become available:
90
Model Execution
• When the mode runs, you should heat the
motors turn on briefly and then turn off.
• The motor just responded to the step and
the model ended after 20 ms of execution.
• We now need to check to see if the data
file was created on the target.
• We will use the xpcexplr to view the root
directory of the target pc.
91
Collected Data File
• Run the xPC Explorer (xpcexplr)
• Connect to the remote target
• E
Expand d th
the Fil
File S
System
t portion
ti off th
the ttree.
• Select local disk C:\ to view the contents of
the root directory:
92
Collected Data File
Root directory
selected.
93
Post Processing
• We now need to read the data file from the
remote target and then process the data.
• The Matlab script is discussed in the next
few slides: Open the file system on the
remote target.
94
Post Processing
Convert the data to a
structure.
95
Post Processing
Determine the 10% and 90%
points. Calculate the time
constant as the 10 to 90% rise
time divided by 2
2.2.
2
96
Post Processing
Plot the scaled data and the
10% and 90% points on the
second plot in the window.
97
Results
Lecture 3A Demo 1
Demo___________
98
Results
• We see that the system does respond
quickly.
• The system is too fast to control with the
hardware targets available in the lab.
• To fix the problem, we will add a flywheel
to slow down the system response.
99
Flywheel
100
Flywheel
• In the model, this change has the effect of adding
more inertia to the system as shown below:
101
Lecture 3A Exercise 2
• Add the flywheel inertia to your system. (Repeat exercise 1 with
the added inertia.)
• Use the fixed-step ode3 (Bokacki-Shampine) solver and
determine the largest
g fixed step
p size that can be used to
simulate the system with out yielding an oscillation in the motor
torque or plant rpm.
• The desired rpm should be set to 1800, number of bulbs to 3,
and the feedback gain to 0.01 (same as used in the previous
slides.)
• Note that when we deploy the controller on the MPC555x
target, a fixed step size will be used. Thus, this is a good test to
determine the required step size needed for our controller.
• Find the max step size to the nearest 1 ms.
Demo___________
102
Lecture 3A – Problem1 Demo___________
103
Lecture 3A – Problem2 Demo___________
.001 1000 1 1
Constant (1/1e6)s+1 (1/5e6)s+1 (1/1e7)s+1
Saturation Scope
Transfer Fcn Transfer Fcn 1 Transfer Fcn 2
Gain
0.1
F=0.1
.001 1000 1 1
Constant (1/1e6)s+1 (1/5e6)s+1 (1/1e7)s+1
Saturation Scope 1
Transfer Fcn Transfer Fcn 1 Transfer Fcn 2
Output
Gain
0.025
F=0.025
.001 1000 1 1
Constant (1/1e6)s+1 (1/5e6)s+1 (1/1e7)s+1
Saturation Scope 1
Transfer Fcn Transfer Fcn 1 Transfer Fcn 2
Output
Gain
0.02
F=0.02
.001 1000 1 1
Constant (1/1e6)s+1 (1/5e6)s+1 (1/1e7)s+1
Saturation Scope 1
Transfer Fcn Transfer Fcn 1 Transfer Fcn 2
Output
Gain
0.0125
F=0.0125
Introduction to Model-Based
Systems Design
Lecture 4 : Plant Model Transfer Function
2
Plant Model – Transfer Function
• To use the tools covered in a classical
control class, we need to determine the
transfer function of the plant model
model.
• We will do this by measuring the
magnitude response versus frequency of
the plant input-output transfer function.
(This will be a Bode magnitude plot.)
• We could also measure the phase plot, but
we will not do this.
4
Plant Model – Transfer Function
5
Plant Model
6
Motor Model
7
Generator Model
8
Plant Model – Transfer Function
• With a constant input of 0.69, the motor-
generator system runs at about 1800 rpm:
9
Plant – Transfer Function
• The previous simulation required a small
step size to prevent numerical oscillations
in the output:
10
Plant – Transfer Function
• Had we left the max step size at auto, we
would see the following output:
11
Plant – Transfer Function
• Now that we have our plant biased at 1800
rpm, we will introduce a small-signal sine
wave at the input and measure the
magnitude of the output at various
frequencies:
12
Plant – Transfer Function
• The properties of the sine wave are:
13
Plant – Transfer Function
• We will let the simulation run for 400
seconds (since the frequency is so low).
• We will set the maximum step size to 1e1e-33
so that the simulation does not take too
long to run (because the simulation will run
for 400 seconds of simulation time).
• We see the following output waveform:
14
Plant Transfer Function
15
Cursors
• We can measure the waveform using
cursors.
• The cursors are not normallyy displayed
p y on
a scope plot.
• To display standard plotting menus on a
scope, run the following Matlab commands
shh = get(0,'ShowHiddenHandles');
set(0,'ShowHiddenHandles','On')
( , , )
set(gcf,'menubar','figure')
set(gcf,'CloseRequestFcn','closereq')
set(gcf,'DefaultLineClipping','Off')
set(0,'ShowHiddenHandles',shh)
16
Cursors
• These commands will cause the File menu
to be displayed on the scope screen.
• To display the cursors,
cursors you can then select
Tools and then Data Cursor to display
the cursors.
• When you click the mouse on a trace, a
square will be displayed with the points
coordinates.
17
Cursor Values
18
Plant – Transfer Function
• For an input frequency of 0.1 rad/sec, we
see the following:
• Peak-to-peak
Peak to peak output is 1830 rpm – 1778
rpm = 52 rpm.
• Output amplitude = 26 rpm.
• Gain = Output amplitude divided by input
amplitude = (26 rpm)/(0.01) = 2600.
• Gaindb = 20*log10(Gain) = 68.3 dB
19
Plant – Transfer Function
• We will measure the gain at several
different frequencies.
• The input amplitude will be kept constant
constant.
• We will change the length of the simulation
and the max step size as appropriate for
higher frequencies.
20
Frequency Output Amplitude Gain Gain (dB)
(rad/sec)
21
Plot with Matlab
• Amplitude=0.01;
• freq=[.1 1 10 20 40, 80 100 200 300 400 1000 10000];
• output=[26, 26, 26,26,25.5,24 23, 17.5 13.5 11 4.5, 0.5];
• mag=output/Amplitude;
• dB=20*log10(mag);
• semilogx(freq,dB,'rx-');
• grid on
• title('Motor Generator Magnitude Response');
• ylabel('Amplitude
l b l('A lit d (dB)');
(dB)')
• xlabel('Frequency (rad/sec)');
22
Plant Magnitude Response
23
Plant Transfer Function
• Our motor-generator system has a single
pole between 100 and 200 rad/sec.
• Note that a single poles system cannot
oscillate because we only have 90
degrees of phase (1 pole).
• So why did we see oscillations at when we
had large proportional gain?
– There must be extra delay somewhere.
24
Lecture 4 Problem 1 Demo___________
• Repeat the bode plot for our system and include the
flywheel inertia of 1.041×10-4 kg·m2.
• Fill in the table below and generate a plot.
F
Frequency (rad/sec)
( d/ ) O t t Amplitude
Output A lit d G i
Gain G i (dB)
Gain
0.1
1
2
4
8
10
20
40
80
100
1000
10000
25
Lecture 4 Problem 2
A plant has the following transfer function
1000
(1 + s 0.1)(1 + s )(1 + s100)
We will use this plant with proportional feedback as shown in class.
a) Use gain and phase plots to find the largest value of the feedback constant F
that can be used to have a stable system with zero degrees phase margin.
b) Use Simulink to show that the system is unstable for values of F larger than
this value of F.
c) Use Simulink to show that the system is stable for values less than or equal
to this value of F.
d) Use gain and phase plots to find the largest value of the feedback constant F
that can be used to have a stable system with a 60 degrees phase margin.
Grade___________
Introduction to Model-Based
Systems Design
Lecture 5 : Improving the Plant Model
6
Full Plant Model
Constant added
here.
8
Clutch Friction
• The peak torque that the clutch can apply
is equal to the number of friction
surfaces times the torque radius times
the peak normal force.
• For our case, the peak torque will be 1
Nm. (More than our motor can supply.)
• The actual torque applied is this peak
torque times the pressure input (a number
between 0 and 1).
Looks
pretty
similar!
Version Version with
without clutch. (3 bulbs.)
clutch
10
11
No generator torque
because it is not spinning
12
13
14
15
Lecture 5 Exercise 1
• Determine the value of the pressure to the
friction clutch so that the system coasts
down from 2700 rpm to zero in about 130
ms.
Demo___________
16
Plant Model – Coast Down Test
• In vehicle design, a data point for verifying the
accuracy of the mechanical model of the vehicle
is a coast-down test.
• With zero wind, run the vehicle at 60 mph.
• Set the engine and motors to zero torque and
plot the vehicle speed as it coasts down to zero.
• Tests and measures aerodynamic drag and
vehicle frictional losses.
• ÎCalibrate your model to match the measured
coast-down.
17
Plant Model – Coast Down
• For our motor-generator system, we will set the
motor-generator rpm to a preset value.
• With no load,, we will time how long g it takes the
rpm to reach zero.
• We will fit the value of the clutch friction in the
model so that the model coast-down time
matches the measured coast-down time.
• We will use a MathWorks tool to automatically y
find the correct value of clutch pressure.
18
Measured Coast-Down
•Tach scaling = 2.5 V per
1000 rpm
⎛ 1000rpm ⎞
Δrpm = Δy⎜⎜ ⎟⎟ Δy
⎝ 2.5V ⎠
⎛ 1000rpm ⎞ Δx
= (6.87 V )⎜⎜ ⎟⎟
⎝ 2.5V ⎠
= 2748 rpm
19
Measured Coast-Down
• We will use the pressure value of the
friction clutch to match the measured
coast-down
coast down time to the simulated coast-
coast
down time.
• Instead of searching for the clutch
pressure manually, we will use the
Simulink Response Optimization toolbox.
• First, we need to measure points from the
measured rpm trace.
• Measured points are shown next:
20
Motor-Generator Coast Down
• %Measured Coast Down Data for Motor-Generator
System
• time=[ 0 0.100 0.1060 0.1187 0.1298 0.1417,...
• 0 1596 0
0.1596 0.1715
1715 00.1834
1834 00.1953
1953 00.2072,...
2072
• 0.2191 0.2340, .5];
• rpm=[2748, 2748, 2525, 2228, 1857, 1560, 1188, 966,...
• 742, 519, 371, 148,0,0];
• plot(time,rpm);
• xlabel(
xlabel('Time
Time (s)
(s)');
);
• ylabel('Speed (rpm)');
• title('Motor-Generator Coast Down');
• grid on;
21
Motor-Generator Coast Down
22
Motor-Generator Coast-Down
• We must now modify the plant so that:
– It has no torque input and no load.
– We set the initial condition to 2748 rpm
rpm.
– Remove whatever torque maintains the speed
at 2748 rpm and allow the motor-generator
system to coast down to 0 rpm.
• The top-level is shown next.
• Note that the controller has been removed.
23
Motor-Generator Coast Down
No motor torque
and no load torque.
24
Motor-Generator Coast-Down
• Inside the plant, we need to set the initial
condition to 2748 rpm.
• We will add a new torque source that
balances the torque due to friction.
• While the forces are balanced, the motor-
generator system will maintain the initial
rpm, whatever it is.
• When we want the system to coast-down,
we set the added torque source to zero.
25
Motor-Generator Coast Down
This step function has an initial
output value of 1 and then steps
down to zero at 100 ms.
Added torque source to
balance friction.
26
Motor-Generator Coast Down
• The settings for the Step input source are
shown below. This part is located in the
Simulink / Sources toolbox.
toolbox
27
Motor-Generator Coast Down
• The initial condition of the drive line is set
as shown:
28
Motor-Generator Coast Down
• Next, in the Matlab workspace set the
value of the constant Pressure to 0.05, the
value we found in the last section
section.
29
Motor-Generator Coast Down
• Run a simulation for 300 ms and verify
that:
– The system starts with an initial rpm of 2748
2748.
– At 100 ms, the system coasts down to zero
rpm.
– The time it takes to coast down is not the
same as the measured time.
30
Motor-Generator Coast Down
Rpm decreases to
0 in about 50 ms.
31
Motor-Generator Coast Down
• We will now use the MathWorks Simulink
Response Optimization toolbox to
determine the optimum value of the
Pressure so that the response of our
model matches the measured response.
• Add a part called Signal Constraint from
the Simulink Design Optimization
toolbox.
32
Motor-Generator Coast Down
We are going to choose the Pressure signal so that
the rpm of the motor-generator system matches the
constraints. (Or minimizes the difference between
the desired and fitted response.)
33
Response Optimization
• Open the Signal Constraint Block
• The plot shown is for having a response fitted
to a set of constraints.
constraints
34
Response Optimization
• We have some measured data that we
would like to use for the response.
• To use the data
data, select Goals and then
Desired Response:
35
Response Optimization
• Set the Reference Signal to the measured
time and rpm data:
36
Response Optimization
• When you click the OK button, the
measured response will be displayed:
37
Response Optimization
• Next, we have to select the parameters
that can be varied to achieve the desired
response
response.
• We have previously defined variable
Pressure in the workspace and gave it a
value of 0.05.
• Select Optimization and then Tuned
Parameters from the menus:
38
Response Optimization
• Presently no parameters are selected.
39
Response Optimization
40
Response Optimization
41
Response Optimization
• Select the Track reference signal option
so that we optimize to the provided data.
Option not
selected.
Option selected.
42
Response Optimization
• To make the system track the desired
response more closely, we need to reduce the
tolerance slightly.
slightly Select Optimization and
then Optimization Options from the menus:
43
Response Optimization
• Set the function tolerance to 0.0001.
• Click the OK button when done.
44
Response Optimization
• Click the Play button and watch the
optimization proceed: Click here.
45
Response Optimization
• Results
46
Lecture 5 Demo 1
Response Optimization
• Optimum value of Pressure is 0.0224.
Demo___________
47
Friction Model Notes
• Our model has a linear change from high
rpm to zero. The actual response looks
like an exponential decay – somewhat.
somewhat
• Out model of a constant frictional torque is
probably too simple.
• Friction is probably a function of rotational
speed.
• Æ Stuff to add in the future.
48
Lecture 5 Problem 1
• In Lecture 3A problem 2, we measured the
coast-down of the motor/generator system
with the flywheel.
y
• Add the flywheel to your model
• Use the measured coast-down data from
Lecture 3A as the reference signal.
• Use the Response Optimization Toolbox
to determine the optimum value of clutch
pressure for the system with the flywheel.
Demo___________
49
Lecture 5 Problem 2
• In both models for this lecture (the model with the flywheel and
the one without the flywheel) we noticed that the measured rpm
had a slight curve while the simulated rpm was a straight line.
• The simulated response is a straight line because we are
applying a constant torque which means that the angular
velocity decrease at a constant rate.
• To model the curvature in the measured rpm, we will try a new
model.
• Modify your model so that the friction has a constant
component plus a component that is proportional to motor
speed (in rad/sec).
• Make both components tunable.
50
Lecture 5 Problem 2
• Use the optimization tool to determine the coefficients for an
optimal fit. You will need to determine two coefficients.
• An optimal plot is shown below. The fit is so close that you
cannot see much difference between the measured data and
the model results in the screen capture.
• You may want to change the optimization method to “Simplex
search.”
• You may want to increase your max step size so that the
simulations take less time.
Demo___________
Demo___________
Any Questions?
Introduction to Model-Based
Systems Design
Lecture 6 : Signal Filtering
2
Signal Modeling
• We now need to clean up our model in
terms of the signals being sent to the
controller
controller.
• Starting with the shaft encoder, it does not
send an rpm signal but rather a voltage
proportional to rpm
– Name plate specification: 2.5 V per 1000 rpm
– At some point we’ll need to verify this.
• Let’s add that to the encoder model
3
Signal Modeling
• Drag a gain into the encoder and set the
value to 2.5/1000.
Freescale
MPC555x
Development
Board
5
Improved Signals – MPC555x
• This 0-8 V signal is next passed through a
combination resistive divider and low pass
filter to
– Eliminate noise on the signal
– Change range to 0-5 V
• The circuit diagram is
6
Improved Signals - MotoTron ECU
• From circuit analysis
Vo R ZC
=
Vin R + R Z C
1
R×
R ZC = sC
1
R+
sC
⎛ R ⎞
⎜ ⎟
1 + sCR ⎠
= ⎝
Vo R
=
Vin ⎛ R ⎞ sCR + 2 R
2
R+⎜ ⎟
⎝ 1 + sCR ⎠
7
Improved Signals - Controller
• Having figured out the appropriate transfer
function to represent our filter and knowing
– R = 10k
– C = 10 nF
• Drag a Transfer Fnc block into the
controller from the Simulink / Continuous
library.
• We’ll also need a gain and a saturation
• We’ll need to disconnect the Actual rpm
input from the P controller as well
9
Improved Signals - Controller
• Changes:
– Actual rpm Æ Actual rpm (0-8V)
– Transfer Fnc Æ Low Pass Filter
– Gain 1 Æ Signal level converter (0-5 V to 0-1)
– Saturation -> hide name
• Link them together
10
Improved Signals - Controller
11
Improved Signals - Controller
• Double click on the Low Pass Filter
transfer function and put in the values for
R and C
• The numerator
coefficient is the value of
R
• The denominator
coefficients are the
multipliers on s and 1
respectively CR2 and 2R
12
Improved Signals - Controller
• The last step in the controller is to take the filtered
signal which ranges from 0-5 V and convert it to a
signal of magnitude 0-1
– Note that our filtered rpm voltage signal has a range of 0
to 4 V.
– We will not use the full range of the A/D converter (which
has an input range of 0 to 5 V)
• Set the gain to1/5 for the conversion
• Set
S t the
th saturation
t ti tto limits
li it to
t 0 and
d1
• Connect the output back to the summing junction.
13
Improved Signals - Controller
Renamed Signal
14
Improved Signals - Controller
• In the controller an rpm of 0 to 4000 rpm is
represented by a signal that ranges from 0
to 1
1.
• We need modify our desired rpm of 1800
rpm to reflect this change.
• We will change the desired rpm signal to
0.45 (equal to 1800/4000).
15
Improved Signals - Controller
16
Improved Signals - Controller
• Before we run our model, let’s think about
the controller
• We initially had our gain at 0.01
0 01 because
that would yield a full torque signal if the
rpm difference was 100 rpm
• Now, 100 rpm is roughly a signal of 0.025
• We should expect to increase our
proportional gain
17
Improved Signal - Controller
• Let’s set our initial condition to zero, the
load to 2 bulbs, the desired rpm to 0.45,
and leave the gain at 0 0.01.
01
18
Improved Signals - Controller
• Now set the gains to 0.1, 1, and 10
Gain = 0.1 Gain = 1 Gain = 10
Small torque
applied. Better Still better.
19
Improved Signals - Controller
• Now set the gains to 20, 50, and 100
Gain = 20 Gain = 50
Gain = 100
Oscillation – Eliminate by
decreasing max step size.
20
Lecture 6 Demo 1
• Demonstrate the system response for
various feedback gains.
• Demonstrate the effect of reducing the
simulation maximum step size.
Demo___________
Demo
21
Model Improvements
• Improved motor from constant torque source to
torque dependent on rpm.
• Improved generator:
– Linearly dependent on rpm with constant max load.
– Linearly dependent on rpm with variable load.
– Linearly based on rpm with physical relationship to
generator voltage and load resistance.
• Added friction
– Constant
C t t
– Linear dependent on rpm
• Scaled signals to match levels used by
Freescale target.
22
Model-Based Design
• We made the improvements one at a time.
• We verified that the system was behaving
as we expected after each improvement.
• We ran extensive tests to identify changes
in system response due to the
improvement.
23
Init File
• We’ve got a lot of magic numbers in our model:
– Motor and Generator Inertia
– Motor Torque Constant
– Etc
• In a typical model, model constants are reused
in several places.
• If we choose to change any of these parameters,
g miss some of them in the model.
we might
• Let’s put these values into an initialization file.
• This file will be executed each time we run our
model, before the model runs.
24
Init File
• Open your Matlab window and open a new m-file:
• Select File, New, and then M-File from the menus
or click on the New M-File icon as shown below:
25
Init File
• Save the file in the same directory as your
Simulink models.
• Save the file as “Init_File.m”
• Enter the text shown on the following page
exactly as shown.
• Save the file when done.
• This will allow us to assign variable names
to parameters inside of our Simulink model
and read those values from the workspace
26
Init File
27
Init File
• Now we need to update our model with the
variable names in the init file
• We
We’llll start with the low pass filter
– Save your model as Lecture6_Model3
– Open up the controller
– Double click on your low pass filter
– Change the numbers to variables as shown
on the next page
28
Init File
[R]
[CR2 2R]
29
Init File
• Update the generator as shown:
30
Init File - Generator
31
Init File - Motor
32
Init File - Flywheel
33
Init File
• Save your file and run!
34
Init File
• We can either run the script file manually to place the
variables into the workspace, or…
• Have Simulink run the init file automatically each time we
run a simulation ((which also pplaces the variables into the
workspace).
• Right click any place in your model where it is blank
• Select Model Properties
• Select the Callback History tab
• Add Init_File to the InitFcn Model Callback section
• Click OK
35
Init File
36
Init File- Lecture 6 Demo 2
• Run your model now Demo___________
• It works
k because
b th
the Init_File
I it Fil runs before
b f
the model runs, and defines all of the
constants needed by the mode.
• From now on, we will define all of our data
and model constants in the init file.
• The model will reference the variables
named in the init file rather than use magic
numbers.
Introduction to Model-Based
Systems Design
Lecture 7: Time Delays and Proportional
and Integral Control
2
Presentation Outline
• Sample Time Delay
– Assess impact of signal delay on system
performance.
p
• PI Control
– Add integral control to eliminate error.
3
Model Updates
• Before we begin, we will update our model
with the coast-down friction components
that we added in Lecture 5 Problem 22.
• Add the following parameters to the init
file:
4
Model Updates
• Add the proportional and constant friction
components to the plant:
5
Model Updates – Complete Plant
Step Response
7
Step Input
• So far we have been running our model for
short simulation times
– We have changed nothing while the
simulation is running
• Let’s slow our system down and watch the
effect of changing the load or desired rpm
• Model Name Change
– Save your model
– Save your model as Lecture7_Model1
8
Step Input
• First, let’s slow down our simulation.
• On your model, again right click any place where
there is a blank area.
• Select Configuration Parameters
• Select the Solver tab.
• Change the Stop Time to inf (it will run forever)
• Change the Max Step Size and Initial Step
Size to 1e-4 seconds ((this will slow it down by
y
decreasing the maximum step size and forcing
more calculations).
9
Step Input
10
Step Input inf – run
until we stop it.
1e-4
Solver selected.
1e-4
11
Step Input
• Now let’s add the ability to change our desired
speed.
• Dragg a Slider Gain from the Math Operations
p
library into the top of your diagram and connect
as shown.
12
Step Input
Slider Gain
added here.
Desired
speed
changed to 1.
13
Step Input
• Double click on the slider gain and set the
lower and upper limits to 0 and 1
respectively and slide the slider
14
Step Input
• Run your simulation.
15
Step Input
16
Scope Settings
• To see the system response, we need to
change the scope’s default x-axis time
range
range.
• The time axis on our scope is 0 to 10
seconds by default.
• We need to change the time axis on our
plots.
17
Step Input
18
Scope Time Range
19
Step Input
• Pretty cool – you can watch the actual rpm try to match the
desired rpm (2 bulb load, Gain = 20.) You may need to slow the
simulation even more by reducing the maximum step size to
1e-5.
20
Lecture 7 Exercise 1
Use the signal builder to create the following
pulsed waveform:
21
Lecture 7 Exercise 1
Use this waveform as the rpm input for the controller.
For this waveform, or a slight modification, observe
the system step response for the following
conditions:
Demo___________
22
Step Input
• Our physical system has 6 light bulbs.
• We would like to see how changing the
load affects the system response
response.
• At the top level of your model
– Change the constant for the number of bulbs
to 1
– Add a slider as shown next.
– Set the limits on the slider from 0 to 6
23
Step Input
Number of bulbs
set to 1.
24
Step Input
• We will now test how our system responds
for changes in the load while holding the
speed constant
constant.
• Set the speed slider to 0.6 and do not
change it.
• Run the simulation and observe how the
system response changes as we change
the load slider.
• Set the proportional feedback gain to 100.
25
Step Input
26
Step Input
• Increasing the load increase the steady state error.
• Decreasing the load decreases the steady state error.
• Notice the changes in torque as we change the load.
Number of bulbs
increased from 0 to 4.
27
Step Input
Number of bulbs is 3.
Number of bulbs is 6.
28
Step Input
• Decreasing the load.
Number of bulbs
d
decreased
d ffrom 4
to 0.
4 Bulb Load.
29
Lecture 7 Exercise 2 Demo___________
30
Controller Cycle Time
• To this point, our controller measures signals and makes
a change every computational step.
• Since this is a variable step size solver, this time
changes as the simulation runs and can be quite smallsmall.
• This is not true in the hardware implementation.
– In the real-time hardware realization, the controller performs all
computations within a fixed time.
– We will call this time the controller cycle time.
– The inputs are read once in this fixed time.
– All calculations are p performed for the measured inputsp once in
this fixed time.
– The outputs are changed once in this fixed time.
– If the controller finishes early, we wait until the fixed time is up
before executing the control loop again.
31
Controller Cycle Time
• The effect of the controller cycle time is:
– We can only sample the inputs once in the time
period. If the input changes, we won’t know about it
until
til the
th nextt fixed
fi d time
ti step.
t
– We can only change the output control signal once in
the fixed time period. This limits how fast we can
make a change. (Or, how fast the controller can
respond.)
• For control people, this time delay is a
phase delay in the feedback loop.
• This delay can cause the system to
become unstable.
32
Controller Cycle Time
• As a first step in modeling this delay , we will use
a sample and hold.
p
• The value will be held for a fixed and specified
amount of time.
• We will model the controller cycle time on both
the inputs and outputs of the controller.
• In the hardware realization, the fixed time can be
g at compile
changed p time. It can be reduced
within limits imposed by your ECU.
• In a future lecture, we will run a Software-in-The-
Loop (SiL) simulation to model this delay.
33
Controller Cycle Time
• Save your model as Lecture7_Model4.
• From the Signal Processing / Signal
p
Operations library,
y, drag
g a Sample
p and Hold
block into your controller.
• From the Simulink / Sources library, drag a
Pulse Generator into your controller
• To start, we will use specify a sample time of
100 ms.
34
Controller Cycle Time
Output control
signal will be changed
only once every 100 ms
35
Controller Cycle Time
• To set our 10 ms
trigger, double
click on the
Pulse Generator
and set the
Period to 0.01
(10 ms)
36
Controller Cycle Time
• Thinking back to our step input work, we have
introduced a physical step into our system!
– The torque request undergoes a step change every
controller cycle time.
– If the cycle time is too long, these steps could be
large.
– Larger step changes can be felt or heard.
• Lets simulate the system and see if a 100 ms
time step on the output affects the controller
controller’s
s
performance.
37
Controller Cycle Time
• Set the following on your model:
– rpm slider to 0.6
– Load slider to 2 bulbs
– The IC to zero
– The feedback gain to 10,
– Simulation end time to 1 s
– The controller sample time to 0.1 seconds. (A
very long time
time.))
– The simulation max step size to 1e-5.
– When the simulation runs, you will notice that
it oscillates at a 100 ms rate!
38
Controller Cycle Time
39
Controller Cycle Time.
• Try reducing the controller cycle time until the
oscillation disappears.
• This simulation is for a cycle time of 50 ms
40
Controller Cycle Time.
• Try reducing the controller cycle time until the oscillation disappears.
• I found that a sample time of 20 ms is sufficient to stop the oscillation.
• A simulation of this type is necessary to determine how much computing
power we will need to run our controller.
• Smaller cycle times require faster hardware targets.
41
Lecture 7 Exercise 3 Demo___________
42
Controller Cycle Time
• Next, we will model the controller cycle
time effect on the input signal.
• Remember that the ECU will only sample
the input once every cycle time.
• Bring in another Pulse Generator and
Sample & Hold and put it on the
generator side just after the low pass filter.
• The pulse generator will have the same
properties as the previous one we added.
43
Controller Cycle Time
44
Controller Cycle Time
• Set the period on both pulse generators to 1 ms. Leave
all other setting the same and run a simulation. (Gain =
10, 2 bulbs, max step size = 1e-5.
45
Controller Cycle Time Conclusion
• Controller cycle time adds delay to a
feedback loop that can cause a system to
oscillate or overshoot
overshoot.
• We can alleviate some of these affects by
changing the gains of our system.
• To model a system, we should include all
sampling delays
– Controller cycle time.
– CAN message rates.
– Other.
47
PI Control
• One of our goals is to design a controller for our
system.
• Now that we have a good plant model, we can
use allll off our kknowledge
l d off control
t l systems
t tto
design controllers. (And simulate them!)
• We will look at adding an integrator to our
system because:
– A proportional gain controller yields an error that is
inversely proportional to the gain
gain.
– Too high of a proportional gain can make the system
oscillate.
• Update your model to version Lecture7_Model6.
48
PI Control
• Set your Controller Cycle Times back to 1 ms
• Set your proportional gain to 10, the desired
rpm slider to 0
0.6,
6 and the load slider to 2 bulbs
bulbs.
Steady state
error.
49
PI Control
• To reduce this error we will add an
integrator to our controller.
• We could use a continuous time integrator
for Simulink simulations.
• When we implement our controller on an
ECU, a discrete solver is usually used and
a continuous integrator will not work.
• We will use a discrete time integrator.
50
PI Control
• From the Simulink / Discrete library drag in a
Discrete-Time Integrator
g in a g
• Drag gain and a sum as well
• Hook up as shown below and on the next slide
51
PI Control
52
Discrete Time Integrator
• This integrator performs a forward Euler
method. (Basically a sum of rectangles.)
• The block implements the sum
y(n) = y(n-1) + K*T*u(n-1)
• K is the gain and is equal to 1 for our
application.
• T is the sampling period (the time between
samples).
53
Discrete Time Integrator
• With K=1 we have the equation
y(n) = y(n-1) + T*u(n-1)
• The
Th presentt output
t t iis th
the previous
i output
t t
plus the previous input times the time slice
T
• Note that T*u(n-1) is the area of a
rectangle.
• We are summing up rectangles.
• Set the integrator properties as shown
next.
54
Discrete Tim Integrator
Gain set to 1. Sample time set the
same as for our
controller cycle time.
Integrator When we deploy this
starts at 0. controller on the ECU,
the integrator sample
time will be the
controller cycle time.
We should probably
define this in our init
file and use it for the
integrator and two
pulse generators.
Do that!
55
Discrete Tim Integrator
•Integrators can integrate to infinity (it
takes a long time!)
•Suppose we turn on too many bulbs.
The motor is not strong enough to
reach the desired rpm and the error
will be large.
•The integrator will integrate this error,
possibly for a long time until you
change the number of bulbs.
•If the integrator does not have
saturation limits, the integrator will
integrate to a large value.
•When you do finally turn off a bulb,
the integrator value decreases slowly
and causes the motor to spin wildly
until the integrator has time to
integrate back to an appropriate value.
•This overshoot is called integrator
wind up.
•To prevent it, add saturation limits.
56
Discrete Time Integrator
• Run a simulation with a proportional gain of 10 and in
integral gain of 1, load = 2 bulbs, and a desired speed of 0.6.
Let the simulation run for 1 second.
57
Discrete Time Integrator
Repeat the simulation run for 10 second.
It appears
pp that the torque
q is
slowly increasing.
58
Discrete Time Integrator
• Change the simulation to allow it to run for
20 seconds.
59
Discrete Time Integrator
• Next, set I_Gain = 10, and P gain = 10. This
should make the integrator respond faster.
60
Discrete Time Integrator
• Next, set I_Gain = 100, and P gain = 10. This
should make the integrator respond faster.
61
Lecture 7 Demo 1
• Demo your PI controller.
• Show how changing the P and I gains
affect the system response
response.
Demo___________
62
Discrete Time Integrator
• For the previous simulations, we were near the
power limitations of the motor.
• We will do some testing at a new set point
• Set the following:
– Desired speed slider = 0.3
– Number of bulbs slider = 1
– Initial condition = 0
– All sample times = 0.001
– Simulation time set appropriately.
63
Discrete Time Integrator
• P_Gain = 10, I_Gain =0
64
Discrete Time Integrator
• P_Gain = 10, I_Gain = 1.
65
Discrete Time Integrator
• P_Gain = 10, I_Gain = 10
66
Discrete Time Integrator
• P_Gain = 10, I_Gain = 100
67
Discrete Time Integrator
• P_Gain = 10, I_Gain = 1000
68
Lecture 7 Exercise 4 Demo___________
69
Discrete Time Integrator
• I like the system response with P_Gain =
100 and I_Gain = 10.
• We will hold these gains constant and hold
the number of bulbs constant at 1 bulb.
• We will observe the system response as
we change the speed slider between 0
and 0.6.
• Change the simulation ending time to inf
and decrease the max simulation step size
to make the simulation run slowly.
70
System response to speed change
requests.
71
Discrete Time Integrator
• Next, keep the speed slider constant at 0.3
and change the bulb load from 0 to 6.
• Vary the load up and down.
down
72
Load changes.
73
PI Controller
• Feel free to experiment with the controller
gains to see their effect.
• Tuning is the process of choosing the
gains to achieve the desired response.
• With this PI controller, we have a lot of
flexibility.
74
Lecture 7 Demo 2
• Demo your PI controller with 1 bulb load.
• Show how changing the P and I gains
affect the system response
response.
• Determine values of P and I gains for
optimum response.
Demo___________
75
Lecture 7 Exercise 5
Investigate the difference between the two controllers below. Note that
the order of the integrator and gain has been switched in the two
models:
76
Lecture 7 Exercise 5
Demo___________
Any Questions?
Start Project 1
Introduction to Model-Based
Systems Design
Lecture 8:
xPC Real-Time Systems 1
2
Outline
• Setting up an xPC Target
• Running Real-Time Simulation
– Proportional Control Model
– Integral Control Model
• Tuning Parameters
• Using xPC Explorer
• Blocks and Gauges
3
Real-Time Simulations
• We would like to run real-time simulations
for several reasons:
– Further debug our controller and model
model.
– Obtain a feel for how the model responds in
real-time.
– Tune the control parameters for a desired
response.
– See how
ho changing inputs
inp ts and model
parameters affect model and controller
operation.
4
Terminology
• Host Computer – The computer where you run
Matlab. The real-time model will not run on this
computer. We will create our models on this
computer
computer.
• Target Computer (Platform)– The computer on
which our real-time model will run.
• We will use the host computer to communicate
with and monitor the target.
• The target computer can run the plant, the
controller, or both depending on the type of
verification we want to do.
5
What is xPC
• xPC allows you to use a personal
computer as a real-time target.
– Inexpensive
– Most of us have an older PC we can use.
• Communication through TCP/IP or RS-232
• Can tune parameters
• Supports I/O hardware in PC such as A/D
A/D,
D/A, DIO, CAN, etc
6
What You Need (For this course)
• An Old PC (can be almost any PC with an Intel
386 or 486 Pentium or AMD K5 or K6/Athlon
processor)
• A fl
floppy di
disk
k (N
(Nott required
i d anymore))
• Microsoft Visual Studio 2005 or Open Watcom
C/C++ (Version 1.3)
• An Ethernet Card
– Card Specifics (Driver/Slot type)
– Network Specifics
• IP Address
• Gateway Address
• LAN Subnet Mask
7
Setting Up xPC
• For our example, we’ll use a PC with a
Pentium III and an Ethernet card.
• From the Matlab prompt
prompt, type the
command >>xpcexplr
• This will allow us to both setup and
monitor the target PC.
8
Visual Studio Compiler
• First, we will select the compiler. We will
assume that you are using the Microsoft
Visual Studio 2005
2005.
• We will assume that you have already
installed the Microsoft compiler and that it is
installed in directory C:\Program
Files\Microsoft Visual Studio 8.
9
Visual Studio Compiler Setup
• The compiler is specified using the xPC
Explorer.
Select VisualC here.
here
10
Visual Studio Compiler Setup
• If you have Microsoft Visual Studio 2005
installed, your settings will be as shown:
Select VisualC here.
here
Compiler Configuration
specified. Specify the directory where
the Visual C compiler is
installed.
Click apply when done.
11
12
13
Communication tab
selected.
14
xPC Setup
• We can specify communication through an
RS-232 cable or a TCP/IP connection:
• We will select the TCP/IP connection
Select communication
settings here.
15
xPC Setup
• Specify the IP addresses for your target
system.
16
xPC Setup
• For the Ethernet card, we need to know
the card chip set and the bus type (ISA or
PCI) into which the card is plugged .
• If you do not know this information, you
might be able to use the Windows Device
Manager to find it.
• A list of the supported Ethernet cards can
be found in the Matlab xPC help with the
following topic: Ethernet Chip Families
Supported by xPC Target
17
Help Selection
18
xPC Setup
• Select the driver/chip set for your Ethernet
card:
Select Ethernet card chip
set here. For the RHIT
MBSD lab, select R8139.
19
xPC Setup
• Select the type of bus into which the
Ethernet card is plugged:
20
xPC Setup
• Next, select Settings.
• Since our model is small, we will use the
default settings for model size:
21
xPC Setup
• Next, we will create a boot floppy for our
target PC.
• Hopefully your host PC (the one running
Matlab) has a floppy disk drive.
• Hopefully you can find a floppy disk.
• Select Configuration in the tree:
22
23
xPC Setup
• Incase you haven’t used a floppy disk in
the past several years, remember the
following:
– You may need to format the disk before
clicking the Create Bootdisk button.
– Make sure that the write protect switch on the
disk is set to allow writing (you should not be
able to see through the hole
hole.))
24
xPC Setup
• When you click the Create Bootdisk
button, you should see the dialog box:
25
xPC Setup
• Next, place the bootdisk in your target PC
and turn it on.
• Your target PC should display a screen
similar to the one shown next.
• You can ignore the error about no
accessible disk. We will not be using the
target PC’s disk.
26
27
28
No red x here.
29
xPC Setup
• Our target setup is now complete.
• We are now ready to modify our model to run on the
target computer.
• We
W will ill use the
h model
d l with
i h proportional
i l feedback
f db k as a
starting point.(Passed out as Lecture8_Model0.mdl)
• Later, we can use the same process to simulate our
more complicated feedback models.
• Open the model with proportional feedback and then
rename it Lecture8_Model1.mdl.
• Make sure that this model has the flywheel inertia in it,
with the inertia specified as 10-4 m2kg
30
Model Modifications
• Add sliders for the speed and number of
bulbs.
31
Model Modifications
• Remove the Sample and Hold locks we
added to model the controller response
time
time.
• These delays will be modeled by the fixed
step size.
32
Model Modifications Sample and Hold removed.
• Controller Block
33
Simulation Parameter Setup
• Select Simulation and then Configuration
Parameters from the Simulink menus
34
Simulation Parameter Setup
• There are a number of parameters we
need to change.
• Select the Solver tab and specify the
following parameters
– Type: Fixed-step
– Solver: ode4 (Runge-Kutta)
– Fixed-Step Size: 0.001 (1 ms time step)
• These selections are shown on the
following slide.
35
Fixed step solver selected. Ode4 solver selected.
36
Simulation Parameter Setup
Next, select the Real-Time Workshop tab:
Real-Time Workshop
selected.
37
Simulation Parameter Setup
• We need to specify that we will be using a
xPC target as our target system.
• Click the Browse button,
button select the file
named xpctarget.tlc, and then select OK.
38
Simulation Parameter Setup
• Your dialog box should look as shown.
39
Simulation Parameter Setup
• We do not need to make any other
changes.
• However,
However we will look at the xPC Target
options tab to see some other options that
control behavior we will see.
• Select the xPC Target options tab.
40
41
Simulink xPC Target Library
• The Configuration Parameters are now
complete so click the OK button to accept
the settings
settings.
• Next, we need to place some xPC scopes
in our model.
• Open the Simulink Library Browser by
selecting View and then Library Browser
from the Simulink menus or clicking the
Library Browser button
•
42
Simulink xPC Target Library
• The xPC Target library is down at the
bottom of the list.
• Click on the + to expand the library:
43
Simulink xPC Target Library
• Take a minute to explore the library.
• Notice that there are both utility blocks like
scopes as well as hardware blocks from
specific hardware vendors.
44
Simulink xPC Target Library
• We are looking for the xPC Scope which is
in the Misc library:
•These
These blocks will
ill
display a trace on
the target PC
screen.
•Place two scopes
in your model as
shown.
45
Model Changes
• In the controller, we want to show the
desired speed and the motor actual speed
on the same plot
plot.
• Modify the controller block as shown:
46
Model Changes
• Next, double-click on the Target Scope
block and make the changes below.
This changes how the plot updates
updates.
You can try different settings to see
the effect.
47
Model Changes
• Other Target Scope block parameters:
We specified
p a step
p size of 1 ms. With
a decimation of 100, our scope will
only record 1 point for every 100
steps. Thus, our scope will only have
a point every 0.1 s.
48
Model Changes
• Click the OK button.
• Place another scope in the Shaft Encoder
y
subsystem of the p
plant and display
p y the Motor rpm
p
49
Model Changes
• Make the same changes to the Target
Scope block as we did before, except let
the y axis range from 0 to 3000:
• Click the OK button.
•We are now ready to
build our model.
•Type ctrl
ctrl-b
b in the
Simulink window to
build and download the
model.
50
Model Changes
• Open The Signal & Scope Manager
• Delete all of the scopes that we created.
• (The
(Th scopes will ill cause Matlab
M tl b errors in
i
the command window.)
• (The simulation will still run if you do not
delete the scopes.)
51
52
53
54
Watcom Compiler Bug Fix
• If you are using the Watcom compiler, you
will receive the error below:
55
Watcom Compiler Bug Fix
• You will need to compile and download the
model to the xPC target manually.
• In the Matlab window change to directory
Motor_Control_P_xPC1_xpc_rtw and edit
the file named Motor_Control_P_xPC1.bat
• To edit the file, right click on the file name
Motor_Control_P_xPC1.bat and then
select Open :
56
Watcom Compiler Bug Fix
57
Watcom Compiler Bug Fix
• A text editor should run and display the
text file:
58
Watcom Compiler Bug Fix
59
Watcom Compiler Bug Fix
• Next, we need to run the batch file by
entering the command
!Motor Control P xPC1 bat at the Matlab
!Motor_Control_P_xPC1.bat
command prompt.
60
Watcom Compiler Bug Fix
• When the compilation process is complete,
you will need to download the model to your
xPC target computer using the xPC Explorer.
• Change back to your working directory.
• Open up the windows explorer (if it is not
already open) by typing xpcexplr at the
Matlab command prompt.
• Connect to your xPC target.
• The available xPC models should be listed in
the xPC Explorer window.
61
Watcom Compiler Bug Fix
62
Watcom Compiler Bug Fix
63
Model Execution
• If you were successful, your model should
be downloaded to your target PC.
• If you have a monitor on your PC,
PC you
should see the following screen.
64
65
X-axis scale is 10 seconds per division. We
specified 500 samples for the x-axis with a
decimation 100. With a simulation step size of 1
ms, a decimation of 100 means that there will be
1 point recorded every 0.1 seconds. We
specified that the plot will display a total of 500
samples, so the x-axis will display 50 seconds of
Y-axis
Y axis range is 0 to 1 at data. Note that there are 5 divisions on the x-
0.2 per division. axis at 10 seconds per division.
Y-axis
Y i range is
i 0 to 3000 rpm
at 500 rpm per division.
66
Model Execution
• We are now ready to run the model on our
target PC.
• We must specify that the model should run
on a an external target.
• Select Simulation and then External from
the Simulink Menus.
• The tool bar should show that you have
selected an external target.
67
68
Model Execution
• Note that a new button has appeared.
• This button means connect to external
target
target.
• Next, we must connect to the external
target.
• Click on the button, or select
Simulation and then Connect to Target
from the Simulink menus.
69
Model Execution
• You might ask, how does Matlab know
which target to connect to.
• In the Simulation Parameters setup
setup, on the
xPC tab we specified to automatically
download the model after building, and we
specified that it should use the default
target.
• In the xPC Explorer, we specified
TargetPC1 as the default target.
• Thus, our model will run on TargetPC1.
70
Model Execution
• After connecting to the target, the play
button should become available:
71
Model Execution
• Before we start the model, we will open
the sliders and set both to zero.
• This will make all of our simulations start
at the same point.
• You may want to arrange your screen as
shown on the next slide to make it easy to
change the inputs to the model.
72
Model Execution
73
Model Execution
• When you click the play button, you should
see the screen below:
Model
M d lh has
been
running for
9.10 s.
•Everything
y g is
zero. Expected
since inputs are
zero.
74
Model Execution
• Change the speed slider and observe the
operation of the model.
• Keep the number of light bulbs at zero (no
load).
• The next few slides will show the operation
of my model as the speed slider changes.
• Note that the desired speed is the value of
the speed slider.
slider
• Proportional Gain set to 10.
75
76
Lecture 8 Demo 1
• Initial xPC real-time system response.
Demo___________
77
Model Execution
• In the previous slide:
– In the top trace, the desired speed (the value
of the slider) is shown in yellow.
– We see that the actual speed follows the
desired speed closely except for very high
speed requests.
– We also see that the system reacts very
quickly This is expected from our SIL
quickly.
simulations, and our physical understanding
of the system (ultra-low inertia motors).
78
Model Execution
• Next, we will show the effect of changing the
load on the motor.
p
• Set the speed so that the motor rpm
p is about
1500 rpm with no load.
• On my model, this corresponds to:
– Number of Light Bulbs = 0.
– Speed ≈ 0.4
79
S ll error b
Small between actuall and
dddesired
i d speed.
d
80
Model Execution
• Next, leaving the speed constant,
experiment with changing the number of
light bulbs
bulbs.
• Note that the speed is held relatively
constant until the load becomes too large
for the motor to drive.
• When the load is too high, you will see the
motor rpm drop off.
• Increase the bulb load from 0 to 6 bulbs
81
4 Bulbs.
0 Bulbs. 1 Bulbs. 3 Bulbs. 5 Bulbs. 6 Bulbs.
2 Bulbs.
82
Lecture 8 Demo 2
• Constant speed, variable load testing.
Demo___________
83
Scope Display
• For a proportional feedback system, we
know that as we change the load, the error
between the desired and actual speed
should increase.
• A large proportional gain will reduce the
error, but the error should increase as we
increase the load.
• For a bulb load of 0 to 2 bulbs, we do not
see much change in the rpm and because
of the scale of the plots.
84
Scope Display
• If we want a better look at what is
happening to the motor speeds, we need
to change the yy-axes
axes of the two plots
plots.
• There are two ways we can do this:
– Change the properties of the target scope
blocks in the Simulink model. (This requires
us to rebuild and download the model.)
– Use
U th the xPC
PC TTargett E
Explorer
l – can change
h
the axes in real-time
85
Scope Display
• Set the bulb load to zero so that the rpm is
close to 1500 and the actual and desired
speeds are close to 00.4.
4
86
Time changes
Connected to here as the model
TargetPC1. is running.
Same information
as displayed on
Expand
E d thi
this the target screen.
screen
portion of the
tree.
87
Scope Display
• Expand the portion of the tree labeled xPC
Scopes.
• Two target scopes should be shown:
– These are the scopes displayed on the xPC
Target screen.
• One Host Scope display is shown.
– This was a Simulink scope we created with the
Signal and Scope Manager.
88
Target Scopes.
Click
Cli k on SScope 1 to
select it and change its
properties.
89
Scope 1 selected.
90
Scope Display
• For Scope 1, change the limits from [0 1]
to [0.34 0.45]
• Click the Apply button to send the
changes to TargetPC1.
91
Click here.
92
93
Scope Display
• Use the same process to change the y-axis
limits on Scope 2 to be from 1300 to 1700.
94
Model Execution
• We can now see the performance of our
controller with light loads more closely.
• We will keep the speed constant at 1500
rpm (Speed = 0.4) and vary the load from
0 to 3 light bulbs.
• The performance of my system is shown
on the next slide.
95
96
Results Summary
• The proportional gain controller appears to
work ok with a gain of 10.
• As the load is changed from 0 to 3 bulb
bulb,
the speed only changes by about 170 rpm.
• When the load becomes too high, the
motor reaches its maximum power output
and can no longer keep the motor speed
constant. (We really need to verify this
conclusion by plotting the motor torque).
97
Proportional Gain
• Test Your system performance with higher
Gains:
– Proportional Gain = 20
– Proportional Gain = 50
– Proportional Gain = 100
• Note that you can change the gain in real-
time while the simulation is running.
• The Next Slide shows the system
performance for 3 bulbs at 1500 rpm and
gains of 10, 20, 50, 100.
98
No Load.
Gain = 50.
Gain = 10.
99
Lecture 8 Demo 3
• System response for constant load,
constant speed, variable feedback gain.
Demo___________
Any Questions?
System Stable
System Stable
System Unstable
System Stable
1
Lecture 9 Problem 1
• The plots demonstrated in this lecture were for our motor-
generator system without the flywheel.
• For the problems in this section, we would like to use the
transfer function from the system with the flywheel
flywheel.
• In lecture 4 problem 1, we measured the frequency response
plot of the motor-generator system including the flywheel.
• Determine the transfer function of this system from the
measured frequency plot.
• Show the magnitude frequency plot whence your transfer
function was generated.
Answer___________
2
Lecture 9 Problem 2
• For a feedback gain of 1, determine the largest fixed
time step where the system will be stable (0.1, 0.01,
0.001, 0.0001)
• Show gain and phase plots using Matlab.
• The plots should be displayed in the same manner as
shown in the notes for lecture 9.
3
Lecture 9 Problem 3
• For a feedback gain of 10, determine the largest fixed
time step where the system will be stable (0.1, 0.01,
0.001, 0.0001)
• Show gain and phase plots using Matlab.
• The plots should be displayed in the same manner as
shown in the notes for lecture 9.
4
Lecture 9 Problem 4
• For a feedback gain of 100, determine the largest
fixed time step where the system will be stable (0.1,
0.01, 0.001, 0.0001)
• Show gain and phase plots using Matlab.
• The plots should be displayed in the same manner as
shown in the notes for lecture 9.
Introduction to Model-Based
Systems Design
Lecture 10:
xPC Real-Time Systems 2
2
xPC - Demo
• Throughout this lecture you will need to
use the xpctargetspy command to obtain
copies of the xPC target screen while your
model is running.
• Print the screens out and turn them in as a
single handout.
XPCTARGETSPY
3
Integral Controller – Class Exercise
• For our next exercises, we would like to
use the PI controller developed earlier and
run it on the xPC real
real-time
time target
target.
• Open the model Lecture8_Model1.mdl.
• Save the file as Lecture10_Model1.mdl
4
Integral Controller – Class Exercise
• The top level model should be as shown.
Slider Renamed.
5
Integral Controller
• Add the integrator we developed earlier in
our SIL simulations.
6
Integral Controller – Class Exercise
• Make the Following Modifications
– Set the Simulation Configuration Parameters
for:
• a fixed step size of 1 ms using the ode4 solver
• xPC Target on the default target
– Add xPC Target scopes to display the
following:
• Motor rpm
• Controller desired speed and actual speed
• Proportional Gain and Integral Gain signals
(Specify a scope y-axis range of -2 to 2).
• Use same settings as in the previous simulation
7
Controller P Gain =1, and I Gain = 10 and
renamed P_Gain and I_Gain. (Note
the underscore in the names.)
8
Controller Model
9
Plant – Shaft Encoder
10
xPC Scope Block Modifications
Make the changes below
in all three xPC scope
blocks in the model.
Value changed.
Value changed.
11
Integral Controller – Class Exercise
• Run the simulation on your xPC Target.
• Note the following
– The integral gives us over and undershoot
undershoot.
– The integral causes ringing.
– The integral drives the error to zero in steady
state. (Even with small proportional gain.)
• The following
g screens show the
performance of my system.
12
Lecture 10 xPC 1
• Obtain a copy of the next screen using the
xpctargetspy command.
XPCTARGETSPY
13
Zero error. Integrator signal.
Measured Desired speed
speed signal. signal.
14
Lecture 10 xPC 2
• Obtain a copy of the next screen using the
xpctargetspy command.
XPCTARGETSPY
15
1 Bulb. 3 Bulbs.
0 Bulbs.
•Desired speedspeed
•Desired input input
constant at 1500 rpm. rpm.
constant at 1500
•Load changed from 0 to 3
•Load changed.
bulbs.
•P_gain = 1, I_Gain = 10.
16
4 Bulbs.
6 Bulbs.
17
Parameter Tuning
• This more complicated PI controller had a
number of interesting characteristics.
• We will use parameter tuning to change
controller parameters (such as the
proportional or integral gain).
• Parameters can be changed while the
simulation is running.
• The ability to change the controller
parameters on the fly gives us the ability to
tune the controller to a desired performance.
18
Parameter Tuning
• There are two ways we can tune
parameters:
– Using the xPC Target Explorer
– Connecting the Simulink model to the model
running on the xPC target and changing
model blocks.
• Both methods allow us to change model
parameters
t while
hil the
th model
d l is
i executing
ti iin
real-time on the xPC target.
19
Parameter Tuning
• We will use xPC Target Explorer to see
what parameters are tunable in our model.
• Assuming that our PI model is loaded on
the TargetPC1, connect to the model with
xPC Target Explorer.
– If your model is not loaded, build your model
so that it is automatically loaded on the
d f lt ttarget.
default t
• Expand the tree under Model Hierarchy
20
Model
Hierarchy tree
expanded.
Controller
subsystem.
Slider in the
top level.
Plant
subsystem.
Slider in the
top level.
21
22
Parameter Tuning
• Expand the Controller to see the tunable
parameters in the controller subsystem.
Controller subsystem
y
expanded.
23
24
Parameter Tuning
• The xPC Target Explorer allows us to find out
which parameters in the model we can change.
(We can also use the xPC Target explorer to
change the parameters, but we will do this later.)
• We will use the Simulink model to change the
values of Proportional Gain and Integral Gain
while the simulation is running.
• Close the xPC Target Explorer.
• Connect your Simulink model to the XPC Target
model and then run the simulation.
25
Model Parameter Tuning
• While the simulation is running:
• Open up the two sliders for the load and
desired speed
speed.
• Set both sliders to zero.
• Open up the controller subsystem.
• A nice arrangement for the windows is
shown on the next slide
slide.
26
27
Parameter Tuning
• Before we change any parameters, lets
run a step response with no load.
– Leave the load slider at 0 bulbs
bulbs.
– Change the desired speed slider to 0.4 and
observe the results.
28
29
Parameter Tuning
• Next, lets change the proportional gain to
10.
– Leave the model running
running.
– Set both sliders back to zero.
– Next, double-click on the Proportional Gain
block and change its value to 10.
– Click the OK button to accept the changes.
30
Double-Click
here.
Change
g to 10
and click the
OK button.
31
Parameter Tuning
• Once again, run a step response with no
load.
– Leave the load slider at 0 bulbs
bulbs.
– Change the desired speed slider to 0.4 and
observe the results.
32
No overshoot and ringing is
gone.
Proportional
control signal
much larger than
in the previous
simulation.
33
34
Integral signal.
•Same gains as
previous slide.
•Load set to two bulbs.
35
Model Parameter Tuning
• The model appears to behave very well
when we increase the proportional gain.
• For our next experiment,
experiment set:
– Proportional Gain to 1.
– Integral Gain to 100.
• Run the step response with no load.
36
More overshoot. However,
the integrator has a saturation
limits.
This limits are removed in the
next slide.
Oscillation?
•P
PGGain
i =11, I G
Gain
i = 100
100.
•Step response with no
load.
37
Lecture 10 xPC 3
• Obtain a copy of the next screen using the
xpctargetspy command.
XPCTARGETSPY
38
Integrator Saturation limits Obviously, we
removed. We see a need the integrator
overshoot, then over and saturation limits.
undershoot oscillations. We will put them
back in.
•P
PGGain
i =1 1, I G
Gain
i = 100
100.
•Step response with no
load.
•Integrator saturation limits
removed.
39
•P
PGGain
i =11, I G
Gain
i = 100
100.
•Step response with load =
1 bulb.
40
•P
PGGain
i =11, I G
Gain
i = 100
100.
•Step response with load =
2 bulbs.
41
Model Results
• From our results we can make the
following observations about our physical
system
system.
– It is a single pole system that can be
controlled easily with proportional gain.
– The integrator causes overshoot and ringing.
– If we can increase the proportional gain to
very large values:
• The difference between desired and actual speed
will become very small.
• The integrator can be eliminated.
42
Notes
• We only changed tuning parameters in our
controller.
• We can easily use parameter tuning to
observe how various plant values affect
the operation of the system as well.
• Most plant parameters have tolerance. We
can observe the effect of changing plant
parameters using the method described
here.
43
xPC Explorer
• We will now show a few techniques using
the xPC Explorer.
• We will show how to
– Load a Model
– Run a Model
– Tune Parameters
• We will start assuming
g yyou jjust started
xPC and Matlab, so
– Reboot your xPC target and restart Matlab
44
xPC Explorer
• When Matlab restarts, change to the
working directory where our motor control
files are located
located.
• Do not run Simulink.
• Run xPC Explorer by typing xpcexplr at
the Matlab prompt. Working directory.
45
xPC Explorer
• First, we need to connect to the xPC Target
computer.
• Right click on TagretPC1 and select Connect.
46
xPC Explorer
Target
connected.
47
xPC Explorer
• Once connected, we want to download the
model with the PI controller.
• Right-click
Right click on the model you want to
download (Lecture10_Model2.dlm) and
select Download to Target TargetPC1:
48
xPC Explorer
• The target screen should show 3 plots as
shown below.
49
xPC Explorer
• If you expand the TargetPC1 tree, it
should indicate that the model is loaded.
50
xPC Explorer
• To start the model, right-click on
Motor_Control_PI_xPC1 in the TargetPC1
tree and select Start:
Right-click here.
51
xPC Explorer
• You model should now be running on the
target:
52
xPC Explorer
• We will now use the xPC Explorer to set
the inputs to zero.
• Expand the Model Hierarchy tree as
shown:
53
54
xPC Target
• Changing the parameters in the xPC
Explorer is the same thing as moving the
sliders in the Simulink model when the
Simulink model is connected to the target
model.
• To see the value of a parameter, and
possibly change it, select the parameter.
• First, select the Slider Gain parameter in
the Number of Bulbs system
55
Parameter selected.
56
xPC Explorer
• We will leave the load at zero. If the
number of bulbs in your model is not zero,
you can follow the procedure shown in the
next few slides to change it to zero.
• Next, we will look at the Speed slider gain.
Select the parameter to display its value.
57
Parameter selected.
58
Value changed
g to 0.4. Then
press the Enter key.
59
xPC Explorer
• After pressing the Enter key, the Update
Parameter button becomes enabled:
60
xPC Explorer
• When you click the Update Parameter
button, the parameter change will be
downloaded to the model on your xPC
target.
• Since the model is running, you will see
the change in real-time.
• Since the parameter we are changing is
the speed, you will see the motor speed
change in response to parameter change.
• My xPC Target screen is shown next.
61
•P
P Gain
G i = 100
•I Gain = 10.
•Step response with load =
0 bulbs.
62
xPC Target
• We can use this method to change any of
the changeable parameters in the model.
• You can see all of the available
parameters by expanding the Model
Hierarchy tree.
63
64
xPC Target
• We will show a few last commands that we
can use with the xPC Target Explorer.
• To stop the model running on our xPC
Target computer, right click on
Lecture10_Model2 and select Stop
65
Right-click here.
66
xPC Explorer
• To unload the present model from our xPC
Target computer, right click on
Lecture10 Model2 and select Unload
Lecture10_Model2
67
Right-click here.
Model unloaded.
68
Gauges Blockset
• For our last example of this section, we
will show how to use the Gauges Blockset
toolbox to display the real-time
real time
performance of our model.
• Save model Lecture10_Model2.mdl as
Lecture10_Model3.mdl.
• Make the changes to the top level as
shown next.
69
Modifications to Model
Changed. Slider deleted.
Constant block renamed to
“Speed.” Value set to 0.
70
Gauges Blockset
• Open up a new model and name it
Motor_Control_PI_xPC2_Panel.mdl.
ace in two
• Place o cop
copies
es o
of the
ebblock
oc ca
called
ed To
o
xPC Target.
• These are located in the xPC Target / Misc
toolbox.
• These parts allow us to send data from the
front panel to the model running on our
xPC target machine.
• Add constants and sliders as shown.
71
Gauges Blockset
Slider range 0 to 1.
72
Gauges Blockset
• The To xPC Target blocks allow us to
change the value of blocks of a model that
is running on an xPC target
target.
• We will use the To xPC Target blocks to
change the value of constants “Load” and
“Speed” in model
Motor_Control_PI_xPC2.
73
Gauges Blockset
The To xPC Target1 block
will change the value of this
constant.
74
Gauges Blockset
• To change a value, you must know the
name of the model
(Motor Control PI xPC2) and the name
(Motor_Control_PI_xPC2)
of the blocks (Speed and Load).
• Right-click on block To xPC Target and
select Mask Parameters from the menu.
• Change the parameters as shown:
75
Gauges Blockset
76
Gauges Blockset
Name of model running on
the xPC Target.
77
Gauges Blockset
After you click the OK button, your block
should appear as shown.
78
Gauges Blockset
This block highlighted in cyan after we double-clicked on the To
xPC Target block in the front panel model. This shows that we
have successfully linked the panel to the xPC model.
79
Gauges Blockset
• Repeat the process for block To xPC
Target1 and link it to the constant block
names “Load”
Load in the xPC Target model
model.
80
Gauges Blockset
• The next thing we want to do is display the
performance of the real-time model on our
panel
panel.
• We will use a gauge for this and an LED
display.
• To transfer information from your xPC
model to the front panel, use the part
called From xPC Target, also located in
the xPC Target / Misc library.
• Place one copy in your panel model.
81
Blocks and Gauges
82
Gauges Blockset
• We wish to display the rpm of the motor in
the plant.
• This signal is located in the Plant
subsystem of the xPC model.
83
Gauges Blockset
• Open the Shaft Encoder subsystem.
We want to display this signal.
84
Gauges Blockset
• Rename the gain block from “rad/sec to
rpm” to “rad_to_rpm”
85
Gauges Blockset
• Right-click on the From xPC Target block
in the Panel model and the select Mask
Parameters from the menu:
•Fill in the
dialog box as
shown next.
86
Gauges Blockset
Model name
Motor_Control_PI_xPC2.
Block name
Plant/Shaft_Encoder/rad_to_rpm.
Note that the block rad_to_rpm is
located inside the Shaft Encoder
subsystem.
87
Gauges Blockset
88
Gauges Blockset
89
Gauges Blockset
• The last thing we want to do is display the
rpm using some of the blocks from the
Gauges Blockset toolbox.
toolbox
• Place the following blocks in your model
– Generic Angular Gauge (Angular Gauges)
– Upper Left (Angular Gauges)
– Generic Numeric LED (Numeric Displays)
90
Gauges Blockset
91
Gauges Blockset
• Double-click on the Generic Angular
Gauge block and change the values as
shown:
Max value se to 3000. (Note Delta value set to 500. (Note
Scales tab selected.) Ticks tab selected.)
92
Gauges Blockset
Note display
changes here.
93
Gauges Blockset
• Make the same changes to the Upper Left
gauge.
94
Gauges Blockset
• Double-click on the Generic Numeric LED
block and make the following changes:
Digits set to 4.
Decimals set to 0.
95
Gauges Blockset
• Make the same changes to the Odometer
block.
96
Gauges Blockset
• We are now ready to run the models.
• Compile and load model
Motor Control PI xPC2 on to the remote
Motor_Control_PI_xPC2
target by typing ctrl-b in the model window.
• Use the xPC Explorer to run the model on
the remote target.
• You should see the three simulation
graphs on your remote target as before:
97
98
Gauges Blockset
• Next, switch back to your panel model
(Motor_Control_PI_xPC2_Panel.mdl) and
run itit.
– Set the simulation type to Normal.
• As you change the sliders, you should see
the plots on the remote target respond
accordingly.
99
100
Gauges Blockset
• The Gauges and LEDs should also
change in real-time as the xPC model
runs
runs.
101
Lecture 10 Gauges - Demo
• Demonstrate your working model to me.
– Front Panel Display
– xPC Real-Time Display
Demo___________
Any Questions?
Introduction to Model-Based
Systems Design
Lecture 10a:
Atomic Subsystems and
Software-in-the-Loop (SIL)
2
Outline
• In this lecture we will take a look at two techniques that
will help verify the operation of the controller subsystem
and bring it closer to the implementation that will be
deployed on the target microcontroller
microcontroller.
• With an atomic subsystem, we can specify the order of
execution of the blocks in the controller subsystem and
give it a different simulation step size than the plant
model.
• With SIL, we will compile the controller into the same c-
code that will be deployed on the target
target, and execute the
controller subsystem as C-code rather than Simulink
blocks.
3
Models
• We will start with Model 2 from lecture 10.
• We will remove all of the xPC target scope blocks and
change the solver back to a variable step solver with a
maximum step size of 0 0.001
001 seconds.
seconds
• The Real-Time Workshop System target file has been
change from xpctarget.tlc to grt.tlc, the default target file
for new models. (Pretending that we just created this
model from scratch…..)
• The simulation mode has been set to normal.
• This model has been saved as Lecture10a_Model0 and
has been passed out as a starting point.
4
Virtual Subsystems
• In a standard model, with non-atomic subsystems (referred to
as virtual subsystems), the blocks are executed when the input
data for the blocks is available.
• That is,
is for a given time step
step, a few but not all blocks in
subsystem “a” could execute, then a few but not all blocks in
subsystem “b” could execute, then a few but not all blocks in
subsystem “c” could execute.
• Then, execution could go back to subsystem “a” and execute
the remainder of the blocks in the subsystem.
• The
Th SiSimulink
li k engine
i sortst bl
blocks
k suchh th
thatt d
data
t needed
d dbby a
particular block is always calculated prior to the execution of the
block.
5
Virtual Subsystems
• In general, some of the blocks in the controller
will execute, then some blocks in the plant, then
some blocks in the controller, then some in the
plant, and so on, until all the blocks have
executed for a given time step.
• This is not how the controller would execute in
the physical system, where all of the controller
code will execute in a specific order, execute
completely,
l t l and d th
there are no blocks
bl k iin th
the
controller because it is the physical system.
6
Atomic Subsystems
• In an atomic subsystem, when a
subsystem is executed, all blocks in the
subsystem run before execution continues
outside the subsystem. (This is closer to
how the controller will execute in the
physical system.)
• Thus, specifying a subsystem as atomic
causes all blocks within a subsystem to
execute as a group.
7
Block Execution Order
• Before we change the controller to an atomic subsystem, we
will look at the execution order of our model.
• To display the block execution order, select Format, Block
Displays, and then Sorted Order from the Simulink menus:
8
Block Execution Order
• The block diagram now shows the execution order in the form
x:y where x is the system level and y is the sorted order within
the system level x.
9
Controller Subsystem
• The Sorted Order of the controller subsystem is:
10
Controller Subsystem
• We see that the integrator sorted order is 0:0 meaning
that it is at level 0 and the first block executed in the
model.
11
Controller Subsystem
• We see that the integrator in the controller
is executed first.
• Then the constant Desired Speed (RPM)
at the top level,
• Then another unlisted block (probably the
speed slider)
• Then the remainder of the blocks in the
controller subsystem.
12
Sorted Order
• We see that a block in the controller is
executed, then blocks outside the
controller are executed
executed, then the
remaining blocks inside the controller are
executed, then execution continues with
the remainder of blocks outside the
controller.
• This order off execution is not the same as
would occur in the physical
implementation of the controller.
13
Sorted Order
• We also see that all blocks in the model
are at level zero (0:x) independent of the
subsystem in which they reside
reside.
• This is because virtual subsystems (ones
that are not atomic or triggered – the ones
we have been using so far) are graphical
conveniences for the user.
• Simulink sees all of the virtual subsystems
at the same level. (Level zero in this case.)
14
Atomic Subsystems
• Next, we will define the
controller as an atomic
subsystem.
• Return to the top-level of the
model and right-click on the
controller subsystem, then
select Subsystem
Parameters
15
Atomic Subsystems
Select this option to specify
the subsystem as atomic.
16
Atomic Subsystems
• After you type ctrl-d to update the model,
you will see the display below:
• W
We see that
th t the
th One
O Bulb
B lb constant
t t is
i now
executed 4th where before it was executed 12th.
17
Atomic Subsystems
18
Controller Atomic Subsystem
19
Controller Atomic Subsystem
• The blocks within the Controller atomic subsystem
execute as a group.
• Some blocks outside the controller will execute before,,
and some will execute after.
• Once the calculations for the Controller begin,
because we specified the Controller as Atomic, all
blocks will execute as a group before execution
continues outside the Controller.
• This order of execution is closer to how we would
expect execution of code to occur when we deploy the
controller on a hardware target.
20
Atomic Subsystems
• With an atomic subsystem, we can specify
that the subsystem execute with a different
time step than the plant
plant.
• For the plant, we will use a small time step
so that we simulate the plant accurately.
• For the controller, we will try to see how
large a time step we can use and still
obtain a stable system.
• Right-click on the Controller subsystem
and select Subsystem Parameters:
21
Atomic Subsystems
Click OK when
done.
22
Simulation Configuration Parameters
• Select Simulation and the Configuration
Parameters to view the simulation
options
options.
• We see that the a variable step solver is
specified with a max step size of 0.001
(1e-3).
23
Simulation Configuration
24
Atomic Subsystems
• The atomic subsystem will allow us to run the
plant with a small step size to simulate the
physics of the plant accurately.
• The atomic subsystem will allow us to use a
large fixed step size for the controller so that
we can determine the fixed step size needed
for the controller target hardware.
• Before we continue, because the controller
now uses a fixed sample time, we need to
make some changes to the controller.
25
Discrete-Time Integrator
• Since the sample time of the controller is
now specified as 0.1, the discrete-time
integrator within the controller will use a
sample time of 0.1 if we specify its Sample
Time as inherited:
26
Discrete-Time Integrator
27
Low-Pass Filter
• The low pass filter placed inside the controller is a
continuous time block and cannot run inside an atomic
subsystem with a fixed time step.
• In the physical implementation
implementation, the low-pass filter is an
analog circuit that filters the input signal to the
controller, and is not part of the control algorithm
implemented by the microcontroller.
• The controller is not part of the plant or the controller,
but a signal conditioning circuit between the plant and
controller.
• We will move the low-pass filter outside of the
controller and place it in the top level between the
plant and controller.
28
Signal Scaling
• The gain block inside the controller that
scales the signal to 1 is also not part of the
controller algorithm
algorithm.
• In the controller, this will be accomplished
with the analog to digital converter and a
gain block, but this will be outside of the
control algorithm.
• We will remove the gain block as well.
29
Updated Controller
30
Updated Top-Level Model
31
Signal Conditioning Block
• The contents of the Signal Conditioning
subsystem are shown below:
32
Atomic Subsystems
• When we run the simulation, we will see that
the system oscillates at the sample time
specified by the controller atomic subsystem
because the sample time of 0.1 seconds is too
large.
33
34
Controller Sample Time
• We can now see how small of a sample time we need for the
controller so that it can accurately control the system.
• We did this previously, but there is a difference.
• When we changed g the time step p before usingg the Simulation
Configuration dialog box, we changed the step size for both
the controller and the plant.
• It was possible that the large step sized used in simulating the
plant was the cause or part of the cause of the oscillations.
• Using this method, we know that the larger step size is used
only in the controller. The plant can use an arbitrarily small
step size.
• We will start reducing the Controller sample time and see how
large of a sample time we can use and achieve a stable
system.
35
36
37
C t ll S
Controller Subsystem
b t S
Sample
l Ti
Time = 0
0.001
001 s
38
Lecture 10A Demo 1
• Demonstrate the controller as an atomic
subsystem with sample times of 0.1, 0.01,
and 0.001
0 001 seconds.
seconds
Demo___________
39
Controller Step Size
• This simulation shows that a controller step size
of 0.001 to 0.003 seconds is small enough to
achieve a stable system.
• This results is similar to what we found earlier,
except we eliminated the possibility that the
oscillation was due to the plant simulation step
size.
• Now we know that the oscillations we found
when making the time step too large were
because of the large time step in the controller,
not the plant.
40
SIL Simulations
• We have taken the first step into seeing
how the controller would behave when
deployed on a controller
controller.
• We have run the controller with a fixed
time step.
• On the target, the controller will run with a
fixed time step.
41
MIL Simulations
• One problem, is that our controller is a
model made out of Simulink blocks
executing in the Matlab environment
environment.
• These type of simulations are sometimes
called Model-in-the-Loop or MIL
simulations.
• When we deploy the controller on the
target hardware, the model will be
converted to C, compiled, and then the
compiled code will run on the target.
42
SIL Simulations
• So we see a slight difference.
• In our MIL simulations, the controller is
implemented by executing Simulink model
blocks.
• On the target hardware, the controller is
implemented by executing C-code.
• How can we gain confidence that the two
implementations are the same, or at least
very close?
43
SIL Simulations
• With SIL simulations, we will convert the controller to
a block of C-code and run the C-code in our
simulation.
• The C-code
C code for the controller logic will be the same C
C-
code as deployed on the target.
• The target will have additional code in the preamble
to initialize the hardware, and some additional code
for accessing the hardware resources (analog and
digital I/O for example)
example).
• The C-code representing the Simulink blocks in the
controller will be the same.
44
SIL Simulations
• SIL simulations will give us confidence that
the C-code generated for the controller
produces the same results as the Simulink
block representation of the controller.
• We will accomplish this by creating an S-
function block out of the controller.
• An S-function is a block of C-code with
inputs and outputs to interface with the
remainder of the Simulink model.
45
Real-Time Workshop Embedded Coder
• Next, from the Simulink menus, select
Simulation and then Configuration
Parameters
Parameters.
• Select the Real-Time Workshop tab.
46
Real-Time Workshop Embedded Coder
47
Real-Time Workshop Embedded Coder
• The default System target file is grt.tlc.
• GRT stands for generic real-time target.
• GRT engages the Real Real-Time
Time Workshop – a subset of
the features of the ert.tlc (mentioned on the next slide)
• It is designed for Rapid Prototyping and hardware-in-
the-loop code generation.
• It is not as efficient or configurable as ert.tlc.
48
Real-Time Workshop Embedded Coder
• ERT stands for Embedded Real-Time Target.
• Ert.tlc engages Real-Time Workshop Embedded
Coder.
• We need to specify the System target file as ert.tlc
which generated code for embedded real-time
hardware targets.
• Click the Browse button:
49
Embedded Real-Time Coder
• Select the first ert.tlc file.
50
Ert.tlc
Ert.tlc now
specified.
Embedded coder
selected.
Click the OK
button.
51
Ert.tlc
• It turns out that the embedded coder is used by
many of the hardware vendors to generate the
code for their targets
targets.
• In this course, we will be using the rappid.tlc
System target file to generate code for our
MPC5554 controllers.
• If we edit the file rappid.tlc located in directory
C:\Program Files\RAppID Toolbox\rappid\rappid
we will see that it references ert.tlc for
generating code for the Simulink blocks:
52
Ert.tlc
53
SIL Simulations
• Because our S-function will use the ert.tlc system
target file, and because the Rappid.tlc file references
the ert.tlc file, the code generated for the S-function
will be the same as the code generated for our targets
(5554).
• Thus, we will be generating the same code for our S-
function as will be generated for the target Hardware.
• This is a good way to test the code for our controller
b f
before we ttestt it on th
the physical
h i l plant.
l t
• Make sure that ert.tlc is specified as the System
target file, save the changes, and return to the top-
level of the model.
54
S-Functions
• To create an S-
function block,
right-click on the
Controller
subsystem and
select Real-Time
Workshop , and
then Generate S-
Function
55
S-Functions
56
S-Functions
• A new model will be created containing the
S-function block.
57
SIL Simulations
• For SIL simulations, we would like to
compare the performance of the system
controlled
co o ed with the
eS Simulink
u model
ode controller
co o e
to the same system controlled with the S-
function controller.
• We can do this with the system shown next.
• Copy the S-function block back into your
original model, duplicate the plant and signal
conditioning subsystems, and wire as shown:
58
59
SIL Simulations
• We would like
to see the
difference
between the
two plant
outputs.
• We will take
the difference
b t
between th
the
two and plot it:
60
Complete Top-Level Model
61
System Performance
• The plot on the next page shows a load of zero bulbs.
• The error between the two systems is zero.
• This shows that the response of the plant to the
Simulink model controller and the S-function controller
are nearly identical.
• This gives us confidence that the code we generate
from the Simulink model that will run on our target
matches closely to the Simulink block version of the
model.
• You should run several tests at different speeds and
different loads to verify the S-function’s operation.
62
SIL Performance
63
Lecture 10A Demo 2
Demo___________
Introduction to Model-Based
Systems Design
Lecture 11:
Introduction to the MPC555x
Target
2
Installing the Software
• The software is already installed on the
computers in the Rose-Hulman Model-
Based Systems Design LabLab.
• Rose-Hulman students can skip to slide 15
and skip the software installation slides.
3
Installing the Software
• You will need the following software
components
– CodeWarrior Development Studio for
MPC55xx, Build Tools Edition (To compile our
Simulink Models)
– RAppID Toolbox (Simulink blocks to access
the MPC555x facilities)
– Esys Flasher (Download models to the
MPC555x development board)
4
CodeWarrior Installation
• Choose the following options when installing
CodeWarrior
– Choose all of the default or typical settings.
– Running the updater is not necessary.
• We will need to make the following changes:
– Copy file C:\Program Files\Freescale\MPC55xx
V2.0\bin\lmgr8c.dll
– To directory C:\Program Files\Freescale\MPC55xx
V2 0\P
V2.0\PowerPC_EABI_Tools\Command_Line_Tools
PC EABI T l \C d Li T l
5
CodeWarrior License
• Request a license from Freescale
• Copy the license.dat file to the following
Directories:
– C:\flexlm
– C:\Program Files\Freescale\MPC55xx V2.0\License
– C:\Program Files\Freescale\MPC55xx V2.0
6
Installing RAppID Toolbox
• Unzip file RAppIDToolboxECV101Release.zip
• Run file setup.exe
– Select the default choices.
choices
– Restart your system.
• Request a License File
– In the RAppID Toolbox program group, run
g
the License Requestor program:
7
Installing RAppID
• Copy the license file to direcory
C:\RAppID_Lic
• Run Matlab.
Matlab
– Change the working directory to C:\Program
Files\RAppIDToolbox\rappid
– From the Matlab Command Line prompt, run
the command rappid_path
8
Installing RAppID
• Next We have to set up an environment
variable in Windows.
• Right click on My Computer and select
Properties:
9
Installing RAppID
• Select the Advanced tab
• Select the Environment Variables button.
Advanced tab
selected.
10
Installing RAppID
• Select the New button as shown:
11
Installing RAppID
• Add a new environment variable
“MW_TOOL” (Note all caps!)
• Give it a value C:/
C:/"Program
Program
Files"/Freescale/"MPC55xx V2.0"
• (Note that you might have a different
version of the compiler.)
12
Installing RAppID
• Click the OK button to define the new
environment variable.
• Click the OK button two more times to exit
the My Computer dialog boxes.
• You will need to restart MATLAB so that it
will recognize the new variable.
13
Installing eSys Flasher
• Run eSysFlasher_v1.3_setup.exe
– Select the defaults.
– Restart your system.
system
14
Installing eSys Flasher
• Plug in the P&E Microcomputer USB
Multilink device into your USB port.
– Select to not use the internet to find a driver.
driver
– It should find the driver locally.
– If the driver installs properly, the blue light
should illuminate on the USB Multilink Box.
15
Connecting the Hardware
• Plug in the ribbon cable of the USB
Multilink into the port labeled JTAG on the
MPC555x board.
– Note that the red stripe should line up with pin
1 on the JTAG connector.
16
MPC555x
• We will now create a simple project where
we flip-flop two LEDs on the MPC555x
board
board.
• If we can do this, we can do anything!
• Note that pin connections for the
MPC555x board are documented in file
MPC5554DEMO_man_G.pdf.
17
MPC555x LED Flasher
• Run MATLAB, run
Simulink, and then
open a new Simulink
Project.
• In the RAppID
library, locate a block
called RAppID-EC
and place it in your
model:
18
MPC555x Setup
19
MPC555x Setup
20
MPC555x Setup
• Select Configuration, Compiler Config,
and then MetroWerks from the menus:
21
MPC555x Setup
• Select Configuration, Target Type, and
then Internal Flash from the menus:
• This command
tells the system to
use non-volatile
flash memory
rather than RAM.
• Select
S l t File
Fil andd
then Save.
• Select File and
then Exit.
22
MPC555x Setup
• The Target Setup block should show the
changes to the configuration:
MetroWerks compiler
and Internal Flash
memory selected.
23
MPC555x Digital Output
• We would like to turn
on two LEDs.
• Place two General
Purpose Output
blocks in your model.
24
MPC555x Digital Output
• Double click on the blocks and select an
output.
• We will use:
– Pin 203: Primary Function “GPIO”
– Pin 204: Primary Function “GPIO”
• After making the changes, your model
should look a shown:
25
MPC555x Digital Output
26
LED Flasher
• We would like the LEDS to flash on and off
at a 1 Hz rate.
• We need to select a discrete solver and
specify a fixed time step of 1 ms. (We can
actually, use a larger time step, but we’ll
use 1 ms.)
• Select Simulation and then
Configuration Parameters from the
Simulink menus.
• Select the solver tab and fill in a shown:
27
LED Flasher Enter infinity (inf).
28
LED Flasher
• If you look at the Real-Time Workshop tab,
you will notice that our model has been
setup for RAppID:
• Click OK to
accept the
changes
we made in
the Solver
tab and
close the
dialog box.
29
Clock
• The next thing we need to do is to add a 1
HZ clock.
• We will do this with a Pulse Generator
block located in the Simulink / Sources
library:
30
Pulse Generator
Pulse width and period are
calculated based on the
number of samples.
31
Compare to Constant
• We would like the LEDs to flip-flop on and
off.
• When one LED is on on, the other should be
off.
• We could do this with a logic function.
• Instead, we will use a compare to constant
block.
• The Compare to Constant block is
located in the Simulink / Logic and Bit
Operations library.
32
Compare to Constant
• Specify the settings a shown:
Compare operator set to
less than or equal to.
to
33
Data Types
• The GPO (general purpose output) blocks
require a Boolean data type for an input.
• The Compare
p to Constant block has the
right output data type.
• The Pulse Generator block as a double-
precision output data type.
• We need to convert from a double-precision
data type to a Boolean.
• Use the Convert block located in the
Simulink / Commonly Used Blocks library.
34
Convert Block
• Specify the Output data type mode to be
Boolean:
35
Complete Model
36
Data Types
• It is important that we use the correct data types
for all of the blocks.
• We can show the data types on the model.
• Select
S l t Format,
F t Port/Signal
P t/Si l Displays,
Di l and
d th
the
Port Data Types from the Simulink menus to
display data types on the model.
37
Displaying Data Types
• To check the model for errors and display
data types, type ctrl-d in your model
window:
38
Data Types
• For this simple model, the data types look
correct.
• The GPO blocks require a Boolean input
input,
and our input data types are Boolean.
• We can now build the model.
• Type ctrl-b to build the model.
• You should see the progress of the build
process in the Matlab command window.
39
40
Build
• If the build completes successfully, you
should see the ending text blow in the
command window:
41
Downloading the Model
• The next thing we need to do is download
the model to our board.
• Make sure that your MPC555x board has
the power turned on.
• Make sure that the USB link is plugged
into a USB port and that it is plugged into
the JTAG port on your MPC555x board.
• Run the eSys Flasher program.
42
eSys Flasher
• Select the P&E Wiggler (USB) option.
43
eSys Flasher
• If you have communication between your
computer and MPC555x, you should see
the screen below:
Click here to
program your board.
b d
44
eSys Flasher
• Select the S-Record File type and click
the Program button:
45
eSys Flasher
46
eSys Flasher
47
MPC555x Wiring
• Next, we need to connect the GPO
outputs on the MPC555x board to the LED
display on the MPC555x board
board.
• Information documenting the MPC555x
demo board is located in file
MPC5554DEMO_man_G.pdf.
• In our model we are using GPO 203 and
GPO 204.
• Open this file and search for the text 203.
48
MPC555x Output Pins
49
MPC5555 Output Pins
50
MPC555x
• We need to locate pins G25 and H24 on
the MPC555x board.
• We can do this by looking at file
MPC5554DEMO_TOP_F-G.pdf in the
MPC555x documentation, or by looking at
the board:
51
MPC555x Board
52
MPC555x Board
53
MPC555x
• We would like to hook up these digital
outputs to the LED display on the
MPC555xDemo boardboard.
• We will use LED1 and LED2.
• The LED connector is shown on the next
slide:
54
MPC555x Board
55
MPC555x Board
56
MPC555x Wiring
• Use the patch-cord wires to connect the
digital outputs to the LEDs.
• When you cycle the power to the board
board, or
press the Reset button, the LEDs should
flash on and off at a 1 Hz rate.
57
Lecture 11 Exercise 1
• Change the LED flasher frequency to 2 Hz
and demonstrate your working system.
Demo___________
58
Lecture 11 Exercise 2
• Create an 8-Bit ring counter that changes
state every ½ second.
• Do not use Stateflow to do this
this.
• The LED output sequence is shown below:
10000000
01000000
00100000
00010000
00001000
00000100 Demo___________
00000010
00000001
59
Lecture 11 Exercise 3
• Create an 8-Bit up-down ring counter that
changes state every ½ second.
• Do not use Stateflow to do this
this.
• The LED output sequence is shown below:
10000000 00000010
01000000 00000100
00100000 00001000
00010000 00010000
00001000 00100000
00000100 01000000
Demo___________
00000010 10000000
00000001 01000000
60
Lecture 11 Exercise 4
• Create an 8-Bit ring counter that:
– Changes the rate at which the counter changes state.
– For five seconds, the state should change every 0.1
seconds.
– For 5 seconds, the state should change every 0.2
seconds.
– The rate change continually flips between 0.1 and 0.2
seconds every 5 seconds.
• Do not use Stateflow to do this
this.
61
Lecture 11 Exercise 4 (Cont)
• You may want to display sample times on the
model. Select Format, Port/Signal Displays,
and the Sample Time Colors from the Simulink
menus.
• You may need to use a Rate Transition block
located in the Simulink / Signal Attributes
library.
Demo___________
Any Questions?
Introduction to Model-Based
Systems Design
Lecture 11A:
The FreeMASTER Debugging
Tool
2
FreeMASTER
• We will next look at a tool called FreeMASTER
from Freescale Semiconductor that allows us to
observe the value of Simulink signals inside the
MPC555x microcontroller in real-time.
• We will assign names to signals of interest in
the Simulink model.
• FreeMASTER can then display the value of the
signal:
– As a text display that is updated at a specified rate.
– Graphically in a plot.
3
Setup
• The only additional setup required is to
connect your PC to the MPC555x board
using a 9-pin
9 pin serial cable
cable.
• The cable plugs into the port labeled
COM-1 on the MPC555x board.
• The communication settings will be
specified in your Simulink model with a
configuration block and a setup dialog box
in FreeMASTER.
4
Two-Speed Ring Counter
• We will start with the model created in Lecture
11, Exercise 4.
• As a reminder,, this model did the following:
g
– Create an 8-Bit ring counter that:
• Changes the rate at which the counter changes state.
• For five seconds, the state should change every 0.1 seconds.
• For 5 seconds, the state should change every 0.2 seconds.
• The rate change continually flips between 0.1 and 0.2
seconds every 5 seconds.
5
Two-Speed Ring Counter
Two-Speed
Ring Counter
6
FreeMASTER
• To use the FreeMASTER tool, we need to place
a block called eSCI_FMSTR_Interface in our
model
model.
• This block is located in library RAppID-Toolbox
/ Utility Blocks / FreeMaster_Interface
• This block sets up the serial communication on
the MPC555x board.
• The only option is the baud rate, which we will
leave at 57600:
7
FreeMASTER
• We can view any signal in the model.
• To view a signal, we need to name the
signal line and then declare the storage
class as ExportedGlobal.
• To name a signal line, right-click on the
signal line and select Signal Properties.
• We will name the signal lines of the
Repeating Sequence signal sources.
• Right-click as shown next:
8
Naming Signals
9
Naming Signals
• Specify the name of the signal as
Repeating_Signal_Fast
Specify signal
name here.
10
Naming Signals
• Next, select the Real-Time Workshop tab and
specify the Storage class as ExportedGlobal:
Select
ExportedGlobal.
11
Naming Signals
12
Naming Signals
• Name the following signals shown on the next few
slides.
• Be sure to declare them as ExternalGlobal.
Signal named.
Signal named.
13
Naming Signals
14
Naming Signals
15
Model Complete
• We have now named all of the signals of
interest.
• Build y
your model and download it to the
MPC555x target.
• Verify that the model runs correctly by displaying
the correct pattern on the LEDs.
– The purpose of learning the FreeMASTER tool is to
help us debug models that are not working correctly.
– We already know that this model works.
– The purpose of this model is to learn how to use the
FreeMASTER tool.
16
Data Types
• Before we continue, it is good to note the data
types of the signals we will be viewing:
• Double
– Repeating_Sequence_Slow,
Repeating_Sequency_Fast, Sequence
• Boolean
– Bit0 through Bit7
• We will need this information later when we
select signals.
17
Run FreeMASTER
18
FreeMASTER Options
• We now need to set up the communication
port and specify the mapping file for the
model
model.
• Select Project and then Options from the
FreeMASTER menus:
19
FreeMASTER Setup
• The default com port is COM1 (which should
work for us) and the speed is 115200.
• In the FreeMASTER setup p block we p
placed in
the model, the BAUD rate was set to 57600.
• Change the speed to 57600: Change to 57600.
Comm tab
selected.
selected
20
FreeMASTER Setup
• Next select the MAP Files tab:
21
MAP Files
• The MAP files are symbol mapping files for our model.
• We are looking for a file with the extension .elf.
• The file is contained in a directory created by Simulink
Simulink.
• If your model name was “x” then the file would be
named “x.elf” and located in directory “x_rappid_rtw”.
• This directory is created by Simulink and placed in the
working directory.
• Select the .elf
elf file for your model:
22
MAP Files
23
MAP FIles
• Next, select the File format as Binary ELF
with DWARF1 or DWARF2 dbg format.
24
FreeMASTER
• After clicking the OK button, we should be
able to establish communication with the
MPC555x board
board.
• In the lower right corner of the
FreeMASTER window, the text
RS232;COM1,speed=57600 should be
displayed:
25
26
Communications
• If you did not establish communication
between FreeMASTER and your
MPC555x board:
– Check the BAUD rate setting of the
eSCI_FMSTR_Interface block in your
Simulink model.
– Check the Speed settings in FreeMASTER by
selecting Project and then Options from the
menus.
– Make sure that you know which port on your
computer is COM1.
27
Watched Variables
• Next, we will display the values of signal
Repeating_Signal_Slow.
• Right click as shown next and select
Create New Watched Variable:
28
Right-click here.
29
30
31
Watched Variables
• Make the following selections
Speed set to fastest.
Repeating_Sequence_Slow
32
Speed Note
• We have selected the Sampling period to fastest.
• If you recall, the fast repeating sequence had a
sampling time of 100 ms.
• To see the waveforms, we need a sampling rate that
is about 10 times faster than 100 ms or about 10 ms
for each signal we are displaying.
• There are two problems with requiring this fast of a
sample rate:
– The tool might not be able to sample this fast.
– If we wish to display a lot of the signals, the faster we
sample, the more data we need to communicate over the
RS232 link.
– At some point the link will become saturated and we will not
be able to view some of the data.
33
Watched Variables
• After Clicking the OK button, you will see
the variable and its value displayed.
• The value is updated at the specified rate:
34
Lecture 11A Demo 1 Demo___________
35
Scopes
• Next, we would like to generate plots of
the three signals.
• Right-click
Right click on the text New Project and
select Create Scope
36
Scopes
• Fill in the Main tab of the dialog box as shown:
A catchy name.
37
Scope Properties – Setup Tab
• The setup tab is used to assign watched
variables to the plot.
• Click on the down arrow as shown:
38
Scope Properties – Setup Tab
• Select Repeating_Sequence_Fast:
39
Scope Properties – Setup Tab
• Next, click as shown to select the second
trace and Block 1:
Click here!
Click here!
40
Scope Properties – Setup Tab
• Click on the down arrow as shown and
then select Repeating_Sequence_Slow
Click here!
Click here!
41
Scope Properties – Setup Tab
• You should see the screen below:
42
Scope Properties – Setup Tab
• This screen shows that signal
Repeating_Sequence_Slow is displayed in Block 0
and signal Repeating_Sequence_Fast is displayed in
Block 1
1.
43
Scope Properties – Setup Tab
• We will now repeat the procedure to
display signal Sequence in Block 3.
44
Scope Properties – Setup Tab
• Click as shown to select the third trace
and Block 2:
Click here!
Click here!
45
Scope Properties – Setup Tab
• Click on the down arrow as shown and
then select Sequence
Click here!
Click here!
46
Scope Properties – Setup Tab
• You should see the screen below:
47
Scope Properties – Setup Tab
• This screen shows that signal
Repeating_Sequence_Slow is displayed in Block 0,
signal Repeating_Sequence_Fast is displayed in
Block 1,
1 and signal Sequence in Block 2
2.
• When you click the
OK button, you will
return to the
screen shown next:
48
Demo___________ 49
Lecture 11A Demo 2
Demo___________ 50
Lecture 11A Problem 1
• Create the following display of information:
Demo___________ 51
Lecture 11A Problem 2
• Create the plot shown on the next page.
Note that only bits 0 through 6 are shown.
52
Lecture 10A Problem 2
Any Questions?
Introduction to Model-Based
Systems Design
Lecture 12:
Number Systems
2
Outline
• Binary
• Hexadecimal
• M tl b Functions
Matlab F ti
• Unsigned Integers
• Signed Integers
• Floating Point Numbers
3
Number Systems
• There are two kinds of engineers in this
world
– Those who know binary and those who don’t.
– That was a joke.
– If you don’t know binary, you probably didn’t
get it.
• This section is for the engineers that didn’t
didn t
get it.
4
Base 10
• Most of us are familiar with base 10
number systems.
• Valid digits are 0 through 9 (Hey! There
are 10 values!)
• The base is also referred to as the radix.
• An example is:
5
Binary
• Binary uses a radix of 2.
• Valid values of a digit are 0 and 1.
( ) ( ) (
10110 = 1× 2 4 + 0 × 23 + 1× 2 2 + 1× 21 + 0 × 20 ) ( ) ( )
Radix = 2
Binary
10110
0’s place
4’s place
7
Binary
• Historically and physically our choice of 0
and 1 for a binary digit comes from:
– Switches which can be on or off off.
– Digital logic circuits that produce either a low
voltage or a high voltage.
• Typical 5 V logic circuits
– Low = logic 0 Æ Voltage from 0 to 0.8 Volts.
– High = Logic 1 Æ Voltage from 3.4 to 5 Volts.
• Synonyms
– 1 = logic 1 = “high” = “True”
– 0 = logic 0 = “low” = “False”
8
Terminology
• A single binary digit is referred to as a bit.
• A group of 4 binary digits is referred to as
a nibble
nibble. (1011 1110) is two nibbles
nibbles.
• A group of 8 binary digits is referred to as
a byte (10111110) is one byte.
• 1k (for digital guys) is 210 = 1024
• 1M (for digital guys) is 1k * 1k = 210 *2210=
1048576.
9
Hexadecimal – Radix = 16
• We will be dealing with long strings of bits.
• It is convenient to group those bits in
groups of 44.
Binary Hex Decimal Binary Hex Decimal
0000 0 0 1000 8 8
0001 1 1 1001 9 9
0010 2 2 1010 A 10
0011 3 3 1011 B 11
0100 4 4 1100 C 12
0101 5 5 1101 D 13
0110 6 6 1110 E 14
0111 7 7 1111 F 15
10
Hexadecimal
• In decimal every digit can have ten values,
0 through 9.
• In hexadecimal each digit
g can have16
values ranging from 0 to 15.
• Hey, we need a single symbol for each
digit!
• How do we do this with only 10 numeric
symbols in our mathematical vernacular.
– For numbers 0 through 9, use 0 through 9.
– For numbers 10 through 15, use letters A
through F.
11
Hexadecimal
1011
{ 0110
{ 1101
{ 0111
{ 0011
{
B 6 D 7 3
( ) ( ) (
B6 D73 = 11×16 4 + 6 × 163 + 13 ×16 2 + 7 × 161 + 3 × 160 ) ( ) ( )
12
Useful Matlab Functions
• Bin2dec – Converts a binary text string to
a decimal number:
>> bin2dec('10110110110101110011')
ans =
748915
13
Useful Matlab Functions
• Hex2dec – Converts a hexadecimal string
to a decimal number:
>> hex2dec('B6D73')
ans =
748915
14
Matlab
• How do we convert from binary to hex?
( ( ))
>> dec2hex(bin2dec('10110110110101110011'))
ans =
B6D73
15
Hexadecimal Numbers
• If we see a number like 123, how do we
know if it is a hexadecimal or decimal
number? ((It could actuallyy be anyy base
greater than 3, but we won’t go there.)
• Ways of indicating a number is a
hexadecimal number
hex 123 - saying it.
$123 - precedingdi th the number
b with
ith a $ sign.
i
x123 - preceding the number with an x which
is short for “hex.”
12316 – Indicating the base explicitly.
16
Basic Data Types in Simulink
• Boolean – True or False (not 0 or 1 numerically)
• Uint8 – Unsigned 8-bit integer. Can represent
values from 0 to 255.
111111112
= 27+26+25+24+23+22+21+20
= 28-1 = 25510
• Uint16 – Unsigned 16-bit integer. Can represent
values from 0 to 65535.
11111111111111112
= 215+214+213+ … + 22+21+20
= 216-1 = 6553510
17
Basic Data Types in Simulink
• Uint32 – Unsigned 32-bit integer. Can represent
values from 0 to 4294967295.
111111111111111111111111111111112
= 231+230+229+ … + 22+21+20
= 232-1 = 429496729510
18
Signed Integers
• There are three common ways of
representing signed numbers
– Sign and magnitude: The most significant bit
represents the sign. (1 is negative, 0 is
positive)
• 10001 would represent the number -1.
• 11111 would represent the number -15.
• 00001 would represent
p the number 1.
• 01111 would represent the number +15.
19
Signed Integers Sign and Magnitude
• With sign and magnitude representation:
– There are an equal number of positive and
negative values that can be represented.
– There are two ways to represent 0:
• 1000000
• 0000000
• We will not be using this method to
represent signed integers
integers.
20
Signed Integers Biased Values
• With biased values, to calculate the
numerical value of the code, calculate the
magnitude of the code and then subtract
off a fixed bias.
• Example: 5-bit codes, bias = 15.
00000 Ævalue = 0 – 15 = -15
00001 Ævalue = 1 – 15 = -14
01111 Ævalue = 15 – 15 = 0
10000 Ævalue = 16 – 15 = 1
11111 Ævalue = 31 – 15 = 16
21
Signed Integers – 2’s Complement
• We will be using a method called two’s
complement to represent positive and
negative integers
integers.
• With 2’s complement, the most significant
bit has a negative weight.
Note this (-) sign.
( ) ( ) (
10110 = − 1× 2 4 + 0 × 23 + 1× 2 2 + 1× 21 + 0 × 20 ) ( ) ( )
= − 16 + 6
= − 10
22
2’s complement Numbers
( ) ( ) (
00110 = − 0 × 2 4 + 0 × 23 + 1× 2 2 + 1× 21 + 0 × 20 ) ( ) ( )
= −0+6
= 6
23
2’s complement Numbers
• We will do some 8-bit examples.
• The most negative number is
27 = -128
10000000 = -2 128
• The most positive number is
011111111 = 127
• The code for -1 is
111111111 = -27+127
-27 127
24
2’s complement
• There is only one representation for 0
– 00000000
25
Signed Integer Types in Simulink
• Int8 – 2’s complement signed 8-bit integer. Can
represent values from -128 to 127.
10000000 = -27 = -128
011111111 = 127
• Int16 – 2’s complement signed 16-bit integer. Can
represent values from -32768 to 32767.
1000000000000000 = -215 = - 32768
0111111111111111 = 32767
• Int32 – 2’s complement signed 32-bit integer.
Represents values from - 2147483648 to 2147483647.
– 10000000000000000000000000000000 = -231 = - 2147483648
– 01111111111111111111111111111111 = 2147483647
26
Floating Point Numbers
• The MathWorks help facility has a good
section on floating point numbers.
• The following few slides were generated
from the information contained in the
MathWorks help facility.
• Search for the topic, “floating-point
numbers” in the MathWorks help facility to
find more in-depth information.
27
Floating Point Numbers
28
Floating Point Numbers
• Fixed-point numbers are limited in that they
cannot simultaneously represent very large or
very small numbers using a reasonable word
size.
• This limitation can be overcome by using
scientific notation.
• With scientific notation, you can dynamically
place the binary point at a convenient location
and use powers of the binary to keep track of
that location.
29
Scientific Notation (Decimal)
• Most of us are familiar with scientific
notation.
– d is a decimal digit with values from 0 to 9
9.
– We can move the decimal point right or left by
decreasing or increasing the power of 10 by
which we multiply.
30
Binary Point
• Binary numbers can have a fractional part
just like decimal numbers:
( ) ( ) ( ) (
101.11 = 1× 2 2 + 0 × 21 + 1× 20 + 1× 2 −1 + 1× 2 −2 ) ( )
101.11 = (1× 4 ) + (0 × 2 ) + (1× 1) + (1× 1 2 ) + (1× 1 4 ) = 5.75
Binary point.
31
Radix Point Notation (Binary)
• Radix point notation is similar. Here we
show radix notation for binary (radix = 2).
– b is a binary digit with values of 0 or 1
1.
– We can move the binary point right or left by
decreasing or increasing the power of 2 by
which we multiply.
± b.bbbb × 2 p = ± bbbbb.0 × 2 p − 4
Binary point. = ± 0.bbbbb × 2 p +1
32
IEEE Floating Point Standard 754
• Single Precision – 32 bits
( )
⎧(− 1)s ⋅ 2 e −127 ⋅ (1. f ) ; normalised ,0 ≤ e ≤ 255, f ≥ 0
⎪
( )
Value = ⎨(− 1) ⋅ 2 e −126 ⋅ (0. f ) ; denormalised , e = 0, f > 0
s
⎪exceptional value
⎩
33
32-bit Floating point example
• 1 10111101 10100000000000000000000
s e f
• s = 1 Æ we have h a negative ti number. b
• e = 10111101=18910
• Æ (2 ) = (2 ) = (262 )
e −127 189 −127
• f = 10100000000000000000000
• 1.ff = 1.10100000000000000000000
= (1× 20 ) + (1× 2−1 ) + (0 × 2−2 ) + (1× 2−3 ) + (0 × 2−4 ) + (0 × 2−5 ) + ....
= 1.625
34
32-bit Floating Point Example
• Our number is
• -1.62510 * 262
• = -7.493989779944505
7 493989779944505 x 1018 (decimal)
(d i l)
35
IEEE Floating Point Standard 754
• Double Precision – 64 bits
( )
⎧(− 1)s ⋅ 2e −1023 ⋅ (1. f ) ; normalised ,0 ≤ e ≤ 2047, f ≥ 0
⎪
( )
Value = ⎨(− 1) ⋅ 2e −1022 ⋅ (0. f ) ; denormalised , e = 0, f > 0
s
⎪exceptional value
⎩
36
Floating Point Numbers
Data Type Low Limit High Limit Exponent Precision
Bias
37
Floating Point Numbers
• NaN – Not a number.
• There are two types of NaN:
– A signaling NaN signals an invalid operation
exception.
– A quiet NaN propagates through almost every
arithmetic operation without signaling an
exception.
• The
Th ffollowing
ll i operations
ti resultlt iin a N
NaN:
N
∞−∞ ∞+∞
0× ∞ 0/0
∞/∞
38
Lecture 12 Problem 1
• Determine the decimal value of the following
bit string (it is 32 bits in length.)
• 10011100111011100110111000000011
• Assuming the following data types
– Uint32 (magnitude)
– Int32 (2’s complement)
– Sign
g and magnitude
g
– Single precision floating point
• Create an m-file that displays all four results
in an mbox.
39
Lecture 12 Problem 2
• Determine the decimal value of the following
bit string (it is 32 bits in length.)
• 01000000111010000110100000000011
• Assuming the following data types
– Uint32 (magnitude)
– Int32 (2’s complement)
– Sign
g and magnitude
g
– Single precision floating point
• Create an m-file that displays all four results
in an mbox.
40
Lecture 12 Problem 3
• Create an m-file that defines a arbitrary 32 character
text string, the contents of which are zeros and ones.
For example,
‘01000000111010000110100000000011’
• The script then displays the value of the bit string in an
mbox, assuming the four data types below:
– Uint32 (magnitude)
– Int32 (2’s complement)
– Sign and magnitude
– Single precision floating point
• Demonstrate your function with a binary value given
by your instructor.
41
Lecture 12 Exercise 1
• Create an counter that changes state every ½ second.
• Do not use Stateflow to do this.
• The repeating LED output sequence is shown below:
00000000 11111111
10000000 01111111
11000000 00111111
11100000 00011111
11110000 00001111
11111000 00000111
Demo___________
11111100 00000011
11111110 00000001
42
Lecture 12 Exercise 2
• Create an counter that changes state every ½
second.
• Do not use Stateflow to do this.
• The repeating LED output sequence is shown below:
00000000 11111111
10000000 11111100
11000000 11111000
11100000 11110000
11110000 11100000
11111000 11000000
Demo___________
11111100 10000000
11111110
Questions?
Introduction to Model-Based
Systems Design
Lecture 13:
MPC555x Digital Input
2
MPC555x Digital Output
• The digital output blocks work about the
same as the digital input blocks.
• These blocks read a 1-bit
1 bit digital input
input.
• The output of the block is a Boolean data
type.
• Use block General Purpose Input located
in library RAppID
RAppID-Toolbox
Toolbox / GPIO
Blocks.
3
MPC555x Digital Input
• We will modify the ring counter we used
before.
• When a push-button
push button is pressed,
pressed the
counter will shift the bit to the right.
• When the push-button is not pressed, the
counter will shift to the left.
• (Right and left are relative. At least I did
not say clockwise.)
• We will start with the ring counter shown
next.
5
MPC555x Digital Input
• Place the General Purpose Input block in
your model.
• Select an input channel.
channel
• Add the remainder of the blocks shown.
7
MPC555x Digital Input
• After the convert block, the Digital Input
Block will output a numerical value of
either 0 or 1
1.
• The threshold of the switch is set to 0.5 so
that there is no ambiguity in the switch
state.
• Use file MPC5554DEMO_man_G.pdf to
determine the correct pin connection for
your chosen digital input.
8
Push-Button Switches
• The MPC555x Demo boards have four push-
buttons for your use.
• Page 7 (Section User Components /
U
User_Switch)
S it h) off th
the U
User’s
’ MManuall specifies
ifi ththe
properties and pins for the push-buttons:
9
Push-Button 1
• This switch has a de-bounced output. This means that
when you press or release the button, you only get a
single edge at the output pin.
• Think of a toggle switch as two metal balls being flipped
back and forth by a spring. When the two metal balls
collide, they will mechanically bounce apart repeatedly
until the kinetic energy is dissipated. When the balls are
touching, the switch is closed. When balls are separated,
the voltage dips down. As the balls mechanically
bounce, the voltageg bounces up p and down as well.
10
Push-Button 1
• CMOS Output (Pin 1) – Can drive a load.
VCC
Switch 1 Pin 1
Debounce 3
10k 2
Logic
+
3.3 V CMOS Buffer
- SW1
11
Push-Button 1
• Open Drain Output (Pin 2) – Cannot drive
a large load.
VCC
VCC 10k
Switch Pin 2
Debounce
10k
Logic
+
3.3 V
- SW1
12
Push-Button 1
• The open drain output is logically
equivalent to the following circuit:
VCC
VCC 10k
Switch Pin 2
Debounce
10k
Logic
+
33V
3.3
- SW1
13
Push-Button 1 (Pin 2)
• When the switch is closed, VCC
14
Push-Buttons 2,3,4 (Pins 3,4,5)
• These switches are shown below.
• Note that the switches are not de-bounced.
VCC
15
Push-Button Switches
• We can use any of the 4 switches (pins 1
through 5) as our digital inputs.
• The physical location of the switch
connections can be found using file
MPC5554DEMO_TOP_F-G.pdf.
• The location of the USER_DEV jumpers is
shown next:
16
17
Pin 1 Pin 8
Pin 2
18
Lecture 13 – Demo 1
• Wire up your circuit.
• Modify the model to display the value of
the digital input and the count using the
FreeMaster tool.
• Compile and download the model.
• Demo your working system.
– The ring counter should change direction
when the push-button is pressed.
Demo___________
19
Ring Counter Problem
• The preceding example has a problem in
that when you change the direction of the
counter the illuminated LED may jump
counter,
several places depending on the count.
• We will correct this problem by creating
our own counter.
• We will first create a counter that shifts in
one direction, but holds and remembers its
position when a push-button is pressed.
20
Triggered Subsystems
• We will use a triggered subsystem.
• Triggered subsystems give us a method to
allow different parts of our program to run
at different rates.
• We will create the system shown next.
This looks pretty close to the previous ring
counter except that we added a triggered
subsystem:
21
22
Triggered Subsystem
23
Triggered Subsystems
24
Triggered Subsystem
• In our example, the entire model is
executed once every 0.001 seconds, as
this the fixed time step we specified in the
simulation setup.
• The triggered subsystem executes once
every 0.5 seconds, as this is the frequency
we will specify for the pulse generator.
• (We will use the triggered subsystem to
increment our counter once every 0.5
seconds.)
25
Triggered Subsystems
• There are two ways to create a triggered
subsystem:
– Use the Triggered
gg Subsystem
y block located
in the Simulink / Ports & Subsystems
library.
– Use a standard Subsystem block. Inside the
subsystem place a Trigger block (also
located in the Simulink / Ports &
Subsystems library).
– With the trigger block, you can specify a rising
edge, falling edge, both rising and falling
edges, or a function call trigger.
26
Triggered Subsystem
• The pulse generator in our example is set
to generate a rising edge every 0.5
seconds (period set to 500 samples)
samples).
27
Triggered Subsystem
• The contents of the subsystem are shown below:
Double-click on this block to change the trigger
type (rising, falling, either, function call).
28
Subsystem Operation
• The input to the subsystem is numerically
either 0 or 1.
1
• The Z block is a one simulation time step
delay. The output of the block is the input
from the previous time step.
• The Simulink model below would be a
counter that counts up at the rate specified
by the trigger:
29
Counter
30
Mod 8 Counter
• In our system, when the count is above
6.5, we set the input to the sum block to -1
so that we get 0 when we add 1 to it:
31
Mod 8 Counter
• Some details about the blocks are shown
next.
32
Sum Block
• The Output data type mode of the Sum block
should be set to double. If you do not do this,
Simulink may not be able to determine the data
types due to the feedback loop:
33
Unit Delay Block
• The sample time of the block should be
set to -1 (inherited) and the initial condition
should be set to zero.
zero
34
Switch Block
• The threshold of the Switch block should be set to
6.5. (We did not choose a threshold of 7 because
you can sometimes have trouble determining if two
floating point numbers are numerically equal.)
35
Model Sample Times
• If you show sample colors on your model
(select Format, Port/Signal Displays,
and then Sample Time Colors from the
Simulink menus) you will see that the
subsystem executes at a different rate
than the main portion of the model.
• The main model is shown in red indicating
that it has the fastest
f sample time.
• The subsystem is shown in cyan,
indicating that it is a triggered subsystem:
36
Sample Time Colors
37
38
Triggered Subsystem
Demo___________ 39
Lecture 13 - Demo 2
Mod 8 counter using a triggered subsystem.
• Wire up your circuit.
• Use the FreeMASTER tool to monitor the following signals for
the triggered
gg subsystem:
y
– The input.
– The output
– The switch output
– The output of the 1/z block
– The trigger
– An example display is shown on the next slide.
• Compile and download the model.
• Demo your working system.
• The counter should hold when you press the pushbutton.
40
Lecture 13 - Demo 2
41
Lecture 13 Exercise 1
• You will notice that the counter does hold when
press the bust-button. However, there is a
problem:
• When the count reaches 7 and you press the
hold push button, all of the LEDs go out and the
count holds (actually at -1).
• Fix this problem so that the count always holds
when the button is pushed, the counter always
remembers the count, and there is one LED on
at all times.
Demo___________
42
Lecture 13 Exercise 2a Demo___________
43
Lecture 13 Exercise 2b Demo___________
44
Lecture 13 Exercise 3
• Create an up-down ring counter that changes
direction when you press a push-button. (A hold
button is not required).
• The counter should not skip or jump when you
press the button. (The count should be
continuous).
• A second push-button should be used to change
the counting frequency. You should be able to
change directions and speed simultaneously.
Demo___________
45
Lecture 13 Exercise 4
• Create two 4-bit ring counters with the following
properties:
– One counter shifts to the right, the other shifts to the left.
– One counter counts at a 1 Hz rate
rate, the other at a 10 Hz rate
rate.
– Your fixed step size is 1 ms.
– Two push-buttons are available that hold the individual counters.
While holding, the counters cannot lose their count. The hold
functions on each counter are independent of the other counter.
• You are required to use triggered subsystem to solve
this problem.
Demo___________
Questions?
Introduction to Model-Based
Systems Design
Lecture 14:
MPC555x Analog Input
2
MPC555x Analog Input
• The MPC555x processor has over 40
analog inputs.
• There are two analog to digital converters
on the processor, so only two channels can
be sampled at the same time.
• Depending on the sample rate, the
accuracy of the conversion is up to 12 bits.
3
Analog Voltmeter - Bar Graph
• We will read a 0 to 5 V signal with an
analog input.
• We will then scale the measured value to
light up LEDs in a linear bar graph.
• Start with a new model and place the
RAppID-EC block in it.
– Set the compiler
p to Metrowerks
– Set the target type to Internal flash.
• You should have an empty model except
for the RAppID-EcoCAR block.
4
Analog Input
• Double-click on the RAppID-EcoCAR
block to obtain the configuration window.
• Click on the eQADC block to configure the
ADC blocks.
Click here.
5
ADC Prescaler
System clock is 128
MHz.
6
Command Message
7
Command Message
8
Command Message
10
Command Message
Choose unsigned since we will be
reading a 0 to 5 V signal.
11
Command Message
12
DMA and Interrupts
DMA.
Enabled.
DMA
DMA.
Enabled.
13
DMA and Interrupts
14
DMA and Interrupts
15
RAppID Setup
16
eQADC Block
• Next, we can place an ADC block in our
model.
• Place a block called eQADC_getdata
eQADC getdata
from library RAppID-Toolbox / Peripheral
Driver Blocks / eQADC Blocks in you
model:
17
eQADC Get Data
18
eQADC Block
19
eQADC
• We will not be using the timestamp
output, so we will connect it to a
terminator
terminator.
• The data output is:
– Has 12 bits of resolution.
– Returned as an unsigned 16-bit integer
(UINT16)
– Centered in the middle 12 bits of the 16 bit
integer! Æ We need to divide by 4 to get at
the 12 bit integer.
20
Voltmeter Model
• The remaining logic of our model is shown
in the next three slides:
21
Voltmeter Model
22
eQADC Initialization
• The last thing we need to do is initialize
the ADC at system start-up.
• Place a block called Simple Target
StartupHook in your model. (Library
RAppID / Utility Blocks / Simple
TargetHookRoutuines.)
• This block generates a function call trigger
at system startup. We will use this to
trigger a subsystem at startup.
23
System Init
• Place a triggered Subsystem in your model
and change the trigger type to a function call
trigger. Your top level model should look as
shown:
24
System Init
• In the triggered subsystem, place a block
called eqadc_triggercmd located in
library RAppID
RAppID-Toolbox
Toolbox / Peripheral
Driver Blocks / eQADC.
• Change the FIFO Queue to Queue 0
(same as we specified in the eQADC
setup slides.)
• You subsystem should look as shown on
the next slide:
25
System Init
26
Analog Voltage Reference
• The last thing we need is a 0 to 5 V signal.
• The MPC555x Demo board has two
potentiometers that will g
p generate this
signal.
• The voltages are available on the same
jumper as we used for the push-button
switches.
27
Analog Voltage Reference
• Pins 7 and 8 are connected to two
separate potentiometers.
• We can use either one as our input.
p
• The location of the pins and the
potentiometers are shown on the next
slide.
28
Pot RV1
Pot RV2
29
30
Lecture 14 – Demo 1
• Analog Input – Demo
• Wire up you circuit.
• Compile and download the model.
• Display all signal values using FreeMASTER:
• Demo your working analog voltmeter / bar graph.
Demo___________
31
Embedded MATLAB Functions
• Before we look at our next example with analog
inputs, we will look at the Embedded MATLAB
Function.
• This function allows us to use MATLAB functions
within a Simulink model.
• The Embedded MATLAB Function block supports a
subset of the language for which it can generate
efficient embeddable code.
• For details about the Embedded MATLAB subset,
see Working with Embedded MATLAB in the
Embedded MATLAB documentation.
32
Embedded MATLAB Functions
• To generate embeddable code, the Embedded
MATLAB Function block relies on an analysis
that determines the size and class of each
variable.
• This analysis imposes the following additional
restrictions on the way in which the above
features may be used.
– The first definition of a variable must define both its
class
l andd size.
i Th
The class
l and
d size
i off a variable
i bl
cannot be changed once it has been set.
– Whether data is complex or real is determined by the
first definition.
33
Embedded MATLAB Functions
• The preceding limitations require you to code in a certain
style.
• Some common idioms to avoid are listed in Limitations
on Indexing Operations and Limitations with Complex
Numbers in the Embedded MATLAB documentation.
34
Embedded MATLAB Functions
• In addition to language restrictions, Embedded MATLAB
Function blocks support only a subset of the functions
available in MATLAB.
• A list of supported functions is given in the Embedded
MATLAB Run-Time Function Library in the Embedded
MATLAB documentation.
• These functions include common categories
– Arithmetic functions like plus, minus, and power
– Matrix operations like size, and length
– Ad anced matri
Advanced matrix operations like lu,
l inv,
in svd,
s d and chol
– Trigonometric functions like sin, cos, sinh, and cosh
35
Ring Counter
• As an example of using an Embedded
MATLAB Function, we will modify the ring
counter model we developed earlier
earlier.
• Instead of using the compare to constant
blocks, we will use a single Embedded
MATLAB Function block.
• The ring counter model we will start with is
shown next.
36
37
Ring Counter
• Remove the Compare to constant blocks and
place a single Embedded MATLAB
Function block in yyour model.
• The block is located in library Simulink /
User-Defined Functions.
38
Double-click on this
block to open it.
39
Embedded MATLAB Function
• When you open the Embedded MATLAB Function
block, a text editor opens and displays the
function.
• Note that the block inputs and outputs are derived
from the function declaration in the first line of the
function.
40
Embedded MATLAB Function
The block will have a single The block will have a
output labeled y. single input labeled u.
41
Embedded MATLAB Function
• We have a single input that is the count.
• We need eight outputs, one for each LED.
• An
A example
l iimplementation
l t ti is i shown
h next:
t
42
43
Outputs predefined as
false and declared as
Boolean data types.
We will not need a
convert block.
A pretty lame
implementation.
44
Embedded MATLAB Function
• When we save the function and look at the
Simulink model, we see that the block
name input,
name, input and outputs reflect the
function declaration:
45
Embedded MATLAB Function
• Connect the function as shown.
• We will need a convert block for the input
to convert the data type of the free running
counter to double.
• When you type ctrl-d, you will notice that
the output signals from the LED_Out block
are Boolean data types.
46
47
Embedded MATLAB Function
• A different realization of the embedded function
is shown below:
48
Embedded MATLAB Functions
• The last implementation we will show uses
a row vector for the output.
49
Embedded MATLAB Functions
Block has a single
output that is a
vector of 8 values.
50
Embedded MATLAB Functions
51
Embedded MATLAB Functions
Size is specified as -1
Variable y selected.
which means that
Simulink must figure it
out.
52
Embedded MATLAB Functions
53
54
Lecture 14 – Demo 2
• Wire up you circuit.
• Compile and download the model.
• Demo
D your working
ki system.
t
– Ring counter with embedded Matlab function.
Demo___________
55
Lecture 14 Exercise 1 Demo___________
56
Lecture 14 Exercise 2 Demo___________
57
Lecture 14 Exercise 3
• Create a ring counter using a Truth Table.
Demo___________
58
Serial Communication
• We will now show an example of using the
Enhanced Serial Communication Interface
(eSCI)
(eSCI).
• This will show examples of:
– Embedded MATLAB function
– For Iterator
– Index Vector
• We will start with the voltmeter me made
earlier.
59
Serial Communication
• We will convert a 0 to 5 V analog signal to
a numerical value of 0 to 500.
• We will convert the number to an arrayy of
ASCII codes.
• We will output the codes to the serial COM
port and view it with a terminal program
such as HyperTerminal.
• We
W willill use a ttriggered
i d subsystem
b t tto
output the text string once a second.
• The top level model is shown next:
60
Gain = 1/16.
61
Serial Communication
Trigger the subsystem
Scale the analog
once a second.
signal to 0 to 500.
Look in here.
62
Output ASCII Text String
63
65
Embedded Functions
• To see what the function does, we can
copy and paste the function into an m-file
and then test it at the command prompt.
prompt
• Some examples are shown next:
66
ASCII 32 is a space.
ASCII 3
67
Output ASCII Text String
Note that this output is an array.
N t look
Next, l k iinside
id thi
this subsystem.
b t
68
Output ASCII Text String
Iterate from 1 to the length of the ACSII string. (The value of output ‘len’ in the previous
slide.). Make sure you check the indexing method. Make sure that it is ones based.
69
Output ASCII Text String
Transmit 1 character at a
time.
This block located in library RAppID-
Toolbox / Peripheral Driver Blocks /
eSCI Blocks.
70
Serial Output
• Using a 9-pin serial cable, connect your
computer to COM 1 of the MPC555x
board
board.
• Use hyper terminal to view the results.
• You will need to set the baud rate
appropriately. (57600, 8-N-1)
71
Lecture 14 Demo 3
• Wire up you circuit.
• Compile and download the model.
• Demo
D your working
ki system.
t
– Analog voltmeter with ASCII output.
Demo___________
72
Function Call Triggered Subsystems
• For the next example, we will show how to
force a sequence of events to occur in a
specific order
order.
• We will do this with triggered subsystems
that use a function call for the trigger.
• The previous example just output a
numerical value between 0 and 500.
• We would like to output the text, ‘Analog
Input 1: ‘).
73
Function Call Triggered Subsystems
• Next, we would like to output the text
equivalent for the number.
• Finally,
Finally we would like to output a period
period,
carriage return, and a line feed.
• We will break up the three sections into
three triggered subsystems.
• We will show how to force the subsystems
to execute in a specific order.
74
Function Call Triggered Subsystems
• We will use the previous Voltmeter model
and make a few modifications.
• The changes are shown below:
75
Function Call Triggered Subsystems
Generate a rising edge
once a second.
Standard rising edge triggered
subsystem. Let’s look inside.
76
Function Call Triggered Subsystems
All this subsystem does is
generate a function call
trigger. Basically, we are
converting an edge
trigger to a function call
trigger.
trigger
77
Function-Call Generator
Sample time set to -1
(inherited) because we
are inside a triggered
subsystem.
78
Function Call Triggered Subsystems
One edge here triggers all three
subsystems once, in order from left to
right.)
This system
triggered first.
79
Subsystem1 Trigger changed from rising edge to
function call.
80
Subsystem2 The embedded function was modified slightly.
The carriage return and line feed are no
longer added at the end of the number. The
modified function is shown next.
81
Embedded MATLAB Function
82
Subsystem 3 Trigger changed from rising edge to
function call.
83
Lecture 14 Demo 4
• Compile and download the model.
• Demo your working system.
• Example
E l output
t t from
f my model
d l is
i shown
h
below:
Demo___________
84
Lecture 14 Exercise 4
• Read two analog input voltages. Use
potentiometers RV1 and RV2 as your inputs.
• Use RV1 to control the outputp of yyour LED
voltmeter.
• Output the following text strings every second,
and in the same order (must be forced in this
order using function call triggered subsystems):
Analogg Input
p 1: xxx.
Analog Input 2: yyy.
Demo___________
85
Lecture 14 Exercise 5
• Use the analog input and a potentiometer to
control the speed at which your ring counter
shifts.
• The counter frequency should be continuously
variable from 1 Hz to 10 Hz.
Demo___________
Questions?
Introduction to Model-Based
Systems Design
Lecture 14A:
RHIT Debug Blocks
2
MPC555x Analog Input
• In lecture 14 we learned how to write ASCII
text to the eSCI port and display that text
with a terminal program such as MS
Terminal.
• The display was somewhat limited as we
could only display line after scrolling line:
3
Terminal Emulation
• When you ran MS terminal, you might have
seen something that reminded you of days
gone past (if you are old like me):
Emulation is
VT100.
4
Video Terminals
• Back in the days of mainframes and video terminals
that printed on paper, VT100 video terminals were the
terminals that dreams were made of.
• Most people used terminals that printed on paper
using a ribbon and a 9-wire head. (If you could afford
it, you would have a 24 wire printer.)
• Techie with toys, professors with huge research
grants, and geeks that would buy hardware rather
than food, used video terminals.
5
VT100
• The VT100 was introduced by Digital
Equipment Corporation (DEC) in 1978.
• The screen had a resolution of 80
characters wide by 23 lines.
• Typically, in a video terminal as with
terminals that printed on paper, text would
print one line at a time.
• Text would move to the next line if you
sent the printer a carriage return and a line
feed.
6
Escape Control Sequences
• The cool thing about the VT100 is that it had non-
printing key sequences that allowed you to move the
cursor around the screen, highlight and underline text,
and many other screen functions.
• We will reach back into the distant past of 1978 to
dredge up ESCape key sequences to make the ASCII
text debugging tool more useful.
• Along the way, we will learn escape key sequences,
high tech in 1978, which will impress absolutely no
one when you go for a job interview.
• However, we will make some useful debugging tools.
7
Terminal Emulation
• First, we must set MS Terminal to emulate
a VT100 so that it will respond to escape
sequences
sequences.
• Select File and then Properties from the
MS Terminal menus:
8
Terminal Emulation
• Select the Settings tab and then specify
VT100 as the Emulation:
Emulation set to
VT100
9
Escape Codes
• You can usually find the escape key sequences if you
search on Google for “VT100 Escape Codes.”
• Some codes are
• <ESC>[H - Move the cursor to the home position. (The upper left
corner.)
• ESC>[{row};{column}H – Move the cursor to the specified
coordinates. 1,1 is the upper left corner (home). The column can go
from 1 to 80, the row can go from 1 to 23.
• <ESC>[K - Erase from the current cursor position to the end of the
line.
• <ESC>[1K - Erase from the current cursor position to the beginning
of the line.
• <ESC>[2J - Erase the entire screen.
10
Escape Codes
• <ESC>[{attr1};…{attrn}m -Set Attributes.
– 0 Reset all attributes
– 1 Bright
– 2 Dim
– 4 Underscore
– 5 Blink
– 7 Reverse
– 8 Hidden
• Source: http://www.termsys.demon.co.uk/vtansi.htm,
http://www termsys demon co uk/vtansi htm
Date accessed February 1, 2010.
11
RHIT Library
• In lecture 14, we learned how to send text
strings.
• Escapep key y sequences
q are jjust non-printing
p g text
strings.
• We will use them to place text on the screen in
specific locations and with various properties.
• We have created a library of blocks for Rose-
Hulman.
• The library is named A_My_Library and can be
found using the Simulink Library Browser.
12
RHIT Library
• It was called A_My_Library so that it would
appear at the top of the list:
13
RHIT Library
• The RHIT Library has a sub-library called
MPC555x Debug Blocks.
• This contains a number of blocks that use
the eSCI port to display text messages using
the VT100 Escape codes.
• Before we start, we will open model
Volt_Meter3 (passed out as
Lecture14A_Model0).
• Save the model as Lecture14A_Model1.mdl.
14
ASCII Test String Output
• If you notice, this model used triggered subsystems to
display a text screen on the terminal screen.
Triggered
gg subsystems
y to
display text.
15
RHIT Debug Blocks
• Block MPC555x ASCII Debug Block in library
A_My_Library / MPC555x Debug Blocks is a
subsystem created from the blocks enclosed in
the red box on the previous slide.
• The subsystem is masked, and passes
parameters to the subsystem contained within.
• The block is shown below:
16
MPC555x ASCII Debug Block
• The input to the block is the numerical
value it will display
• If you double
double-click
click on the block
block, it will open
as if it were any other Simulink block:
• Here you enter the text
you wish to be
displayed before the
numerici value
l andd th
the
rate at which you want
the value refreshed (in
milliseconds).
17
MPC555x ASCII Debug Block
• Click the OK button to close the dialog box.
• If you right click on the MPC555x ASCII Debug Block and then
select Look Under Mask, you will see the subsystem that
implements the block:
• This is the same set of blocks
that we used to display an
ASCII text string in the volt
meter model.
• The only difference is that the
text before and pulse
generator period are specified
using masked subsystem
parameters rather then hard
coded into the constants.
18
MPC555x ASCII Position Debug Block
• The MPC555x ASCII
Position Debug
Block is the same as
the Debug Block
except that is uses
ESCape key
sequences to position
the cursor at a
specified position on
the VT100 screen:
19
MPC555x ASCII Position Debug Block
• If you look under the mask, you will see that the
text string contains the sequence <ESC[
{row},{Column}H.
• Note that 27 is the ASCII code for the ESCAPE
key.
20
Debug Blocks
• Several other blocks are defined for placing
text a specific locations on the screen and
making the text underlined, reverse, or
blinking.
• Note that the MPC555x Debug Clear Screen
block only clears the screen and should be
used as the first block called to clear the
screen andd remove unwanted t d old
ld ttext.
t
• The input to the clear screen block is a trigger.
21
Lecture 14A Problem1
• Add debug blocks to model
Lecture14A_Model1 to obtain the display
shown on the following slide
slide.
• Values should be updated every 250 ms.
No unwanted text should appear on the
screen.
Demo___________ 22
Lecture 14A Problem1
Demo___________ 23
Lecture 14A Problem2
• We would like to create a new subsystem block that
displays text with the following characteristics.
• The input to the block is a numerical value of type
double
double.
• The block should be a masked subsystem that specifies:
– The row and column where the block is placed on the screen.
– The text displayed on the screen before the numerical value.
– The period in milliseconds at which the numerical value is
refreshed.
– Two threshold values:
• When the numerical value is below Threshold1, the text is displayed in
black.
• When the numerical value is between Threshold1 and Threshold2, the text is
underlined.
• When the numerical value is above Threshold2, the text blinks.
Questions?
Introduction to Model-Based
Systems Design
Lecture 15:
Analog Output (PWM)
2
PWM
• A high current variable DC supply is hard
and expensive to build.
• Many systems have a fixed voltage DC
supply available.
• We can make a “variable” DC supply by
“chopping” a constant DC supply on and
off at high frequency.
• The average value of the voltage is
variable.
3
PWM +
+ VO
5V
-
-
4
PWM
T
tON
⎛t ⎞ ⎛ 12.5 μs ⎞
Vavg = 5V ⎜ on ⎟ = 5V ⎜⎜ ⎟⎟ = 1.25V
⎝T ⎠ ⎝ 50 μs ⎠
5
PWM
• In a PWM waveform, we vary the on time
and keep the period constant.
T
tON
⎛t ⎞ ⎛ 25 μs ⎞
Vavg = 5V ⎜ on ⎟ = 5V ⎜⎜ ⎟⎟ = 2.5V
⎝T ⎠ ⎝ 50 μs ⎠
6
PWM
tON
⎛t ⎞ ⎛ 37.5 μs ⎞
Vavg = 5V ⎜ on ⎟ = 5V ⎜⎜ ⎟⎟ = 3.75V
⎝T ⎠ ⎝ 50 μs ⎠
8
PWM
• From a circuit point of view, we can extract
the average value using a low pass filter.
• Choose the cutoff frequency (FC) of the
filter to be much less than the frequency of
the PWM waveform.
• Note that the frequency of the PWM
waveform F is 1/T. R
+ +
C
Analog Voltage
PWM Waveform In Î (Average) Out
- -
1
FC =
2πRC
9
PWM
• Note that objects with a large inertia
cannot respond on a microsecond time
scale
scale.
• These items respond to the average of the
waveform rather than the instantaneous
value.
• Examples are solenoids and motors.
• We can speed control a motor using
pulse-width modulation.
10
MPC555x eMIOS PWM Output
11
MPC555x eMIOS PWM Output
• Open the block to specify the initial duty
cycle, the initial PWM frequency, and the
PWM channel:
• In file
MPC5554DEMO_man_
G.pdf, search for the
text EMIOS to find the
pin number for your
channel.
12
Mobile Studio Desktop
• Create the model shown below.
• Build your model and download it to your
MPC555x board
board.
• We will use Mobile Studio Desktop to
observe the output waveforms for this
lecture.
13
Mobile Studio Desktop
• Mobile Studio Desktop is a combination
hardware/software solution that replaces traditional
bench top in an educational lab with a single board
that plugs into your laptop’s USB port.
• Instruments included are an oscilloscope, spectrum
analyzer, function generator, and logic analyzer.
• The product was developed as a joint venture
between Rose-Hulman Institute of Technology and
Rensselaer Polytechnic Institute
14
Mobile Studio Desktop
• The hardware board is shown below:
15
Mobile Studio Desktop
• We will be using Channel 1 of the
oscilloscope to display the PWM
waveform
waveform.
• Hook up two clip leads to the A1+ and
Ground terminals of the board as shown:
Channel 1 positive
reference (A1+).
Channel 1 ground
reference.
16
Mobil Studio Desktop
• Plug in the USB cable into the board and your
computer.
p p
• Connect the A1+ terminal to the PWM output pin on
your MPC555x board
• Connect the ground terminal on the Mobile Desktop
Studio board to a ground pin on your MPC555x board.
• Run the Mobil Studio Desktop application from your
PC.
• The application is in the Windows Start Menu at
Rensselear/Mobile Studio Desktop/Mobile Studio
Desktop.
17
Mobile Studio Desktop
18
Oscilloscope
19
Oscilloscope
• Select Windows and then choose to
display Channel 1 and the Horizontal
Settings
20
Horizontal settings
•Time/Div: 100 µs
•Mode: Y-T
21
PWM Waveform
• The PWM Waveform is shown below:
22
Lecture 15 Demo 1
• MPC555x eMIOS PWM Output
• Verify that the frequency is 20 kHz and that
the duty cycle is 50%
50%.
• Display waveforms of the PWM output with
the Mobile Studio Desktop Oscilloscope
Demo___________
23
MPC5554 eMIOS PWM Output
• Next, we would like to create a 60 Hz
analog sine wave using the PWM output.
• Create the model shown:
Time-based sine
wave.
24
MPC5554 eMIOS PWM Output
• The settings of the sine
wave are shown below.
Note that the pulse width
never goes to 0 or 100
%.
25
Lecture 15 Demo 2
• Demo the PWM output of the sine wave
using a 2 kHz PWM waveform.
• The duty cycle should change with the
sine wave input.
• We are using a 2 kHz waveform so that
we can easily see that the pulse-width
change with the sine wave.
• When we filter the sine wave later, we will
need to increase the PWM frequency to
generate a smooth analog waveform.
26
Lecture 2 Demo 2 Demo___________
27
Lecture 15 Demo 3
• MPC5554 eMIOS PWM Output
• Add the filter shown below and observe a 60 Hz Sine Wave at
the output of the filter.
q
• Choose the cutoff frequency y of the filter to be 600 Hz or higher.
g
(A decade above 60 Hz)
• You may need to increase the PWM frequency to reduce the
ripple on the filter output. (20 kHz or higher.)
• Display the Sine wave on Channel 1 of the scope, Display the
PWM waveform on Channel 2 of the scope.
R
+ +
C
Demo___________
- -
28
Motor Control Demo
Create the following model.
29
Lecture 15 Demo 4
1) Before connecting the motor, verify that
you can use the POT to control the output
duty cycle.
cycle (Display in the scope)
Demo___________
30
Motor Control Demo 5
2) Once you have verified the PWM signal
on the scope, connect the PWM output of
the MPC555x to the PWM input of the
motor controller demo.
3) Verify the motor speed is controlled by
the potentiometer.
Demo___________
Questions?
Introduction to Model-Based
Systems Design
Lecture 15A:
Hardware In The loop Simulations
2
HIL
• Up to this point we have:
– Learned several levels of simulations: Model-
in-the-Loop
in the Loop (MIL), Software-in-the-Loop
Software in the Loop (SIL)
and Real-Time.
– Learned several software packages:
MATLAB, Simulink, RAppID, FreeMASTER,
– Used many platforms: Windows, xPC
– Used several different hardware targets: PC
PC,
xPC, MPC5554.
3
HIL
• It is now time to put it all together and perform
Hardware-in-the-loop (HIL) simulations.
p in
• We will start with the full model developed
Lecture 10A and split the model so that:
– The controller runs in the MPC5554 target.
– The plant runs on the Speedgoat xPC target.
• The two targets will be connected with a wiring
harness, the same harness that will be used in
the final product.
• Both models will run in real time.
4
HIL
• This is a test of the controller:
– Hardware - It is running on the target we will
use in the final implementation.
– Speed - It is running in real time.
– Wiring Harness - It is connected to the plant
using the same interface that will be used in
the final implementation.
• If the controller works when hooked to our
virtual plant, we have confidence that it will
work when we hook it to the physical plant.
5
HIL
• We will start with Lecture10A_Model3.mdl and
split it into two models, the plant and the
controller.
• The plant will:
– Run on the xPC Target.
– The xPC Target: Speedgoat I/O Driver blocks will be
used to create a shell to interface between the model
and the physical world.
– The inputs and outputs will be analog voltages.
• The controller will
– Run on an MPC5554 target.
– Use RAppID to interface between the model and
physical world.
– The inputs and outputs will be analog voltages.
6
HIL
• We will be using the test platform below:
7
HIL
• We will split the development of the HIL
system into several steps:
1 We will deploy the controller on to the
1.
MPC5554 target.
2. We will deploy the plant on to the xPC
target.
3. We will test the plant with analog inputs and
verify its operation.
operation
4. We will connect the controller and plant
together using a wiring harness.
5. We will test the entire system.
8
HIL
• If the controller on the MPC5554 target works
successfully in the HIL simulation:
– We will take the final step of testing the controller
by connecting it to the physical plant.
– If it works, we will drink (depending on your state
of mind):
• Champagne
• An energy drink
• Mountain Dew (non-diet for the full compliment of sugar)
• Or all of the above in no specific order.
HIL Simulations
10
Motor Controller Deployment
• From lectures 11 through 15, we now know how
to use the hardware resources of the MPC555x
well enough to use it as the target for the
controller of our motor-generator system.
• We will use the control method we proved,
tested, and verified in the MIL, SIL, and real-
time portions of the class.
• First, we will create a shell that accesses the
hardware resources of our target (MPC555x).
11
Motor Controller Deployment
• The controllers we developed for our
motor-generator system all used the
following input:
– Speed Set point – A continuous (analog)
signal between 0 and 1. We will use one of
the potentiometers on the MPC555x board for
this reference. We read this as a 5 V signal
and then scale it to 0 to 1 in the MPC555x.
12
Motor Controller Deployment
• The controllers we developed for our
motor-generator system all used the
following input:
– Motor rpm – An analog signal measured from
the motor rpm sensor (shaft encoder). The
encoder outputs a signal that is 2.5 V per
1000 rpm. We scale this signal to 0 to 4 V with
g
resistors and then read the signal with the
MPC555x. Internal to the MPC555x, the
signal is scaled to a number between 0 and 1.
13
Motor Controller
Controller Deployment
Realization
on the
• The MPC5554
controllers weTarget
developed for our
motor-generator system all used the
following input and outputs:
– Controller Output – In our simulations, the
torque request from the controller was a
signal between 0 and 1. We will scale this
signal to 0 to 100 and then use PWM output
of the MPC555xMPC5554 y drive our motor.
to directly
Target
14
Motor Controller Deployment
• The controllers we developed for our
motor-generator system all used the
following output:
– Motor torque request. An analog signal
between 0 and 1. The realization will be a
PWM signal between 0 and 100%
– The actual input to the plant is a PWM input
that directly controls the gate of a MOSFET
chopper circuit.
– The PWM output of the controller directly
modulates the waveform to the motor.
15
Hardware Shell
• We will now create a top-level “shell” for
our controller that:
– Initializes the MPC555x
MPC555x.
– Reads and scales the analog inputs.
– Passes the information to a subsystem that
contains our control method.
– Outputs a PWM signal for the requested
torq e
torque.
16
Hardware Shell
• The basic idea is that our interface to the
hardware will not change that much.
• Given the same interface,, we can make
significant changes to our control method.
• All of these changes will be implemented in the
controller subsystem.
• The hardware shell will remain relatively
g
unchanged. ((Occasionally,
y, a new control
method will require new inputs or outputs. In this
case, we will need to modify the hardware shell.)
17
Hardware Shell
Target Setup Block
Start Analog Input Queues
18
Hardware Shell
All controller logic goes in
here.
19
Hardware Shell
All controller logic goes in
here. PWM output to drive motor.
20
ASCII Output
• As a last
enhancement,
we will display
th d
the desired
i d andd
measured rpm
using RHIT
Debug blocks
we used earlier.
21
FreeMASTER
• It is also suggested that you use FreeMASTER to
monitor signals within the controller including the
Speed_Setpoint, Measured_Speed, and the controller
Torque Request output.
Torque_Request
22
Debugging Tools
• Note that you might not be able to use
both the FreeMASTER tool and the RHIT
debug blocks at the same time as they
both use the eSCI port.
• You can attempt to use both. However, if
they are incompatible, you should use the
one you feel most comfortable with and
the one that gives you the most
information and help in debugging the
system.
23
Complete Hardware Shell
24
Controller
• We now will use the controller from Lecture10A_Model3.
• Note that this model was an SIL test and had two versions
of the controller, an s-function and a Simulink model. We
will be using the Simulink
S model, as it will be compiled
and downloaded to the MPC555x target.
• The idea is that we proved the controller in Lecture 10A in
many simulation methods and this is the most mature of
our controller models.
• In the HIL simulation we are about to run, except for any
misunderstanding of the hardware target performance or
the wiring interface between the controller and plant, the
controller performance should be close to what we
observed during our previous simulations.
25
Controller.
• Lecture10A_Model3 was the most mature
controller we developed.
• The last tests we did were our SIL
simulations.
• The model is shown on the next few
slides.
26
SIL Model Most of the stuff in here goes in
our controller in the target. (Look
inside on next slide.)
27
SIL Model - Controller
28
MPC555x Target - Controller
29
Controller
• Build the model and download it to the
MPC5554 target.
• We will not be able to test it yet
yet, but you
should verify that the two LEDs flash and
toggle back and forth.
• We are now ready to work on the plant.
30
HIL Simulations
31
Plant Model
• In Lecture 10, we simulated the entire model
(plant and controller) using xPC Target.
• Here we want to run just the plant on xPC
target.
• The same plant model was used for Lecture 10
and Lecture 10A.
• Thus, we will use model Lecture 10 as a
starting point.
• Most of the settings used in lecture 10 will apply
here as well.
32
Lecture 10 Model 3
33
Plant Model
• At the top level, delete the controller and
control inputs.
34
Plant Model
• Inside the plant is a single xPC Target
Scope displaying the motor speed in rpm.
• Add xPC Target scopes to display:
– The Torque Request input to the plant.
– The Number of Bulbs input to the plant.
– The encoder output in volts.
35
Plant Model xPC Target Scope
xPC Target Scope
added here!
added here!
36
Encoder Model
xPC Target Scope
added here!
37
Speedgoat target.
• We are going to use the Speedgoat Target libraries
and I/O blocks to provide physical inputs and
outputs for out plant model.
• We
W mustt first
fi t configure
fi th
the hhardware
d on th
the
Speedgoat PCM730 board.
• We did this in Lecture 3A, but we will review it here.
• Place a Simulink block named PMC730 5 located in
the xPC Target: Speedgoat I/O Driver Library /
IO101 library
lib iin your model.
d l
38
PMC730 Acromag Setup
• This single block is used to setup all functions of
the PMC730 card.
• Onlyy 1 copy
py of this block is needed to set up p the
analog I/O and digital I/O facilities of the card.
• Double-click on the block to open it.
• Note that the block will appear differently
depending on the parameter group selected.
• The screen captures on the next page show the
same block with different Parameter groups
selected.
39
40
PMC730 5 Acromag Setup Bblock
• We notice that the module identifier in all of the
screen captures on the previous slide was set to 1.
• If a Speedgoat target has more than one PMC730
target, we can use this card to address each PMC730
individually.
• Our targets have a single PMC730 installed, so the
module identifier will be specified as 1.
• We will now set the parameters on this block to have
a single analog input and a single analog output.
41
PMC730 5 Acromag setup block
• We fist must specify the Module setup.
• Since we only have a single PMC730 module, we can
specify that xPC automatically determine in which slot
th PMC730 is
the i installed.
i t ll d If we had
h d more than
th one
PMC730 installed, we would specify the slot
manually:
Module 1 specified.
Module setup
p specified.
p
42
PMC730 5 Acromag setup block
• We need to specify two channels for analog input:
Module 1 specified.
43
PMC730 5 Acromag setup block
• We need to specify one channel for analog output:
Module 1 specified.
44
Analog Output
• Next, we will add an analog output block to the
plant output.
• Place a block called PMC730 2 located in the
xPC Target: Speedgoat I/O Driver Library /
IO101 library in your model.
• Connect it to the plant as shown:
45
Analog Output
• The settings for the analog output block are:
46
Analog Input
• We will use an analog input channels to measure the torque
request and number of bulbs.
• Place a block called PMC730 1 located in the xPC Target:
Speedgoat I/O Driver Library / IO101 library in your model.
• After placing the block, if you type Ctrl-d, two inputs will be
shown on the block. This is because in the Acromag block, we
specified two analog input channels.
47
Analog Input
• The properties of the analog input block
are:
48
Plant Model
• We are now done with the hardware setup
for the plant.
• Since we copied this model from the xPC
model developed in Lecture 10, the
simulation parameters should be set up
correctly.
• However, just to make sure the settings
are correct, we will show the required
settings in the next two slides.
49
Simulation Parameters
50
Simulation Parameters
51
Plant Deployment
• Build and download the plant model to the
Speedgoat xPC target.
• Connect to the target
target.
• Remember to use the xPC Explorer
(xpcexplr) to specify the target IP address.
(Review lectures 3A and 10 if needed.)
52
Model Wiring
• The last thing we need to do before running the
model is to identify the pin numbers for the
inputs and output
output.
• Pin connections for the PMC730 are defined in
the users manual located on the website for
MBSD1.
• We are using Analog Output 1.
• We need to also find the ground reference for
this output.
• The data sheet is shown on the next slide:
53
Analog Output Pin Connection
54
Analog Output Pin Connection
We specified the first analog output
channel. Thus, our output is pin 12.
55
Analog Input Pin Connection
We can use any of the common connections specified in
the previous slide as our ground reference.
56
HIL Simulations
57
Plant Test
• We are now ready to test our plant.
• As a first step, we will use two DC voltage sources
to test the inputs of the plant.
• We will connect a 0 to 6 V DC voltage source to
the Bulb Load input (Analog input 1 pin 33).
• We will connect a 0 to 1 V DC voltage source to
the Torque Requested input signal (Analog input 0
pins 34).
• We will observe the rpm signal (channel Analog
out 0 pin 12) with a scope.
• Note that ground is pin 18 (and others if needed).
58
Plant Test
Speedgoat
xPC Target
59
Plant Test
• The Speedgoat Target is connected to the outside
world through a cable and a breakout connector:
60
Plant Test
• The pin numbers on the breakout connector
match 1 to 1 with the pin numbers on the
Speedgoat target:
• This connector
allows easy
access to the
inputs through
screw terminals.
61
62
Plant Test
• For the first test, we will just connect the two DC
power supplies directly to the breakout box with
jumper wires and alligator clips.
63
Plant Test
• Connect to the Speedgoat xPC target
• Run
R ththe model.
d l
64
Bulb Load
• As you change the DC input for the bulb
load, you should see the indicators change
as integer steps even though the DC
source is an analog voltage and changes
continuously.
• This is because we specified that these
indicators change in integer steps and are
limited to 0 to 6 volts.
• Remember that we used a floor block in
our Simulink model for the bulb input.
65
Bulb Load
66
Torque Request
• As you change the torque request from 0
to 1, the indicators should follow and
agree with the input voltage displayed on
the DC source.
• The stepped nature of the waveform
shown in the next slide is because the DC
source I am using is set to change its
voltage in 0.1 V steps.(It
( has nothing to do
with how we set up the LabVIEW
indicators.)
67
68
Plant Test
• As we change the input torque request, we
see the motor RPM increase and
decrease in response to the changing
torque request and bulb load.
• Verify that the RPM signal corresponds to
the analog output voltage of channel
Analog Output 0.
70
71
Lecture 15A – Demo 1
Plant Test
• From previous simulations, you have a good
idea of how the plant should respond to changes
in the torque request and bulb load.
• Test your plant for various inputs and verify that
it responds correctly.
• If your plant passes all of the above tests, we
can now connect the plant to the controller and
test our system using a complete HIL setup.
Demo___________
72
HIL Simulations
73
HIL Simulation
• We are now ready to connect our controller to the plant,
but we require one more modification.
• The torque output of our controller is a 20 kHz, 0 to 5 V
PWM signal
signal, and this is the signal expected by our motor
controller. (The duty cycle will go between 0 to 100%
corresponding to 0 to max torque request.
• The Plant expects an analog voltage from 0 to 1 volt
corresponding to 0 to max torque request.
• (In future model improvements, we might design our
plant to use a PWM input rather than an analog voltage
input. – However, this would require that the plant use a
timer, which is not a facility available on our Speedgoat
hardware.)
74
HIL Simulation
• The difference between the two signals requires
that we create a PWM to analog voltage
converter circuit.
• We
W willill use an iinexpensive
i llow-pass filter
filt with
ith a
voltage divider.
• We will choose the pole of the filter to be much
less than 20 kHz so that it filters out the 20 kHz
PWM frequency, but high enough so that the
delay of the filter is small compared to the
dynamic response of the plant.
• Keep in mind that this filter will not be part of the
system when we control the physical plant.
75
HIL Simulation
• Also not that this filter adds delay to the HIL
simulation that is not in the physical system nor
was it in our MIL and SIL simulations.
• It is possible that we may see an instability in the
HIL simulation due to this added delay that is not
present in the physical realization nor our
previous simulations.
• We will connect the MPC555x controller target to
the Speedgoat Plant target with the connections
shown on the next slide.
76
Divides signal by a
factor of 5. Has a
cutoff frequency of
about 200 Hz.
78
79
Low-Pass Filter
• Note that the filter we added to convert the PWM waveform
to an analog signal has a cutoff frequency of 200 Hz.
• This frequency was chosen because it is a factor of 100
below the PWM frequency
q y of 20 kHz.
• Since we have a first order filter that attenuates the signal at
20 dB per decade above the cutoff frequency, the 20 kHz
signal will be reduced by a factor of 100 (40 dB) by the filter.
• This is good, but not great.
• For a 5 V, 20 kHz PWM waveform input the filter, the filter
will have 50 mV of ripple at 20 kHz at the output
output.
• This ripple will cause a ripple on the torque output of the
motor.
80
Low-Pass Filter
• The cutoff frequency of 200 Hz is close to
the bandwidth of the motor-generator
system
system.
• This means that the delay added by the
filter will be significant and may make the
system unstable.
• We will keep this in mind as we do our
testing.
81
HIL Setup
• My setup is shown on the next two slides.
• Note that the circuits to interface between
the controller and plant been hardwired on
to the prototyping area of the
MPC555xEWB to keep the implementation
clean.
• You may want to use a prototyping board
to construct the circuits needed for this lab
so that you can change the circuits and
filter constants easily.
82
Interface circuits
between the plant and
controller. (Can be Controller running
easily disconnected on a MPC555x
when not needed.) target.
84
85
Interface circuits
between the plant and
controller. (Can be
easily disconnected
when not needed.)
86
Plant running on
Speedgoat xPC
target.
Interface / wiring
harness.
87
HIL Simulations
88
HIL Simulations
• We are now ready to run our HIL
simulation.
• Use the Simulink Plant model or the xPC
Explorer to run your plant model on the
Speedgoat Target.
• Download and run your controller model
on the MPC555x.
• Monitor important signals on the MPC555x
using FreeMASTER or the RHIT ASCII
debug blocks.
89
HIL Simulations
• The next slide shows my plant
performance for the following controller
settings:
– Proportional Gain = 1
– Integral Gain = 10
– Fixed Step size = 1 ms
– PWM frequency is set to 20 kHz
• The number of bulbs is set to 2.
91
• Constant speed request. Bulb load step
response.
92
Lecture 15A – Demo 2
• Demo of HIL simulation.
– Proportional Gain = 1
– Integral Gain = 10
– Fixed Step size = 1 ms
– PWM frequency is set to 20 kHz
• Speed Step Response
• Bulb Step Response
Demo___________
93
HIL Simulations
• We notice that there is a lot of ringing in
the system response.
• From previous simulations
simulations, we found that
a proportional gain of 100 and an integral
gain of 10 worked well.
• Change these gains, rebuild the controller,
download the controller model to the
MPC555x and then redo the previous
tests.
94
• Step response in rpm speed request. Bulb
load held constant at 2 bulbs.
Looks clean.
95
• Constant speed request. Bulb load step
response.
96
Lecture 15A – Demo 3
• Demo of HIL simulation.
– Proportional Gain = 100
– Integral Gain = 10
– Fixed Step size = 1 ms
– PWM frequency is set to 20 kHz
• Speed Step Response
• Bulb Step Response
Demo___________
97
HIL Simulations
• The step response (RPM signal output)now looks
clean, but we see large oscillations in the torque
request signal.
• This
Thi could
ld be
b ffor severall reasons:
– The filter we added for the PWM signal (which is not part of
the physical system) added extra delay.
– The interface / wiring harness added noise and delay that
was not modeled earlier.
– The PWM nature of the torqueq request
q signal
g is adding
g noise
to the system. (Because we only attenuate the 20 kHz signal
by a factor of 100.)
– The gain is just too high, and caused the system to oscillate.
(Review earlier simulations and see if the selected gains
caused the system to be unstable.)
98
HIL Simulations
• Note that we are not really sure that the wild
oscillations on the torque request signals are
actually there.
• The signal is a PWM signal that is a square
wave that oscillates between 0 & 5 volts. We are
trying to use the average of that signal bu using
a low-pass filter.
• The filter output contains 50 mV of 20 kHz ripple.
• This ripple may be what is causing the
oscillations in the torque request.
99
HIL Simulations
• We will try different gains to improve the
performance of the system while still
having a stable system.
system
• Unfortunately, we cannot change the
controller gains in real-time, so we will
have to modify the gains, rebuild the
model, and then download it to the
MPC555x
C every time we make a change.
• Next, try a proportional gain of 10 and an
integral gain of 10.
100
• Step response in rpm speed request. Bulb
load held constant at 2 bulbs.
No so clean anymore.
101
• Constant speed request. Bulb load step
response.
102
Lecture 15A – Demo 4
• Demo of HIL simulation.
– Proportional Gain = 10
– Integral Gain = 10
– Fixed Step size = 1 ms
– PWM frequency is set to 20 kHz
• Speed Step Response
• Bulb Step Response
Demo___________
103
HIL Simulations
• The step response of the rpm signal looks clean, but we still
see large spikes on the torque request signal.
• If we compare the response of the HIL simulations to our
previous simulations for the specified
p p g
gains and the simulations
give different results, then we have learned something:
– Our interface may have introduced something that was not previously
modeled. (We need to solve this.)
– The controller running on the actual target with a discrete time step is
causing the problem. (We need to solve this.)
• The HIL simulations have shown us something new and we
need
d tto make
k adjustments
dj t t or resolve
l ththe iissues b
before
f we
deploy our controller on the physical plant.
104
HIL Simulations
• It is also possible that the plant running on a discrete
target is causing the problem.
• This not an issue in the real system because the
plant will be replaced by the actual physical system.
• We do need to test this possibility and make changes
if it is the cause. (By say, decreasing the time step of
the plant – if possible.)
• Since we ran the entire system in real-time on an
xPC target with the same time step as used here and
we did not see the oscillations, the plant time step is
probably not the issue.
105
HIL Simulations
• It is also possible that the filter we added
for the PWM signal is causing a problem.
• This filter is not part of the physical system
or controller, and we should investigate to
see if this is causing the problem.
– Noise:
• Measure the output of the filter and make sure that
20 kH
kHz ripple
i l iis nott presentt on th
the signal.
i l
– Delay:
• Increase the PWM frequency (to say 200 kHz).
• Increase the pole of the filter (to say 2 kHz).
106
HIL Simulations
• The next slides show the system response for
proportional and integral gains of 10 (same as the
previous simulation).
• The PWM frequency was increased to 200 kHz and
the filter cutoff frequency was changed to 2 kHz (a
much faster filter).
– This filter will have the same 50 mV of ripple as the last filter
since the PWM frequency is 100 times higher than the
filter’s cutoff frequency.
– Since the filter’s cutoff frequency has been increased to 2
kHz, (a factor of 10 higher) we have decreased the amount
of delay added by the filter by a factor of 10.
• This experiment will test if the filter delay was the
cause of the problem.
107
• Step response in rpm speed request. Bulb
load held constant at 2 bulbs.
108
Lecture 15A – Demo 5
• Demo of HIL simulation.
– Proportional Gain = 10
– Integral Gain = 10
– Fixed Step size = 1 ms
– PWM frequency is set to 200 kHz
– Filter Cutoff frequency 2 kHz
• Speed
p Step
p Response
p
• Bulb Step Response
Demo___________
109
HIL Simulations
• The wild oscillations are still present in the
system.
• Next,
Next we will keep the PWM frequency at
200 kHz and then change the filter cutoff
frequency back to 200 Hz.
• This will increase the filter delay, but
reduce the 200 kHz ripple at the filter by a
factor of 10. (The 200 kHz PWM frequency
will now be attenuated by a factor of
1000.)
110
• Step response in rpm speed request. Bulb
load held constant at 2 bulbs.
Yuck.
111
HIL Simulations
• Reducing the delay and reducing the ripple do not
seem to fix the problem.
yp
• We could test the hypothesis further that the
oscillation is due to the filter and PWM ripple further by
eliminating the filter completely and using a plant
target that can measure the pulse-width directly.
• Our hardware does not allow this test.
• Next,, we will see if reducing g the gain
g fixes the
problem. We will keep the filter cutoff frequency at 200
Hz and the PWM frequency at 200 kHz.
112
• Step response in rpm speed request. Bulb
load held constant at 2 bulbs.
Stable Oscillations.
.
Random spikes.
Oscillations.
113
Lecture 15A – Demo 6
• Demo of HIL simulation.
– Proportional Gain = 1
– Integral Gain = 10
– Fixed Step size = 1 ms
– PWM frequency is set to 200 kHz
– Filter Cutoff frequency 200 Hz
• Speed
p Step
p Response
p
• Bulb Step Response
Demo___________
114
Deja Vu
• I know that I remember this system
working better before.
• As a last step
step, we will change the filter
back to having a cutoff frequency of 2 kHz.
We will keep everything else the same.
• (PWM at 200 kHz, proportional gain = 1,
integral gain = 10).
• This will reduce the delay of the added
filter.
115
• Step response in rpm speed request. Bulb
load held constant at 2 bulbs.
Oscillations.
Stable
.
Oscillations.
116
• Constant speed request. Bulb load step
response.
Torq e prett
Torque pretty well
ell beha
behaved.
ed
117
Lecture 15A – Demo 7
• Demo of HIL simulation.
– Proportional Gain = 1
– Integral Gain = 10
– Fixed Step size = 1 ms
– PWM frequency is set to 200 kHz
– Filter Cutoff frequency 2 kHz
• Speed
p Step
p Response
p
• Bulb Step Response
Demo___________
118
HIL Simulations - Conclusions
• The HIL simulations give us some new results.
• First, it appears that we need a proportional gain of 1 to make
the system stable. This is much lower than the gain we
determined in earlier systems.
• We are not sure if the added filter is the cause of the reduced
gain and bad system behavior.
• We should really eliminate the added filter as it is not part of the
physical plant and may be causing issues in the simulation.
• The poor performance of the system in the HIL simulations
suggest that we need for work in improving the system’s
system s
performance before we deploy the controller on the physical
plant. Torque spikes can damage equipment.
• (In this course, we do not have time to investigate the cause of
the observed problems.)
119
Controller Notes
• Remember that we only increased the
PWM frequency to 200 kHz to try to
eliminate the effects of the filter and PWM
ripple.
• When we deploy the controller on the
physical plant in the next lecture, we need
to use a frequency of 20 kHz as the plant
hardware is designed for
f a PWM
frequency of 20 kHz.
Introduction to Model-Based
Systems Design
Lecture 16:
Motor Controller Deployment
2
System Deployment
• We have placed our control algorithm and controller hardware
through several levels of testing:
– Model-in-the-Loop (MIL) where we tested the controller as a Simulink
model connected to a Simulink model of the plant running in the
Windows environment.
– Real-Time simulations where we ran both the controller and plant in real
time on a single xPC target.
– Software-in-the-Loop (SIL) where we compiled the controller into the
same code that would run on the hardware target an ran the model with
a fixed time step.
– Hardware
Hardware-in-the-Loop
in the Loop (HIL) simulations where we deployed the
controller onto the target that will be used in the final implementation and
tested that controller by connecting it to another real-time-computer
running the plant model.
3
System Deployment
• By going through all of these levels of simulation, we
gain confidence that when we hook the controller to
the physical plant:
– The system will behave as expected
expected.
– The system will operate in a safe manner.
– We will not break anything mechanically.
– We will not let the smoke out of any electrical components.
• The only reason the system will fail is that our models
of the plant are not accurate:
– This is always possible and we should always expect that
there are things we can do to improve the plant model.
– One thing we did not do in this course is make exhaustive
measurements of the plant components, and then update
the plant model to reflect the measurements.
4
System Deployment
• With the HIL simulations, we deployed the control
method on the target hardware that will be used in the
final realization.
• We identified all of the inputs and outputs for the plant
and controller.
• We hooked the controller inputs and outputs to a real-
time computer running a model of the physical plant,
not the physical plant itself.
• The last step is to take that same controller and
connect it to the physical plant.
5
Connections
• The controller has the following connections:
– A PWM output for the motor torque. This is connected
directly to the PWM input of the plant and the motor is PWM
controlled. We do not need the low-pass
p filter that causes us
problems in the HIL simulation.
– An analog input to measure the motor rpm. This is
connected to the rpm output of the plant. Note that a 2:1
voltage divider is included in the plant, but the filter capacitor
is not included. You will have to add the capacitor.
– You will need to run one ground connection between the
plant and the controller
• A wiring diagram is shown on the next slide.
6
Wiring Diagram
Controller! 7
Physical Connections
8
Plant I/O Connections
9
Lecture 16 Demo 1 Demo___________
10
Lecture 16 Demo 2 Demo___________
11
Lecture 16 Demo 3 Demo___________
12
Lecture 16 Demo 4 Demo___________
13
System Verification
• Now that we have a working system, we
need to test the system and compare the
results to our simulations
simulations.
• If measured and simulated results do not
agree, we will need to determine the
discrepancy and update out plant models
if necessary.
• We will start with steady state testing.
14
System Tests
• We will be measuring the rpm on the next
few tests.
• We can use a volt meter and measure the
encoder output to determine the system
rpm.
• Remember that the nameplate spec for
the encoder is 2.5 V per 1000 rpm.
15
System Tests
• Although these are steady state tests, you
will learn a great deal about the system
transient response as you turn on an off
light bulbs.
• You will be able to see and hear overshoot
in the system rpm as you turn on and off
light bulbs.
16
Bulb Load Test, rpm = 1200 rpm
• Set Integral Gain = 0. With No load, set
the rpm to 1200. Observe how the rpm
changes as the load changes from 0 bulbs
to 6 bulbs. (Measure the rpm for various
gains and loads.)
P_Gain No 1 Bulb 2 Bulbs 3 Bulbs 4 Bulbs 5 Bulbs 6 Bulbs
Bulbs
1 1200
10 1200
100 1200
17
Bulb Load Test, rpm = 1800 rpm
• Set Integral Gain = 0. With No load, set
the rpm to 1800. Observe how the rpm
changes as the load changes from 0 bulbs
to 6 bulbs. (Measure the rpm for various
gains and loads.)
P_Gain No 1 Bulb 2 Bulbs 3 Bulbs 4 Bulbs 5 Bulbs 6 Bulbs
Bulbs
1 1800
10 1800
100 1800
18
Bulb Load Test, rpm = 2400 rpm
• Set Integral Gain = 0. With No load, set
the rpm to 2400. Observe how the rpm
changes as the load changes from 0 bulbs
to 6 bulbs. (Measure the rpm for various
gains and loads.)
P_Gain No 1 Bulb 2 Bulbs 3 Bulbs 4 Bulbs 5 Bulbs 6 Bulbs
Bulbs
1 2400
10 2400
100 2400
19
Integral Gain Tests
• For the next tests, we will keep the rpm
constant at the 1800 rpm.
• We will then specify a fixed proportional
gain, and observe the system response for
varying values of integral gain.
• Note that these are steady state
responses.
20
Integral Gain Test, rpm = 1800
• Set Proportional Gain = 1. With No load, set the
rpm to 1800. Observe how the rpm changes as
the load changes from 0 bulbs to 6 bulbs.
(Measure the steady state rpm for various
integral gains and loads.)
21
Integral Gain Test, rpm = 1800
• Set Proportional Gain = 10. With No load, set
the rpm to 1800. Observe how the rpm changes
as the load changes from 0 bulbs to 6 bulbs.
(Measure the steady state rpm for various
integral gains and loads.)
22
Integral Gain Test, rpm = 1800
• Set Proportional Gain = 100. With No load, set
the rpm to 1800. Observe how the rpm changes
as the load changes from 0 bulbs to 6 bulbs.
(Measure the steady state rpm for various
integral gains and loads.)
23
Fixed Step Size Test
• For the next tests, we will keep the rpm
constant at the 1800 rpm.
• Choose a values for the integral and
proportional gains that give the system,
the best response.
• We will keep these values constant in the
next set of tests and see the effect of
changing the fixed step size.
24
Controller Step Size Test
• Set Proportional Gain = ___. Set Integral Gain =
___. With No load, set the rpm to 1800. Observe
how the rpm changes as the load changes from
0 bulbs to 6 bulbs
bulbs. (Measure the steady state
rpm for various values of the system step size.)
25
SIL Tests
• We would like to compare the measured
results to the simulated results.
• Repeat all of the above tests using the
model from Lecture 10A Model 3.
26
(SIL) Bulb Load Test, rpm = 1200 rpm
• Set Integral Gain = 0. With No load, set
the rpm to 1200. Observe how the rpm
changes as the load changes from 0 bulbs
to 6 bulbs. (Measure the rpm for various
gains and loads.)
P_Gain No 1 Bulb 2 Bulbs 3 Bulbs 4 Bulbs 5 Bulbs 6 Bulbs
Bulbs
1 1200
10 1200
100 1200
27
(SIL) Bulb Load Test, rpm = 1800 rpm
• Set Integral Gain = 0. With No load, set
the rpm to 1800. Observe how the rpm
changes as the load changes from 0 bulbs
to 6 bulbs. (Measure the rpm for various
gains and loads.)
P_Gain No 1 Bulb 2 Bulbs 3 Bulbs 4 Bulbs 5 Bulbs 6 Bulbs
Bulbs
1 1800
10 1800
100 1800
28
(SIL) Bulb Load Test, rpm = 2400 rpm
• Set Integral Gain = 0. With No load, set
the rpm to 2400. Observe how the rpm
changes as the load changes from 0 bulbs
to 6 bulbs. (Measure the rpm for various
gains and loads.)
P_Gain No 1 Bulb 2 Bulbs 3 Bulbs 4 Bulbs 5 Bulbs 6 Bulbs
Bulbs
1 2400
10 2400
100 2400
29
(SIL)Integral Gain Test, rpm = 1800
• Set Proportional Gain = 1. With No load, set the
rpm to 1800. Observe how the rpm changes as
the load changes from 0 bulbs to 6 bulbs.
(Measure the steady state rpm for various
integral gains and loads.)
30
(SIL) Integral Gain Test, rpm = 1800
• Set Proportional Gain = 10. With No load, set
the rpm to 1800. Observe how the rpm changes
as the load changes from 0 bulbs to 6 bulbs.
(Measure the steady state rpm for various
integral gains and loads.)
31
(SIL) Integral Gain Test, rpm = 1800
• Set Proportional Gain = 100. With No load, set
the rpm to 1800. Observe how the rpm changes
as the load changes from 0 bulbs to 6 bulbs.
(Measure the steady state rpm for various
integral gains and loads.)
32
(SIL) Controller Step Size Test
• Set Proportional Gain = ___. Set Integral Gain = ___.
With No load, set the rpm to 1800. Observe how the rpm
changes as the load changes from 0 bulbs to 6 bulbs.
((Measure the steadyy state rpm
p for various values of the
system step size. Use the same values of gain as we did
for the physical system in slide 25.)
33
34
Lecture 16 Comparison 1200 rpm
• Compare SIL results to measured (act) results.
• Set Integral Gain = 0. With No load, set the rpm
to 1200. Observe how the rpm changes as the
load changes from 0 b bulbs
lbs to 6 b
bulbs.
lbs
10 1200 1200
35
Lecture 16 Comparison 1800 rpm
• Compare SIL results to measured (act) results.
• Set Integral Gain = 0. With No load, set the rpm
to 1800. Observe how the rpmp changesg as the
load changes from 0 bulbs to 6 bulbs.
10 1800 1800
36
Lecture 16 Comparison 2400 rpm
• Compare SIL results to measured (act) results.
• Set Integral Gain = 0. With No load, set the rpm
to 2400. Observe how the rpmp changesg as the
load changes from 0 bulbs to 6 bulbs.
10 2400 2400
37
Lecture 16 Comparison 1800 rpm
• Compare SIL results to measured (act) results.
• Set Proportional Gain = 1. With No load, set the rpm to
1800. Observe how the rpm changes as the load
changes from 0 bulbs to 6 bulbs.
10 1800 1800
38
Lecture 16 Comparison 1800 rpm
10 1800 1800
39
Lecture 16 Comparison 1800 rpm
10 1800 1800
40
Lecture 16 Comparison Step Size Test
• Compare SIL results to measured (act) results.
• Set Proportional Gain = ___ (optimum value). Set
integral Gain = ___ (optimum value). With No load, set
the rpm to 1800. Observe how the rpm changes as the
load changes from 0 bulbs to 6 bulbs.
Questions?
Introduction to Model-Based
Systems Design
Lecture 17:
Improved Bulb Model
Intro to Design of Experiments
2
Model Problems - Motor
• When we first designed our plant, we
understood that the models we created
were very idealized:
– The motor model uses a fictitious a torque
curve.
– The motor is 100% efficient.
– The is no current limit on the motor. (For us,
this would be a limit on the DC power supply.)
supply )
3
Model Problems - Generator
• The generator has the same non-idealities as
the motor, plus a few more that we need to
consider:
• For our load (generator combined with the light
bulbs), we assumed that the load torque was a
linear function of the rpm.
• In reality, a bulb looks like a temperature
dependent resistance. The temperature
depends on the bulb voltage, which in turn
depends on the generator speed.
4
Generator Model
• The experience we have gained by using
our motor-generator system has shown us
the following about the generator:
– The output voltage is a function of the rpm.
– The output voltage drops as we draw more
current from the generator.
• We would like to create a model that
i l d both
includes b th off th
these effects.
ff t
• (After we do the bulb model.)
5
Bulb Model
• The bulb looks like a temperature
dependent resistor (with a large positive
temperature coefficient)
coefficient).
– As the temperature of the resistor goes up, its
resistance goes up.(Or so we think.)
– The power drawn by the bulb is the voltage
squared divided by the bulb resistance.
– The resistance is a function of the bulb power,
power
since more bulb power heats up the bulb.
• We will create a model that includes all of
these effects.
6
Old Generator Load Model
• Just as a reminder, the old generator and bulb load is
shown below:
7
New Generator Load Model
• We will use the following model for the generator that includes all of
the bulb effects:
8
New Plant Model
• We can measure the light bulb I-V characteristic
if we have a variable voltage power supply.
• We will use the Model-Based Calibration toolbox
to:
– Design a set of experiments.
– Measure the bulb and generator characteristics with
the specified set of experiments.
– Create a model for the measured data and export it to
Sim link
Simulink.
• We could also use the measured data to:
– Create a look up table.
– Implement a Simulink function.
9
Blub Model
• We will first develop the model of the bulb.
• The input to the model is the bulb voltage.
• The output of the mode is the bulb current
current.
• We will use the Model-Based Calibration toolbox
to set up a set of experiments for us to measure
the bulb characteristic.
• To start the Model-Based Calibration, type
mbcmodel at the Matlab command prompt:
10
Model-Based Calibration Toolbox
• All of the files we create will be saved in
the current working directory.
• Select File and then New Test Plan from
the Model Browser menus:
11
Model-Based Calibration Toolbox
12
Model-Based Calibration
One-Stage selected.
Double-click here.
13
Model-Based Calibration
14
Model-Based Calibration
Symbol: Voltage
Min: 0
Max: 15
Transform: None
15
Model-Based Calibration
16
Model-Based Calibration
17
Model-Based Calibration
• We know that the resistance of the bulb will
change with temperature.
• Thus,, the bulb I-V characteristic will deviate from
a straight line. (How much – we don’t know –
we’ve never done this before.)
• We will guess that it will deviate slightly from a
straight line so a 2nd or 3rd order polynomial
should be a good fit.
• We can change the model later if the model we
pick does not fit the data very well.
• We will choose a 3rd order polynomial model:
18
Model-Based Calibration
Polynomial spline
selected.
Minimize PRESS
selected.
Order set to 3.
19
Model-Based Calibration
20
Model-Based Calibration
21
Model-Based Calibration
22
Model-Based Calibration
• Select Design and then Optimal from the
Design Editor menus:
• For a 3rd order polynomial fit, we
need a minimum of 4 points.
• Since we are not really sure a 3rd
order polynomial will work, we will
specify that we want a 16 additional
points.
• More points will take more time to
measure (and thus be more
expensive for your company), but it
will also help reduce the effects of
measurement error on our model.
23
Model-Based Calibration
After clicking the OK
button, the tool will
calculate the voltage
points for the model.
16 additional
points selected.
24
Model-Based Calibration
20 measurementt
points.
20 measurement
points.
25
Model-Based Calibration
Name changed.
26
Model-Based Calibration
• The points for our experiment have been
created.
• We will export them to an Excel
spreadsheet so that we can easily collect
data.
• Select File and then Export Design from
the Design Editor menus:
27
Model-Based Calibration
• Select a comma separated values format:
• After
f clicking the OK
O button, you can open
the file with Excel.
28
Model-Based Calibration
• We are now ready to
run our experiment.
p
• For the specified
voltages, we will
measure the bulb
current.
• Note that we do not
have to use the exact
same voltages, but
we will try to come
close.
29
Measured Data
• The data can be saved
in a standard Excel
format file
file.
30
Model-Based Calibration
• Close the Design Editor by selecting File
and then Close from the menus:
31
Model-Based Calibration
• Before we continue, select File and then
Save Project from the Model Browser
Window to save our design
design.
• Save the file as Light_Bulb_Model.mat.
• Select TestPlan and then New Data from
the menus:
32
Select
S l t the
th Excel
E l fil
file with
ith
the collected data.
Columns in our
measured data.
33
Select this option
to match
measured data to
our model created
earlier.
Click the Next button.
Voltage signal in
our model
matched to
voltage signal in
the measured
data. Click the Next button.
34
Current added as
an output.
35
Data Editor
• The Data Editor opens and displays the data.
36
Data Editor
• Select View, Current View, and then 2D Data
Plot from the menus:
37
Data Editor
• To view the data, make the selections below
38
Data Editor
• We see that the current-voltage characteristic is
indeed not a straight line.
p
• You can experiment with other views if yyou want
to view the data differently. (For a one-
dimensional plot, there is not that much else to
look at.)
• Select File and then Close to close the Data
Editor.
• When you return to the Model Browser, you will
notice that there is now a response model for the
Current.
39
Model Browser
40
Model Browser
41
Model Browser
• Suppose that we want to try a different fit to our
data.
42
New Response Model
Click here to create a new model for
the measured Current output.
43
New Response Model
44
New Response Model
45
3rd Order Response Model
3rd Order
model
selected.
46
2nd Order Response Model
2nd Order
model
selected.
47
The Two Models are Slightly Different
48
Models
• You can experiment with more models.
• An 8th order polynomial comes pretty close
to modeling the bulb at low voltages.
voltages
• An 8th order poly is much more expensive
to calculate than a 3rd order polynomial
49
Model Export
• Once we are happy with the model, we
can export it to Simulink.
• We have several different models
models, so we
need to select the model we want to
export.
3rd order
model
selected.
50
Model Exporter Select Simulink here.
Note the file name.
• Click the OK
button.
• Simulink will start
and display the
model.
• Resize the model
to see the ports.
51
Export Model
52
Export Model
• You should probably add a saturation
block to limit the input voltage range of the
model
model.
• The accuracy of the model outside the
range of measured data will be
questionable.
53
Model Evaluation
• Next, we will look at a tool for evaluating
our model.
• Select one of yyour models:
Model selected.
54
Model Evaluation
55
Model Evaluation
• Select View and then Response Surface.
Plot selected.
selected
56
Model Evaluation
Points from
model fit.
57
Simulink Look-Up Table
• To create a look up table in Simulink:
58
Simulink Look-Up Table
• To create a look up table in Simulink:
59
Simulink Look-Up Table
• Select a Lookup method of Interpolation-Use
End Values so that we only use the table for the
values that we actually measured.
60
Simulink Look-up Table
• When you click the OK button on the
Look-Up table dialog box, the curve should
be shown on the block:
61
New Bulb Model
• You can use either the look-up table
model or one of the models that we
exported from the MCBModel tool.
tool
• One note is that with the models
generated by MCBModel, none of the
ones we created had zero current when
the bulb voltage was zero.
• This is unphysical and will cause the
generator to apply a negative torque when
the generator is not spinning.
62
New Bulb Model
• This negative torque will tend to cause the
motor-generator system to spin backwards
when the motor-generator
motor generator system should be
at rest and no motor torque is applied.
• We probably will not notice anything because
this torque might be small compared to the
rotational friction we added.
• To avoid this problem, we will use the look-
up table for our model.
63
New Generator Model
64
New Generator Model
65
Lecture 17
Generator Model With Bulb
• Demo your working model with the New
Bulb Load
Demo___________
66
Lecture 17
• Start Lecture 17 MBC Project
Introduction to Model-Based
Systems Design
Lecture 18:
Verification and Validation
MathWorks SystemTest
2
Verification and Validation
• As we develop our model, we will make periodic
changes.
• Everyy time we make a change,g , we need to verify
y
that our system passes a rigorous set of tests.
• Ideally, we would have a predefined set of tests,
and run all of the tests each time we make a
change.
• We would then analyzey the results of the tests
an determine if our system meets the required
specifications.
3
Verification and Validation
• Ideally, we would set up a battery of tests
at several levels in the Model-Based-
System Design process:
– Simulations (SIL)
– Real-Time Simulations (xPC)
– Hardware in the Loop Simulations
• We want to create a set of tests that
“thoroughly” test the system, and then run
all of the tests automatically.
4
Verification and Validation
• Proving that a set of tests completely
covers a design is a challenge and will not
be discussed here
here.
• Instead, we will demonstrate a tool that:
– Allows us to create a set of tests
– Run the tests automatically
– Perform data analysis on the results
– Evaluate the results against performance
specifications.
5
Verification and Validation
• We will use a MathWorks tool called
SystemTest and use it to verify the step
response of our system.
system
• We will start with model Lecture17_Model3.
• Save the model as Lecture18_Model1.
• We will need to make a few changes to the
model.
• Changes to the top level are shown next:
6
Motor-Generator
Model
Slider and constant
replaced by step input.
Slider removed.
7
Model Changes
• We are going to need to collect some data
from our model when it runs.
• We will do this using the To Workspace
part located in the Simulink / Sinks
library.
• This part writes data from the Simulink
simulation to a MATLAB variable in the
workspace.
• Place one in the controller subsystem and
connect as shown:
8
Controller Subsystem
To Workspace part
added.
9
Controller Subsystem
• Change the parameters of the To
Workspace block as shown:
Name of the MATLAB
variable where the data is
saved.
Do not limit the size of the
array Scaled_RPM_Signal
where the data is saved.
A decimation value of 3 would take
every 3rd point. A decimation of 1 takes
every point
point.
Sample_Time was defined in the init file
as 0.001 seconds. Dave a data point
every 0.001 seconds.
10
Controller Subsystem
11
Controller Subsystem
Add another To Workspace here
with the same settings except a
different variable name.
12
Controller Subsystem
13
Model Changes
• Next, change the simulation ending time to
1 second:
Changed to 1.
1
14
Init File
• We do not need to make any changes to
the Init_File for our model.
• The SystemTest tool will run our Simulink
model a large number of times.
• The contents of the Init_File never change
during the test and we never need to
change the values of the variables defined
in the Init_File during the series of tests.
15
Init File
• We only need to run the init file once, then
we can run our model through the series
of tests.
tests
• Instead of using a Callback to have
Simulink run the init file, we will use the
Pre Test function in SystemTest to
initialize the needed parameters once.
• We will change the CallBack function in
Simulink so that it does not ruin our
Init_File.
16
Init_File
• Right-click somewhere on the motor-
generator Simulink model and select
Model Properties from the menu:
17
Init_File
• Select the Callbacks tab and select the
InitFcn selection
Callbacks tab
selected.
18
Post Processing File
• The test we are going to run is to observe
the step response of our motor-generator
system and calculate the rise time
time.
• We will then determine if the system
passes the step response specification.
• We need to create a MATLAB script that
calculates the rise time from the measured
data:
19
Rise Time MATLAB Script
%Find the rise time.
Ten_Pct_Value = 0.1*Speed_Step;
Ninety_Pct_Value = 0.9*Speed_Step;
Ten_Pct_Time = 0;
Ninety_Pct_Time = 0;
20
Rise Time MATLAB Script
%Find the time of the 10% Point.
for i = 1: (length(time)-1)
if (Scaled_RPM_Signal (i) <= Ten_Pct_Value) &&...
(Scaled RPM Signal (i
(Scaled_RPM_Signal (i+1)
1) >= Ten_Pct_Value)
Ten Pct Value)
Ten_Pct_Time=time(i);
end
21
Rise Time MATLAB Script
% Calculate the rise time as the difference between the
% 10% and 90% points. If a rise time is not found, set the
% Rise_Time to infinity.
22
SystemTest
• We will now use MathWorks System test
to run the model at various speeds and
measure the step response for different
loads.
• Type systemtest at the MATLAB
command prompt to run the tool.
23
SystemTest
24
SystemTest
• Select File and then Save As from the
System Test menus
• Change the dircetory to your MATLAB
working directory
• Save the file as “Motor_Generator.test”
• The tree will change as shown:
25
26
Pre Test
• The pretest section allows us to initialize
variables that we could use in our test.
• This is done once even though multiple
tests will be run.
• We would like to use the Pre Test section
to initialize the workspace constants that
we use in our model.
• Select the Pre Test leaf of the tree:
27
Pre Test
28
Pre Test
29
Pre Test
30
Pre Test
31
32
Main Test
• The remainder of our elements will go in
the Main Test Section.
• Select the section as shown:
33
Test Vectors
• Test vectors are MATLAB row vectors
whose values are used as inputs to our
tests
tests.
• If we have a test vector with the values [1,
3, 5,8,10], a test will be run for the value 1,
the value 5, the value 8, and the value 10.
• We can assign the values of the test
vectors to parts of our Simulink model.
34
Test Vectors
• For each magnitude of step, we would like
to measure the rise time for different bulb
loads
loads.
• We will set the bulb load test vector to [0,
1, 2, 3, 4, 5,6].
• We will call this test vector ST_Bulb_Load.
• We will have a total of 35 tests.
• We now need to define these test vectors.
35
Test Vectors
selected.
36
Test Vectors
Test Vectors name.
37
38
39
Main Test
• Next we will define the Main Test Section.
• In this section, for each iteration in the test
vectors we want to:
vectors,
– Run our Simulink model
– Calculate the Rise Time
– Plot the desired and measured rpm response.
– Determine if the response meets a
performance criteria.
40
Init_File
• Before adding your Simulink Model to the
test plan, manually run the Init_File to
define workspace parameters for the
model.
• The Pre_Test function will not run until we
start the test, so some model parameters
are not known and will generate an error
message.
41
Select Simulink.
42
43
Model loaded.
44
45
Simulink Model
Select this block.
When you switch back to SystemTest,
the block will be listed.
46
47
The step occurs at time “Step time.” We set this time to 0.1 seconds
in the block. At time zero, the step has a value specified by parameter
“Initial value.” We set this value to 0 in the block. At the step time, the
bl k output
block t t goes from
f the
th initial
i iti l value
l tto the
th “Fi
“Finall value”,
l ” and dh
holds
ld
at the final value for the remainder of the simulation.
We want the value “Final Value” to be set by the test vector so select
it.
48
49
50
51
Simulink Output
• For our reports, we would like to include a
plot of the desired and measured step
response
response.
• To do this, we need to get the data from
the MATLAB workspace to System Test.
• In our Simulink model, we added three To
Workspace blocks so that we would save
the desired data in the workspace.
• We now need to take that data and save it
as a test variable.
52
53
54
55
56
Simulink Output
• Repeat the procedure for the other Two
Workspace Blocks:
– To Workspace Æ ST_Desired_RPM
ST Desired RPM
– To Workspace2 Æ ST_time
57
58
Plots
• After each Simulink simulation, we want to
plot the desired and measured response.
• First, make sure that Simulink is selected in
the tree:
Simulink
selected.
59
60
ST_Scaled_RPM_Signal
_ _ _ g ST_Desired_RPM plotted
plotted in blue on the Y in red on the Y Axis.
Axis.
61
Rise Time
• Next, we have to evaluate the data in the
workspace and calculate the Rise Time.
• To do this we need to add a MATLAB
script to the test plan.
• Make sure that the Vector Plot is selected.
Vector Plot
Selected.
62
63
Script to calculate
the Rise Time.
64
65
Rise Time
• We are going to use the value of
Rise_Time calculated in the script to
evaluate against a constraint in
System_Test.
• We will need to define Rise_Time as a
Test Variable.
66
67
Test Variables
• Repeat the process to add a variable
called Rise_Time_limit.
• Give this variable an Initial Value of 0.4.
• This variable will be used as a constraint
where we will check to see that the
measured rise time is less than or equal to
this limit.
68
Rise_Time_limit added
with an initial value of 0.4.
69
Constraints
• Next we need to add our constraints to
verify the performance of our system.
• We can add several constraints and then
measure what proportion of our tests pass
the constraints.
• For this example, we will only have a
single constraint.
70
Constraints
• We would like to check the constraint after
we run the MATLAB script that calculates
the rise time.
time
• Select MATLAB from the tree:
71
72
73
74
If a test fails, we go on to
the next test because we
want to see how many tests
pass.
75
After Test Runs
• We are now finished setting up our test.
• We would like to create a report that we
can view after all 35 tests run
run.
• Select the Motor_Generator leaf.
Motor_Generator leaf
selected.
76
77
Running the Test
• Select Run from the SystemTest menus or
click the Play button.
• A plot should display after each test
showing the desired and measured step
response.
78
79
M results
My lt show
h th
thatt only
l Clickk here
Cli h to
t view
i the
th
12 of the 35 tests passed results in a web browser.
the 0.4 second rise time The next three screens
condition. show part of my report.
80
81
82
83
New Test
• The controller model in the previous test
had a proportional gain of 5 and an
integral gain of 10
10.
• Lets try increasing the integral gain to
reduce the rise time.
• Run the test again and measure the
results.
84
M results
My lt show
h th
thatt only
l Clickk here
Cli h to
t view
i the
th
34 of the 35 tests passed results in a web browser.
the 0.4 second rise time The next two screens
condition. show part of my report.
85
86
87
Lecture 18 Demo 1
• We notice that we now have overshoot.
• Add a second test that verifies that the
overshoot is less than 5%
5%.
• You need to check to see how many tests
pass both the rise time specification and
the overshoot specification.
Demo___________
88
Lecture 18 Exercise 1
• Verify summary of results showing that 34
of 35 runs passed the specification.
Demo___________
89
Lecture 18 Project 3
• Start Project 3.