60
University College of Southeast Norway http://home.hit.no/~hansha Control and Simulation in LabVIEW Hans-Petter Halvorsen, 2016.10.28

Tutorial: Control and Simulation in LabVIEW

Embed Size (px)

Citation preview

Page 1: Tutorial: Control and Simulation in LabVIEW

UniversityCollegeofSoutheastNorway

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

ControlandSimulation inLabVIEW

Hans-PetterHalvorsen,2016.10.28

Page 2: Tutorial: Control and Simulation in LabVIEW

PrefaceThisdocumentexplainsthebasicconceptsofusingLabVIEWforControlandSimulationpurposes.

YoushouldhavesomebasicknowledgeaboutLabVIEW,e.g.,thetraining:โ€œAnIntroductiontoLabVIEWโ€.Thisdocumentandotherresourcesisavailablefordownloadat:

http://home.hit.no/~hansha/?tutorial=control

FormoreinformationaboutLabVIEW,visitmyBlog:http://home.hit.no/~hansha/.

Youneedthefollowingsoftware:

โ€ข LabVIEWโ€ข LabVIEWControlDesignandSimulationModuleโ€ข LabVIEWMathScriptRTModuleโ€ข NI-DAQmxโ€ข NIMeasurement&AutomationExplorer

Page 3: Tutorial: Control and Simulation in LabVIEW

iii

TableofContentsPreface......................................................................................................................................2

TableofContents.....................................................................................................................iii

1 IntroductiontoLabVIEW...................................................................................................1

1.1 Dataflowprogramming...............................................................................................1

1.2 Graphicalprogramming..............................................................................................1

1.3 Benefits.......................................................................................................................2

2 IntroductiontoControlandSimulation............................................................................3

3 IntroductiontoControlandSimulationinLabVIEW.........................................................4

3.1 LabVIEWControlDesignandSimulationModule.......................................................4

3.1.1 Simulation............................................................................................................5

3.1.2 ControlDesign.....................................................................................................5

3.2 LabVIEWPIDandFuzzyLogicToolkit..........................................................................6

3.2.1 PIDControl..........................................................................................................6

3.2.2 FuzzyLogic...........................................................................................................6

3.3 LabVIEWSystemIdentificationToolkit.......................................................................7

4 Simulation.........................................................................................................................8

4.1 SimulationinLabVIEW................................................................................................8

4.2 SimulationSubsystem...............................................................................................13

4.3 ContinuousLinearSystems.......................................................................................14

Exercises..............................................................................................................................19

5 PIDControl......................................................................................................................31

5.1 PIDControlinLabVIEW............................................................................................32

Page 4: Tutorial: Control and Simulation in LabVIEW

iv TableofContents

Tutorial: Control and Simulation in LabVIEW

5.2 Auto-tuning...............................................................................................................33

6 ControlDesign.................................................................................................................34

6.1 ControlDesigninLabVIEW.......................................................................................34

7 SystemIdentification.......................................................................................................35

7.1 SystemIdentificationinLabVIEW.............................................................................35

8 FuzzyLogic.......................................................................................................................36

8.1 FuzzyLogicinLabVIEW.............................................................................................36

9 LabVIEWMathScript.......................................................................................................38

9.1 Help...........................................................................................................................39

9.2 Examples...................................................................................................................39

9.3 Usefulcommands.....................................................................................................42

9.4 Plotting.....................................................................................................................42

10 Discretization...................................................................................................................43

10.1 Low-passFilter..........................................................................................................43

10.2 PIController..............................................................................................................46

10.2.1 PIControllerasaState-spacemodel.................................................................49

10.3 ProcessModel..........................................................................................................50

Page 5: Tutorial: Control and Simulation in LabVIEW

1

1 IntroductiontoLabVIEWLabVIEW(shortforLaboratoryVirtualInstrumentationEngineeringWorkbench)isaplatformanddevelopmentenvironmentforavisualprogramminglanguagefromNationalInstruments.Thegraphicallanguageisnamed"G".OriginallyreleasedfortheAppleMacintoshin1986,LabVIEWiscommonlyusedfordataacquisition,instrumentcontrol,andindustrialautomationonavarietyofplatformsincludingMicrosoftWindows,variousflavorsofLinux,andMacOSX.VisitNationalInstrumentsatwww.ni.com.

Thecodefileshavetheextensionโ€œ.viโ€,whichisanabbreviationforโ€œVirtualInstrumentโ€.LabVIEWofferslotsofadditionalAdd-OnsandToolkits.

1.1 DataflowprogrammingTheprogramminglanguageusedinLabVIEW,alsoreferredtoasG,isadataflowprogramminglanguage.Executionisdeterminedbythestructureofagraphicalblockdiagram(theLV-sourcecode)onwhichtheprogrammerconnectsdifferentfunction-nodesbydrawingwires.Thesewirespropagatevariablesandanynodecanexecuteassoonasallitsinputdatabecomeavailable.Sincethismightbethecaseformultiplenodessimultaneously,Gisinherentlycapableofparallelexecution.Multi-processingandmulti-threadinghardwareisautomaticallyexploitedbythebuilt-inscheduler,whichmultiplexesmultipleOSthreadsoverthenodesreadyforexecution.

1.2 GraphicalprogrammingLabVIEWtiesthecreationofuserinterfaces(calledfrontpanels)intothedevelopmentcycle.LabVIEWprograms/subroutinesarecalledvirtualinstruments(VIs).EachVIhasthreecomponents:ablockdiagram,afrontpanel,andaconnectorpanel.ThelastisusedtorepresenttheVIintheblockdiagramsofother,callingVIs.Controlsandindicatorsonthefrontpanelallowanoperatortoinputdataintoorextractdatafromarunningvirtualinstrument.However,thefrontpanelcanalsoserveasaprogrammaticinterface.Thusavirtualinstrumentcaneitherberunasaprogram,withthefrontpanelservingasauserinterface,or,whendroppedasanodeontotheblockdiagram,thefrontpaneldefinestheinputsandoutputsforthegivennodethroughtheconnectorpane.ThisimplieseachVIcanbeeasilytestedbeforebeingembeddedasasubroutineintoalargerprogram.

Page 6: Tutorial: Control and Simulation in LabVIEW

2 IntroductiontoLabVIEW

Tutorial: Control and Simulation in LabVIEW

Thegraphicalapproachalsoallowsnon-programmerstobuildprogramssimplybydragginganddroppingvirtualrepresentationsoflabequipmentwithwhichtheyarealreadyfamiliar.TheLabVIEWprogrammingenvironment,withtheincludedexamplesandthedocumentation,makesitsimpletocreatesmallapplications.Thisisabenefitononeside,butthereisalsoacertaindangerofunderestimatingtheexpertiseneededforgoodquality"G"programming.Forcomplexalgorithmsorlarge-scalecode,itisimportantthattheprogrammerpossessanextensiveknowledgeofthespecialLabVIEWsyntaxandthetopologyofitsmemorymanagement.ThemostadvancedLabVIEWdevelopmentsystemsofferthepossibilityofbuildingstand-aloneapplications.Furthermore,itispossibletocreatedistributedapplications,whichcommunicatebyaclient/serverscheme,andarethereforeeasiertoimplementduetotheinherentlyparallelnatureofG-code.

1.3 BenefitsOnebenefitofLabVIEWoverotherdevelopmentenvironmentsistheextensivesupportforaccessinginstrumentationhardware.Driversandabstractionlayersformanydifferenttypesofinstrumentsandbusesareincludedorareavailableforinclusion.Thesepresentthemselvesasgraphicalnodes.Theabstractionlayersofferstandardsoftwareinterfacestocommunicatewithhardwaredevices.Theprovideddriverinterfacessaveprogramdevelopmenttime.ThesalespitchofNationalInstrumentsis,therefore,thatevenpeoplewithlimitedcodingexperiencecanwriteprogramsanddeploytestsolutionsinareducedtimeframewhencomparedtomoreconventionalorcompetingsystems.Anewhardwaredrivertopology(DAQmxBase),whichconsistsmainlyofG-codedcomponentswithonlyafewregistercallsthroughNIMeasurementHardwareDDK(DriverDevelopmentKit)functions,providesplatformindependenthardwareaccesstonumerousdataacquisitionandinstrumentationdevices.TheDAQmxBasedriverisavailableforLabVIEWonWindows,MacOSXandLinuxplatforms.

Page 7: Tutorial: Control and Simulation in LabVIEW

3

2 IntroductiontoControlandSimulation

Controldesignisaprocessthatinvolvesdevelopingmathematicalmodelsthatdescribeaphysicalsystem,analyzingthemodelstolearnabouttheirdynamiccharacteristics,andcreatingacontrollertoachievecertaindynamiccharacteristics.

