Tutorial: Introduction to Simulink

49
University College of Southeast Norway http://home.hit.no/~hansha Introduction to Simulink Hans-Petter Halvorsen, 2016.11.01

Transcript of Tutorial: Introduction to Simulink

Page 1: Tutorial: Introduction to Simulink

UniversityCollegeofSoutheastNorway

http://home.hit.no/~hansha

IntroductiontoSimulinkHans-PetterHalvorsen,2016.11.01

Page 2: Tutorial: Introduction to Simulink

PrefaceSimulink,developedbyTheMathWorks,isacommercialtoolformodeling,simulatingandanalyzingdynamicsystems.Itsprimaryinterfaceisagraphicalblockdiagrammingtoolandacustomizablesetofblocklibraries.ItofferstightintegrationwiththerestoftheMATLABenvironmentandcaneitherdriveMATLABorbescriptedfromit.Simulinkiswidelyusedincontroltheoryanddigitalsignalprocessingforsimulationanddesign.

ThistrainingwillgiveyouthebasicknowledgeofSimulinkandhowyoucanuseittogetherwithMATLAB.

FormoreinformationaboutMATLABandSimulink,seemyBlog:http://home.hit.no/~hansha

Page 3: Tutorial: Introduction to Simulink

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

Page 4: Tutorial: Introduction to Simulink

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

Page 5: Tutorial: Introduction to Simulink

1

1 IntroductiontoSimulinkSimulinkisanenvironmentforsimulationandmodel-baseddesignfordynamicandembeddedsystems.Itprovidesaninteractivegraphicalenvironmentandacustomizablesetofblocklibrariesthatletyoudesign,simulate,implement,andtestavarietyoftime-varyingsystems,includingcommunications,controls,signalprocessing,videoprocessing,andimageprocessing.

Simulinkoffers:

• Aquickwayofdevelopyourmodelincontrasttotextbased-programminglanguagesuchase.g.,C.

• Simulinkhasintegratedsolvers.Intextbased-programminglanguagesuchase.g.,Cyouneedtowriteyourownsolver.

Page 6: Tutorial: Introduction to Simulink

2

2 StartusingSimulinkYoustartSimulinkfromtheMATLABIDE:

OpenMATLABandselecttheSimulinkiconintheToolbar:

Ortype“simulink”intheCommandwindow,likethis:

Thenthefollowingwindowappears(SimulinkLibraryBrowser):

Page 7: Tutorial: Introduction to Simulink

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:

Page 8: Tutorial: Introduction to Simulink

4 StartusingSimulink

Tutorial: Introduction to Simulink

HerearesomecommonusedMathOperationsBlocks:

HerearesomecommonusedSignalRoutingBlocks:

HerearesomecommonusedSinksBlocks:

HerearesomecommonusedSourcesBlocks:

Page 9: Tutorial: Introduction to Simulink

5 StartusingSimulink

Tutorial: Introduction to Simulink

InadditiontherearelotsofblockindifferentToolboxes:

2.2 CreateanewModelClicktheNewiconontheToolbarinordertocreateanewSimulinkmodel:

Thefollowingwindowappears:

Page 10: Tutorial: Introduction to Simulink

6 StartusingSimulink

Tutorial: Introduction to Simulink

YoumaynowdragtheblocksyouwanttousefromtheSimulinkLibraryBrowsertothemodelsurface(orright-clickonablockandselect“Addto…”).

Example:

Inthisexampleweplace(draganddrop)toblocks,aSineWaveandaScope,onthemodelsurface:

2.3 WiringtechniquesUsethemousetowiretheinputsandoutputsofthedifferentblocks.Inputsarelocatedontheleftsideoftheblocks,whileoutputsarelocatedontherightsideoftheblocks.

Page 11: Tutorial: Introduction to Simulink

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.

Page 12: Tutorial: Introduction to Simulink

8 StartusingSimulink

Tutorial: Introduction to Simulink

AllstandardblocksinSimulinkhavedetailedHelp.ClicktheHelpbuttonintheBlockParameterwindowforthespecificblockinordertogetdetailedhelpforthatblock.

TheHelpWindowthenappearswithdetailedinformationabouttheselectedblock:

Page 13: Tutorial: Introduction to Simulink

9 StartusingSimulink

Tutorial: Introduction to Simulink

2.5 ConfigurationTherearelotsofparametersyoumaywanttoconfigureregardingyoursimulation.Select“ConfigurationParameters…”intheSimulationmenu.

Thefollowingwindowappears:

Page 14: Tutorial: Introduction to Simulink

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:

Page 15: Tutorial: Introduction to Simulink

11 StartusingSimulink

Tutorial: Introduction to Simulink

Step1:Placetheblocksonthemodelsurface

