university college of southeast norway - home.usn.no · • intermediate topics in labview •...
TRANSCRIPT
UniversityCollegeofSoutheastNorway
http://home.hit.no/~hansha
IntroductiontoState-basedApplicationsinLabVIEW
Hans-PetterHalvorsen,2016.10.31
PrefaceStatechartsorStateDiagramsareusefulinsimplifyingthedesignofapplicationsthatusecomplexdecision-makingalgorithms.Byconstructingastatechart,youcanvisualizetheflowofacomplexdecision-makingalgorithmandachieveahigh-levelviewofanapplication.
Thisdocumentexplainsthebasicconceptsofcreatingstate-basedapplicationsinLabVIEW.
YoushouldhavesomebasicknowledgeaboutLabVIEW,e.g.,the“AnIntroductiontoLabVIEW”training.Thisdocumentisavailablefordownloadathttp://home.hit.no/~hansha/.
InadditiontoLabVIEWProfessionalDevelopmentSystem,youneedtoinstallthe“LabVIEWStatechartModule”.
iii
TableofContentsPreface......................................................................................................................................2
TableofContents.....................................................................................................................iii
1 IntroductiontoLabVIEW...................................................................................................1
1.1 Dataflowprogramming...............................................................................................1
1.2 Graphicalprogramming..............................................................................................2
1.3 Benefits.......................................................................................................................2
2 IntroductiontoSequentialControl...................................................................................3
3 IntroductiontoStateDiagrams.........................................................................................4
4 IntroductiontoSequentialFunctionCharts(SFC).............................................................5
5 State-machinewithLabVIEW............................................................................................7
5.1 WhileLoop..................................................................................................................7
5.2 CaseStructure.............................................................................................................8
5.3 ShiftRegister...............................................................................................................9
5.4 StateProgrammingArchitecture..............................................................................10
5.5 State-machine...........................................................................................................11
6 ASequentialControlexampleinLabVIEW......................................................................14
7 IntroductiontoLabVIEWStatechartModule..................................................................16
7.1 ProcedureforcreatingaStatechartapplicationinLabVIEW...................................17
7.2 StatechartEditor.......................................................................................................21
7.2.1 StatechartDevelopmentobjects.......................................................................23
7.3 UsingaCallerVItoExecuteaStatechart..................................................................25
8 Tutorial:CreateaStatechart...........................................................................................28
iv TableofContents
Tutorial: Introduction to State-based Applications in LabVIEW
9 AdvancedTopicsinLabVIEWStatechartModule...........................................................42
9.1 UsingRegionsandSubstates....................................................................................42
9.2 UsingOrthogonalRegionsandStateHistory............................................................42
9.3 SplittingandMergingTransitionSegments..............................................................43
10 WhatsNext?....................................................................................................................44
10.1 MyBlog.....................................................................................................................44
10.2 Training.....................................................................................................................44
10.3 AdditionalResources................................................................................................44
10.4 Examples...................................................................................................................44
10.5 Documentation.........................................................................................................45
10.6 LabVIEWWiki................................................................Error!Bookmarknotdefined.
10.7 LabVIEWonYouTube....................................................Error!Bookmarknotdefined.
QuickReference......................................................................................................................46
1
1 IntroductiontoLabVIEWLabVIEW(shortforLaboratoryVirtualInstrumentationEngineeringWorkbench)isaplatformanddevelopmentenvironmentforavisualprogramminglanguagefromNationalInstruments.Thegraphicallanguageisnamed"G".OriginallyreleasedfortheAppleMacintoshin1986,LabVIEWiscommonlyusedfordataacquisition,instrumentcontrol,andindustrialautomationonavarietyofplatformsincludingMicrosoftWindows,variousflavorsofUNIX,Linux,andMacOSX.VisitNationalInstrumentsatwww.ni.com.
Thecodefileshavetheextension“.vi”,whichisanabbreviationfor“VirtualInstrument”.LabVIEWofferslotsofadditionalAdd-OnsandToolkits.
ThispaperispartofaserieswithLabVIEWtutorials,suchas:
• IntroductiontoLabVIEW• DataAcquisitioninLabVIEW• ControlandSimulationinLabVIEW• LabVIEWMathScript• LinearAlgebrainLabVIEW• DataloggingandSupervisoryControlinLabVIEW• WirelessDataAcquisitioninLabVIEW• IntermediateTopicsinLabVIEW• AdvancedTopicsinLabVIEW
Eachtutorialmaybeusedindependentlyofeachother.
1.1 DataflowprogrammingTheprogramminglanguageusedinLabVIEW,alsoreferredtoasG,isadataflowprogramminglanguage.Executionisdeterminedbythestructureofagraphicalblockdiagram(theLV-sourcecode)onwhichtheprogrammerconnectsdifferentfunction-nodesbydrawingwires.Thesewirespropagatevariablesandanynodecanexecuteassoonasallitsinputdatabecomeavailable.Sincethismightbethecaseformultiplenodessimultaneously,Gisinherentlycapableofparallelexecution.Multi-processingandmulti-threadinghardwareisautomaticallyexploitedbythebuilt-inscheduler,whichmultiplexesmultipleOSthreadsoverthenodesreadyforexecution.
2 IntroductiontoLabVIEW
Tutorial: Introduction to State-based Applications in LabVIEW
1.2 GraphicalprogrammingLabVIEWtiesthecreationofuserinterfaces(calledfrontpanels)intothedevelopmentcycle.LabVIEWprograms/subroutinesarecalledvirtualinstruments(VIs).EachVIhasthreecomponents:ablockdiagram,afrontpanel,andaconnectorpanel.ThelastisusedtorepresenttheVIintheblockdiagramsofother,callingVIs.Controlsandindicatorsonthefrontpanelallowanoperatortoinputdataintoorextractdatafromarunningvirtualinstrument.However,thefrontpanelcanalsoserveasaprogrammaticinterface.Thusavirtualinstrumentcaneitherberunasaprogram,withthefrontpanelservingasauserinterface,or,whendroppedasanodeontotheblockdiagram,thefrontpaneldefinestheinputsandoutputsforthegivennodethroughtheconnectorpane.ThisimplieseachVIcanbeeasilytestedbeforebeingembeddedasasubroutineintoalargerprogram.
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 IntroductiontoSequentialControl
Sequentialcontroliscrucialinmanycontrolapplications,asinchemicalbatchprocesses.Asequentialcontrolprocedurecanberepresentedgraphicallybye.g.oneofthefollowingtwomethods:
• AStatediagram,alsodenotedaStatemachine• ASequentialfunctionchart(SFC)
StatediagramsandSFCarequitesimilar,astheyhavethesamebasicelements:
• Stateswithactionstobeexecutedwhenthestateisactive• Transitionsfromoneactivestatetoanother
SequentialcontrolcanbeimplementedusinggraphicalprogrammingofstatediagramsorSFCsinproperprogrammingtools.Forexample,statediagramsaresupportedbytheLabVIEWStatechartModule.DifferentPLC(ProgrammableLogicController)toolssupportSFC.
4
3 IntroductiontoStateDiagrams
Statediagramshavestateswithactionstobeexecutedwhenthestateisactive.Theyhavetransitionsfromoneactivestatetoanothertakingplaceifthetransitionconditionislogicallytrue.
Belowweseeatypicalstatediagram:
ByFredtheOyster,CCBY-SA4.0,https://commons.wikimedia.org/w/index.php?curid=35221177
Astatediagramrepresentsastatemachine.Statesofastatemachineareeitheractiveorpassive.Onlyonestateisactiveatatime.Thestatemachinealwaysstartsinaparticularstatedefinedastheinitialstate,anditends(stops)afterthefinalstate.Specialsymbolsorcolorsmaybeusedfortheinitialstateandthefinalstate.SeetheFigureabove.
5
4 IntroductiontoSequentialFunctionCharts
SequentialFunctionChartsdescribecontrolsequencesingraphicalform.StateDiagramsandSequentialfunctioncharts(SFC)techniquesareverysimilar.Theyhavestates/steps(inSFCthetermstepsisused)withactionstobeexecutedwhenthestateisactive.Theyhavetransitionsfromoneactivestatetoanothertakingplaceifthetransitionconditionislogicallytrue.
Sequentialfunctionchart(SFC)isagraphicalprogramminglanguageoftenusedforPLCs(PLC-ProgrammableLogicController).
BelowweseeatypicalSFCchart:
[Figure:http://www.plcdev.com/sequential_function_charts_all]
The Sequential Function Charts break a sequential task down into Steps, Transitions andActions.Thesearedrawngraphicallytodescribeasequenceofinteractionsasseenabove.Steps:
• Everystepcanexecuteoneormoreactions.• A step can be either active or inactive. When it becomes active, it's actions are
executed
6 IntroductiontoSequentialFunctionCharts
Tutorial: Introduction to State-based Applications in LabVIEW
Transitions:
• Therearetransitionsbetweeneverystep.• WhenaStep is activeand the following transitionbecome true the successor step
becomesactiveandtheprecedingstepbecomesinactive.• Eachtransitionhasassociatedeventswhicharecalledtransitionconditions.• ThetransitionconditionsmustcombinetomakeasimpleBooleanresult,TrueorFalse.
StepActions:
• Every action is associated with a step. The step can have none or several actionsassociated.
• Ifthereisnoassociatedactiontothestep,itwillbeconsideredasaWAITfunction. • Eachstep/actionassociationshallhaveanassociatedactionqualifier.
TheProgramFlowisasfollows:• Astepbecomesactivewhenitsprecedingtransitionactivates(thatisthetransitionis
true,whilethestepbeforethattransitionisactive.)• Astepbecomesinactivewhenit'ssubsequenttransitionbecomestrue• InParallelbranches,alltheinitialstepsbecomeactivewhentheprecedingtransition
activates• Aparallelbranchendwhenallthestepsbeforethebranchendarebeactive,andthe
subsequenttransitionbecomestrueManysystemshavesequentialoperationrequirementsandSequentialFunctionCharts(SFC’s)have become a popularmethod of accurately specifying sequential control requirements.SFC’shavemanyadvantagesforsoftwaredevelopmentbothinthedesignstageaswellastheimplementationandtesting,maintainingandfaultfindingstages,suchas:
• DesignStageo Detailedcleargraphicalspecificationo Nonsoftwarepeoplecanspecify/verify
• Implementationo Straightforwardconversionfromspecificationtocodeo Structuredtesting/debugging
• MaintenanceofSoftwareo Readilyunderstoodbyengineermodifyingsoftware
• MachineMaintenanceo Allowsquickaccuratefaultdiagnosis
7
5 State-machinewithLabVIEW
TheStateMachineapproachinLabVIEWusesaCasestructureinsideaWhilelooptohandlethedifferentstatesintheprogram,andthetransitionsbetweenthem.TheShiftRegisterisusedtosavedatafromandbetweenthedifferentstates.
BelowweshortlyrepeattheWhileLoop,theCasestructureandtheShiftRegisterbeforewedigintotheprinciplesofthestate-machine.
FormoredetailsaboutbasicLabVIEWprogrammingtechniques,refertothetutorial“IntroductiontoLabVIEW”.Thetutorialisavailablefordownloadfrom:http://home.hit.no/~hansha.
5.1 WhileLoopAWhilelooprepeatsthesubdiagraminsideituntiltheconditionalterminal,aninputterminal,receivesaparticularBooleanvalue.TheBooleanvaluedependsonthecontinuationbehavioroftheWhileLoop.Right-clicktheconditionalterminalandselectStopifTrueorContinueifTruefromtheshortcutmenu.Youalsocanwireanerrorclustertotheconditionalterminal,right-clicktheterminal,andselectStoponErrororContinuewhileErrorfromtheshortcutmenu.Note!TheWhileLoopalwaysexecutesatleastonce.
BelowweseeanemptyWhileloop:
8 State-machinewithLabVIEW
Tutorial: Introduction to State-based Applications in LabVIEW
AfteryoucreateaWhileLoop,youcanuseshiftregisterstopassvaluesfromoneiterationtothenext.IfyouwireanarraytoaWhileLoop,youcanreadandprocesseveryelementinthatarraybyenablingauto-indexing.Seexamplebelow.
InordertoconvertaWhileLoopintoaForLoop,right-clicktheWhileLoopandselect“ReplacewithForLoop”fromtheshortcutmenu.ToconvertaWhileLoopintoaTimedLoop,right-clicktheWhileLoopandselect“ReplacewithTimedLoop”fromtheshortcutmenu.
5.2 CaseStructureTheCaseStructurehasoneormoresubdiagrams,orcases,exactlyoneofwhichexecuteswhenthestructureexecutes.ThevaluewiredtotheselectorterminaldetermineswhichcasetoexecuteandcanbeBoolean,string,integer,orenumeratedtype.Youmayright-clickthestructurebordertoaddordeletecases.UsetheLabelingtooltoentervalue(s)inthecaseselectorlabelandconfigurethevalue(s)handledbyeachcase.
BelowweseeanemptyCasestructure:
9 State-machinewithLabVIEW
Tutorial: Introduction to State-based Applications in LabVIEW
BelowweseeanexampleofaCasestructurewith2cases,a“True”caseanda“False”case.DependingoftheBooleaninputvalue,theNumeric1andNumeric2iseitherAddedorSubtracted.
Youmayalsoconnectanerrorclusterdirectlytoacasestructure,likethis:
Thecasestructureautomaticallyswitchestoa“NoError”caseandan“Error”case.
5.3 ShiftRegister
10 State-machinewithLabVIEW
Tutorial: Introduction to State-based Applications in LabVIEW
UseshiftregistersonForLoopsandWhileLoopstotransfervaluesfromoneloopiterationtothenext.Shiftregistersaresimilartostaticvariablesintext-basedprogramminglanguages.Ashiftregisterappearsasapairofterminals,directlyoppositeeachotherontheverticalsidesoftheloopborder.Therightterminalcontainsanuparrowandstoresdataonthecompletionofaniteration.LabVIEWtransfersthedataconnectedtotherightsideoftheregistertothenextiteration.Createashiftregisterbyright-clickingtheleftorrightborderofaloopandselectingAddShiftRegisterfromtheshortcutmenu.
Ashiftregistertransfersanydatatypeandautomaticallychangestothedatatypeofthefirstobjectwiredtotheshiftregister.Thedatayouwiretotheterminalsofeachshiftregistermustbethesametype.
Toinitializeashiftregister,wireanyvaluefromoutsidethelooptotheleftterminal.Ifyoudonotinitializetheshiftregister,theloopusesthevaluewrittentotheshiftregisterwhenthelooplastexecutedorthedefaultvalueforthedatatypeiftheloophasneverexecuted.
UsealoopwithanuninitializedshiftregistertorunaVIrepeatedlysothateachtimetheVIruns,theinitialoutputoftheshiftregisteristhelastvaluefromthepreviousexecution.UseanuninitializedshiftregistertopreservestateinformationbetweensubsequentexecutionsofaVI.Aftertheloopexecutes,thelastvaluestoredintheshiftregisterremainsattherightterminal.Ifyouwiretherightterminaloutsidetheloop,thewiretransfersthelastvaluestoredintheshiftregister.Youcanaddmorethanoneshiftregistertoaloop.Ifyouhavemultipleoperationswithinaloop,usemultipleshiftregisterstostorethedatavaluesfromthosedifferentprocessesinthestructure.
ShiftRegisterExample:
CreateandRunthisexampletoseewhathappens.
5.4 StateProgrammingArchitecture
11 State-machinewithLabVIEW
Tutorial: Introduction to State-based Applications in LabVIEW
CreatingVIsusingtheStateMachineapproachisveryusefulwhencreating(large)applications.
Ingeneral,astatemachineisamodelofbehaviorcomposedofafinitenumberofstates,transitionsbetweenthosestates,andactions.Itissimilartoa"flowgraph"wherewecaninspectthewayinwhichthelogicrunswhencertainconditionsaremet.
[Wikipedia]
Sometimes,youmaywanttochangetheorderofthesequence,repeatoneiteminthesequencemoreoftenthantheotheritems,stopasequenceimmediately,orhaveitemsinthesequencethatmayexecuteonlywhencertainconditionsaremet.Althoughyourprogrammaynothaveanysuchrequirements,thereisalwaysthepossibilitythattheprogrammustbemodifiedinthefuture.Therefore,astateprogrammingarchitectureisagoodchoice,evenifasequentialprogrammingstructureissufficient.Thefollowinglistdescribesmorecomplexprogrammingrequirementsthatjustifytheuseofastateprogrammingarchitectureforanapplication.
• Youneedtochangetheorderofthesequence• Youmustrepeataniteminthesequencemoreoftenthanotheritems• Youwantsomeitemsinthesequencetoexecuteonlywhencertainconditionsare
met
5.5 State-machineTheStateMachineapproachinLabVIEWusesaCasestructureinsideaWhilelooptohandlethedifferentstatesintheprogram,andthetransitionsbetweenthem.TheShiftRegisterisusedtosavedatafromandbetweenthedifferentstates.
BelowweseeexamplesofastatemachineprincipleimplementedinLabVIEW.
12 State-machinewithLabVIEW
Tutorial: Introduction to State-based Applications in LabVIEW
SimpleStateMachineprinciple
StateMachinewithmultipletransitionsdependingontheState:
MoreadvancedStateMachineusingShiftRegisters:
13 State-machinewithLabVIEW
Tutorial: Introduction to State-based Applications in LabVIEW
TemplatesforState-machinesinLabVIEWareavailablefordownloadat:http://home.hit.no/~hansha
14
6 ASequentialControlexampleinLabVIEW
Thisexampleillustrateshowwemayusethestate-machineprincipleinLabVIEWtocreateasequentialcontrolapplication.
Thisexampleusesastatemachineforsequentialcontrolofthepositionofabicycle.
Thestate-machineisimplementedwith:
• AnoverallCase-structurewhichdefinesthestatesandcontainstheactionsofeachstate
• AShift-registerwhichrememberswhichstateistheactivestate• AninternalCase-structureinsideeachstate(CaseintheoverallCase-structure)
togetherwithproperBooleancomparisonfunctionsimplementingthetransitionconditions.
Thestate-machinecontrolsasimulatedprocess(bicycleposition)givenbythefollowingdynamicmodel:
𝑑𝑥𝑑𝑡 = 𝑣
Wherexispositionandvisspeed.Thespeedismanipulatedbythestate-machine.
ThismodelisimplementedinaSimulationLoopwhichrunsinparallelwiththeWhileloop.Data(variables)areexchangedbetweentheseloopsusinglocalvariables.
ThearrowonaVerticalPointerSlideisreplacedwithapictureofabicycle.TheproceduretosubstituteanygraphicalpartofanindicatororcontrolontheFrontpanelisasfollows:Right-clickontheitem(graphicalpart),e.g.thearrowofaVerticalPointerSlide.SelectAdvanced/Customizeinthemenuthatisopened.ClicktheToolbuttoninthetoolbarofthenewwindowthatisopened.Right-clickonthearrowontheslider,andselectthepictureyouwant.Etc.
Howtouseit?
UsethisVIasatemplateforyourownstate-machinecontrollerforanysimulateddynamicsystem.Tocontrolareal(physical)processinstead,justsubstitutethesimulatedprocesswithreadand/orwritefunctionsforanalogand/ordigitalI/O(input/output).
15 ASequentialControlexampleinLabVIEW
Tutorial: Introduction to State-based Applications in LabVIEW
TheFrontPanellookslikethis:
TheBlockDiagramlookslikethis:
Inordertogetthefeelingwithstatemachines,whileloops,casestructuresandshiftregisters,trytoreproducetheexample.
TheexampleiscreatedbyFinnHaugen,UniversityCollegeofSoutheastNorway.
16
7 IntroductiontoLabVIEWStatechartModule
TheNILabVIEWStatechartModuleprovidesaprogrammingmodelthatyoucanusetodesignapplicationsatahigherlevelthanwaspreviouslypossible.WiththeLabVIEWStatechartModule,youcandevelopstatechartdiagrams,definebehaviorswithLabVIEWdataflowprogramming.
Statechartsexpandtheclassicstatediagramwiththeadditionalfeaturesofhierarchy,concurrency,andcomprehensiveactions.
LabVIEWstatechartsareespeciallyusefulforprogrammingevent-responseapplicationssuchasintricateuserinterfacesandadvancedstatemachinesusedtoimplementdynamicsystemcontrollers,machinecontrollogic,anddigitalcommunicationprotocols.
UsingtheLabVIEWStatechartModuleinvolvesthefollowingtwosteps:
• UsingtheStatechartEditorwindowtobuildastatechart. • CreatingaVIthatexecutesthestatechart.ThisVIalsosendsinformationto,and
receivesinformationfrom,thestatechart.
BuildingaStatechart
Buildingastatechartinvolvesdefiningthefollowingitems:
• States • Actionsandstaticreactionsthesestatesexecute • Transitionsbetweenstates • Actionsthesetransitionsexecute • Triggers
Whenyoubuildastatechart,youdefineuniquestatesinwhichthestatechartcanbe.Youalsodefinetransitionsbetweenthesestates,whenthestatechartcantakethesetransitions,andwhatactionsthesetransitionscantake.Youthendefinetriggersthatcausethestatecharttobeginevaluatingacertaintransition.Forexample,considerastatechartthatyouusetocontrolachemicalprocess.YoucanspecifythatthestatechartmovesfromState1toState2afterreceivingtheValveOpentrigger.Statesandtransitionsalsohave
17 IntroductiontoLabVIEWStatechartModule
Tutorial: Introduction to State-based Applications in LabVIEW
associatedactions,whichyouusetomodifyoutputandstatedataassociatedwiththestatechart.
CreatingaVIthatExecutestheStatechart
Afteryoudefinethevalidtriggersandconfigurethestatecharttoreacttothosetriggers,youmustsendthosetriggerstothestatechart.YousendtriggerstothestatechartbycreatingaVI,knownastheCallerVI,tosendtriggersataspecifictime.Forexample,youcanconfigurethecallerVItosendtheStoptriggerafteryouclicktheStopfrontpanelbutton.
ThecallerVIalsosendsinputdatatothestatechartsothestatechartcanactonthatdata.ThecallerVIreceivesdatathatthestatechartmodifiesasaresultofastateortransitionaction.YouthencanusethisdatainotherpartsofthecallerVIorsendthisdatatootherVIs.
ThefollowingfigureshowshowacallerVIinteractswithastatechart.
ThefigureaboveshowshowthecallerVIsendsdatatothestatechart,whichreturnsoutputdatatothecallerVI.Ifthestatechartisasynchronous,thecallerVIalsomightsendatriggertothestatechart.Sendingatriggertothestatechartcausesthestatecharttobeginexecuting.
7.1 ProcedureforcreatingaStatechartapplicationinLabVIEW
TheprocedureforcreatingastatechartapplicationinLabVIEWwiththeLabVIEWStatechartModuleisasfollows:
Step1:IntheNewdialogselect“Statechart”.
18 IntroductiontoLabVIEWStatechartModule
Tutorial: Introduction to State-based Applications in LabVIEW
Step2:NametheStatechart
Step3:TheProjectExplorerfortheStatechartapplicationappears:
19 IntroductiontoLabVIEWStatechartModule
Tutorial: Introduction to State-based Applications in LabVIEW
Asyousee,theLabVIEWStatechartModuleautomaticallygeneratesasetofVisandControls.
LabVIEWStatechartPalette:
LabVIEWStatechartModuleoffersthefollowingFunctionsandObjectsintheStatechartpalette:
StatechartCommunicationFunctions:
UsetheStatechartCommunicationfunctionstoexecuteastatechart,sendtriggerstoastatechart,anddeterminewhetheraparticularstateisactive.Youcanplacethesefunctionsonablockdiagram.
StatechartCommunicationpalette:
20 IntroductiontoLabVIEWStatechartModule
Tutorial: Introduction to State-based Applications in LabVIEW
RunStatechartExecutesaninstanceofthelinkedstatechart.YoutypicallyplacethisfunctioninsidealoopinthecallerVI.
Example:
SendExternalTriggerSendsatriggertotheexternalqueueofaninstanceofthelinkedstatechart.YoucanusethisfunctioninthecallerVIorinaVIthatrunsparalleltothecallerVI.Seexampleabove
IsInDetermineswhetherthespecifiedstateisactive.Anactivestateisonethatastatechartiscurrentlyin.Youcanusethisfunctioninaguard,anaction,orasubVIthataguardoractioncalls.
SendInternalTriggerSendsatriggertotheinternalqueueofthestatechart.YoucanusethisfunctionwithinonlyanactionorinasubVIthatanactioncalls.
21 IntroductiontoLabVIEWStatechartModule
Tutorial: Introduction to State-based Applications in LabVIEW
StatechartDevelopmentObjects:
UsetheStatechartDevelopmentobjects,consistingofstates,regions,“pseudostates”,andconnectors,toconstructstatecharts.Note!Youcanplacetheseobjectsonlyonastatechartdiagram.
StatechartDevelopmentpalette:
Thedifferentobjectsareexplainedbelow.
7.2 StatechartEditorYouusetheStatechartEditorwindowtoeditastatechart.YoucandisplaytheStatechartEditorwindowinoneofthefollowingways:
• Double-clickthe“Diagram.vi”itemintheProjectExplorerwindowofthestatechart. • Right-clickthe“Diagram.vi”itemandselectOpenfromtheshortcutmenu. • Right-clickaRunStatechartfunctionthatlinkstothestatechartandselect
View»StatechartDiagramfromtheshortcutmenu.
StatechartEditorWindow:
22 IntroductiontoLabVIEWStatechartModule
Tutorial: Introduction to State-based Applications in LabVIEW
TheStatechartEditorwindow,whichdisplaysastatechartdiagram,issimilartotheLabVIEWwindowthatdisplaysablockdiagram.Inbothofthesewindows,youcanplaceobjectsfromtheFunctionspaletteonthediagram,usetheLabVIEWtoolstomanipulateobjects,andconnectobjectstogether.However,theStatechartEditorwindowisdifferentfromtheLabVIEWwindowinthefollowingways:
• YoucanplaceonlyStatechartDevelopmentobjectsonastatechartdiagram.YoucannotplaceLabVIEWVIs,functions,orstructuresdirectlyonastatechartdiagram.
• TheLabVIEWblockdiagramwindowdisplaystheRunbuttononthetoolbar.The
StatechartEditorwindowdisplaysthe“GenerateCode“button onthetoolbar.Clickingthisbuttongeneratescodeforthestatechart.
23 IntroductiontoLabVIEWStatechartModule
Tutorial: Introduction to State-based Applications in LabVIEW
• TheLabVIEWblockdiagramhasafrontpanelwindow.TheStatechartEditorwindowdoesnothaveafrontpanelwindow.
• OntheLabVIEWblockdiagram,youusethewiringtooltocreatewiresbetweenVIsandfunctions.IntheStatechartEditorwindow,youusethewiringtooltocreatetransitionsbetweenstatesandotherobjects.
• TheLabVIEWblockdiagramprovidesoptionsfordebuggingVIs.TheStatechartEditorwindowdoesnotprovideanydebuggingoptions.Youdebugstatechartsbyusingaseparatewindowthatyoucanaccesswhilethestatechartisrunning.
• TheStatechartEditorwindowdisablesmanyLabVIEWpull-downmenuitemsthatdonotapplytostatecharts.
7.2.1 StatechartDevelopmentobjects
UsetheStatechartDevelopmentobjectstoconstructstatecharts.Youcanplacetheseobjectsonastatechartdiagram.
TheStatechartDevelopmentobjectsconsistofstates,regions,andconnectors.
TheStatechartDevelopmentpalette:
TheStatechartDevelopmentobjectsareasfollows:
StateDefinesastate,whichisauniqueconditioninwhichthestatechartcanbe.Youmustplaceallstateswithinaregion.Note!Thetop-levelstatechartdiagramrepresentsaregion.Allstatesmusthaveatleastoneincomingtransition.
24 IntroductiontoLabVIEWStatechartModule
Tutorial: Introduction to State-based Applications in LabVIEW
InitialSpecifiesthefirststatethattheenclosingregionenterswhenthestatechartentersthatregion.Tospecifythisstate,createatransitionfromtheInitialpseudostatetothestatethatyouwanttoenterfirst.Youcanplacethispseudostatewithinonlyaregionoratthetoplevelofastatechartdiagram.EachregionmusthaveoneandonlyoneInitialpseudostate.
TerminalSpecifiesastatethatcanterminatetheexecutionoftheenclosingregion.Tospecifythisstate,createatransitionfromastatetoaTerminalpseudostate.Youcanplacethispseudostatewithinonlyaregion.YoucanplacemorethanoneTerminalpseudostateinaregion.
JunctionConnectscommonelementsofmultipletransitionstogether.Forexample,youcanuseaJunctionconnectortospecifythatmultipletransitionsusethesameaction,eventhougheachtransitionmighthaveadifferenttrigger.Youcanplacethisconnectoronlyinaregion.
RegionDefinestheareainwhichyoucanplacestatesandpseudostates.EachregionmustcontainanInitialpseudostateandatleastonesubstate.Note!Thetop-levelstatechartdiagramrepresentsaregion.Youcanplaceregionswithinonlyastate.
ForkSplitsoneincomingtransitionsegmentintomultipleoutgoingsegments.Youcanplacethisconnectorwithinonlyastate.
JoinMergesmultipleincomingtransitionsegmentsintooneoutgoingsegment.Youcanplacethisconnectorwithinonlyastate.
25 IntroductiontoLabVIEWStatechartModule
Tutorial: Introduction to State-based Applications in LabVIEW
PortIndicateswhereatransitionleavesastateorconnector.Portsalsoindicatewhereatransitionpassesthrougharegion.Whenyouareeditingastatechart,portsappearautomaticallyasyoucreatetransitions.Youcanplaceportsmanuallyonlywhenyouareviewingastateasasubdiagram.
ShallowHistorySpecifiesthat,whenthestatechartleavesandthenreturnstoaregion,thestatechartentersthehighest-levelsubstatesthatwereactivewhenthestatechartlefttheregion.TousetheShallowHistorypseudostate,placethispseudostateinaregionandthencreateatransitionfromastatetothispseudostate.
DeepHistorySpecifiesthat,whenthestatechartleavesandthenreturnstoaregion,thestatechartentersthelowest-levelsubstatesthatwereactivewhenthestatechartlefttheregion.TousetheDeepHistorypseudostate,placethispseudostateinaregionandthencreateatransitionfromastatetothispseudostate.
7.3 UsingaCallerVItoExecuteaStatechartThecallerVIistheVIyoucreatethatcontainsa“RunStatechart”function.Thisfunctioncreatesandexecutesaninstanceofastatechart.Executingastatechartmeanssendinginputdatatoastatechart.YoualsocanusethecallerVItosendtriggerstoastatechart.
ThecallerVIhasadifferentstructuredependingonwhetherthestatechartisasynchronousorsynchronous.Thefollowingsectionsprovideinformationaboutthesedifferences.
Executingasynchronousstatechartsinvolvesthefollowingtwoprocesses:
• Executingthestatechartbyusingthe“RunStatechart”function. • Sendingtriggerstotheexternalqueuebyusingthe“SendExternalTrigger”function.
Inthissituation,theVIthatcontainsthe“RunStatechart”functionisthecallerVI.YoucansendtriggerstotheexternalqueuefromanotherVIoraparallelloopinthecallerVI.ThefollowingfigureshowsacallerVIthatbothexecutesanasynchronousstatechartandsendstriggerstotheexternalqueue.
26 IntroductiontoLabVIEWStatechartModule
Tutorial: Introduction to State-based Applications in LabVIEW
Inthefigureabove,theStatechartLoop,whichisaWhileLoop,executesthestatechart.TheInputscontrolcontainsanyinputdataofthetypesthatyoudefined.TheOutputsindicatorreturnsoutputdatafromthestatechart.TheInstanceNameconstantspecifiesStatechart1asthenameofthestatechartinstance.
TheTriggerLoop,whichcanexecuteinparallelwiththeStatechartLoop,containsanEventstructure.ThisEventstructurehandleseventsthatoccurwithintheVI.Inthiscase,aneventoccurswhenyouclicktheButtonfrontpanelcontrol.Whenyouclickthiscontrol,theEventstructuredetectsthiseventandtheSendExternalTriggerfunctionsendstheTrigger1triggertotheStatechart1statechartinstance.
Note!ThisexampleusesthecallerVItosendtriggerstoanexternalqueue.However,aslongasthecallerVIisrunningandthestatechartisinmemory,youcanuseanyVItosendtriggerstoanexternalqueue.ThisbehaviormeansthatyoucanplacetheTriggerLoopandStatechartLoopinseparateVIs.
StatechartEditor:
OpentheStatechartDiagram(intheStatechartEditor)asfollows:
Right-clickonthe“RunStatechart”VIandselectView→StatechartDiagram.
27 IntroductiontoLabVIEWStatechartModule
Tutorial: Introduction to State-based Applications in LabVIEW
ProjectExplorer:
OpentheProjectExplorerasfollows:
Right-clickonthe“RunStatechart”VIandselectView→Statechart.
28
8 Tutorial:CreateaStatechart
InthisTutorialyouwilllearnhowtocreateastatechartfromscratch.Inthisexamplewewillcreatethefollowingapplication:
Whenyoupushthedifferentbuttons,thecurrentstatewillbedisplayedinthe“CurrentActivity”indicator
ThisTutorialgoesthroughthefollowingsteps:
• Step1:CreatingandConfiguringtheStatechart• Step2:DefiningStates• Step3:CreatingaTransition• Step4:CreatingaTriggerandConfiguringaTransition• Step5:CreatingandConfiguringtheTerminalTransitions• Step6:CreatingandConfiguringtheInitialpseudostateandTransition• Step7:DefiningtheTypeofOutputData• Step8:DefiningtheTypeofStateData• Step9:ConfiguringaStateEntryAction• Step10:ConfiguringtheActionofaTransition• Step11:DuplicatingtheTransitionNode• Step12:GeneratingCodefortheStatechart
29 Tutorial:CreateaStatechart
Tutorial: Introduction to State-based Applications in LabVIEW
• Step13:CreatingtheCallerVI• Step14:Debugging
Let’sstarttheTutorial:
Step1:CreatingandConfiguringtheStatechart
Completethefollowingstepstocreateandconfigurethestatechart.
1. LaunchLabVIEWanddisplaytheGettingStartedwindow. 2. SelectFile»NewtolaunchtheNewdialogbox. 3. SelectOtherFiles»StatechartfromtheCreateNewtree.
4. ClicktheOKbutton.LabVIEWpromptsyoutosavethestatechart. 5. Enterthename“Tutorial”asthenameofyourstatechart(Note!Ithastheending
.lvsc)andsavethestatechartinaconvenientlocationondisk. 6. LabVIEWdisplaysaProjectExplorerwindowthatcontainsthenecessarysupport
files.Thisprojectitemrepresentsthe“Tutorial.lvsc”fileinwhichLabVIEWstoresstatechartinformation.
7. Right-clickthe“Tutorial.lvsc”itemandselectProperties.LabVIEWlaunchesthePropertiesdialogbox.
30 Tutorial:CreateaStatechart
Tutorial: Introduction to State-based Applications in LabVIEW
8. Selectthe“StatechartCodeGeneration”itemfromtheCategorylist.LabVIEWdisplaysoptionsrelatingtostatechartcodegeneration.
9. SelectAsynchronousfromtheUsagepull-downmenu.Thisactionspecifiesthatthestatechartisasynchronous.
10. ClicktheOKbuttontosavechangesandreturntotheProjectExplorerwindow.
Step2:DefiningStates
Thenextstepiscreatingthestatesthatcomprisethestatechart.Astateisauniqueconditioninwhichthestatechartcanbe.
Thisstatechartconsistsofthreestates:Menu,Play,andPause.Completethefollowingstepstocreatethesestates.
1. IntheProjectExplorerwindow,double-clicktheDiagram.viitemtolaunchtheStatechartEditorwindow.Thiswindowdisplaysthestatechartdiagram.Youbuildastatechartbyplacingstatechartobjectsonthestatechartdiagram.
2. IfyoudonotseetheFunctionspalette,selectView»FunctionsPalettetodisplaythispalette.
31 Tutorial:CreateaStatechart
Tutorial: Introduction to State-based Applications in LabVIEW
3. Onthispalette,selectStatechart»StatechartDevelopmenttodisplaytheStatechartDevelopmentpalette.
4. ClicktheStateobject. 5. Movethecursoroverthestatechartdiagram.Clicktoplacethetopleftcornerofthe
state,dragthecursordiagonallytoestablishthesizeofthestate,andclickagaintoplacethestateonthestatechartdiagram.
6. NoticethestateislabeledState.Double-clickthislabeltoenabletexteditingandenter“Menu”asthenewlabel.
7. MovethecursorovertheblackborderoftheMenustateuntilthecursorchangestothePositioningtool.
8. Pressthe<Ctrl>keyandclickanddragthecursortotherightoftheMenustate.Thisactioncreatescopyofthestate.
9. Labelthisnewstate“Play”. 10. Createanothernewstatelabeled“Pause”.PlacethisstatetotherightofthePlay
state. 11. ReturntotheStatechartDevelopmentpaletteandplacea“Terminal”pseudostate
belowthePlaystate.
Thediagramshouldlooklikethis:
Step3:CreatingaTransition
Thenextstepisdefiningthewaysinwhichthestatechartcanmovebetweenstates.Todefinethisbehavior,youusetransitionstoconnectonestatetoanothervisually.Completethefollowingstepstocreatetransitionsbetweentwostates.
32 Tutorial:CreateaStatechart
Tutorial: Introduction to State-based Applications in LabVIEW
1. MovethecursorovertherightborderoftheMenustateandchangethecursortotheWiringtool.
2. Clickthestateborder.Asyoumovethecursoracrossthestatechartdiagram,LabVIEWdrawsadottedlinebetweenthestateandtheWiringtool.
3. MovethecursorovertheleftborderofthePlaystate.Agrayboxappearsunderthecursor.
4. Clickthebordertofinishthetransition.LabVIEWcreatesatransitionbetweenthetwostates.
Thestatechartdiagramshouldlooklikethis:
Step4:CreatingaTriggerandConfiguringaTransition
Thenextstepisspecifyingthatthestatecharttakesthetransitiononlyafterreceivingaspecificevent,alsocalledatrigger.Bydefault,transitionsareconfiguredtoreacttotheNULLtrigger.However,thecallerVIthatexecutesthisstatechartdoesnotsendtheNULLtrigger.Therefore,youmustconfigurethistransitiontoreacttoadifferenttrigger.
Eachstatecharthasalistoftriggersfromwhichyoucanchoosewhenconfiguringatransition.Configuringatransitioninvolvescreatingatriggerandthenassociatingthattriggerwiththetransition.Completethefollowingstepstoconfigurethetransition.
1. Double-clickthetransitionnodebetweentheMenuandPlaystates.ThisactionlaunchestheConfigureTransitiondialogbox.Youusethisdialogboxtoconfiguretransitions.ThefirsttabinthisdialogboxistheTriggers/Groupstab.NoticethattheNULLtriggerisselectedbydefaultintheTriggersandGroupslist.Everystatecharthasthistriggerbydefault.
33 Tutorial:CreateaStatechart
Tutorial: Introduction to State-based Applications in LabVIEW
2. Clickthe“EditTriggersandGroups”buttontolaunchtheEditTriggersandGroupsdialogbox.Youusethisdialogboxtocreateandmodifytriggers.
3. ClicktheCreateTriggerbuttontocreateanewtrigger,whichappearsintheTriggersandGroupslist.
4. Enter“Play”asthenewtriggername. 5. ClicktheOKbuttontosavechangesandreturntotheConfigureTransitiondialog
box.NoticethenewtriggerappearsintheTriggerslist. 6. IntheTriggers/Groupslist,placeacheckmarkinthePlaycheckboxtospecifythatthis
triggercausesthestatecharttotakethetransition. 7. RemovethecheckmarkfromtheNULLcheckbox. 8. ClicktheOKbuttontosavechangesandreturntothestatechartdiagram. 9. SavethestatechartbyselectingFile»SaveintheStatechartEditorwindow.Youalso
canpressthe<Ctrl-S>keys.
Noticethebluerectangleonthetransitionnode.Thisrectangleindicatesthatyouhavespecifiedanon-NULLtriggerforthetransition.Ifyoumovethecursoroverthetransitionnode,theContextHelpwindowdisplaysthepropertiesofthetransition,includingthetrigger.IfyoudonotseetheContextHelpwindow,pressthe<Ctrl-H>keystodisplaythiswindow.
Createandconfigurethefollowingtransitionsandtriggers.RememberalsotodeselecttheNULLtriggerforeachtransition.
34 Tutorial:CreateaStatechart
Tutorial: Introduction to State-based Applications in LabVIEW
• Fromthe“Play”statetothe“Menu”state.Configurethistransitiontoreacttothe“Menu”trigger.
• Fromthe“Pause”statetothe“Play”state.Configurethistransitiontoreacttothe“Play”trigger.
• Fromthe“Play”statetothe“Pause”state.Configurethistransitiontoreacttothe“Pause”trigger.
Thestatechartshouldlooklikethis:
Step5:CreatingandConfiguringtheTerminalTransitions
Createatransitionfromthe“Menu”statetothe“Terminal”pseudostate.Configurethistransitiontoreactonlytoanewtrigger,Stop.ThistransitionspecifiesthatifthestatechartisintheMenustateandreceivestheStoptrigger,thestatechartterminates.
Tip!Right-clickthetransitionnodeandselecteitherRotateorReversetoensurethenodefacestheproperdirection.
Then,savethestatechartbypressingthe<Ctrl-S>keys.
Thestatechartdiagramshouldnowlooklikethis:
35 Tutorial:CreateaStatechart
Tutorial: Introduction to State-based Applications in LabVIEW
Step6:CreatingandConfiguringtheInitialpseudostateandTransition
PlaceanInitialpseudostate,locatedontheStatechartDevelopmentpalette,totheleftofthe“Menu”state.
Createatransitionbetweenthispseudostateandthe“Menu”state.NoticetheGenerateCodebuttonnolongerisbroken.
Thestatechartshouldlooklikethis:
Step7:DefiningtheTypeofOutputData
Ifyouwantthestatecharttomodifydata,youfirstmustdefinethetypeofdata.Thisprocessinvolvescreatingthecontrolsand/orindicatorsthatrepresentthestatechartdata.
Completethefollowingstepstodefinethestatechartoutputdata.Laterinthispartofthetutorial,youconfigurethestatecharttomodifythisdata.
1. Double-clicktheOutputs.ctlitemintheprojectExplorer.LabVIEWdisplaystheControlEditorwindowforthistypedefinition.
2. NoticethenumericcontrolNumericinsidetheOutputscluster.Right-clickthiscontrolandselectChangetoIndicatortochangethiscontroltoanumericindicator.
3. Right-clicktheNumericindicatorandselectReplace»StringIndicator.Thisactionreplacesthenumericindicatorwithastringindicator.
4. Double-clicktheStringlabelandenterCurrentActivityasthenewlabel. 5. Pressthe<Ctrl-S>keystosavethistypedefinition. 6. ClosetheControlEditorwindowtoreturntotheProjectExplorerwindow.
36 Tutorial:CreateaStatechart
Tutorial: Introduction to State-based Applications in LabVIEW
Step8:DefiningtheTypeofStateData
Statedataisdifferentfromoutputdata.Statedataisaccessiblefromonlythestatechart,whereasoutputdataalsoisaccessiblefromaVIthatcallsthestatechart.UsestatedatatodefinedatatypesthatotherVIsdonotneedtoaccess.
Completethefollowingstepstodefinethestatechartstatedata.
1. IntheProjectExplorerwindow,double-clicktheStateData.ctlitem. 2. Right-clicktheDatacontrolandselectChangetoIndicator.Thisactionreplacesthe
numericcontrolwithanumericindicator. 3. Double-clicktheDatalabelandenterCounterasthenewlabel. 4. Pressthe<Ctrl-S>keystosavethistypedefinition. 5. ClosetheControlEditorwindowtoreturntotheProjectExplorerwindow.
Step9:ConfiguringaStateEntryAction
ThenextstepisconfiguringeachstatetomodifytheCurrentActivityindicatorthatyoudefinedearlier.Youaccomplishthistaskbydefininganentryactionforastate.AnentryactionisLabVIEWblockdiagramcodethatthestatechartexecutesimmediatelyafterenteringastate.
37 Tutorial:CreateaStatechart
Tutorial: Introduction to State-based Applications in LabVIEW
CompletethefollowingstepstoconfiguretheMenustatetoupdatethisindicator.
1. Double-clicktheDiagram.viitemtodisplaytheStatechartEditorwindow. 2. Double-clicktheborderoftheMenustate.ThisactionlaunchestheConfigureState
dialogbox.Note!Whenyouconfigureastate,awrenchicon appearsonthestate()intheStatechartEditorwindow.Thestatealsochangescolor.
3. NoticetheOutputsclusterelementontherightsideofthisblockdiagram.ClickthisclusterelementandselectOutputs»CurrentActivity.ThiselementnowdisplaysOutputs.CurrentActivity,whichindicatesyoucanwritetothevalueofthetypedefinitionyoudefined.
4. MovethecursorovertheinputofthisclusterelementuntilthecursorchangestotheWiringtool.
5. Right-clicktheinputandselectCreate»Constant.LabVIEWplacesastringconstantontheblockdiagram.
6. EnterMenuasthevalueoftheconstant.
38 Tutorial:CreateaStatechart
Tutorial: Introduction to State-based Applications in LabVIEW
7. Thisentryactioncodemeansthat,immediatelyafterenteringtheMenustate,thestatechartchangestheCurrentActivityindicatortoreadMenu.Laterinthistutorial,youwilldisplaythevalueofthisindicatorintheVIthatcallsthestatechart.
8. ClicktheOKbuttontosavechangesandreturntothestatechartdiagram. 9. Thenextstepisdefiningthe“Play”and“Pause”statestoupdatetheCurrentActivity
indicatorappropriately.ConfiguretheEntryActionforeachstatetoupdatethisindicatorto“Playing”or“Paused”,respectively.
10. Savethestatechart.
Step10:ConfiguringtheActionofaTransition
Thetransitionfromthe“Menu”statetothe“Terminal”pseudostatealsocausesachangeintheactivityofthestatechart.Completethefollowingstepstoconfigurethistransition.
Double-clickthetransitionnodeinbetweenthe“Menu”stateand“Terminal”pseudostate.ThisactionlaunchestheConfigureTransitiondialogbox.
ClicktheActiontab.
Writetheblockdiagramcodethatchangesthevalueofthe“CurrentActivity”indicatorto“Stopped”.
ClicktheOKbuttontosavechangesandreturntothestatechartdiagram.
Note!Thetransitionnodeyoujustconfigurednowdisplaystwobluerectangles.Thesecondbluerectangleindicatesthetransitionhasaspecifiedaction.
Step11:DuplicatingtheTransitionNode
ThenextstepiscreatingtransitionsfromthePlayandPausestatestotheTerminalpseudostate.Insteadofconfiguringadditionaltransitionnodes,youcanduplicatethetransitionnodeyouconfiguredalready.Completethefollowingstepstoduplicatethistransitionnode.
1. Pressthe<Ctrl>keyandclickanddragthetransitionnodeyoujustconfigured. 2. MovethisnodeunderthePlaystate. 3. ClickthebottomborderofthePlaystatetoinitiateatransitionsegment. 4. MovethecursorovertheincomingtunnelofthetransitionnodeuntilLabVIEW
displaysatipstripthatreadsSegmentIn. 5. Clickagaintocompletethetransitionsegment. 6. CreateatransitionsegmentfromtheothersideofthisnodetotheTerminal
pseudostate. 7. Right-clickthetransitionnodeandselecteitherRotateorReversetoensurethenode
facestheproperdirection.
39 Tutorial:CreateaStatechart
Tutorial: Introduction to State-based Applications in LabVIEW
Repeatsteps1–7tocreateanadditionaltransitionnodefromthePausestatetotheTerminalpseudostate.AllthreestatesnowhaveatransitiontotheTerminalpseudostate.
Savethestatechart.
Step12:GeneratingCodefortheStatechart
Thenextstepisgeneratingcodeforthestatechart.ThiscodeiscontainedinasingleRunStatechartfunctionthatyouplaceontheblockdiagramofthecallerVI.Completethefollowingstepstogeneratecodeforthisstatechart.
1. DisplaytheStatechartEditorwindow.
2. Clickthe“GenerateCode”button ,whichislocatedonthetoolbarofthiswindow.
3. ClosetheStatechartEditorwindow.
Note!Youalsocangeneratecodebyright-clickingthe.lvscfileintheProjectExplorerwindowandselectingGenerateCodefromtheshortcutmenu.
Step13:CreatingtheCallerVI
ThenextstepistocreatethecallerVItoexecuteandsendtriggerstothestatechart.ThisVIcontainstwofunctions,RunStatechartandSendExternalTrigger,thatyoumustlinktothestatechart.
RunStatechartExecutesaninstanceofthelinkedstatechart.YoutypicallyplacethisfunctioninsidealoopinthecallerVI.
SendExternalTriggerSendsatriggertotheexternalqueueofaninstanceofthelinkedstatechart.YoucanusethisfunctioninthecallerVIorinaVIthatrunsparalleltothecallerVI.
Completethefollowingsteps.
1. SelectFile»NewVIfromtheProjectExplorerwindow2. Create2WhileLoopscalled“StatechartLoop”and“TriggerLoop”3. Addthe“RunStatechart”VIinthe“StatechartLoop”4. Add“SendExternalTrigger”functioninthe“TriggerLoop”
40 Tutorial:CreateaStatechart
Tutorial: Introduction to State-based Applications in LabVIEW
5. Link“RunStatechart”and“SendExternalTrigger”tothestatechart.Right-clickandselect“Linktostatechart…”
6. FinishtheCallerVIsoitlookslikethis:
7. TheFrontPanelshouldlooklikethis:
41 Tutorial:CreateaStatechart
Tutorial: Introduction to State-based Applications in LabVIEW
8. Pressthe<Ctrl-R>keystorunthecallerVI.ClickthefrontpanelbuttonsandnoticehowtheCurrentActivityindicatorschangesaccordingtothestate.
Step14:Debugging
Right-clicktheRunStatechartfunctionandselect“DebugStatechart…”.ThisactiondisplaysthestatechartintheStatechartDebuggingwindow.
Clickthe“HighlightExecution”button ,locatedonthetoolbaroftheStatechartDebuggingwindow,toenablestatechartexecutionhighlighting.
RuntheCallerVIandseehowthedebuggingworks.
42
9 AdvancedTopicsinLabVIEWStatechartModule
InthischapterwewillmentionsomeofthemoreadvancefeaturesintheLabVIEWStatechartModule.
9.1 UsingRegionsandSubstatesWerecallthefollowingobjectsfromtheStatechartDevelopmentpalette:
RegionDefinestheareainwhichyoucanplacestatesandpseudostates.EachregionmustcontainanInitialpseudostateandatleastonesubstate.Thetop-levelstatechartdiagramrepresentsaregion.Youcanplaceregionswithinonlyastate.
PortIndicateswhereatransitionleavesastateorconnector.Portsalsoindicatewhereatransitionpassesthrougharegion.Whenyouareeditingastatechart,portsappearautomaticallyasyoucreatetransitions.Youcanplaceportsmanuallyonlywhenyouareviewingastateasasubdiagram.
9.2 UsingOrthogonalRegionsandStateHistory
WerecallthefollowingobjectsfromtheStatechartDevelopmentpalette:
ShallowHistorySpecifiesthat,whenthestatechartleavesandthenreturnstoaregion,thestatechartentersthehighest-levelsubstatesthatwereactivewhenthestatechartlefttheregion.TousetheShallowHistorypseudostate,placethispseudostateinaregionandthencreateatransitionfromastatetothispseudostate.
DeepHistorySpecifiesthat,whenthestatechartleavesandthenreturnstoaregion,thestatechartentersthelowest-levelsubstatesthatwereactivewhenthestatechartleft
43 AdvancedTopicsinLabVIEWStatechartModule
Tutorial: Introduction to State-based Applications in LabVIEW
theregion.TousetheDeepHistorypseudostate,placethispseudostateinaregionandthencreateatransitionfromastatetothispseudostate.
9.3 SplittingandMergingTransitionSegmentsWerecallthefollowingobjectsfromtheStatechartDevelopmentpalette:
ForkSplitsoneincomingtransitionsegmentintomultipleoutgoingsegments.Youcanplacethisconnectorwithinonlyastate.
JoinMergesmultipleincomingtransitionsegmentsintooneoutgoingsegment.Youcanplacethisconnectorwithinonlyastate.
44
10 WhatsNext?
10.1 MyBlogFormoreinformationaboutLabVIEW,visitmyBlog:http://home.hit.no/~hansha/
10.2 TrainingThisTutorialisapartofaserieswithotherTutorialsIhavemade,suchas:
• IntroductiontoLabVIEW• DataAcquisitioninLabVIEW• ControlandSimulationinLabVIEW• LabVIEWMathScript• LinearAlgebrainLabVIEW• DataloggingandSupervisoryControlinLabVIEW• WirelessDataAcquisitioninLabVIEW• IntermediateTopicsinLabVIEW• AdvancedTopicsinLabVIEW
TheseTutorialsareavailablefordownloadfrommyblog:http://home.hit.no/~hansha
10.3 AdditionalResourceswww.ni.com
10.4 ExamplesIntheNIexampleFinder(Help→FindExamples…)youfindlotsofusefulexamplesthatyoucanplaywithoruseasastartwhencreatingyourownapplications.
45 WhatsNext?
Tutorial: Introduction to State-based Applications in LabVIEW
10.5 DocumentationAspartoftheLabVIEWinstallationthereislotsofusefuldocumentation.
46
QuickReference
47 QuickReference
Tutorial: Introduction to State-based Applications in LabVIEW
Hans-PetterHalvorsen,M.Sc.
E-mail:[email protected]
Blog:http://home.hit.no/~hansha/
UniversityCollegeofSoutheastNorway
www.usn.no