Simulationisaprocessthatinvolvesusingsoftwaretorecreateandanalyzethebehaviorofdynamicsystems.Youusethesimulationprocesstolowerproductdevelopmentcostsbyacceleratingproductdevelopment.Youalsousethesimulationprocesstoprovideinsightintothebehaviorofdynamicsystemsyoucannotreplicateconvenientlyinthelaboratory.

Belowweseeaclosed-loopfeedbackcontrolsystem:

Page 8: Tutorial: Control and Simulation in LabVIEW

4

3 IntroductiontoControlandSimulationinLabVIEW

LabVIEWhasseveraladditionalmodulesandToolkitsforControlandSimulationpurposes,e.g.,โ€œLabVIEWControlDesignandSimulationModuleโ€,โ€œLabVIEWPIDandFuzzyLogicToolkitโ€,โ€œLabVIEWSystemIdentificationToolkitโ€andโ€œLabVIEWSimulationInterfaceToolkitโ€.LabVIEWMathScriptisalsousefulforControlDesignandSimulation.

โ€ข LabVIEWControlDesignandSimulationModuleโ€ข LabVIEWPIDandFuzzyLogicToolkitโ€ข LabVIEWSystemIdentificationToolkitโ€ข LabVIEWSimulationInterfaceToolkit

Thistutorialwillfocusonthemainaspectsinthesemodulesandtoolkits.

AllVIsrelatedtothesemodulesandtoolkitsareplacedintheControlDesignandSimulationToolkit:

3.1 LabVIEWControlDesignandSimulationModule

WithLabVIEWControlDesignandSimulationModuleyoucanconstructplantandcontrolmodelsusingtransferfunction,state-space,orzero-pole-gain.Analyzesystemperformancewithtoolssuchasstepresponse,pole-zeromaps,andBodeplots.Simulatelinear,nonlinear,anddiscretesystemswithawideoptionofsolvers.WiththeNILabVIEWControlDesignand

Page 9: Tutorial: Control and Simulation in LabVIEW

5 IntroductiontoControlandSimulationinLabVIEW

Tutorial: Control and Simulation in LabVIEW

SimulationModule,youcananalyzeopen-loopmodelbehavior,designclosed-loopcontrollers,simulateonlineandofflinesystems,andconductphysicalimplementations.

3.1.1 Simulation

TheSimulationpaletteinLabVIEW:

ThemainfeaturesintheSimulationpaletteare:

โ€ข ControlandSimulationLoop-YoumustplaceallSimulationfunctionswithinaControl&SimulationLooporinasimulationsubsystem.

โ€ข ContinuousLinearSystemsFunctions-UsetheContinuousLinearSystemsfunctionstorepresentcontinuouslinearsystemsofdifferentialequationsonthesimulationdiagram.

โ€ข SignalArithmeticFunctions-UsetheSignalArithmeticfunctionstoperformbasicarithmeticoperationsonsignalsinasimulationsystem.

3.1.2 ControlDesign

TheControlDesignpaletteinLabVIEW:

Page 10: Tutorial: Control and Simulation in LabVIEW

6 IntroductiontoControlandSimulationinLabVIEW

Tutorial: Control and Simulation in LabVIEW

3.2 LabVIEWPIDandFuzzyLogicToolkitTheNILabVIEWPIDandFuzzyLogicToolkitaddcontrolalgorithmstoLabVIEW.BycombiningthePIDandfuzzylogiccontrolfunctionsinthistoolkitwiththemathandlogicfunctionsinLabVIEWsoftware,youcanquicklydevelopprogramsforautomatedcontrol.Youmayintegratethesecontroltoolswiththepowerofdataacquisition.

3.2.1 PIDControl

ThePIDpaletteinLabVIEW:

3.2.2 FuzzyLogic

Page 11: Tutorial: Control and Simulation in LabVIEW

7 IntroductiontoControlandSimulationinLabVIEW

Tutorial: Control and Simulation in LabVIEW

TheFuzzyLogicpaletteinLabVIEW:

3.3 LabVIEWSystemIdentificationToolkitTheโ€œLabVIEWSystemIdentificationToolkitโ€combinesdataacquisitiontoolswithsystemidentificationalgorithmsforplantmodeling.YoucanusetheLabVIEWSystemIdentificationToolkittofindempiricalmodelsfromrealplantstimulus-responseinformation.

TheSystemIdentificationpaletteinLabVIEW:

Page 12: Tutorial: Control and Simulation in LabVIEW

8

4 SimulationSimulationisaprocessthatinvolvesusingsoftwaretorecreateandanalyzethebehaviorofdynamicsystems.Youusethesimulationprocesstolowerproductdevelopmentcostsbyacceleratingproductdevelopment.Youalsousethesimulationprocesstoprovideinsightintothebehaviorofdynamicsystemsyoucannotreplicateconvenientlyinthelaboratory.Forexample,simulatingajetenginesavestime,labor,andmoneycomparedtobuilding,testing,andrebuildinganactualjetengine.YoucanusetheLabVIEWControlDesignandSimulationModuletosimulateadynamicsystemoracomponentofadynamicsystem.Forexample,youcansimulateonlytheplantwhileusinghardwareforthecontroller,actuators,andsensors(Hardware-in-the-loopSimulation).

Adynamicsystemmodelisadifferentialordifferenceequationthatdescribesthebehaviorofthedynamicsystem.

4.1 SimulationinLabVIEWUsetheSimulationVIsandfunctionstocreatesimulationapplicationsinLabVIEW.IntheControlDesign&SimulationpalettewehavetheSimulationSubpalette:

BelowweseetheSimulationSubpalette:

Page 13: Tutorial: Control and Simulation in LabVIEW

9 Simulation

Tutorial: Control and Simulation in LabVIEW

Note!Alltheโ€œBlocksโ€intheSimulationpalettearenotSubVIs,i.e.,wecannotdouble-clickonthemandopentheBlockDiagrambecausetheyhavenone.AlltheBlocksintheSimulationpalettemustbeusedinsidetheControlandSimulationLoop(explainedbelow).

ControlandSimulationLoop:

Intheโ€œSimulationโ€Subpalettewehavetheโ€œControlandSimulationLoopโ€whichisveryusefulinsimulations:

YoumustplaceallSimulationfunctionswithinaControl&SimulationLooporinasimulationsubsystem.YoualsocanplacesimulationsubsystemswithinaControl&SimulationLooporanothersimulationsubsystem,oryoucanplacesimulationsubsystemsonablockdiagramoutsideaControl&SimulationLooporrunthesimulationsubsystemsasstand-aloneVIs.

Page 14: Tutorial: Control and Simulation in LabVIEW

10 Simulation

Tutorial: Control and Simulation in LabVIEW

TheControl&SimulationLoophasanInputNode(upperleftcorner)andanOutputNode(upperrightcorner).UsetheInputNodetoconfiguresimulationparametersprogrammatically.YoualsocanconfiguretheseparametersinteractivelyusingtheConfigureSimulationParametersdialogbox.Accessthisdialogboxbydouble-clickingtheInputNodeorbyright-clickingtheborderandselectingConfigureSimulationParametersfromtheshortcutmenu.

Configuration:

Whenyouplacetheseblocksonthediagramyoumaydouble-clickorright-clickandthenselectโ€œConfigurationโ€ฆโ€

Example:ConfigurationDialogbox

Fortheโ€œTransferFunctionโ€(Simulationโ†’ContinuousLinearSystems)blockwehavethefollowingConfigurationwindow:

Page 15: Tutorial: Control and Simulation in LabVIEW

11 Simulation

Tutorial: Control and Simulation in LabVIEW

AllthedifferentblockshavetheirowndifferentConfigurationwindow.

IntheParametersourceyoumayselectbetween:

โ€ข ConfigurationDialogBoxโ€ข Terminal

Ifyouselectโ€œConfigurationDialogBoxโ€youentertheconfigurationintheConfigurationwindowlikeweseeabove,whileifyouselectโ€œTerminalโ€thatspecificconfigurationissetfromtheBlockDiagramlikethis:

IconStyle:

Whenyouplacetheblockontheblockdiagramyoumayselecthowthatshouldappear.Right-clickontheblock/iconandselectโ€œIconStyleโ€:

Page 16: Tutorial: Control and Simulation in LabVIEW

12 Simulation

Tutorial: Control and Simulation in LabVIEW

Example:IconStyle

Fortheโ€œTransferFunctionโ€(Simulationโ†’ContinuousLinearSystems)blockwehavethefollowingdifferenticonstyles:

Static:

Dynamic:

TextOnly:

Express:

WeseefortheDynamicandExpressstylesthattheappearancechangesaccordingtoconfigurationparametersweset.

Page 17: Tutorial: Control and Simulation in LabVIEW

13 Simulation

Tutorial: Control and Simulation in LabVIEW