Thisexampleusethefollowingblocks:

Step2:Configuration

Double-clickontheIntegratorblock.TheParameterwindowfortheIntegratorblockappears:

Page 16: Tutorial: Introduction to Simulink

12 StartusingSimulink

Tutorial: Introduction to Simulink

Select“Initialconditionsource=external”.TheIntegratorblocknowlookslikethis:

Double-clickontheConstantblock.TheParameterwindowfortheConstantblockappears:

Page 17: Tutorial: Introduction to Simulink

13 StartusingSimulink

Tutorial: Introduction to Simulink

IntheConstantvaluefieldwetypeintheinitialvaluefortheintegrator,e.g.,typethevalue1.

Step3:Wiring

Usethemousetowiretheinputsandoutputsofthedifferentblocks.

Whenholdingthemouseoveraninputoranoutputthemousechangetothefollowingsymbol.

DrawawirebetweentheoutputontheConstantblocktothelowerinputintheIntegratorblock,likethis:

Youcouldalsodolikethis:

Wiretherestoftheblockstogetherandyouwillgetthefollowingdiagram:

Page 18: Tutorial: Introduction to Simulink

14 StartusingSimulink

Tutorial: Introduction to Simulink

Step4:Simulation

Startthesimulationbyclickingthe“StartSimulation”iconintheToolbar:

Step5:TheResults

Double-clickintheScopeblockinordertoseethesimulatedresult:

Page 19: Tutorial: Introduction to Simulink

15 StartusingSimulink

Tutorial: Introduction to Simulink

Example:SineWave

Createtheblockdiagramasshownbelow:

SetthefollowingparameterfortheIntegratorblock:

Theresultshouldbelikethis:

Page 20: Tutorial: Introduction to Simulink

16 StartusingSimulink

Tutorial: Introduction to Simulink

Example:Usingvectors

Createthefollowingblockdiagram:

FortheGainblock,typethefollowingparameters:

Page 21: Tutorial: Introduction to Simulink

17 StartusingSimulink

Tutorial: Introduction to Simulink

Asyousee,wecanusestandardMATLABsyntaxtocreateavector.

Ifyouwanttoseethesignaldimensions,select“SignalDimensions”and“WideNonscalarLines”asshownhere:

Theblockdiagramshouldnowlooklikethis:

Page 22: Tutorial: Introduction to Simulink

18 StartusingSimulink

Tutorial: Introduction to Simulink

Thethicklinesindicatevectors,whilethenumber(8)isthesizeofthevector.

Let’schangetheSaturationblock:

AsyouseeyoumayusestandardMATLABfunctionsandsyntax.

RunthesimulationandseetheresultsintheScopeblock.

Page 23: Tutorial: Introduction to Simulink

19

3 UsefulFeaturesYoushouldknowaboutthesefeaturesinSimulinkinordertotakefulladvantageofSimulink.

3.1 Comments/LabelsDouble-clickonyoursurfaceinordertowriteLabelsorCommentsinyourmodelblockdiagram.

3.2 AlignandDistributeBlocksYoumayalignyourblocks:

Page 24: Tutorial: Introduction to Simulink

20 UsefulFeatures

Tutorial: Introduction to Simulink

3.3 FlipBlocksNormallytheinputsareontheleftandtheoutputsontheright,butinsomecasesitisconvenienttohavetheinputsontherightandoutputontheleftside.

Inorderto“flip”theinputandoutputsright-clickontheblockandselect“FlipBlock”.

Page 25: Tutorial: Introduction to Simulink

21 UsefulFeatures

Tutorial: Introduction to Simulink

3.4 HideNamesHidedefaultlabelsthatappearonthediagram,suchasConstant1,Integrator1,etc.

Select“HideNames”onthe“Format”menu:

Page 26: Tutorial: Introduction to Simulink

22

4 Data-drivenModellingYoumayuseSimulinktogetherwithMATLABinordertospecifydataandparameterstoyourSimulinkmodel.YoumayspecifycommandsintheMATLABCommandWindoworascommandsinanm-file.Thisiscalleddata-drivenmodeling.

4.1 Commandwindow

Example:

Note!Inordertoget3inputsontheScopeblock:

Double-clickontheScopeandselecttheParametersiconintheToolbar:

ThenselectNumberofAxes=3:

Page 27: Tutorial: Introduction to Simulink

23 Data-drivenModelling

Tutorial: Introduction to Simulink

Configurethezero-orderholdblockslikethis:

WritethefollowingintheCommandwindowinMATLAB:

Page 28: Tutorial: Introduction to Simulink

24 Data-drivenModelling

Tutorial: Introduction to Simulink

RuntheSimulinkmodelfromtheSimulink:

