Introduction to Simulink

UniversityCollegeofSoutheastNorway
IntroductiontoSimulink
Hans-PetterHalvorsen,2016.11.01
http://home.hit.no/~hansha
Preface
Simulink,developedbyTheMathWorks,isacommercialtoolformodeling,simulatingand
analyzingdynamicsystems.Itsprimaryinterfaceisagraphicalblockdiagrammingtoolanda
customizablesetofblocklibraries.ItofferstightintegrationwiththerestoftheMATLAB
environmentandcaneitherdriveMATLABorbescriptedfromit.Simulinkiswidelyusedin
controltheoryanddigitalsignalprocessingforsimulationanddesign.
ThistrainingwillgiveyouthebasicknowledgeofSimulinkandhowyoucanuseittogether
withMATLAB.
FormoreinformationaboutMATLABandSimulink,seemyBlog:
http://home.hit.no/~hansha
TableofContents
Preface......................................................................................................................................2
TableofContents.....................................................................................................................iii
1
IntroductiontoSimulink....................................................................................................1
2
StartusingSimulink...........................................................................................................2
3
4
2.1
BlockLibraries.............................................................................................................3
2.2
CreateanewModel...................................................................................................5
2.3
Wiringtechniques.......................................................................................................6
2.4
Helpwindow...............................................................................................................7
2.5
Configuration..............................................................................................................9
2.6
Examples...................................................................................................................10
UsefulFeatures...............................................................................................................19
3.1
Comments/Labels.....................................................................................................19
3.2
AlignandDistributeBlocks.......................................................................................19
3.3
FlipBlocks.................................................................................................................20
3.4
HideNames...............................................................................................................21
Data-drivenModelling....................................................................................................22
4.1
Commandwindow....................................................................................................22
4.2
m-file.........................................................................................................................25
4.3
SimulationCommands..............................................................................................26
5
HybridSystems(continuousanddiscrete)......................................................................28
6
Example:Mass-Spring-DamperSystem...........................................................................30
6.1
Model........................................................................................................................30
iii
iv
TableofContents
6.2
Simulink....................................................................................................................31
6.3
m-File........................................................................................................................32
6.4
Results......................................................................................................................32
7
EmbeddedAlgorithms.....................................................................................................35
8
Subsystems......................................................................................................................38
9
ModelExplorer................................................................................................................42
10 Exercises..........................................................................................................................43
Tutorial: Introduction to Simulink
1 IntroductiontoSimulink
Simulinkisanenvironmentforsimulationandmodel-baseddesignfordynamicand
embeddedsystems.Itprovidesaninteractivegraphicalenvironmentandacustomizableset
ofblocklibrariesthatletyoudesign,simulate,implement,andtestavarietyoftime-varying
systems,includingcommunications,controls,signalprocessing,videoprocessing,andimage
processing.
Simulinkoffers:
•
•
Aquickwayofdevelopyourmodelincontrasttotextbased-programminglanguage
suchase.g.,C.
Simulinkhasintegratedsolvers.Intextbased-programminglanguagesuchase.g.,C
youneedtowriteyourownsolver.
1
2 StartusingSimulink
YoustartSimulinkfromtheMATLABIDE:
OpenMATLABandselecttheSimulinkiconintheToolbar:
Ortype“simulink”intheCommandwindow,likethis:
Thenthefollowingwindowappears(SimulinkLibraryBrowser):
2
3
StartusingSimulink TheSimulinkLibraryBrowseristhelibrarywhereyoufindalltheblocksyoumayusein
Simulink.Simulinksoftwareincludesanextensivelibraryoffunctionscommonlyusedin
modelingasystem.Theseinclude:
•
•
•
Continuousanddiscretedynamicsblocks,suchasIntegration,Transferfunctions,
TransportDelay,etc.
Mathblocks,suchasSum,Product,Add,etc
Sources,suchasRamp,RandomGenerator,Step,etc
2.1 BlockLibraries
HerearesomecommonusedContinuousBlocks:
Tutorial: Introduction to Simulink
4
HerearesomecommonusedMathOperationsBlocks:
HerearesomecommonusedSignalRoutingBlocks:
HerearesomecommonusedSinksBlocks:
HerearesomecommonusedSourcesBlocks:
Tutorial: Introduction to Simulink
StartusingSimulink 5
StartusingSimulink InadditiontherearelotsofblockindifferentToolboxes:
2.2 CreateanewModel
ClicktheNewiconontheToolbarinordertocreateanewSimulinkmodel:
Thefollowingwindowappears:
Tutorial: Introduction to Simulink
6
StartusingSimulink YoumaynowdragtheblocksyouwanttousefromtheSimulinkLibraryBrowsertothe
modelsurface(orright-clickonablockandselect“Addto…”).
Example: Inthisexampleweplace(draganddrop)toblocks,aSineWaveandaScope,onthemodel
surface:
2.3 Wiringtechniques
Usethemousetowiretheinputsandoutputsofthedifferentblocks.Inputsarelocatedon
theleftsideoftheblocks,whileoutputsarelocatedontherightsideoftheblocks.
Tutorial: Introduction to Simulink
7
StartusingSimulink Whenholdingthemouseoveraninputoranoutputthemousechangestothefollowing
symbol.
Usethemouse,whileholdingtheleftbuttondown,todragwiresfromtheinputtothe
output.
AutomaticBlockConnection:
Anotherwiringtechniqueistoselectthesourceblock,thenholddowntheCtrlkeywhile
left-clickingonthedestinationblock.
Trythedifferenttechniquesontheexampleabove.
Connectionfromawiretoanotherblock
Ifwireaconnectionfromawiretoanotherblock,liketheexamplebelow,youneedtohold
downtheCtrlkeywhileleft-clickingonthewireandthentotheinputofthedesiredblock.
2.4 Helpwindow
Inordertoseedetailedinformationaboutthedifferentblocks,usethebuilt-inHelpsystem.
Tutorial: Introduction to Simulink
8
StartusingSimulink AllstandardblocksinSimulinkhavedetailedHelp.ClicktheHelpbuttonintheBlock
Parameterwindowforthespecificblockinordertogetdetailedhelpforthatblock.
TheHelpWindowthenappearswithdetailedinformationabouttheselectedblock: Tutorial: Introduction to Simulink
9
StartusingSimulink 2.5 Configuration
Therearelotsofparametersyoumaywanttoconfigureregardingyoursimulation.Select
“ConfigurationParameters…”intheSimulationmenu.
Thefollowingwindowappears:
Tutorial: Introduction to Simulink
10
StartusingSimulink Hereyousetimportantparameterssuchas:
•
•
•
StartandStoptimeforthesimulation
WhatkindofSolvertobeused(ode45,ode23etc.)
Fixed-step/Variable-step
Note!EachofthecontrolsontheConfigurationParametersdialogboxcorrespondstoa
configurationparameterthatyoucansetviathe“sim”and“simset”commands.Youwill
learnmoreaboutthesecommandslater.
Solversarenumericalintegrationalgorithmsthatcomputethesystemdynamicsovertime
usinginformationcontainedinthemodel.Simulinkprovidessolverstosupportthe
simulationofabroadrangeofsystems,includingcontinuous-time(analog),discrete-time
(digital),hybrid(mixed-signal),andmultiratesystemsofanysize.
2.6 Examples
Belowwewillgothroughsomeexamplesinordertoillustratehowtocreateblockdiagrams
andrelatedfunctionality.
Example:Integratorwithinitialvalue
Createthefollowingmodel(anintegrator)andrunthesimulation:
Tutorial: Introduction to Simulink
11
StartusingSimulink Step1:Placetheblocksonthemodelsurface
Thisexampleusethefollowingblocks:
Step2:Configuration
Double-clickontheIntegratorblock.TheParameterwindowfortheIntegratorblock
appears:
Tutorial: Introduction to Simulink
12
StartusingSimulink Select“Initialconditionsource=external”.TheIntegratorblocknowlookslikethis:
Double-clickontheConstantblock.TheParameterwindowfortheConstantblockappears:
Tutorial: Introduction to Simulink
13
StartusingSimulink IntheConstantvaluefieldwetypeintheinitialvaluefortheintegrator,e.g.,typethevalue
1.
Step3:Wiring
Usethemousetowiretheinputsandoutputsofthedifferentblocks.
Whenholdingthemouseoveraninputoranoutputthemousechangetothefollowing
symbol.
DrawawirebetweentheoutputontheConstantblocktothelowerinputintheIntegrator
block,likethis: Youcouldalsodolikethis:
Wiretherestoftheblockstogetherandyouwillgetthefollowingdiagram:
Tutorial: Introduction to Simulink
14
StartusingSimulink Step4:Simulation
Startthesimulationbyclickingthe“StartSimulation”iconintheToolbar:
Step5:TheResults
Double-clickintheScopeblockinordertoseethesimulatedresult:
Tutorial: Introduction to Simulink
15
StartusingSimulink Example:SineWave
Createtheblockdiagramasshownbelow:
SetthefollowingparameterfortheIntegratorblock:
Theresultshouldbelikethis:
Tutorial: Introduction to Simulink
16
StartusingSimulink Example:Usingvectors
Createthefollowingblockdiagram:
FortheGainblock,typethefollowingparameters:
Tutorial: Introduction to Simulink
17
StartusingSimulink Asyousee,wecanusestandardMATLABsyntaxtocreateavector.
Ifyouwanttoseethesignaldimensions,select“SignalDimensions”and“WideNonscalar
Lines”asshownhere:
Theblockdiagramshouldnowlooklikethis:
Tutorial: Introduction to Simulink
18
StartusingSimulink Thethicklinesindicatevectors,whilethenumber(8)isthesizeofthevector.
Let’schangetheSaturationblock:
AsyouseeyoumayusestandardMATLABfunctionsandsyntax.
RunthesimulationandseetheresultsintheScopeblock.
Tutorial: Introduction to Simulink
3 UsefulFeatures
YoushouldknowaboutthesefeaturesinSimulinkinordertotakefulladvantageof
Simulink.
3.1 Comments/Labels
Double-clickonyoursurfaceinordertowriteLabelsorCommentsinyourmodelblock
diagram.
3.2 AlignandDistributeBlocks
Youmayalignyourblocks:
19
20
UsefulFeatures 3.3 FlipBlocks
Normallytheinputsareontheleftandtheoutputsontheright,butinsomecasesitis
convenienttohavetheinputsontherightandoutputontheleftside.
Inorderto“flip”theinputandoutputsright-clickontheblockandselect“FlipBlock”.
Tutorial: Introduction to Simulink
21
UsefulFeatures 3.4 HideNames
Hidedefaultlabelsthatappearonthediagram,suchasConstant1,Integrator1,etc.
Select“HideNames”onthe“Format”menu:
Tutorial: Introduction to Simulink
4 Data-drivenModelling
YoumayuseSimulinktogetherwithMATLABinordertospecifydataandparameterstoyour
Simulinkmodel.YoumayspecifycommandsintheMATLABCommandWindoworas
commandsinanm-file.Thisiscalleddata-drivenmodeling.
4.1 Commandwindow
Example:
Note!Inordertoget3inputsontheScopeblock:
Double-clickontheScopeandselecttheParametersiconintheToolbar:
ThenselectNumberofAxes=3:
22
23
Data-drivenModelling Configurethezero-orderholdblockslikethis:
WritethefollowingintheCommandwindowinMATLAB:
Tutorial: Introduction to Simulink
24
Data-drivenModelling RuntheSimulinkmodelfromtheSimulink:
Wethengetthefollowingresults:
Tutorial: Introduction to Simulink
25
Data-drivenModelling 4.2 m-file
ItisgoodpracticetobuildyourinSimulinkandconfigureandrunthesimulationfroma
MATLABm-file.
ATypicalm-filecouldlooklikethis:
Tutorial: Introduction to Simulink
26
Data-drivenModelling Youusethesimsetcommandtoconfigureyoursimulationparametersandthesim
commandtorunthesimulation.
Thevariablesyourefertointhem-fileissetintheConstantvaluefieldintheParameter
windowforeachblock.
4.3 SimulationCommands
Tutorial: Introduction to Simulink
27
Data-drivenModelling Themostusedcommandis:
•
•
simset
sim
UsethesecommandsifyouconfigureandrunyourSimulinkmodelfromam-file.
Example:
%Simulator Settings
t_stop=100; %[s]
T_s=t_stop/1000; %[s]
options=simset('solver', 'ode5', 'fixedstep', T_s);
%Starting simulation
sim('mass_spring_damper', t_stop, options);
Tutorial: Introduction to Simulink
5 HybridSystems(continuous
anddiscrete)
Youmaymixcontinuousblocksanddiscreteblocksinthesamesystem,so-calledHybrid
systems.
Example:HybridSystem
Createthefollowingblockdiagram:
28
29
HybridSystems(continuousanddiscrete) TheBlockdiagramnowlookslikethis:
Theblackcoloristhecontinuoussystemwhilethecoloredpart(redandgreen)isthe
discretepartofthesystem.
Tutorial: Introduction to Simulink
6 Example:Mass-SpringDamperSystem
6.1 Model
Inthisexamplewewillcreateamass-spring-dampermodelinSimulinkandconfigureand
runthesimulationfromaMATLABm-file.
Inthisexerciseyouwillconstructasimulationdiagramthatrepresentsthebehaviorofa
dynamicsystem.Youwillsimulateaspring-massdampersystem.
𝐹(𝑡) − 𝑐𝑥(𝑡) − 𝑘𝑥(𝑡) = 𝑚𝑥(𝑡)
wheretisthesimulationtime,F(t)isanexternalforceappliedtothesystem,cisthe
dampingconstantofthespring,kisthestiffnessofthespring,misamass,andx(t)isthe
positionofthemass. 𝑥 isthefirstderivativeoftheposition,whichequalsthevelocityof
themass. 𝑥 isthesecondderivativeoftheposition,whichequalstheaccelerationofthe
mass.
Thefollowingfigureshowsthisdynamicsystem.
[Figure:Wikipedia]
Thegoalistoviewthepositionx(t)ofthemassmwithrespecttotimet.Youcancalculate
thepositionbyintegratingthevelocityofthemass.Youcancalculatethevelocityby
integratingtheaccelerationofthemass.Ifyouknowtheforceandmass,youcancalculate
thisaccelerationbyusingNewton'sSecondLawofMotion,givenbythefollowingequation:
30
31
Example:Mass-Spring-DamperSystem Force=Mass×Acceleration
Therefore, Acceleration=Force/Mass
Substitutingtermsfromthedifferentialequationaboveyieldsthefollowingequation:
𝑥=
1
(𝐹 − 𝑐𝑥 − 𝑘𝑥)
𝑚
Youwillconstructasimulationdiagramthatiteratesthefollowingstepsoveraperiodof
time.
6.2 Simulink
Createtheblockdiagramforthemass-spring-dampermodelabove.
Insteadofhard-codingthemodelparametersintheblocksyoushouldrefertothemas
variablessetinanm-file.
Thesevariablesshouldbeconfigured:
•
•
•
•
•
•
x_init
dxdt_init
m=
c=
k
t_step_F
Tutorial: Introduction to Simulink
32
•
•
Example:Mass-Spring-DamperSystem F_O
F_1
6.3 m-File
Thefollowingvariablesshouldthenbesetinthem-file:
x_init=4; %[m]. Initial position.
dxdt_init=0; %[m/s]. Initial Speed.
m=20; %[kg]
c=4; %[N/(m/s)]
k=2; %[N/m]
t_step_F=50; %[s]
F_O=0; %[N]
F_1=4; %[N]
6.4 Results
TheBlockDiagramshouldlooksomethinglikethis:
Them-Fileshouldlooksomethinglikethis:
Tutorial: Introduction to Simulink
33
Example:Mass-Spring-DamperSystem Graphs:
ForceF
Position 𝑥 andspeed 𝑥:
Tutorial: Introduction to Simulink
34
Example:Mass-Spring-DamperSystem Tutorial: Introduction to Simulink
7 EmbeddedAlgorithms
ThischapterexplainshowyouincorporateanexistingMATLABfunctionintoyourSimulink
model.
MakesureyourMATLABfunctioniscompiledasanembeddedMATLABfunctionusingthe
#emldirective,e.g.:
35
36
EmbeddedAlgorithms DragintheEmbeddedMATLABfunction:
Double-clickontheEmbeddedMATLABfunctiongiveusthestandardtemplateforan
embeddedfunction:
ModifythetemplatesoitcallsyourMATLABfunction:
Tutorial: Introduction to Simulink
37
EmbeddedAlgorithms Wirethesystemlikethis:
RuntheSimulation:
Tutorial: Introduction to Simulink
8 Subsystems
Youcreatesubsystemstocreatehierarchicalsystemsandhidedetailsinthemodel.
Selectthepartofyoursystemfromwhichyouwanttocreateasubsystem,right-clickand
select“CreateSubsystem”.
Example:
Right-clickandselect“CreateSubsystem”:
38
39
Subsystems Ifwedouble-clickonthesubsystemweseetheblocksinthesubsystem:
Right-clickontheblockandselect“EditMask”inordertoopentheMaskEditor:
Tutorial: Introduction to Simulink
40
Subsystems TheMaskEditorallowsyoutochangehowthesubsystemshouldlook,e.g.,thesubsystem
icon.
SetParametersforthesubsystem:
DoubleclickonthesubsystemnowgivestheParameterwindowforthesubsystem:
Tutorial: Introduction to Simulink
41
Subsystems Tutorial: Introduction to Simulink
9 ModelExplorer
TheModelExplorerallowsyoutoquicklylocate,view,andchangeelementsofaSimulink
modelorStateflowchart. TodisplaytheModelExplorer,selectModelExplorerfromtheSimulinkViewmenu.
42
10 Exercises
Inthischapterweprovidemoreexercises.
Exercise:
Buildthefollowingblockdiagram:
Inthisexercisewewillmodelarubberballthatisthrownintheairwithaninitialvelocityof
15m/sfromaheightof10m.Wewillmodelthedynamicsoftheballasitbounces,under
theinfluenceofgravity.Wewillassumethat20%oftheenergyislostoneachbounce.(That
is,aftereachimpact,theballwilltravelat80%ofitspriorvelocity,butintheopposite
direction.) Wecanmodelthisexamplebyintegratingg(g=-9.81m/s^2)overtimewiththeinitial
conditionsetto15m/s.Weresettheintegratoreachtimethepositionreacheszerometers
andsetthenewinitialconditionto-80%oftheimpactvelocity.Positionismodeledby
integratingthevelocityovertimewiththeinitialconditionsetto10m/s.
Theresultshouldbe:
43
44
Subsystems Watchthisvideotoseetheresult:
http://www.mathworks.com/products/demos/simulink/Simulink_Key_Features/videos/buil
ding.html
Tutorial: Introduction to Simulink
Hans-PetterHalvorsen,M.Sc.
E-mail:[email protected]
Blog:http://home.hit.no/~hansha/
UniversityCollegeofSoutheastNorway
www.usn.no