Ipersonallyprefertheโ€œstaticโ€iconstylebecauseitdoesnotrequirelotsofspaceonthediagram.

4.2 SimulationSubsystemYoumaycreateaSimulationSubsystem(Fileโ†’Newโ€ฆ):

TheSimulationSubsystemisveryusefulwhendealingwithlargersimulationsystemsinordertocreateamorestructuredcode.Irecommendthatyou(always)usethisfeature.

TheSimulationSubsystemisalmostequaltoanormalLabVIEWBlockDiagrambutnoticethebackgroundcolorisslightlydarker.

Note!InordertoopentheSimulationSubsystem,right-clickandselectโ€œOpenSubsystemโ€.

TheSimulationSubsystemmayalsoberepresentedbydifferenticons.Ifyouselectโ€œdynamicโ€iconstyle,youwillseeaโ€œminiatureโ€versionofthesubsystemlikethis:

Page 18: Tutorial: Control and Simulation in LabVIEW

14 Simulation

Tutorial: Control and Simulation in LabVIEW

Youmaydraginthecornerinordertoincreaseordecreasethedynamicicon.

Ifyouselectโ€œstaticโ€iconstyleyouseetheiconyoucreatedwiththeIconEditor.

Likethis:

4.3 ContinuousLinearSystemsIntheโ€œContinuousLinearSystemsโ€Subpalettewewanttocreateasimulationmodel:

ThemostusedblocksprobablyareIntegrator,TransportDelay,State-SpaceandTransferFunction.

Page 19: Tutorial: Control and Simulation in LabVIEW

15 Simulation

Tutorial: Control and Simulation in LabVIEW

Whenyouplacetheseblocksonthediagramyoumaydouble-clickorright-clickandthenselectโ€œConfigurationโ€ฆโ€

Integrator-Integratesacontinuousinputsignalusingtheordinarydifferentialequation(ODE)solveryouspecifyforthesimulation.

TheConfigurationwindowfortheIntegratorblocklookslikethis:

TransportDelay-Delaystheinputsignalbytheamountoftimeyouspecify.

TheConfigurationwindowfortheTransportDelayblocklookslikethis:

TransferFunction-Implementsasystemmodelintransferfunctionform.YoudefinethesystemmodelbyspecifyingtheNumeratorandDenominatorofthetransferfunctionequation.

Page 20: Tutorial: Control and Simulation in LabVIEW

16 Simulation

Tutorial: Control and Simulation in LabVIEW

TheConfigurationwindowfortheTransferFunctionblocklookslikethis:

State-Space-Implementsasystemmodelinstate-spaceform.Youdefinethesystemmodelbyspecifyingtheinput,output,state,anddirecttransmissionmatrices.

TheConfigurationwindowfortheState-Spaceblocklookslikethis:

SignalArithmetic:

Theโ€œSignalArithmeticโ€Subpaletteisalsousefulwhencreatingasimulationmodel:

Page 21: Tutorial: Control and Simulation in LabVIEW

17 Simulation

Tutorial: Control and Simulation in LabVIEW

Example:SimulationModel

BelowweseeanexampleofasimulationmodelcreatedinLabVIEW.

Example:Simulation

BelowweseeanexampleofasimulationmodelusingtheControlandSimulationLoop.

Noticethefollowing:

Page 22: Tutorial: Control and Simulation in LabVIEW

18 Simulation

Tutorial: Control and Simulation in LabVIEW

Clickontheborderofthesimulationloopandselectโ€œConfigureSimulationParametersโ€ฆโ€

Thefollowingwindowappears(ConfigureSimulationParameters):

InthiswindowyousetsomeParametersregardingthesimulation,someimportantare:

โ€ข FinalTime(s)โ€“sethowlongthesimulationshouldlast.Foraninfinitetimesetโ€œInfโ€.โ€ข EnableSynchronizedTiming-Specifiesthatyouwanttosynchronizethetimingof

theControl&SimulationLooptoatimingsource.Toenablesynchronization,placea

Page 23: Tutorial: Control and Simulation in LabVIEW

19 Simulation

Tutorial: Control and Simulation in LabVIEW

checkmarkinthischeckboxandthenchooseatimingsourcefromtheSourcetypelistbox.

ClicktheHelpbuttonformoredetails.

YoumayalsosetsomeoftheseParametersintheBlockDiagram:

YoumayusethemousetoincreasethenumbersofParametersandright-clickandselectโ€œSelectInputโ€.

ExercisesExercise:Simulationofaspring-massdampersystem

Inthisexerciseyouwillconstructasimulationdiagramthatrepresentsthebehaviorofadynamicsystem.Youwillsimulateaspring-massdampersystem.

๐น(๐‘ก) โˆ’ ๐‘๐‘ฅ(๐‘ก) โˆ’ ๐‘˜๐‘ฅ(๐‘ก) = ๐‘š๐‘ฅ(๐‘ก)

wheretisthesimulationtime,F(t)isanexternalforceappliedtothesystem,cisthedampingconstantofthespring,kisthestiffnessofthespring,misamass,andx(t)isthepositionofthemass. ๐‘ฅ isthefirstderivativeoftheposition,whichequalsthevelocityofthemass. ๐‘ฅ isthesecondderivativeoftheposition,whichequalstheaccelerationofthemass.

Thefollowingfigureshowsthisdynamicsystem.

Page 24: Tutorial: Control and Simulation in LabVIEW

20 Simulation

Tutorial: Control and Simulation in LabVIEW

Thegoalistoviewthepositionx(t)ofthemassmwithrespecttotimet.Youcancalculatethepositionbyintegratingthevelocityofthemass.Youcancalculatethevelocitybyintegratingtheaccelerationofthemass.Ifyouknowtheforceandmass,youcancalculatethisaccelerationbyusingNewton'sSecondLawofMotion,givenbythefollowingequation:

Force=Massร—Acceleration

Therefore,

Acceleration=Force/Mass

Substitutingtermsfromthedifferentialequationaboveyieldsthefollowingequation:

๐‘ฅ =1๐‘š (๐น โˆ’ ๐‘๐‘ฅ โˆ’ ๐‘˜๐‘ฅ)

Youwillconstructasimulationdiagramthatiteratesthefollowingstepsoveraperiodoftime.

CreatingtheSimulationDiagram

YoucreateasimulationdiagrambyplacingaControl&SimulationLoopontheLabVIEWblockdiagram.

1. LaunchLabVIEWandselectFileยปNewVItocreateanew,blankVI. 2. SelectWindowยปShowBlockDiagramtoviewtheblockdiagram.Youalsocanpress

the<Ctrl-E>keystoviewtheblockdiagram. 3. IfyouarenotalreadyviewingtheFunctionspalette,selectViewยปFunctionsPaletteto

displaythispalette. 4. SelectControlDesign&SimulationยปSimulationtoviewtheSimulationpalette. 5. ClicktheControl&SimulationLoopicon. 6. Movethecursorovertheblockdiagram.Clicktoplacethetopleftcorneroftheloop,

dragthecursordiagonallytoestablishthesizeoftheloop,andclickagaintoplacetheloopontheblockdiagram.

ThesimulationdiagramistheareaenclosedbytheControl&SimulationLoop.Noticethesimulationdiagramhasapaleyellowbackgroundtodistinguishitfromtherestoftheblockdiagram.YoucanresizetheControl&SimulationLoopbydraggingitsborders.

ConfiguringSimulationParameters

TheControl&SimulationLoopcontainstheparametersthatdefinehowthesimulationexecutes.Completethefollowingstepstoviewandconfigurethesesimulationparameters.

1. Double-clicktheInputNode,attachedtotheleftsideoftheControl&SimulationLoop,todisplaytheConfigureSimulationParametersdialogbox.Youalsocanright-

Page 25: Tutorial: Control and Simulation in LabVIEW

21 Simulation

Tutorial: Control and Simulation in LabVIEW

clicktheloopborderandselectConfigureSimulationParametersfromtheshortcutmenu.

2. EnsurethevalueoftheFinalTime(s)numericcontrolis10,whichspecifiesthatthistutorialsimulatestensecondsoftime.

3. ClicktheODESolverpull-downmenutoviewthelistofODEsolverstheControlDesignandSimulationModuleincludes.Iftheterm(variable)appearsnexttoanODEsolver,thatsolverhasavariablestepsize.TheotherODEsolvershaveafixedstepsize.EnsureacheckmarkisbesidethedefaultODEsolverRunge-Kutta23(variable).

4. BecausethisODEsolverisavariablestep-sizesolver,youcanspecifytheMinimumStepSize(s)andMaximumStepSize(s)thisODEsolvercantake.Enter0.01intheMaximumStepSize(s)numericcontroltolimitthesizeofthetimestepthisODEsolvercantake.