Wethengetthefollowingresults:

Page 29: Tutorial: Introduction to Simulink

25 Data-drivenModelling

Tutorial: Introduction to Simulink

4.2 m-fileItisgoodpracticetobuildyourinSimulinkandconfigureandrunthesimulationfromaMATLABm-file.

ATypicalm-filecouldlooklikethis:

Page 30: Tutorial: Introduction to Simulink

26 Data-drivenModelling

Tutorial: Introduction to Simulink

Youusethesimsetcommandtoconfigureyoursimulationparametersandthesimcommandtorunthesimulation.

Thevariablesyourefertointhem-fileissetintheConstantvaluefieldintheParameterwindowforeachblock.

4.3 SimulationCommands

Page 31: Tutorial: Introduction to Simulink

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);

Page 32: Tutorial: Introduction to Simulink

28

5 HybridSystems(continuousanddiscrete)

Youmaymixcontinuousblocksanddiscreteblocksinthesamesystem,so-calledHybridsystems.

Example:HybridSystem

Createthefollowingblockdiagram:

Page 33: Tutorial: Introduction to Simulink

29 HybridSystems(continuousanddiscrete)

Tutorial: Introduction to Simulink

TheBlockdiagramnowlookslikethis:

Theblackcoloristhecontinuoussystemwhilethecoloredpart(redandgreen)isthediscretepartofthesystem.

Page 34: Tutorial: Introduction to Simulink

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:

Page 35: Tutorial: Introduction to Simulink

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

Page 36: Tutorial: Introduction to Simulink

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:

Page 37: Tutorial: Introduction to Simulink

33 Example:Mass-Spring-DamperSystem

Tutorial: Introduction to Simulink

Graphs:

ForceF

Position 𝑥 andspeed 𝑥:

Page 38: Tutorial: Introduction to Simulink

34 Example:Mass-Spring-DamperSystem

Tutorial: Introduction to Simulink

Page 39: Tutorial: Introduction to Simulink

35

7 EmbeddedAlgorithmsThischapterexplainshowyouincorporateanexistingMATLABfunctionintoyourSimulinkmodel.

MakesureyourMATLABfunctioniscompiledasanembeddedMATLABfunctionusingthe#emldirective,e.g.:

Page 40: Tutorial: Introduction to Simulink

36 EmbeddedAlgorithms

Tutorial: Introduction to Simulink

DragintheEmbeddedMATLABfunction:

Double-clickontheEmbeddedMATLABfunctiongiveusthestandardtemplateforanembeddedfunction:

ModifythetemplatesoitcallsyourMATLABfunction:

Page 41: Tutorial: Introduction to Simulink

37 EmbeddedAlgorithms

Tutorial: Introduction to Simulink

Wirethesystemlikethis:

RuntheSimulation:

Page 42: Tutorial: Introduction to Simulink

38

8 SubsystemsYoucreatesubsystemstocreatehierarchicalsystemsandhidedetailsinthemodel.

Selectthepartofyoursystemfromwhichyouwanttocreateasubsystem,right-clickandselect“CreateSubsystem”.

Example:

Right-clickandselect“CreateSubsystem”:

Page 43: Tutorial: Introduction to Simulink

39 Subsystems

Tutorial: Introduction to Simulink

Ifwedouble-clickonthesubsystemweseetheblocksinthesubsystem:

Right-clickontheblockandselect“EditMask”inordertoopentheMaskEditor:

Page 44: Tutorial: Introduction to Simulink

40 Subsystems

Tutorial: Introduction to Simulink

TheMaskEditorallowsyoutochangehowthesubsystemshouldlook,e.g.,thesubsystemicon.

SetParametersforthesubsystem:

DoubleclickonthesubsystemnowgivestheParameterwindowforthesubsystem:

Page 45: Tutorial: Introduction to Simulink

41 Subsystems

Tutorial: Introduction to Simulink

Page 46: Tutorial: Introduction to Simulink

42

9 ModelExplorerTheModelExplorerallowsyoutoquicklylocate,view,andchangeelementsofaSimulinkmodelorStateflowchart.

TodisplaytheModelExplorer,selectModelExplorerfromtheSimulinkViewmenu.

Page 47: Tutorial: Introduction to Simulink

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:

Page 48: Tutorial: Introduction to Simulink

44 Subsystems

Tutorial: Introduction to Simulink

Watchthisvideotoseetheresult:http://www.mathworks.com/products/demos/simulink/Simulink_Key_Features/videos/building.html

Page 49: Tutorial: Introduction to Simulink

Hans-PetterHalvorsen,M.Sc.

E-mail:[email protected]

Blog:http://home.hit.no/~hansha/

UniversityCollegeofSoutheastNorway

www.usn.no