Upload
trankiet
View
246
Download
3
Embed Size (px)
Citation preview
UniversityCollegeofSoutheastNorway
http://home.hit.no/~hansha
IntroductiontoSimulinkHans-PetterHalvorsen,2016.11.01
PrefaceSimulink,developedbyTheMathWorks,isacommercialtoolformodeling,simulatingandanalyzingdynamicsystems.Itsprimaryinterfaceisagraphicalblockdiagrammingtoolandacustomizablesetofblocklibraries.ItofferstightintegrationwiththerestoftheMATLABenvironmentandcaneitherdriveMATLABorbescriptedfromit.Simulinkiswidelyusedincontroltheoryanddigitalsignalprocessingforsimulationanddesign.
ThistrainingwillgiveyouthebasicknowledgeofSimulinkandhowyoucanuseittogetherwithMATLAB.
FormoreinformationaboutMATLABandSimulink,seemyBlog:http://home.hit.no/~hansha
iii
TableofContentsPreface......................................................................................................................................2
TableofContents.....................................................................................................................iii
1 IntroductiontoSimulink....................................................................................................1
2 StartusingSimulink...........................................................................................................2
2.1 BlockLibraries.............................................................................................................3
2.2 CreateanewModel...................................................................................................5
2.3 Wiringtechniques.......................................................................................................6
2.4 Helpwindow...............................................................................................................7
2.5 Configuration..............................................................................................................9
2.6 Examples...................................................................................................................10
3 UsefulFeatures...............................................................................................................19
3.1 Comments/Labels.....................................................................................................19
3.2 AlignandDistributeBlocks.......................................................................................19
3.3 FlipBlocks.................................................................................................................20
3.4 HideNames...............................................................................................................21
4 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
iv TableofContents
Tutorial: Introduction to Simulink
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
1
1 IntroductiontoSimulinkSimulinkisanenvironmentforsimulationandmodel-baseddesignfordynamicandembeddedsystems.Itprovidesaninteractivegraphicalenvironmentandacustomizablesetofblocklibrariesthatletyoudesign,simulate,implement,andtestavarietyoftime-varyingsystems,includingcommunications,controls,signalprocessing,videoprocessing,andimageprocessing.
Simulinkoffers:
• Aquickwayofdevelopyourmodelincontrasttotextbased-programminglanguagesuchase.g.,C.
• Simulinkhasintegratedsolvers.Intextbased-programminglanguagesuchase.g.,Cyouneedtowriteyourownsolver.
2
2 StartusingSimulinkYoustartSimulinkfromtheMATLABIDE:
OpenMATLABandselecttheSimulinkiconintheToolbar:
Ortype“simulink”intheCommandwindow,likethis:
Thenthefollowingwindowappears(SimulinkLibraryBrowser):
3 StartusingSimulink
Tutorial: Introduction to Simulink
TheSimulinkLibraryBrowseristhelibrarywhereyoufindalltheblocksyoumayuseinSimulink.Simulinksoftwareincludesanextensivelibraryoffunctionscommonlyusedinmodelingasystem.Theseinclude:
• Continuousanddiscretedynamicsblocks,suchasIntegration,Transferfunctions,TransportDelay,etc.
• Mathblocks,suchasSum,Product,Add,etc• Sources,suchasRamp,RandomGenerator,Step,etc
2.1 BlockLibrariesHerearesomecommonusedContinuousBlocks:
4 StartusingSimulink
Tutorial: Introduction to Simulink
HerearesomecommonusedMathOperationsBlocks:
HerearesomecommonusedSignalRoutingBlocks:
HerearesomecommonusedSinksBlocks:
HerearesomecommonusedSourcesBlocks:
5 StartusingSimulink
Tutorial: Introduction to Simulink
InadditiontherearelotsofblockindifferentToolboxes:
2.2 CreateanewModelClicktheNewiconontheToolbarinordertocreateanewSimulinkmodel:
Thefollowingwindowappears:
6 StartusingSimulink
Tutorial: Introduction to Simulink
YoumaynowdragtheblocksyouwanttousefromtheSimulinkLibraryBrowsertothemodelsurface(orright-clickonablockandselect“Addto…”).
Example:
Inthisexampleweplace(draganddrop)toblocks,aSineWaveandaScope,onthemodelsurface:
2.3 WiringtechniquesUsethemousetowiretheinputsandoutputsofthedifferentblocks.Inputsarelocatedontheleftsideoftheblocks,whileoutputsarelocatedontherightsideoftheblocks.
7 StartusingSimulink
Tutorial: Introduction to Simulink
Whenholdingthemouseoveraninputoranoutputthemousechangestothefollowingsymbol.
Usethemouse,whileholdingtheleftbuttondown,todragwiresfromtheinputtotheoutput.
AutomaticBlockConnection:
Anotherwiringtechniqueistoselectthesourceblock,thenholddowntheCtrlkeywhileleft-clickingonthedestinationblock.
Trythedifferenttechniquesontheexampleabove.
Connectionfromawiretoanotherblock
Ifwireaconnectionfromawiretoanotherblock,liketheexamplebelow,youneedtoholddowntheCtrlkeywhileleft-clickingonthewireandthentotheinputofthedesiredblock.
2.4 HelpwindowInordertoseedetailedinformationaboutthedifferentblocks,usethebuilt-inHelpsystem.
8 StartusingSimulink
Tutorial: Introduction to Simulink
AllstandardblocksinSimulinkhavedetailedHelp.ClicktheHelpbuttonintheBlockParameterwindowforthespecificblockinordertogetdetailedhelpforthatblock.
TheHelpWindowthenappearswithdetailedinformationabouttheselectedblock:
9 StartusingSimulink
Tutorial: Introduction to Simulink
2.5 ConfigurationTherearelotsofparametersyoumaywanttoconfigureregardingyoursimulation.Select“ConfigurationParameters…”intheSimulationmenu.
Thefollowingwindowappears:
10 StartusingSimulink
Tutorial: Introduction to Simulink
Hereyousetimportantparameterssuchas:
• StartandStoptimeforthesimulation• WhatkindofSolvertobeused(ode45,ode23etc.)• Fixed-step/Variable-step
Note!EachofthecontrolsontheConfigurationParametersdialogboxcorrespondstoaconfigurationparameterthatyoucansetviathe“sim”and“simset”commands.Youwilllearnmoreaboutthesecommandslater.
Solversarenumericalintegrationalgorithmsthatcomputethesystemdynamicsovertimeusinginformationcontainedinthemodel.Simulinkprovidessolverstosupportthesimulationofabroadrangeofsystems,includingcontinuous-time(analog),discrete-time(digital),hybrid(mixed-signal),andmultiratesystemsofanysize.
2.6 ExamplesBelowwewillgothroughsomeexamplesinordertoillustratehowtocreateblockdiagramsandrelatedfunctionality.
Example:Integratorwithinitialvalue
Createthefollowingmodel(anintegrator)andrunthesimulation:
11 StartusingSimulink
Tutorial: Introduction to Simulink
Step1:Placetheblocksonthemodelsurface
Thisexampleusethefollowingblocks:
Step2:Configuration
Double-clickontheIntegratorblock.TheParameterwindowfortheIntegratorblockappears:
12 StartusingSimulink
Tutorial: Introduction to Simulink
Select“Initialconditionsource=external”.TheIntegratorblocknowlookslikethis:
Double-clickontheConstantblock.TheParameterwindowfortheConstantblockappears:
13 StartusingSimulink
Tutorial: Introduction to Simulink
IntheConstantvaluefieldwetypeintheinitialvaluefortheintegrator,e.g.,typethevalue1.
Step3:Wiring
Usethemousetowiretheinputsandoutputsofthedifferentblocks.
Whenholdingthemouseoveraninputoranoutputthemousechangetothefollowingsymbol.
DrawawirebetweentheoutputontheConstantblocktothelowerinputintheIntegratorblock,likethis:
Youcouldalsodolikethis:
Wiretherestoftheblockstogetherandyouwillgetthefollowingdiagram:
14 StartusingSimulink
Tutorial: Introduction to Simulink
Step4:Simulation
Startthesimulationbyclickingthe“StartSimulation”iconintheToolbar:
Step5:TheResults
Double-clickintheScopeblockinordertoseethesimulatedresult:
15 StartusingSimulink
Tutorial: Introduction to Simulink
Example:SineWave
Createtheblockdiagramasshownbelow:
SetthefollowingparameterfortheIntegratorblock:
Theresultshouldbelikethis:
16 StartusingSimulink
Tutorial: Introduction to Simulink
Example:Usingvectors
Createthefollowingblockdiagram:
FortheGainblock,typethefollowingparameters:
17 StartusingSimulink
Tutorial: Introduction to Simulink
Asyousee,wecanusestandardMATLABsyntaxtocreateavector.
Ifyouwanttoseethesignaldimensions,select“SignalDimensions”and“WideNonscalarLines”asshownhere:
Theblockdiagramshouldnowlooklikethis:
18 StartusingSimulink
Tutorial: Introduction to Simulink
Thethicklinesindicatevectors,whilethenumber(8)isthesizeofthevector.
Let’schangetheSaturationblock:
AsyouseeyoumayusestandardMATLABfunctionsandsyntax.
RunthesimulationandseetheresultsintheScopeblock.
19
3 UsefulFeaturesYoushouldknowaboutthesefeaturesinSimulinkinordertotakefulladvantageofSimulink.
3.1 Comments/LabelsDouble-clickonyoursurfaceinordertowriteLabelsorCommentsinyourmodelblockdiagram.
3.2 AlignandDistributeBlocksYoumayalignyourblocks:
20 UsefulFeatures
Tutorial: Introduction to Simulink
3.3 FlipBlocksNormallytheinputsareontheleftandtheoutputsontheright,butinsomecasesitisconvenienttohavetheinputsontherightandoutputontheleftside.
Inorderto“flip”theinputandoutputsright-clickontheblockandselect“FlipBlock”.
21 UsefulFeatures
Tutorial: Introduction to Simulink
3.4 HideNamesHidedefaultlabelsthatappearonthediagram,suchasConstant1,Integrator1,etc.
Select“HideNames”onthe“Format”menu:
22
4 Data-drivenModellingYoumayuseSimulinktogetherwithMATLABinordertospecifydataandparameterstoyourSimulinkmodel.YoumayspecifycommandsintheMATLABCommandWindoworascommandsinanm-file.Thisiscalleddata-drivenmodeling.
4.1 Commandwindow
Example:
Note!Inordertoget3inputsontheScopeblock:
Double-clickontheScopeandselecttheParametersiconintheToolbar:
ThenselectNumberofAxes=3:
23 Data-drivenModelling
Tutorial: Introduction to Simulink
Configurethezero-orderholdblockslikethis:
WritethefollowingintheCommandwindowinMATLAB:
24 Data-drivenModelling
Tutorial: Introduction to Simulink
RuntheSimulinkmodelfromtheSimulink:
Wethengetthefollowingresults:
25 Data-drivenModelling
Tutorial: Introduction to Simulink
4.2 m-fileItisgoodpracticetobuildyourinSimulinkandconfigureandrunthesimulationfromaMATLABm-file.
ATypicalm-filecouldlooklikethis:
26 Data-drivenModelling
Tutorial: Introduction to Simulink
Youusethesimsetcommandtoconfigureyoursimulationparametersandthesimcommandtorunthesimulation.
Thevariablesyourefertointhem-fileissetintheConstantvaluefieldintheParameterwindowforeachblock.
4.3 SimulationCommands
27 Data-drivenModelling
Tutorial: Introduction to Simulink
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);
28
5 HybridSystems(continuousanddiscrete)
Youmaymixcontinuousblocksanddiscreteblocksinthesamesystem,so-calledHybridsystems.
Example:HybridSystem
Createthefollowingblockdiagram:
29 HybridSystems(continuousanddiscrete)
Tutorial: Introduction to Simulink
TheBlockdiagramnowlookslikethis:
Theblackcoloristhecontinuoussystemwhilethecoloredpart(redandgreen)isthediscretepartofthesystem.
30
6 Example:Mass-Spring-DamperSystem
6.1 ModelInthisexamplewewillcreateamass-spring-dampermodelinSimulinkandconfigureandrunthesimulationfromaMATLABm-file.
Inthisexerciseyouwillconstructasimulationdiagramthatrepresentsthebehaviorofadynamicsystem.Youwillsimulateaspring-massdampersystem.
𝐹(𝑡) − 𝑐𝑥(𝑡) − 𝑘𝑥(𝑡) = 𝑚𝑥(𝑡)
wheretisthesimulationtime,F(t)isanexternalforceappliedtothesystem,cisthedampingconstantofthespring,kisthestiffnessofthespring,misamass,andx(t)isthepositionofthemass. 𝑥 isthefirstderivativeoftheposition,whichequalsthevelocityofthemass. 𝑥 isthesecondderivativeoftheposition,whichequalstheaccelerationofthemass.
Thefollowingfigureshowsthisdynamicsystem.
[Figure:Wikipedia]
Thegoalistoviewthepositionx(t)ofthemassmwithrespecttotimet.Youcancalculatethepositionbyintegratingthevelocityofthemass.Youcancalculatethevelocitybyintegratingtheaccelerationofthemass.Ifyouknowtheforceandmass,youcancalculatethisaccelerationbyusingNewton'sSecondLawofMotion,givenbythefollowingequation:
31 Example:Mass-Spring-DamperSystem
Tutorial: Introduction to Simulink
Force=Mass×Acceleration
Therefore,
Acceleration=Force/Mass
Substitutingtermsfromthedifferentialequationaboveyieldsthefollowingequation:
𝑥 =1𝑚 (𝐹 − 𝑐𝑥 − 𝑘𝑥)
Youwillconstructasimulationdiagramthatiteratesthefollowingstepsoveraperiodoftime.
6.2 SimulinkCreatetheblockdiagramforthemass-spring-dampermodelabove.
Insteadofhard-codingthemodelparametersintheblocksyoushouldrefertothemasvariablessetinanm-file.
Thesevariablesshouldbeconfigured:
• x_init• dxdt_init• m=• c=• k• t_step_F
32 Example:Mass-Spring-DamperSystem
Tutorial: Introduction to Simulink
• F_O• F_1
6.3 m-FileThefollowingvariablesshouldthenbesetinthem-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 ResultsTheBlockDiagramshouldlooksomethinglikethis:
Them-Fileshouldlooksomethinglikethis:
33 Example:Mass-Spring-DamperSystem
Tutorial: Introduction to Simulink
Graphs:
ForceF
Position 𝑥 andspeed 𝑥:
34 Example:Mass-Spring-DamperSystem
Tutorial: Introduction to Simulink
35
7 EmbeddedAlgorithmsThischapterexplainshowyouincorporateanexistingMATLABfunctionintoyourSimulinkmodel.
MakesureyourMATLABfunctioniscompiledasanembeddedMATLABfunctionusingthe#emldirective,e.g.:
36 EmbeddedAlgorithms
Tutorial: Introduction to Simulink
DragintheEmbeddedMATLABfunction:
Double-clickontheEmbeddedMATLABfunctiongiveusthestandardtemplateforanembeddedfunction:
ModifythetemplatesoitcallsyourMATLABfunction:
37 EmbeddedAlgorithms
Tutorial: Introduction to Simulink
Wirethesystemlikethis:
RuntheSimulation:
38
8 SubsystemsYoucreatesubsystemstocreatehierarchicalsystemsandhidedetailsinthemodel.
Selectthepartofyoursystemfromwhichyouwanttocreateasubsystem,right-clickandselect“CreateSubsystem”.
Example:
Right-clickandselect“CreateSubsystem”:
39 Subsystems
Tutorial: Introduction to Simulink
Ifwedouble-clickonthesubsystemweseetheblocksinthesubsystem:
Right-clickontheblockandselect“EditMask”inordertoopentheMaskEditor:
40 Subsystems
Tutorial: Introduction to Simulink
TheMaskEditorallowsyoutochangehowthesubsystemshouldlook,e.g.,thesubsystemicon.
SetParametersforthesubsystem:
DoubleclickonthesubsystemnowgivestheParameterwindowforthesubsystem:
41 Subsystems
Tutorial: Introduction to Simulink
42
9 ModelExplorerTheModelExplorerallowsyoutoquicklylocate,view,andchangeelementsofaSimulinkmodelorStateflowchart.
TodisplaytheModelExplorer,selectModelExplorerfromtheSimulinkViewmenu.
43
10 ExercisesInthischapterweprovidemoreexercises.
Exercise:
Buildthefollowingblockdiagram:
Inthisexercisewewillmodelarubberballthatisthrownintheairwithaninitialvelocityof15m/sfromaheightof10m.Wewillmodelthedynamicsoftheballasitbounces,undertheinfluenceofgravity.Wewillassumethat20%oftheenergyislostoneachbounce.(Thatis,aftereachimpact,theballwilltravelat80%ofitspriorvelocity,butintheoppositedirection.)
Wecanmodelthisexamplebyintegratingg(g=-9.81m/s^2)overtimewiththeinitialconditionsetto15m/s.Weresettheintegratoreachtimethepositionreacheszerometersandsetthenewinitialconditionto-80%oftheimpactvelocity.Positionismodeledbyintegratingthevelocityovertimewiththeinitialconditionsetto10m/s.
Theresultshouldbe:
44 Subsystems
Tutorial: Introduction to Simulink
Watchthisvideotoseetheresult:http://www.mathworks.com/products/demos/simulink/Simulink_Key_Features/videos/building.html
Hans-PetterHalvorsen,M.Sc.
E-mail:[email protected]
Blog:http://home.hit.no/~hansha/
UniversityCollegeofSoutheastNorway
www.usn.no