5. ClicktheTimingParameterstabtoaccessparametersthatcontrolhowoftenthesimulationexecutes.

6. EnsuretheSynchronizeLooptoTimingSourcecheckboxdoesnotcontainacheckmark.Thisoptionspecifiesthatthesimulationexecuteswithoutanytimingrestrictions.Usethisoptionwhenyouwantthesimulationtorunasfastaspossible.Ifyouarerunningthissimulationinreal-time,youcanplaceacheckmarkinthischeckboxandconfigurehowoftenthesimulationexecutes.

7. ClicktheOKbuttontosavechangesandreturntothesimulationdiagram.

BuildingtheSimulation

ThenextstepistobuildthesimulationbyplacingSimulationfunctionsonthesimulationdiagramandwiringthesefunctionstogether.NotethatyoucanplacemostSimulationfunctionsonlyonthesimulationdiagram,thatis,youcannotplaceSimulationfunctionsonaLabVIEWblockdiagram.Completethefollowingstepstobuildthesimulationofthisdynamicsystem.

PlacingFunctionsontheSimulationDiagram

1. OpentheSimulationpalette. 2. SelecttheSignalArithmeticpaletteandplaceaMultiplicationfunctiononthe

simulationdiagram.Youwillusethisfunctiontodividetheforcebythemasstocalculatetheacceleration.

3. Double-clicktheMultiplicationfunctiontodisplaytheMultiplicationConfigurationdialogbox.Youcandouble-clickmostSimulationfunctionstoviewandchangetheparametersofthatfunction.

4. Thefunctioncurrentlydisplaystwoร—symbolsontheleftsideofthedialogbox.Thissettingspecifiesthatbothincomingsignalsaremultipliedtogether.Clickthebottomร—symboltochangeittoaรทsymbol.ThisMultiplicationfunctionnowdividesthetopsignalbythebottomsignal.

5. ClicktheOKbuttontosavechangesandreturntothesimulationdiagram.

Page 26: Tutorial: Control and Simulation in LabVIEW

22 Simulation

Tutorial: Control and Simulation in LabVIEW

6. Right-clicktheMultiplicationfunctionandselectVisibleItemsยปLabelfromtheshortcutmenu.Double-clicktheMultiplicationlabelandenterCalculateAccelerationasthenewlabel.

7. ReturntotheSimulationpaletteandselecttheContinuousLinearSystemspalette. 8. PlaceanIntegratorfunctiononthesimulationdiagram.Youwillusethisfunctionto

calculatevelocitybyintegratingacceleration. 9. LabelthisIntegratorfunctionCalculateVelocity. 10. Pressthe<Ctrl>keyandclickanddragtheIntegratorfunctiontoanotherlocationon

thesimulationdiagram.ThisactioncreatesacopyoftheIntegratorfunction,whichyouwillusetocalculatepositionbyintegratingvelocity.LabelthisnewIntegratorfunctionCalculatePosition.

11. SelecttheGraphUtilitiespaletteandplacetwoSimTimeWaveformfunctionsonthesimulationdiagram.Youwillusethesefunctionstoviewtheresultsofthesimulationovertime.

12. EachSimTimeWaveformfunctionhasanassociatedWaveformChart.LabelthefirstwaveformchartVelocityandthesecondwaveformchartPosition.

13. Arrangethefunctionstolooklikethefollowingsimulationdiagram. 14. SavethisVIbyselectingFileยปSave.SavethisVItoaconvenientlocationasโ€œSpring-

MassDamperExample.viโ€.

TheBlockDiagramshouldnowlooklikethis:

WiringtheSimulationFunctionsTogether

Thenextstepiswiringthefunctionstogethertorepresenttheflowofdatafromonefunctiontoanother.

Note!Wiresonthesimulationdiagramincludearrowsthatshowthedirectionofthedataflow,whereaswiresonaLabVIEWblockdiagramdonotshowthesearrows.

Page 27: Tutorial: Control and Simulation in LabVIEW

23 Simulation

Tutorial: Control and Simulation in LabVIEW

Completethefollowingstepstowirethesefunctionstogether.

1. Right-clicktheOperand1inputoftheCalculateAccelerationfunctionandselectCreateยปControlfromtheshortcutmenutoaddanumericcontroltothefrontpanelwindow.

2. LabelthiscontrolForce. 3. Double-clickthiscontrolonthesimulationdiagram.LabVIEWdisplaysthefrontpanel

andhighlightstheForcecontrol. 4. DisplaytheblockdiagramandcreateacontrolfortheOperand2inputofthe

CalculateAccelerationfunction.LabelthisnewcontrolMass. 5. WiretheResultoutputoftheCalculateAccelerationfunctiontotheinputinputof

theCalculateVelocityfunction. 6. WiretheoutputoutputoftheCalculateVelocityfunctiontotheinputinputofthe

CalculatePositionfunction. 7. Right-clickthewireyoujustcreatedandselectCreateWireBranchfromtheshortcut

menu.WirethisbranchtotheValueinputoftheSimTimeWaveformfunctionthathastheVelocitywaveformchart.

8. WiretheoutputoutputoftheCalculatePositionfunctiontotheValueinputoftheSimTimeWaveformfunctionthathasthePositionwaveformchart.

TheBlockDiagramshouldnowlooklikethis:

RunningtheSimulation

YounowcanrunthissimulationtotestthatthedataisflowingproperlythroughtheSimulationfunctions.Completethefollowingstepstorunthissimulation.

Page 28: Tutorial: Control and Simulation in LabVIEW

24 Simulation

Tutorial: Control and Simulation in LabVIEW

1. SelectWindowยปShowFrontPanel,orpress<Ctrl-E>,toviewthefrontpanelofthissimulation.Thefrontpaneldisplaysthefollowingobjects:acontrollabeledForce,acontrollabeledMass,awaveformchartlabeledVelocity,andawaveformchartlabeledPosition.

2. Ifnecessary,rearrangethesecontrolsandindicatorssothatallobjectsarevisible. 3. Enter-9.8intheForcenumericcontrol.Thisvaluerepresentstheforceofgravity,9.8

meterspersecondsquared,actingonthedynamicsystem. 4. Enter1intheMassnumericcontrol.Thisvaluerepresentsamassofonekilogram. 5. ClicktheRunbutton,orpressthe<Ctrl-R>keys,toruntheVI.

TheFrontPanelshouldlooklikethis:

IntheFigureabovenoticethattheforceofgravitycausesthemasspositionandvelocitytoconstantlydecrease.However,intherealworld,amassattachedtoaspringoscillatesupanddown.Thissimulatedspringdoesnotoscillatebecausethesimulationdiagramdoesnotrepresentdampingorstiffness.Youmustrepresentthesefactorstohaveacompletesimulationofthedynamicsystem.

RepresentingDampingandStiffness

Page 29: Tutorial: Control and Simulation in LabVIEW

25 Simulation

Tutorial: Control and Simulation in LabVIEW

Representingdampingandstiffnessinvolvesfeedingbackthevelocityandposition,eachmultipliedbyadifferentconstant,totheinputoftheCalculateAccelerationfunction.RecallthefollowingdifferentialequationthisVIsimulates.

๐น(๐‘ก) โˆ’ ๐‘๐‘ฅ(๐‘ก) โˆ’ ๐‘˜๐‘ฅ(๐‘ก) = ๐‘š๐‘ฅ(๐‘ก)

Inthepreviousequation,noticeyoumultiplythedampingconstantcbythevelocityofthemass ๐‘ฅ.Youmultiplythestiffnessconstantkbythemasspositionx(t).Youthensubtractthesequantitiesfromtheexternalforceappliedtothemass.

Completethefollowingstepstorepresentdampingandstiffnessinthisdynamicsystemmodel.

1. Viewthesimulationdiagram. 2. SelecttheSignalArithmeticpaletteandplaceaSummationfunctiononthe

simulationdiagram.MovethisfunctiontotheleftoftheForceandMasscontrols. 3. Double-clicktheSummationfunctiontoconfigureitsoperation.Bydefault,the

Summationfunctiondisplaysthefollowingthreeinputterminals:aร˜symbol,a+symbol,andaโ€“symbol.Thisconfigurationsubtractsoneinputsignalfromanother.

4. Clicktheร˜symboltwicetochangethisterminaltotheโ€“symbol.ThisSummationfunctionnowsubtractsthetopandbottominputsignalsfromtheleftinputsignal.

5. ClicktheOKbuttontosavechangesandreturntothesimulationdiagram. 6. SelecttheSignalArithmeticpaletteandplaceaGainfunctiononthesimulation

diagram.MovethisfunctionabovetheexistingsimulationdiagramcodebutstillwithintheControl&SimulationLoop.

