Professional Documents
Culture Documents
ApplicationDesignPatterns:StateMachinesNationalInstruments
ApplicationDesignPatterns:StateMachines
PublishDate:sep08,2011
Overview
TheStateMachineisoneofthefundamentalarchitecturesLabVIEWdevelopersfrequently
usetobuildapplicationsquickly.StateMachinearchitecturecanbeusedtoimplement
complexdecisionmakingalgorithmsrepresentedbystatediagramsorflowcharts.More
precisely,astatemachineimplementsanyalgorithmdescribedbyaMooremachine,which
performsaspecificactionforeachstateinthediagram.
StateMachinesareusedinapplicationswheredistinguishablestatesexist.Eachstatecan
leadtooneormultiplestates,andcanalsoendtheprocessflow.AStateMachinerelieson
userinputorinstatecalculationtodeterminewhichstatetogotonext.Manyapplications
requireaninitializestate,followedbyadefaultstatewheremanydifferentactionscanbe
performed.Theactionsperformedcandependonpreviousandcurrentinputsaswellas
states.Ashutdownstatecanthenbeusedtoperformcleanupactions.
StateMachinesaremostcommonlyusedwhenprogramminguserinterfaces.Whencreating
auserinterface,differentuseractionssendtheuserinterfaceintodifferentprocessing
segments.EachofthesesegmentswillactasstatesintheStateMachine.Thesesegments
caneitherleadtoanothersegmentforfurtherprocessingorwaitforanotheruserevent.In
thisexample,theStateMachineconstantlymonitorstheuserforthenextactiontotake.
Thereisanotherdesignpatternthatcanbeusedtoimplementauserinterface,theQueued
MessageHandler.AQueuedMessageHandlerisamoresophisticatedversionoftheState
Machineandoffersadditionalflexibility,butitalsoaddsadditionalcomplexity.Queued
MessageHandlerswillbecoveredatanothertime.
ProcesstestingisanothercommonapplicationofStateMachines.Inthisexample,each
segmentoftheprocessisrepresentedbyastate.Dependingontheresultofeachstates
test,adifferentstatemaybecalled.Thiscanhappencontinually,performingindepth
analysisoftheprocessbeingtested.
TableofContents
1.WhyUseaStateMachine?
2.BuildaStateMachine
3.ExampleCokeMachine
4.IMPORTANTNOTES
1.WhyUseaStateMachine?
Besidesitspowerfulabilitytoimplementdecisionmakingalgorithms,statemachinesare
alsofunctionalformsofapplicationplanning.Asthecomplexityofapplicationsgrow,sodoes
theneedforadequatedesign.Statediagramsandflowchartsareusefulandsometimes
essentialforthedesignprocess.NotonlyareStateMachinesadvantageousinapplication
planning,theyarealsoeasytocreate.CreatinganeffectiveStateMachinerequiresthe
designertomakeatableofpossiblestates.Withthistablethedesignercanplanhoweach
stateisrelatedtoanother.ThedesignprocessinvolvedincreatinganoperativeState
Machinewillalsoimprovetheoveralldesignoftheapplication.
2.BuildaStateMachine
Wewanttogenerateanapplicationthatfiresacannoncontinuouslywithoutallowingittoget
dangerouslyhot.Tobegin,wewillrepresentthislogicwithastatediagram(Fig.1).Notice
thatinthisdiagram,thestates(ovalnodes)describetheactionsthatareperformedwhen
thecontrolprocessisinthatstate,whereasthetransitions(arrows)simplydescribewhen
andhowtheprocesscanmovefromonestatetoanother.
Estesitioutilizacookiesparaofrecerleunamejorexperienciadebsqueda.Conozcanuestrapolticadeprivacidad.
(http://www.ni.com/legal/privacy/unitedstates/us/)
OK
http://www.ni.com/whitepaper/3024/en/
1/5
3/7/2016
ApplicationDesignPatterns:StateMachinesNationalInstruments
Figure1:StateDiagram
EachstateinaStateMachinedoessomethinguniqueandcallsotherstates.State
communicationdependsonsomeconditionorsequence.Totranslatethestatediagraminto
aLabVIEWdiagram,youneedthefollowinginfrastructure:
Whileloopcontinuallyexecutesthevariousstates
Casestructureeachcasecontainscodetobeexecutedforeachstate
Shiftregistercontainsstatetransitioninformation
Transitioncodedeterminesthenextstateinthesequence(seebelowforexamples)
Theflowofthestatediagram(Fig.1)isimplementedbytheloop,whiletheindividualstates
arereplacedbycasesinthecasestructure.Ashiftregisteronthewhileloopkeepstrackof
thecurrentstate,whichisfedintothecasestructureinput.
Figure2:StateMachine
Therearedifferentmethodstodeterminewhichstatetotransitiontonext.Fourcommon
methodsarediscussedbelow(Noteinthefollowingmethodexamples,Initcould
transitiontoanystate):
Estesitioutilizacookiesparaofrecerleunamejorexperienciadebsqueda.Conozcanuestrapolticadeprivacidad.
(http://www.ni.com/legal/privacy/unitedstates/us/)
OK
http://www.ni.com/whitepaper/3024/en/
2/5
3/7/2016
ApplicationDesignPatterns:StateMachinesNationalInstruments
Figure3a
Figure3ademonstratesanInitstatethathasonlyonepossibletransition.
Figure3b
Figure3bdemonstratesanInitstatewithtwopossibletransitions,ShutDownorPower
Up.
Figure3c
Figure3cdemonstratesanInitstateusingabooleanarrayalongwithanarrayofenum
constants.ThereisabooleaninthebooleanarraycorrespondingtoeachtransitionInitcan
make.Thearrayofenumconstantsrepresentseachtransitionname.Theindexofthefirst
Truebooleaninthebooleanarraycorrespondstotheindexofthenewstateinthearrayof
enums.
Figure3d
Figure3ddemonstratesanInitstateusinganinnerloopandcasestructuretotransitionto
thenextstate.Theinnercasestructurecontainsonediagramforeachtransitionthatleaves
thecurrentstate.Eachofthecasesintheinnercasestructurehastwooutputsaboolean
value,whichspecifieswhetherornotthetransitionshouldbetaken,andanenumerated
constant,whichspecifiesthestatetowhichthetransitiongoes.Byusingtheloopindexas
aninputtothecasestructure,thiscodeeffectivelyrunsthrougheachtransitioncaseoneby
one,untilitfindsadiagramwithaTruebooleanoutput.AftertheTruebooleanoutputis
found,thecaseoutputsthenewstatetowhichthetransitiongoes.Thoughthismethodmay
Estesitioutilizacookiesparaofrecerleunamejorexperienciadebsqueda.Conozcanuestrapolticadeprivacidad.
appearslightlymorecomplicatedthanthepreviousmethods,itdoesoffertheabilitytoadd
(http://www.ni.com/legal/privacy/unitedstates/us/)
namestotransitionsbycastingtheoutputoftheloopindextoanenumeratedtype.This
benefitallowsyoutoaddautomaticdocumentationtoyourtransitioncode.
3.ExampleCokeMachine
http://www.ni.com/whitepaper/3024/en/
OK
3/5
3/7/2016
ApplicationDesignPatterns:StateMachinesNationalInstruments
Thisapplicationhasthefollowingrequirements:
AllCokeproductsaresoldfor50cents.
Themachineonlyacceptsnickels,dimes,andquarters.
Exactchangeisnotneeded.
Changecanbereturnedatanytimeduringtheprocessofenteringcoins.
Ourfirststepwillbetocreateastatediagram.Therearequiteafewwaysthiscanbedone,
butrememberthatmorestatesequalslessefficiency.Forthisexample,ourstatediagram
willhaveeightstates.Thestateswewillbeusingare:
1.)INITinitializeourCokeMachine
2.)WAITFOREVENTwherethemachinewaitsforcoins
3.)RETURNCHANGEwherethemachinereturnschange
4.)COKEPRODUCTwhenthemachinehasreceived50ormorecentsitwilldispensethe
beverage
5.)QUARTERwhenthecustomerentersaquarter
6.)DIMEwhenthecustomerentersadime
7.)NICKLEwhenthecustomerentersanickel
8.)EXITafterthechangeisreturnedand/orbeveragedispensed,themachinewillpower
down(applicationwillterminate)
Figure4
Withthestatediagramcomplete,wearenowreadytobeginourLabVIEWStateMachine
application.ToviewthefinalStateMachine,pleaseopentheattachedVI.
4.IMPORTANTNOTES
TherearesomecaveatstobeawareofwhencreatingaStateMachine,i.e.code
redundancyanduseofEnum.
Coderedundancy
Problem:ThehardestpartofcreatingaStateMachineistodifferentiatebetweenpossible
statesinthestatediagram.Forexample,intheCokeMachinestatediagram(Fig.4),we
couldhavehad0,5,10,15,20,25,30,35,40,45,50centstatesratherthanhavingawait
forresponsestatethatgoesfromonestatetoanotherdependingonwhichtypeofcoinis
dropped.Thatwouldcreate11differentstateswiththeexactsamecasediagram.
Estesitioutilizacookiesparaofrecerleunamejorexperienciadebsqueda.Conozcanuestrapolticadeprivacidad.
Redundantcodecancreateabigprobleminalargerapplication.
(http://www.ni.com/legal/privacy/unitedstates/us/)
Solution:Ifdifferentstateshavethesamecasediagram,trytocombinethemintoonestate.
Forexample,thewaitforresponsestateiscreatedinordertoavoidcoderedundancy.
Enumuse
http://www.ni.com/whitepaper/3024/en/
OK
4/5
3/7/2016
ApplicationDesignPatterns:StateMachinesNationalInstruments
Problem:EnumsarewidelyusedascaseselectorsinStateMachines.Iftheuserattempts
toaddordeleteastatefromthisenum,theremainingconnectedwirestothecopiesofthis
enumwillbreak.ThisisoneofthemostcommonobstacleswhenimplementingState
Machineswithenums.
Solution:Twopossiblesolutionstothisproblemare:
1.Ifalltheenumsarecopiedfromthechangedenum,thebreakswilldisappear.
2.Createanewcontrolwiththeenum,andselecttypedeffromthesubmenu.Byselecting
typedef,alloftheenumcopieswillbeautomaticallyupdatedifuseraddsorremovesastate.
PRODUCTOS
SOPORTE
Estadodelpedidoehistorial
(http://www.ni.com/status/)
Enviarunasolicituddeservicio
SobresucursaldeNationalInstruments
(https://sine.ni.com/srm/app/myServiceRequests) (http://www.ni.com/company/esa/)
Comprarpornmerodeparte
(http://sine.ni.com/apps/utf8/nios.store?
action=purchase_form)
Manuales(http://www.ni.com/manuals/esa/)
Controladores
(http://www.ni.com/downloads/drivers/esa/)
Activarunproducto
(http://sine.ni.com/myproducts/app/main.xhtml? AlliancePartners
lang=en)
(http://www.ni.com/alliance/esa/)
COMPAA
AVANZANDO JUNTOS
NIpreparaaingenierosycientficosparaque
resuelvanlosdesafosdeunmundocada
vezmscomplejo.
SobresucursaldeNationalInstrumentsLatin
America(http://latam.ni.com/compania)
(http://www.facebook.com/NILatam)
Eventos(http://www.ni.com/events/)
(http://twitter.com/nilatinoamerica)
Carreras(http://www.ni.com/careers/)
(http://nifeeds.ni.com/f/newses)
Informacindecompraypago
(http://www.ni.com/howtobuy/esa/)
(http://www.youtube.com/nilatinoamerica)
ComunqueseconNI
deSitio(http://www.ni.com/help/map.htm)
(http://www.ni.com/contactus/)
Estesitioutilizacookiesparaofrecerleunamejorexperienciadebsqueda.Conozcanuestrapolticadeprivacidad.
(http://www.ni.com/legal/privacy/unitedstates/us/)
OK
http://www.ni.com/whitepaper/3024/en/
5/5