Upload
doanngoc
View
267
Download
7
Embed Size (px)
Citation preview
UniversityCollegeofSoutheastNorway
http://home.hit.no/~hansha
ControlandSimulation inLabVIEW
Hans-PetterHalvorsen,2016.10.28
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
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
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
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.
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.
3
2 IntroductiontoControlandSimulation
Controldesignisaprocessthatinvolvesdevelopingmathematicalmodelsthatdescribeaphysicalsystem,analyzingthemodelstolearnabouttheirdynamiccharacteristics,andcreatingacontrollertoachievecertaindynamiccharacteristics.
Simulationisaprocessthatinvolvesusingsoftwaretorecreateandanalyzethebehaviorofdynamicsystems.Youusethesimulationprocesstolowerproductdevelopmentcostsbyacceleratingproductdevelopment.Youalsousethesimulationprocesstoprovideinsightintothebehaviorofdynamicsystemsyoucannotreplicateconvenientlyinthelaboratory.
Belowweseeaclosed-loopfeedbackcontrolsystem:
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
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:
6 IntroductiontoControlandSimulationinLabVIEW
Tutorial: Control and Simulation in LabVIEW
3.2 LabVIEWPIDandFuzzyLogicToolkitTheNILabVIEWPIDandFuzzyLogicToolkitaddcontrolalgorithmstoLabVIEW.BycombiningthePIDandfuzzylogiccontrolfunctionsinthistoolkitwiththemathandlogicfunctionsinLabVIEWsoftware,youcanquicklydevelopprogramsforautomatedcontrol.Youmayintegratethesecontroltoolswiththepowerofdataacquisition.
3.2.1 PIDControl
ThePIDpaletteinLabVIEW:
3.2.2 FuzzyLogic
7 IntroductiontoControlandSimulationinLabVIEW
Tutorial: Control and Simulation in LabVIEW
TheFuzzyLogicpaletteinLabVIEW:
3.3 LabVIEWSystemIdentificationToolkitTheโLabVIEWSystemIdentificationToolkitโcombinesdataacquisitiontoolswithsystemidentificationalgorithmsforplantmodeling.YoucanusetheLabVIEWSystemIdentificationToolkittofindempiricalmodelsfromrealplantstimulus-responseinformation.
TheSystemIdentificationpaletteinLabVIEW:
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:
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.
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:
11 Simulation
Tutorial: Control and Simulation in LabVIEW
AllthedifferentblockshavetheirowndifferentConfigurationwindow.
IntheParametersourceyoumayselectbetween:
โข ConfigurationDialogBoxโข Terminal
IfyouselectโConfigurationDialogBoxโyouentertheconfigurationintheConfigurationwindowlikeweseeabove,whileifyouselectโTerminalโthatspecificconfigurationissetfromtheBlockDiagramlikethis:
IconStyle:
Whenyouplacetheblockontheblockdiagramyoumayselecthowthatshouldappear.Right-clickontheblock/iconandselectโIconStyleโ:
12 Simulation
Tutorial: Control and Simulation in LabVIEW
Example:IconStyle
FortheโTransferFunctionโ(SimulationโContinuousLinearSystems)blockwehavethefollowingdifferenticonstyles:
Static:
Dynamic:
TextOnly:
Express:
WeseefortheDynamicandExpressstylesthattheappearancechangesaccordingtoconfigurationparametersweset.
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:
14 Simulation
Tutorial: Control and Simulation in LabVIEW
Youmaydraginthecornerinordertoincreaseordecreasethedynamicicon.
IfyouselectโstaticโiconstyleyouseetheiconyoucreatedwiththeIconEditor.
Likethis:
4.3 ContinuousLinearSystemsIntheโContinuousLinearSystemsโSubpalettewewanttocreateasimulationmodel:
ThemostusedblocksprobablyareIntegrator,TransportDelay,State-SpaceandTransferFunction.
15 Simulation
Tutorial: Control and Simulation in LabVIEW
Whenyouplacetheseblocksonthediagramyoumaydouble-clickorright-clickandthenselectโConfigurationโฆโ
Integrator-Integratesacontinuousinputsignalusingtheordinarydifferentialequation(ODE)solveryouspecifyforthesimulation.
TheConfigurationwindowfortheIntegratorblocklookslikethis:
TransportDelay-Delaystheinputsignalbytheamountoftimeyouspecify.
TheConfigurationwindowfortheTransportDelayblocklookslikethis:
TransferFunction-Implementsasystemmodelintransferfunctionform.YoudefinethesystemmodelbyspecifyingtheNumeratorandDenominatorofthetransferfunctionequation.
16 Simulation
Tutorial: Control and Simulation in LabVIEW
TheConfigurationwindowfortheTransferFunctionblocklookslikethis:
State-Space-Implementsasystemmodelinstate-spaceform.Youdefinethesystemmodelbyspecifyingtheinput,output,state,anddirecttransmissionmatrices.
TheConfigurationwindowfortheState-Spaceblocklookslikethis:
SignalArithmetic:
TheโSignalArithmeticโSubpaletteisalsousefulwhencreatingasimulationmodel:
17 Simulation
Tutorial: Control and Simulation in LabVIEW
Example:SimulationModel
BelowweseeanexampleofasimulationmodelcreatedinLabVIEW.
Example:Simulation
BelowweseeanexampleofasimulationmodelusingtheControlandSimulationLoop.
Noticethefollowing:
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
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.
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-
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.
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.
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.
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
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:
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:
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).
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:
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
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.
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.
32 PIDControl
Tutorial: Control and Simulation in LabVIEW
Thefollowingformularepresentsthederivativeaction.
5.1 PIDControlinLabVIEWIntheโPIDโSubpalettewehavethefunctions/SubVIsforPIDControl.IrecommendthatyouusetheโPIDAdvanced.viโ.
Example:PIDControl
BelowweseehowwecanusethePIDAdvanvanced.viinordertocontrolasimulatedModel.
33 PIDControl
Tutorial: Control and Simulation in LabVIEW
5.2 Auto-tuningTheLabVIEWPIDandFuzzyLogicToolkitincludeaVIforauto-tuning.
34
6 ControlDesignControldesignisaprocessthatinvolvesdevelopingmathematicalmodelsthatdescribeaphysicalsystem,analyzingthemodelstolearnabouttheirdynamiccharacteristics,andcreatingacontrollertoachievecertaindynamiccharacteristics.
6.1 ControlDesigninLabVIEWControlDesignpalette:
35
7 SystemIdentification
7.1 SystemIdentificationinLabVIEWTheโSystemIdentificationToolkitโcombinesdataacquisitiontoolswithsystemidentificationalgorithmsforaccurateplantmodeling.YoucantakeadvantageofLabVIEWintuitivedataacquisitiontoolssuchastheDAQAssistanttostimulateandacquiredatafromtheplantandthenautomaticallyidentifyadynamicsystemmodel.Youcanconvertsystemidentificationmodelstostate-space,transferfunction,orpole-zero-gainformforcontrolsystemanalysisanddesign.Thetoolkitincludesbuilt-infunctionsforcommontaskssuchasdatapreprocessing,modelcreation,andsystemanalysis.Usingotherbuilt-inutilities,youcanplotthemodelwithintuitivegraphicalrepresentationaswellasstorethemodel.
SystemIdentificationpalette:
36
8 FuzzyLogicFuzzylogicisamethodofrule-baseddecisionmakingusedforexpertsystemsandprocesscontrol.FuzzylogicdiffersfromtraditionalBooleanlogicinthatfuzzylogicallowsforpartialmembershipinaset.Youcanusefuzzylogictocontrolprocessesrepresentedbysubjective,linguisticdescriptions.
Afuzzysystemisasystemofvariablesthatareassociatedusingfuzzylogic.Afuzzycontrollerusesdefinedrulestocontrolafuzzysystembasedonthecurrentvaluesofinputvariables.
[Wikipedia]
8.1 FuzzyLogicinLabVIEWTheFuzzyLogicpaletteinLabVIEW:
37 PIDControl
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:
39 LabVIEWMathScript
Tutorial: Control and Simulation in LabVIEW
9.1 HelpYoumayalsotypehelpinyourcommandwindow
>>help
Ormorespecific,e.g.,
>>help plot
9.2 ExamplesIadviseyoutotestalltheexamplesinthistextinLabVIEWMathScriptinordertogetfamiliarwiththeprogramanditssyntax.Allexamplesinthetextareoutlinedinaframelikethis:
>> โฆ
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
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
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)
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
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:
45 Discretization
Tutorial: Control and Simulation in LabVIEW
ItisagoodideatobuildthisasaSubVIs,andthenwecaneasilyreusetheLow-passfilterinallourapplications.
Wewilltestthediscretelow-passfilter,tomakesureitworksasexpected:
Wecreateasimpletestapplicationwhereweaddsomerandomwhitenoisetoasinesignal.Wewillplottheunfilteredandthefilteredsignaltoseeifthelow-passfilterisabletoremovethenoisefromthesinesignal.
Wegetthefollowingresults:
46 Discretization
Tutorial: Control and Simulation in LabVIEW
Weseethatthefilterworksfine.Theredlineistheunfilteredsinesignalwithwhitenoise,whiletheredlineisthefilteredresults.
[EndofExample]
10.2 PIControllerAPIcontrollermaybewritten:
๐ ๐ = ๐๐ + ๐ฒ๐๐ ๐ +๐ฒ๐
๐ป๐๐๐ ๐๐
๐
Where ๐ข isthecontrolleroutputand ๐isthecontrolerror:
๐ ๐ก = ๐ ๐ก โ ๐ฆ(๐ก)
Laplaceversion:
๐ข ๐ = ๐พ[๐ ๐ +๐พ[๐\๐
๐ ๐
Discreteversion:
Westartwith:
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:
48 Discretization
Tutorial: Control and Simulation in LabVIEW
ThePIcontrollerisimplementedasaSubVI,soitiseasytoreusethealgorithminallourapplications.
WetestourdiscretePIcontrollerwiththefollowingapplication:
49 Discretization
Tutorial: Control and Simulation in LabVIEW
BlockDiagram:
[EndofExample]
10.2.1 PIControllerasaState-spacemodel
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
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`
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
53 Discretization
Tutorial: Control and Simulation in LabVIEW
Thisgives:
๐ฅN=O = ๐ฅN + ๐C(๐๐ฅN โ ๐๐ฅNw)
Step2:WeimplementthemodelintheFormulaNodeandcreateaSubVI.
Step3:WecreatethesimulationprogramusingaForLoop.
Wegetthefollowingresults(notetheScalingFactorssetintheGraphProperties):
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:
55 Discretization
Tutorial: Control and Simulation in LabVIEW
FrontPanel:
[EndofExample]
Hans-PetterHalvorsen,M.Sc.
E-mail:[email protected]
Blog:http://home.hit.no/~hansha/
UniversityCollegeofSoutheastNorway
www.usn.no