7. TheinputoftheGainfunctionisontheleftsideofthefunction,andtheoutputisontherightside.Youcanreversethedirectionoftheseterminalstoindicatefeedbackbetter.Right-clicktheGainfunctionandselectReverseTerminalsfromtheshortcutmenu.TheGainfunctionnowpointstowardtheleftsideofthesimulationdiagram.

8. LabelthisGainfunctionDamping. 9. Pressthe<Ctrl>keyanddragtheGainfunctiontocreateaseparatecopy.Movethis

copybelowtheexistingsimulationdiagramcodebutstillwithintheControl&SimulationLoop.LabelthisfunctionStiffness.

10. Right-clickthewireconnectingtheForcecontroltotheCalculateAccelerationfunctionandselectDeleteWireBranchfromtheshortcutmenu.MovetheForcecontroltotheleftoftheSummationfunction,andwirethiscontroltotheOperand2inputoftheSummationfunction.

11. Createwires1โ€“5asindicatedintheFigurebelow.Thesimulationdiagramnowfullyrepresentstheequationthatdefinesthebehaviorofthedynamicsystem.

12. Press<Ctrl-S>tosavetheVI.

TheBlockDiagramshouldnowlooklikethis:

Page 30: Tutorial: Control and Simulation in LabVIEW

26 Simulation

Tutorial: Control and Simulation in LabVIEW

ConfiguringtheStiffnessoftheSpring

Beforeyourunthesimulationagain,youmustconfigurethestiffnessofthesimulatedspring.CompletethefollowingstepstoconfigurethisSimulationfunction.

1. Double-clicktheStiffnessfunctiontodisplaytheGainConfigurationdialogbox. 2. Enter100inthegainnumericcontrol.Thisvaluerepresentsastiffnessof100

Newtonspermeter. 3. ClickOKtoreturntothesimulationdiagram.NoticethattheStiffnessfunction

displays100. 4. DisplaythefrontpanelandensuretheForcecontrolissetto-9.8andtheMass

controlissetto1. 5. Runthesimulation.TheVelocityandPositionchartsdisplaythebehaviorofthemass

asthespringoscillates.Noticethenewbehaviorcomparedtothelasttimeyouranthesimulation.Thistime,thevelocityandpositiondonotconstantlydecrease.Bothvaluesoscillate,whichishowaspringbehavesintherealworld.

6. ChangethevalueoftheMasscontrolto10andrunthesimulationagain.NoticethedifferentbehaviorintheVelocityandPositioncharts.The10kgmassforcesthespringtooscillatelessfrequentlyandwithinasmallervelocity/positionrange.

TheFrontPanelshouldlooklikethis:

Page 31: Tutorial: Control and Simulation in LabVIEW

27 Simulation

Tutorial: Control and Simulation in LabVIEW

ConfiguringSimulationFunctionsProgrammatically

TheprevioussectionprovidedinformationaboutconfiguringSimulationfunctionsusingtheconfigurationdialogbox.Insteadofusingtheconfigurationdialogbox,youcanimprovetheinteractivityofasimulationbycreatingfrontpanelcontrolsthatconfigureaSimulationfunctionprogrammatically.CompletethefollowingstepstoconfiguretheStiffnessfunctionprogrammatically.

1. IfyouarenotalreadyviewingtheContextHelpwindow,press<Ctrl-H>todisplaythiswindow.

2. DisplaytheblockdiagramandmovethecursorovertheStiffnessfunction.Noticethisfunctionhasonlyoneinputterminal.

3. DisplaytheGainConfigurationdialogboxoftheStiffnessfunction. 4. SelectTerminalfromtheParametersourcepull-downmenu.Thisactiondisablesthe

gainnumericcontrol. 5. ClicktheOKbuttontosavechangesandreturntotheblockdiagram. 6. MovethecursorovertheStiffnessfunction.NoticetheContextHelpwindowdisplays

theGainfunctionwiththenewgaininputterminal. 7. Createacontrolforthisinput,andlabelthecontrolgain(k).

Page 32: Tutorial: Control and Simulation in LabVIEW

28 Simulation

Tutorial: Control and Simulation in LabVIEW

8. Viewthefrontpanel.Noticethenewcontrolgain(k).Enteravalueof100forthiscontrolandrunthesimulation.NoticethebehaviorisexactlythesameaswhenyouusedtheconfigurationdialogboxtoconfiguretheStiffnessfunction.

ModularizingSimulationDiagramCode

Youcancreatesimulationsubsystemstodividesimulationdiagramsintocomponentsthataremodular,reusable,andindependentlyverifiable.Completethefollowingstepstocreateasimulationsubsystemfromthissimulationdiagram.

1. Viewthesimulationdiagram. 2. SelecttheCalculateAcceleration,CalculateVelocity,andCalculatePositionfunctions

bypressingthe<Shift>keyandclickingeachfunction. 3. SelectEditยปCreateSimulationSubsystem.LabVIEWreplacesthesethreefunctions

withasinglefunctionthatrepresentsthesimulationsubsystem,whichiscircledintheFigurebelow.Theinputsandoutputsofthesimulationsubsystemincludetheinputsandoutputsofallthefunctionsyouselected.Also,noticetheamountofblankspaceonthesimulationdiagram.Becauseyoucombinedthreefunctionsintoasubsystem,youcanresizetheControl&SimulationLoopandrepositionthefunctionstomakethesimulationdiagrameasiertoview.

4. Press<Ctrl-S>tosavethesimulationdiagram.LabVIEWpromptsyoutosavethesimulationsubsystemyoujustcreated.ClicktheYesbuttonandsavethissimulationsubsystemasโ€œNewton.viโ€.YounowhaveasimulationsubsystemthatobtainsthepositionofamassbyusingNewton'sSecondLawofMotion.

Note!Youcanresizethesimulationsubsystemtobetterdisplayitssimulationdiagram.Youalsocandouble-clickthesimulationsubsystemtodisplaytheconfigurationdialogboxofthatsimulationsubsystem.

Thesimulationsubsystemshouldlooklikethis:

Page 33: Tutorial: Control and Simulation in LabVIEW

29 Simulation

Tutorial: Control and Simulation in LabVIEW

EditingtheSimulationSubsystem

Editthesimulationsubsystemโ€œNewton.viโ€byright-clickingthissubsystemandselectingOpenSubsystemfromtheshortcutmenu.Viewthesimulationdiagram.

NoticethissimulationsubsystemdoesnotcontainaControl&SimulationLoop,buttheentirebackgroundispaleyellowtoindicateasimulationdiagram.IfyouplacethissimulationsubsysteminaControl&SimulationLoop,thesimulationsubsysteminheritsallsimulationparametersfromtheControl&SimulationLoop.

Ifyourunthissubsystemasastand-aloneVI,youcanconfigurethesimulationparametersbyselectingOperateยปConfigureSimulationParameters.AnyparametersyouconfigureusingthismethoddonottakeeffectwhenthesubsystemiswithinanotherControl&SimulationLoop.IfyouplacethissimulationsubsystemonablockdiagramoutsideaControl&SimulationLoop,youcanconfigurethesimulationparametersbydouble-clickingthesimulationsubsystemtodisplaytheconfigurationdialogboxofthatsimulationsubsystem.

ConfiguringSimulationParametersProgrammatically

Earlierinthisexercise,youusedtheConfigureSimulationParametersdialogboxtoconfiguretheparametersofโ€œSpring-MassDamperExample.viโ€.YoualsocanconfiguresimulationparametersprogrammaticallybyusingtheInputNodeoftheControl&SimulationLoop.Completethefollowingstepstoconfiguresimulationparametersprogrammatically.

1. Viewthesimulationdiagramofโ€œSpring-MassDamperExample.viโ€. 2. MovethecursorovertheInputNodetodisplayresizinghandles. 3. DragthebottomhandledowntodisplayallavailableNodeinputs.Youusethese

inputstoconfigurethesimulationparameterswithoutdisplayingtheConfigureSimulationParametersdialogbox.Youalsocanright-clicktheInputNodeandselectShowAllInputsfromtheshortcutmenu. Noticethegrayboxesnexttoeachinput.TheseboxesdisplayvaluesyouconfigureintheConfigureSimulationParametersdialogbox.Forexample,thethirdgrayboxfromthetopdisplays10.0000,whichisthevalueoftheFinalTimenumericcontrolthatyouconfigured.ThefifthgrayboxfromthetopdisplaysRK23.ThisboxspecifiesthecurrentODEsolver,whichyouconfiguredasRunge-Kutta23(variable).MovethecursorovertheleftedgeofeachNodeinputtodisplaythelabelofthatinput.

4. Right-clicktheinputterminaloftheODESolverinputandselectCreateยปConstantfromtheshortcutmenu.AblockdiagramconstantappearsoutsidetheControl&SimulationLoop.ThevalueofthisconstantisRunge-Kutta1(Euler),whichisdifferentthanwhatyouconfiguredintheConfigureSimulationParametersdialogbox.However,thegrayboxdisappearsfromtheInputNode,indicatingthatthevalue

Page 34: Tutorial: Control and Simulation in LabVIEW

30 Simulation

Tutorial: Control and Simulation in LabVIEW

ofthisparameterdoesnotcomefromtheConfigureSimulationParametersdialogbox.ValuesthatyouprogrammaticallyconfigureoverrideanysettingsyoumadeintheConfigureSimulationParametersdialogbox.

TheInputNodeshouldnowlookslikethefollowingfigure:

Summary

Thisexerciseintroducedyoutothefollowingconcepts:

Thesimulationdiagramreflectsthedynamicsystemmodelyouwanttosimulate.Thisdynamicsystemmodelisadifferentialordifferenceequationthatrepresentsadynamicsystem.

TheControl&SimulationLoopcontainstheparametersthatdefinethebehaviorofthesimulation.TheControl&SimulationLoopalsodefinesthevisualboundaryofthesimulationdiagram.Double-clicktheInputNodeoftheControl&SimulationLooptoaccessconfigurableparameters.YoualsocanexpandtheInputNodetoaccesstheseparameters.

TheSimulationpalettecontainstheVIsandfunctionsyouusetobuildasimulation.Youcandouble-clickmostSimulationfunctionstodisplayadialogboxthatconfiguresthatfunction.Youalsocancreateinputterminalsforfunctioninputs.

Youcancreatesimulationsubsystemstomodularize,encapsulate,validate,andre-useportionsofthesimulationdiagram.

Page 35: Tutorial: Control and Simulation in LabVIEW

31

5 PIDControlCurrently,theProportional-Integral-Derivative(PID)algorithmisthemostcommoncontrolalgorithmusedinindustry.Often,peopleusePIDtocontrolprocessesthatincludeheatingandcoolingsystems,fluidlevelmonitoring,flowcontrol,andpressurecontrol.InPIDcontrol,youmustspecifyaprocessvariableandasetpoint.Theprocessvariableisthesystemparameteryouwanttocontrol,suchastemperature,pressure,orflowrate,andthesetpointisthedesiredvaluefortheparameteryouarecontrolling.APIDcontrollerdeterminesacontrolleroutputvalue,suchastheheaterpowerorvalveposition.Thecontrollerappliesthecontrolleroutputvaluetothesystem,whichinturndrivestheprocessvariabletowardthesetpointvalue.

[Wikipedia]

ThePIDcontrollercomparesthesetpoint(SP)totheprocessvariable(PV)toobtaintheerror(e).

ThenthePIDcontrollercalculatesthecontrolleraction,u(t),whereKciscontrollergain.

Tiistheintegraltimeinminutes,alsocalledtheresettime,andTdisthederivativetimeinminutes,alsocalledtheratetime.

Thefollowingformularepresentstheproportionalaction.

Thefollowingformularepresentstheintegralaction.

Page 36: Tutorial: Control and Simulation in LabVIEW

32 PIDControl

Tutorial: Control and Simulation in LabVIEW

Thefollowingformularepresentsthederivativeaction.

5.1 PIDControlinLabVIEWIntheโ€œPIDโ€Subpalettewehavethefunctions/SubVIsforPIDControl.Irecommendthatyouusetheโ€œPIDAdvanced.viโ€.

Example:PIDControl

BelowweseehowwecanusethePIDAdvanvanced.viinordertocontrolasimulatedModel.

Page 37: Tutorial: Control and Simulation in LabVIEW

33 PIDControl

Tutorial: Control and Simulation in LabVIEW

5.2 Auto-tuningTheLabVIEWPIDandFuzzyLogicToolkitincludeaVIforauto-tuning.

Page 38: Tutorial: Control and Simulation in LabVIEW

34

6 ControlDesignControldesignisaprocessthatinvolvesdevelopingmathematicalmodelsthatdescribeaphysicalsystem,analyzingthemodelstolearnabouttheirdynamiccharacteristics,andcreatingacontrollertoachievecertaindynamiccharacteristics.

6.1 ControlDesigninLabVIEWControlDesignpalette:

Page 39: Tutorial: Control and Simulation in LabVIEW

35

7 SystemIdentification

7.1 SystemIdentificationinLabVIEWTheโ€œSystemIdentificationToolkitโ€combinesdataacquisitiontoolswithsystemidentificationalgorithmsforaccurateplantmodeling.YoucantakeadvantageofLabVIEWintuitivedataacquisitiontoolssuchastheDAQAssistanttostimulateandacquiredatafromtheplantandthenautomaticallyidentifyadynamicsystemmodel.Youcanconvertsystemidentificationmodelstostate-space,transferfunction,orpole-zero-gainformforcontrolsystemanalysisanddesign.Thetoolkitincludesbuilt-infunctionsforcommontaskssuchasdatapreprocessing,modelcreation,andsystemanalysis.Usingotherbuilt-inutilities,youcanplotthemodelwithintuitivegraphicalrepresentationaswellasstorethemodel.

SystemIdentificationpalette:

Page 40: Tutorial: Control and Simulation in LabVIEW

36

8 FuzzyLogicFuzzylogicisamethodofrule-baseddecisionmakingusedforexpertsystemsandprocesscontrol.FuzzylogicdiffersfromtraditionalBooleanlogicinthatfuzzylogicallowsforpartialmembershipinaset.Youcanusefuzzylogictocontrolprocessesrepresentedbysubjective,linguisticdescriptions.

Afuzzysystemisasystemofvariablesthatareassociatedusingfuzzylogic.Afuzzycontrollerusesdefinedrulestocontrolafuzzysystembasedonthecurrentvaluesofinputvariables.

[Wikipedia]

8.1 FuzzyLogicinLabVIEWTheFuzzyLogicpaletteinLabVIEW:

Page 41: Tutorial: Control and Simulation in LabVIEW

37 PIDControl

Tutorial: Control and Simulation in LabVIEW

Page 42: Tutorial: Control and Simulation in LabVIEW

38

9 LabVIEWMathScriptRequires:MathScriptRTModule

Theโ€œLabVIEWMathScriptWindowโ€isaninteractiveinterfaceinwhichyoucanenter.mfilescriptcommandsandseeimmediateresults,variablesandcommandshistory.Thewindowincludesacommand-lineinterfacewhereyoucanentercommandsone-by-oneforquickcalculations,scriptdebuggingorlearning.Alternatively,youcanenterandexecutegroupsofcommandsthroughascripteditorwindow.

Asyouwork,avariabledisplayupdatestoshowthegraphical/textualresultsandahistorywindowtracksyourcommands.Thehistoryviewfacilitatesalgorithmdevelopmentbyallowingyoutousetheclipboardtoreuseyourpreviouslyexecutedcommands.

Youcanusetheโ€œLabVIEWMathScriptWindowโ€toentercommandsoneattime.Youalsocanenterbatchscriptsinasimpletexteditorwindow,loadedfromatextfile,orimportedfromaseparatetexteditor.Theโ€œLabVIEWMathScriptWindowโ€providesimmediatefeedbackinavarietyofforms,suchasgraphsandtext.

Example:

Page 43: Tutorial: Control and Simulation in LabVIEW

39 LabVIEWMathScript

Tutorial: Control and Simulation in LabVIEW

9.1 HelpYoumayalsotypehelpinyourcommandwindow

>>help

Ormorespecific,e.g.,

>>help plot

9.2 ExamplesIadviseyoutotestalltheexamplesinthistextinLabVIEWMathScriptinordertogetfamiliarwiththeprogramanditssyntax.Allexamplesinthetextareoutlinedinaframelikethis:

>> โ€ฆ

Page 44: Tutorial: Control and Simulation in LabVIEW

40 LabVIEWMathScript

Tutorial: Control and Simulation in LabVIEW

ThisiscommandsyoushouldwriteintheCommandWindow.

YoutypeallyourcommandsintheCommandWindow.Iwillusethesymbolโ€œ>>โ€toillustratethatthecommandsshouldbewrittenintheCommandWindow.

Example:Matrices

Definingthefollowingmatrix

๐ด = 1 20 3

Thesyntaxisasfollows:

>> A = [1 2;0 3]

Or

>> A = [1,2;0,3]

Ifyou,foranexample,wanttofindtheanswerto

๐‘Ž + ๐‘,๐‘คโ„Ž๐‘’๐‘Ÿ๐‘’๐‘Ž = 4, ๐‘ = 3

>>a=4 >>b=3 >>a+b

MathScriptthenresponds:

ans = 7

MathScriptprovidesasimplewaytodefinesimplearraysusingthesyntax:โ€œinit:increment:terminatorโ€.Forinstance:

>> array = 1:2:9 array = 1 3 5 7 9

definesavariablenamedarray(orassignsanewvaluetoanexistingvariablewiththenamearray)whichisanarrayconsistingofthevalues1,3,5,7,and9.Thatis,thearraystartsat1(theinitvalue),incrementswitheachstepfromthepreviousvalueby2(theincrementvalue),andstopsonceitreaches(ortoavoidexceeding)9(theterminatorvalue).

Theincrementvaluecanactuallybeleftoutofthissyntax(alongwithoneofthecolons),touseadefaultvalueof1.

>> ari = 1:5 ari = 1 2 3 4 5

Page 45: Tutorial: Control and Simulation in LabVIEW

41 LabVIEWMathScript

Tutorial: Control and Simulation in LabVIEW

assignstothevariablenamedarianarraywiththevalues1,2,3,4,and5,sincethedefaultvalueof1isusedastheincrementer.

Notethattheindexingisone-based,whichistheusualconventionformatricesinmathematics.Thisisatypicalforprogramminglanguages,whosearraysmoreoftenstartwithzero.

Matricescanbedefinedbyseparatingtheelementsofarowwithblankspaceorcommaandusingasemicolontoterminateeachrow.Thelistofelementsshouldbesurroundedbysquarebrackets:[].Parentheses:()areusedtoaccesselementsandsubarrays(theyarealsousedtodenoteafunctionargumentlist).

>> A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1] A = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 >> A(2,3) ans = 11

Setsofindicescanbespecifiedbyexpressionssuchas"2:4",whichevaluatesto[2,3,4].Forexample,asubmatrixtakenfromrows2through4andcolumns3through4canbewrittenas:

>> A(2:4,3:4) ans = 11 8 7 12 14 1

Asquareidentitymatrixofsizencanbegeneratedusingthefunctioneye,andmatricesofanysizewithzerosoronescanbegeneratedwiththefunctionszerosandones,respectively.

>> eye(3) ans = 1 0 0 0 1 0 0 0 1 >> zeros(2,3) ans = 0 0 0 0 0 0 >> ones(2,3) ans = 1 1 1 1 1 1

Page 46: Tutorial: Control and Simulation in LabVIEW

42 LabVIEWMathScript

Tutorial: Control and Simulation in LabVIEW

9.3 UsefulcommandsHerearesomeusefulcommands:

Command Descriptioneye(x), eye(x,y) Identitymatrixoforderxones(x), ones(x,y) Amatrixwithonlyoneszeros(x), zeros(x,y) Amatrixwithonlyzerosdiag([x y z]) Diagonalmatrixsize(A) DimensionofmatrixAAโ€™ InverseofmatrixA

9.4 PlottingThischapterexplainsthebasicconceptsofcreatingplotsinMathScript.

Topics:

โ€ข BasicPlotcommands

Example:Plotting

Functionplotcanbeusedtoproduceagraphfromtwovectorsxandy.Thecode:

x = 0:pi/100:2*pi; y = sin(x); plot(x,y)

Page 47: Tutorial: Control and Simulation in LabVIEW

43

10 DiscretizationOftenweneedtodevelopdiscretealgorithmsofourprocess.InadditionwemightneedtocreateourowndiscretePI(D)controller.Adiscretelow-passfilterisalsogoodtohave.

Thereexistslotsofdifferentdiscretizationmethodsliketheโ€œZeroOrderHoldโ€(ZOH)method,Tustinโ€™smethodandEulerโ€™smethods(ForwardandBackward).WewillfocusonEulersmethodsinthisdocument,becausetheyareveryeasytouse.

EulerForwarddiscretizationmethod:

๐’™ โ‰ˆ๐’™๐’Œ=๐Ÿ โˆ’ ๐’™๐’Œ

๐‘ป๐’”

EulerBackwarddiscretizationmethod:

๐’™ โ‰ˆ๐’™๐’Œ โˆ’ ๐’™๐’ŒA๐Ÿ

๐‘ป๐’”

๐‘‡C istheSamplingTime.

10.1 Low-passFilterThetransferfunctionforafirst-orderlow-passfiltermaybewritten:

๐‘ฏ ๐’” =๐’š๐’‡(๐’”)๐’š(๐’”) =

๐Ÿ๐‘ป๐’‡๐’” + ๐Ÿ

Where ๐‘‡G isthetime-constantofthefilter, ๐‘ฆ(๐‘ ) isthefilterinputand ๐‘ฆG ๐‘  isthefilteroutput.

Discreteversion:

Itcanbeshownthatadiscreteversioncanbestatedas:

๐’š๐’‡,๐’Œ = ๐Ÿ โˆ’ ๐’‚ ๐’š๐’‡,๐’ŒA๐Ÿ + ๐’‚๐’š๐’Œ

Where

Page 48: Tutorial: Control and Simulation in LabVIEW

44 Discretization

Tutorial: Control and Simulation in LabVIEW

๐’‚ =๐‘ป๐’”

๐‘ป๐’‡ + ๐‘ป๐’”

Where ๐‘‡C istheSamplingTime.

Itisagoldenrulethat ๐‘‡C โ‰ช ๐‘‡G andinpracticeweshouldusethefollowingrule:

๐‘‡C โ‰ค๐‘‡G5

Example:

Wewillimplementthediscretelow-passfilteralgorithmbelowusingaFormulaNodeinLabVIEW:

๐‘ฆG,N = 1 โˆ’ ๐‘Ž ๐‘ฆG,NAO + ๐‘Ž๐‘ฆN

Where

๐‘Ž =๐‘‡C

๐‘‡G + ๐‘‡C

TheBlockDiagrambecomes:

TheFrontPanel:

Page 49: Tutorial: Control and Simulation in LabVIEW

45 Discretization

Tutorial: Control and Simulation in LabVIEW

ItisagoodideatobuildthisasaSubVIs,andthenwecaneasilyreusetheLow-passfilterinallourapplications.

Wewilltestthediscretelow-passfilter,tomakesureitworksasexpected:

Wecreateasimpletestapplicationwhereweaddsomerandomwhitenoisetoasinesignal.Wewillplottheunfilteredandthefilteredsignaltoseeifthelow-passfilterisabletoremovethenoisefromthesinesignal.

Wegetthefollowingresults:

Page 50: Tutorial: Control and Simulation in LabVIEW

46 Discretization

Tutorial: Control and Simulation in LabVIEW

Weseethatthefilterworksfine.Theredlineistheunfilteredsinesignalwithwhitenoise,whiletheredlineisthefilteredresults.

[EndofExample]

10.2 PIControllerAPIcontrollermaybewritten:

๐’– ๐’• = ๐’–๐ŸŽ + ๐‘ฒ๐’‘๐’† ๐’• +๐‘ฒ๐’‘

๐‘ป๐’Š๐’†๐’…๐‰๐’•

๐ŸŽ

Where ๐‘ข isthecontrolleroutputand ๐‘’isthecontrolerror:

๐‘’ ๐‘ก = ๐‘Ÿ ๐‘ก โˆ’ ๐‘ฆ(๐‘ก)

Laplaceversion:

๐‘ข ๐‘  = ๐พ[๐‘’ ๐‘  +๐พ[๐‘‡\๐‘ 

๐‘’ ๐‘ 

Discreteversion:

Westartwith:

Page 51: Tutorial: Control and Simulation in LabVIEW

47 Discretization

Tutorial: Control and Simulation in LabVIEW

๐‘ข ๐‘ก = ๐‘ข] + ๐พ[๐‘’ ๐‘ก +๐พ[๐‘‡\

๐‘’๐‘‘๐œ`

]

Inordertomakeadiscreteversionusing,e.g.,Euler,wecanderivebothsidesoftheequation:

๐‘ข = ๐‘ข] + ๐พ[๐‘’ +๐พ[๐‘‡\๐‘’

IfweuseEulerForwardweget:

๐‘ขN โˆ’ ๐‘ขNAO๐‘‡C

=๐‘ข],N โˆ’ ๐‘ข],NAO

๐‘‡C+ ๐พ[

๐‘’N โˆ’ ๐‘’NAO๐‘‡C

+๐พ[๐‘‡\๐‘’N

Thenweget:

๐’–๐’Œ = ๐’–๐’ŒA๐Ÿ + ๐’–๐ŸŽ,๐’Œ โˆ’ ๐’–๐ŸŽ,๐’ŒA๐Ÿ + ๐‘ฒ๐’‘ ๐’†๐’Œ โˆ’ ๐’†๐’ŒA๐Ÿ +๐‘ฒ๐’‘

๐‘ป๐’Š๐‘ป๐’”๐’†๐’Œ

Where

๐‘’N = ๐‘ŸN โˆ’ ๐‘ฆN

Wecanalsosplittheequationabovein2differentparsbysetting:

โˆ†๐‘ขN = ๐‘ขN โˆ’ ๐‘ขNAO

ThisgivesthefollowingPIcontrolalgorithm:

๐’†๐’Œ = ๐’“๐’Œ โˆ’ ๐’š๐’Œ

โˆ†๐’–๐’Œ = ๐’–๐ŸŽ,๐’Œ โˆ’ ๐’–๐ŸŽ,๐’ŒA๐Ÿ + ๐‘ฒ๐’‘ ๐’†๐’Œ โˆ’ ๐’†๐’ŒA๐Ÿ +๐‘ฒ๐’‘

๐‘ป๐’Š๐‘ป๐’”๐’†๐’Œ

๐’–๐’Œ = ๐’–๐’ŒA๐Ÿ + โˆ†๐’–๐’Œ

ThisalgorithmcaneasilybeimplementedinLabVIEWorotherlanguagessuchas,e.g.,C#orMATLAB.

FormoredetailsabouthowtoimplementthisinC#,seetheTutorialโ€œDataAcquisitioninC#โ€,availablefromhttp://home.hit.no/~hansha.

LabVIEWExample:

BelowwehaveimplementedthediscretePIcontrollerusingaFormulaNodeinLabVIEW:

Page 52: Tutorial: Control and Simulation in LabVIEW

48 Discretization

Tutorial: Control and Simulation in LabVIEW

ThePIcontrollerisimplementedasaSubVI,soitiseasytoreusethealgorithminallourapplications.

WetestourdiscretePIcontrollerwiththefollowingapplication:

Page 53: Tutorial: Control and Simulation in LabVIEW

49 Discretization

Tutorial: Control and Simulation in LabVIEW

BlockDiagram:

[EndofExample]

10.2.1 PIControllerasaState-spacemodel

Page 54: Tutorial: Control and Simulation in LabVIEW

50 Discretization

Tutorial: Control and Simulation in LabVIEW

Weset ๐‘ง = OC๐‘’ โ‡’ ๐‘ ๐‘ง = ๐‘’ โ‡’ ๐‘ง = ๐‘’

Thisgives:

๐‘ง = ๐‘’

๐‘ข = ๐พ[๐‘’ +๐พ[๐‘‡\๐‘ง

Where

๐‘’ = ๐‘Ÿ โˆ’ ๐‘ฆ

Discreteversion:

UsingEuler:

๐‘ง โ‰ˆ๐‘งN=O โˆ’ ๐‘งN

๐‘‡C

Where ๐‘‡C istheSamplingTime.

Thisgives:

๐‘งN=O โˆ’ ๐‘งN๐‘‡C

= ๐‘’N

๐‘ขN = ๐พ[๐‘’N +๐พ[๐‘‡\๐‘งN

Finally:

๐’†๐’Œ = ๐’“๐’Œ โˆ’ ๐’š๐’Œ

๐’–๐’Œ = ๐‘ฒ๐’‘๐’†๐’Œ +๐‘ฒ๐’‘

๐‘ป๐’Š๐’›๐’Œ

๐’›๐’Œ=๐Ÿ = ๐’›๐’Œ + ๐‘ป๐’”๐’†๐’Œ

ThisalgorithmcaneasilybeimplementedinLabVIEWorotherlanguagessuchas,e.g.,C#orMATLAB.

FormoredetailsabouthowtoimplementthisinC#,seetheTutorialโ€œDataAcquisitioninC#โ€,availablefromhttp://home.hit.no/~hansha.

10.3 ProcessModel

Page 55: Tutorial: Control and Simulation in LabVIEW

51 Discretization

Tutorial: Control and Simulation in LabVIEW

Wewilluseasimplewatertanktoillustratehowtocreateadiscreteversionofamathematicalprocessmodel.Belowweseeanillustration:

Averysimple(linear)modelofthewatertankisasfollows:

๐ด`โ„Ž = ๐พ[๐‘ขโˆ’๐นfg`

or

โ„Ž =1๐ด`

๐พ[๐‘ขโˆ’๐นfg`

Where:

โ€ข โ„Ž [cm]isthelevelinthewatertankโ€ข ๐‘ข [V]isthepumpcontrolsignaltothepumpโ€ข ๐ด` [cm2]isthecross-sectionalareainthetankโ€ข ๐พ[ [(cm3/s)/V]isthepumpgainโ€ข ๐นfg` [cm3/s]istheoutflowthroughthevalve(thisoutflowcanbemodeledmore

accuratelytakingintoaccountthevalvecharacteristicexpressingtherelationbetweenpressuredropacrossthevalveandtheflowthroughthevalve).

WecanusetheEulerForwarddiscretizationmethodinordertocreateadiscretemodel:

๐‘ฅ โ‰ˆ๐‘ฅN=O โˆ’ ๐‘ฅN

๐‘‡C

Thenweget:

โ„ŽN=O โˆ’ โ„ŽN๐‘‡C

=1๐ด`

๐พ[๐‘ขNโˆ’๐นfg`

Page 56: Tutorial: Control and Simulation in LabVIEW

52 Discretization

Tutorial: Control and Simulation in LabVIEW

Finally:

๐’‰๐’Œ=๐Ÿ = ๐’‰๐’Œ +๐‘ป๐’”๐‘จ๐’•

๐‘ฒ๐’‘๐’–๐’Œโˆ’๐‘ญ๐’๐’–๐’•

Thismodelcaneasilybeimplementedinacomputerusing,e.g.,MATLAB,LabVIEWorC#.

FormoredetailsforhowtodothisinC#,seetheTutorialโ€œDataAcquisitioninC#โ€.

InLabVIEWthiscan,e.g.,beimplementedinaFormulaNodeorMathScriptNode.

Example:

InthisexamplewewillsimulateaBacteriaPopulation.

InthisexamplewewilluseLabVIEWandtheLabVIEWControlDesignandSimulationModuletosimulateasimplemodelofabacteriapopulationinajar.

Themodelisasfollows:

birthrate=bx

deathrate=px2

Thenthetotalrateofchangeofbacteriapopulationis:

๐‘ฅ = ๐‘๐‘ฅ โˆ’ ๐‘๐‘ฅw

Wesetb=1/hourandp=0.5bacteria-hourinourexample.

Wewillsimulatethenumberofbacteriainthejarafter1hour,assumingthatinitiallythereare100bacteriapresent.

WewillsimulatethesystemusingaForLoopinLabVIEWandimplementthediscretemodelinaFormulaNode.

Step1:Westartbycreatingthediscretemodel.

IfweuseEulerForwarddifferentiationmethod:

๐‘ฅ โ‰ˆ๐‘ฅN=O โˆ’ ๐‘ฅN

๐‘‡C

Where ๐‘‡C istheSamplingTime.

Weget:

๐‘ฅN=O โˆ’ ๐‘ฅN๐‘‡C

= ๐‘๐‘ฅN โˆ’ ๐‘๐‘ฅNw

Page 57: Tutorial: Control and Simulation in LabVIEW

53 Discretization

Tutorial: Control and Simulation in LabVIEW

Thisgives:

๐‘ฅN=O = ๐‘ฅN + ๐‘‡C(๐‘๐‘ฅN โˆ’ ๐‘๐‘ฅNw)

Step2:WeimplementthemodelintheFormulaNodeandcreateaSubVI.

Step3:WecreatethesimulationprogramusingaForLoop.

Wegetthefollowingresults(notetheScalingFactorssetintheGraphProperties):

Page 58: Tutorial: Control and Simulation in LabVIEW

54 Discretization

Tutorial: Control and Simulation in LabVIEW

[EndofExample]

Example:

Giventhefollowingmathematicalmodel(nonlinear):

๐‘ฅ = โˆ’๐พO ๐‘ฅ + ๐พw๐‘ข

WewillcreateanewapplicationinLabVIEWwherewesimulatethismodelusingaFormulaNodetoimplementthediscretemodel.

WewillusetheEulerForwardmethod(becausethisisanonlinearequation):

๐‘ฅ โ‰ˆ๐‘ฅN=O โˆ’ ๐‘ฅN

๐‘‡C

Thisgives:

๐‘ฅN=O โˆ’ ๐‘ฅN๐‘‡C

= โˆ’๐พO ๐‘ฅ + ๐พw๐‘ข

๐‘ฅN = ๐‘ฅNAO + ๐‘‡C โˆ’๐พO ๐‘ฅNAO + ๐พw๐‘ขNAO

BlockDiagram:

Page 59: Tutorial: Control and Simulation in LabVIEW

55 Discretization

Tutorial: Control and Simulation in LabVIEW

FrontPanel:

[EndofExample]

Page 60: Tutorial: Control and Simulation in LabVIEW

Hans-PetterHalvorsen,M.Sc.

E-mail:[email protected]

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

UniversityCollegeofSoutheastNorway

www.usn.no