Anda di halaman 1dari 47

CLADStudyGuide

PreparedbyLabVIEWStudentAmbassadors:
JulianFerrerRios
KristenHeck
FrancescaRamadori
KelvinTang

TableofContents
Section 1: LabVIEW Programming Concepts...........................................................................................2
Section 2: LabVIEW Environment............................................................................................................6
Section 3: Software Constructs in LabVIEW............................................................................................9
Section 4: Programming Vis and functions..............................................................................................16
Section 5: Data Communication and Synchronization VIs and Functions..............................................18
Section 6: VI Server and Functions.........................................................................................................21
Section 7: Errors handling VIs and Functions........................................................................................26
Section 8: VI Design Patterns..................................................................................................................29
Section 9: SubVI Design..........................................................................................................................37
Section 10: Debugging VIs.....................................................................................................................39
Section 11: VI Design and Documentation..............................................................................................43
Section 12: Memory, Performance, and Determinism.............................................................................45

-1-

Section1:LabVIEWProgrammingConcepts
DataFlow
LabVIEWfollowsadataflowmodelforrunningVis.
Ablockdiagramnodeexecuteswhenallitsinputsareavailable.Whenanodecompletesexecution,itsupplies
datatoitsoutputterminalsandpassestheoutputdatatothenextnodeinthedataflowpath.
VisualBasic,C++,JAVA,andmostothertextbasedprogramminglanguagesfollowacontrolflowmodelof
programexecution.Incontrolflow,thesequentialorderofprogramelementsdeterminestheexecutionorderofa
program.

Considertheblockdiagramabove.Itaddstwonumbersandthenmultipliesby2fromtheresultoftheaddition.In
thiscase,theblockdiagramexecutesfromlefttoright,notbecausetheobjectsareplacedinthatorderbut
becauseoneoftheinputsoftheMultiplyfunctionisnotvaliduntiltheAddfunctionhasfinishedexecutingand
passedthedatatotheMultiplyfunction.Rememberthatanodeexecutesonlywhendataareavailableatallofits
inputterminals,anditsuppliesdatatoitsoutputterminalsonlywhenitfinishesexecution.Inthesecondpieceof
code,theSimulateSignalExpressVIreceivesinputfromthecontrolsandpassesitsresulttothegraph.
Youmayconsidertheaddmultiplyandthesimulatesignalcodetocoexistonthesameblockdiagraminparallel.
Thismeansthattheybeginexecutingatthesametimeandrunindependentlyofoneanother.Ifthecomputer
runningthiscodehadmultipleprocessors,thesetwopiecesofcodecouldrunindependentlyofoneanother(each
onitsownprocessor)withoutanyadditionalcoding.
-2-

Polymorphism

Aprogramminglanguagefeaturethatallowsvaluesofdifferentdatatypestobehandledusingauniforminterface.
InLabVIEW:theabilityofVIsandfunctionstoautomaticallyadapttoacceptinputdataofdifferentdatatypes(i.e.
NumericFunctions);Usefulwhenperformingthesameoperationondifferentdatatypes
Section1PracticeQuestions
1.
YoudevelopaSubVIthatonlyoutputsavalueandneedtousethisSubVIina(calling)VI.Whichofthe
followingisthebestwaytoenforcedataflowtocontroltheexecutionoftheSubVI?
a.UsetheSubVIinaSequencestructure
b.ModifytheSubVItohavedummyinputsthatcanbeusedfromthecallingVI
c.ModifytheSubVItohaveErrorclustersthatcanbeusedfromthecallingVI
d.ModifytheSubVItohaveaglobalvariableanduseitfromthecallingVI
2.

Whichofthefollowingdoesnotconformtodataflowprogrammingparadigm?

a.ShiftRegisters
b.Tunnels
c.SubVIs
d.LocalVariables

-3-

3.

Inthefigurebelow,whatwillResultequalwhenthiscalculationisexecuted?

a.55
b.70
c.65
d.Indeterminate
4.

WhatisthevalueinXORResultafterthefollowingcodehasexecuted?

a.0
b.1
c.True
d.False
5.

WhatdeterminestheprogramorderofexecutionofcodeinLabVIEW?

a.Thetimewhenyouenteredthecode
b.Itgoesfromlefttoright.
c.Thedataflow

-4-

6.

InthefollowingVI,whatwillbetheexecutionorderoffunctions?

a.
b.
c.
d.
Section1Answers
1.C
2.D
3.B
4.B
5.C
6.C

-5-

Section2:LabVIEWEnvironment
LabVIEWprogramsarecalledvirtualinstruments(Vis).
Controlsareinputsandindicatorsareoutputs.
EachVIcontainsthreemainparts:
FrontpanelHowtheuserinteractswiththeVI

BlockdiagramThecodethatcontrolstheprogram

Icon/connectorThemeansofconnectingaVItootherVis

-6-

InLabVIEW,youbuildauserinterfacebyusingasetoftoolsandobjects.Theuserinterfaceisknownasthe
frontpanel.Youthenaddcodeusinggraphicalrepresentationsoffunctionstocontrolthefrontpanelobjects.The
blockdiagramcontainsthiscode.Insomeways,theblockdiagramresemblesaflowchart.
Youinteractwiththefrontpanelwhentheprogramisrunning.Youcancontroltheprogram,changeinputs,and
seedataupdatedinrealtime.Controlsareusedforinputssuchasadjustingaslidecontroltosetanalarmvalue,
turningaswitchonoroff,orstoppingaprogram.Indicatorsareusedasoutputs.Thermometers,lights,andother
indicatorsdisplayoutputvaluesfromtheprogram.Thesemayincludedata,programstates,andotherinformation.
Everyfrontpanelcontrolorindicatorhasacorrespondingterminalontheblockdiagram.WhenyourunaVI,
valuesfromcontrolsflowthroughtheblockdiagram,wheretheyareusedinthefunctionsonthediagram,andthe
resultsarepassedintootherfunctionsorindicatorsthroughwires.
ControlsPalette
UsetheControlspalettetoplacecontrolsandindicatorsonthefrontpanel.TheControlspaletteisavailableonly
onthefrontpanel.Toviewthepalette,selectViewControlsPalette.YoualsocandisplaytheControlspalette
byrightclickinganopenareaonthefrontpanel.TackdowntheControlspalettebyclickingthepushpinonthe
topleftcornerofthepalette.
FunctionsPalette
UsetheFunctionspalettetobuildtheblockdiagram.TheFunctionspaletteisavailableonlyontheblock
diagram.Toviewthepalette,selectViewFunctionsPalette.YoualsocandisplaytheFunctionspaletteby
rightclickinganopenareaontheblockdiagram.TackdowntheFunctionspalettebyclickingthepushpinonthe
topleftcornerofthepalette.
ToolsPalette

AutomaticSelectionTool

-7-

YoucanviewtheToolsPaletteonboththefrontpanelandblockdiagram.Toviewthepalette,selectViewTools
Palette.YoualsocandisplaytheToolspalettebyholdingshift+rightclickinganopenareaonthefrontpanelor
blockdiagram.
Ifyouenabletheautomaticselectiontoolandyoumovethecursoroverobjectsonthefrontpanelorblock
diagram,LabVIEWautomaticallyselectsthecorrespondingtoolfromtheToolspalette.Toggleautomatic
selectiontoolbyclickingtheAutomaticSelectionToolbuttonintheToolspalette.
UsetheOperatingTooltochangethevaluesofacontrolorselectthetextwithinacontrol.
UsethePositioningTooltoselect,move,orresizeobjects.ThePositioningToolchangesshapewhenitmoves
overacornerofaresizableobject.
UsetheLabelingTooltoedittextandcreatefreelabels.TheLabelingToolchangestoacursorwhenyoucreate
freelabels.
UsetheWiringTooltowireobjectstogetherontheblockdiagram.
Section2PracticeQuestions
1.

Whichofthefollowingisthebestmethodtoupdateanindicatoronthefrontpanel?

a.UseaValuepropertynode
b.Wiredirectlytotheindicatorterminal
c.Usealocalvariable
d.Useafunctionalglobalvariable
Section2Answers
1.B

-8-

Section3:SoftwareConstructsinLabVIEW
1. Frontpanelwindowandblockdiagramobjects
a. Controls,indicators,IOcontrolsandrefnums
i. Controlfrontpanelobjectforsimulatinginput,displaysvaluesthatwillbepassedTO
functionsonblockdiagram
1. Knobs,pushbuttons,etc.
2. Usuallyhasawhitebackground
ii. Indicatorfrontpanelobjectforoutput,displaysvaluespassedFROMfunctionson
blockdiagram
1. Graphs,LEDs,etc.
2. Usuallyhasagraybackground
iii.
I/OControls
iv.
Refnums
b. Terminals,constants,nodes
i. Terminalsrepresentationoffrontpanel(FP)objects(controlsandindicators)onthe
blockdiagram(BD);entryandexitpointsfordataexchangebetweenFPandBD
1. Rememberpositionofterminaldoesntmatterlabelanddatatypedefineswhat
FPobjecttheterminalisconnectedto
ii. ConstantsonlyonBD
iii.
Nodes
1. Function
a. Paleyellowbackground
b. FundamentaloperatingelementsofLV
-9-

c.
2. subVI
a.
b.
c.
d.

Doubleclickingselectsitem

VIwithinaVI
AnyVIhaspotentialtobeasubVI
DoubleclickonsubVItoopenFP
ExpressVIs=specialtype
i. Configurationwindow
3. Structure
a. Examples:whileloop,forloop,casestructure,sequencestructure
c. Palettes,updatemodes,andlegendsofchartsandgraphs
i. Palettes
1. Graphpalette
a. Cursormodefocustocursorsocursormoves
b. zoommodehorzorvertonlyzoom,boxzoom,zoomin/out(shift+click
forzoomout)
c. dragmodeclickanddragplotviewaroundscaleautoupdates
ii. Updatemodes
1. Chartaddspointeachiterationmaintainshistory
a. Stripchartentireplotredrawneachiterationinorderforplottoappear
toscrolltotheleft
b. Scopechartpointsplotteduntilendofxscalereached,thenplotclears,
andplotbeginsatfarleftagain
c. Sweepchartredlinethatindicatesthefrontedgeofnewdatabeing
plottedoverolddata.
2. Graphredrawspoint(s)eachiteration
a. Useachartinsidealooptoseefullsetofdata(dynamicallyupdates)
b. Useagraphoutsidealooptoseefullsetofdata
iii.
Legends
1. Plotlegend
a. Showscolorofeachplotandplotname
2. Scalelegend
a. Showsxandyscaletitles,canlockscales,showfulldatarange,and
edittheformatofthenumbers
3. Cursorlegend
a. Onlyavailableforgraphs
b. Listscursorsandcoordinates
c. Cancreatecursorsfromhere
-10-

d. MechanicalactionofBooleanobjects[reallyhelpfulexampleVI:MechanicalActionof
Booleans.viintheExampleFindersearchmechanical]
i. Switch
1. Whenpressedvaluechangeondownclickofleftmousebutton
2. Whenreleasedvaluechangeonreleaseofleftmousebutton
3. Untilreleasedvaluechanceondownclickandreleaseofleftmousebutton
ii. LatchhastobereadbyLVandreturnstoitsoriginalstate
1. Whenpressedvaluechangeondownclickofleftmousebutton
2. Whenreleasedvaluechangeonreleaseofleftmousebutton
3. Untilreleasedvaluechanceondownclickandreleaseofleftmousebutton
e. Propertynodes
i. Accesspropertiesofanobject(item)
ii. Allowyoutomodifyobjectsappearanceorbehavior(forexample)programmatically
iii.
Operatetoptobottom
iv.
Bydefault,iferroroccurshalfwaydown,remainingpropertymodificationswillnot
executeanderrorwillbeoutput
2. Datatypesanddatastructures[formoredetails(morethancoveredonCLAD)
>http://zone.ni.com/reference/enXX/help/371361B01/lvexcodeconcepts/manager_data_types/]
a. Numeric
i. representnumbers
ii. chooserepresentation=numberofbitsusedtostorethenumber(morebits,more
precisionpossible);ieI32,U8,DBL
iii.
Orange(DBL),Blue(Integer),Gray(FXP)
b. String
i. SequenceofASCIIcharacters
ii. Tables,textentry,labelsareexamplesofstringobjects
iii.
Changedisplayformat:Normal,\Codes,Password,Hex
iv.
Pink
c. Boolean
i. True/False
ii. Green
iii.
Mechanicalaction(seeabove)
d. EnumeratedControl/Constant/Indicator(Enum)
i. Pairsofstringandnumericindefinedlist
ii. Usefulbecauseeasiertomanipulatenumbersthanstringssometimes(statemachines)
e. pathdatatype
i. platform(OS)independent;thefilemanager(lowlevelLV)determineshowthedatatype
-11-

isdefined
f. Arrayandclusterdatatypes
i. Arrays
1. Composedofelements(data)anddimension(size)
2. Allelementsmustbeofsamedatatypedefinedwhencreated(placing
numericalcontrolinanarrayshellcontrolcreatesanumericarraycontrol)
g. Waveform
i. Threepartstoit
1. t0:timezero
2. delta_t:timeincrement
3. Y:value,intensity,voltage,etc.
h. Timestampdatatype
i. timezoneindependentnumberofsecondsthathaveelapsedsince12:00a.m.,Friday,
January1,1904,UniversalTime.Ifyearandmonthareoutofrange,theresultsare
unpredictable.Ifyearisbefore1904,timestampisnegative.
i.

Variantdatatype
i. Allowsyoutohandledatainageneralway
3. Workingwithobjectsanddatatypesonfrontpanelwindows
a. Ranges,formats,representation,andscaling
i. Appropriateuse
1. Example:ifyouaremeasuringtheangleofahalfrotationtherangeshouldbe0
180
b. Customizingcontrols
i. Customcontrol
1. Singleinstanceofuniquecontrolorindicator
ii. Typedefinitions
1. Linkedtofilesochangestofilewillbeseenineachinstanceoftypedeffed
control/indicator
2. Appearanceisnotlinkedtofiledatatype(I32,U8,listofenum,string)
iii.
Stricttypedefinitions
1. Linkedtofilesochangestofilewillbeseenineachinstanceoftypedeffed
control/indicator
2. AppearanceISlinkedsoEVERYTHINGexceptlabel,description,anddefault
valuechanges
4. Programcontrolstructuresanddatastorage
a. Loopingstructures(forloopsandwhileloops)
i. ForLoop
-12-

1. ExecutessetnumberoftimesdefinedbyNterminalorindexedtunnel
2. Possibleexecutezerotimes
3. Tunnelsautomaticallyoutputanarrayofdata
ii. WhileLoop
1. Stopsexecutingbasedonthevalueattheconditionalterminal
2. Mustrunatleastonce(dowhileloop)
3. Tunnelsautomaticallyoutputlastvalue
iii.
Indexingonloopboundaries
1. Input:oneelementinthearraywillbepassedinwitheachloopiteration
2. Output:anelementisaddedtothearraywitheachloopiteration,theentirearray
willbepassedout
iv.
Shiftregisters
1. Pairofterminalsonleftandrightsideofloopforcedtobealigned
2. Valuereadfromoutputofshiftregister(leftside)willbethesamevalueasthe
valuepassedtotheshiftregisterinput(rightside).
3. 1stiterationofloop:
a. ifinitialized(valuepassedintoshiftregisterfromoutsidetheloop),the
initializingvaluewillbethevaluereadfromtheshiftregister.
b. Ifuninitialized,thevalueintheshiftregisterfromthelasttimetheloop
wasexecutedwillbethevaluereadfromtheshiftregister(thisisutilized
infunctionalglobals)ifneverrunbefore,usesdefaultvalue(usually0)
b. Caseandsequencestructures
i. Flatandstackedsequencestructures
1. Canbeusedtoforceexecutionorder,butusuallyanotherway(errorwire)
2. Shouldbeavoidedbecausecannotbestoppedinthemiddle.
3. Stackedmeansthatyouonlyseeoneframeatatimescrollthroughtosee
others
ii. Caseselectorvaluesanddatatypes
1. Caseselectoracceptsvaluestodeterminewhichcasetoexecute
2. Ifvaluecaseselectorreadsdoesnotmatchanyofthecases,defaultcasewill
execute.
3. Enumsusefulbecausedonthavetoworryabouttyposwithstrings,andplain
numericsarehardertokeeptrackof.
4. Errorwirecanbewiredtocaseselectortoprogrammaticallychoosetoexecute
certaincodewhenthereisorisnotanerrorcasestructureturnsredandgreen
toindicateerrorcaseandnoerrorcase.
iii.
Datapassingtunnelsandsequencelocals
1. Tunnelspassvaluesinoroutofstructures
-13-

a. Colorwillmatchdatatype
i. Solidallcaseswired,noindexing,normal
ii. Open(notseenonloops;output/rightsideonly)oneormore
casesisntprovidingavaluetooutput
iii.
Smallwhitesquareinsideusedefaultifunwired
iv.
Whitewithbracketsofdatatypecolor(seenonlyon
loops)autoindexingenabled
2. Sequencelocalonlyforstackedsequencestructures
a. Similartoshiftregisterinthatitpassesdatafromoneinstance(loop,
sequenceframe)toanother
b. Arrowtoindicateifinputorouput
c. Eventstructures
i. Notifyandfilterevents(userinterface)
1. Notify
a. Leftsideofeventstructure
b. eventhappened,getvaluesfromevent
c. GreenarrowinEditEventwindow
2. Filter
a. eventisabouttohappen,abletochangewhathappens
b. rightsideofeventstructure
c. redarrowinEditEventwindowandendswith?
ii. Value(signaling)propertiesofcontrols
1. Thesepropertiescanbecaughtbyaneventstructure
iii.
Dynamiceventsanduserevents
1. Dynamicevents
a. usewhenonlywanteventtoberegisteredduringpartoftheapplications
execution
b. enableyoutohandleeventsinasubVI
c. rightclickoneventstructuretoselectShowDynamicEventTerminals
2. UserEvents
a. Programmaticallycreateaneventthatyoudefine(insteadoftheones
alreadyavailablethroughtheeventstructure)
b. UseGenerateUserEventtohaveeventoccurandbesenttoevent
structuretobehandled
d. Formulanode
i. Allowsyoutousetexttoexecuteafunctionandmathematicalformulas(cos,sin,log,etc)
e. Conditionaldisableanddiagramdisablestructures
-14-

i. ProgrammaticallyenableanddisablecodeusefulifwantingtomakefileI/Ofunction
correctlyinbothdevelopmentandexecutableenvironments
ii. Usefulintroubleshootingcodetonarrowdownproblemspot
f. Timedstructuresloopandsequence
i. Moreusefulinarealtimeoperatingsystem(deterministic)
ii. Eachlooporframewilloperateinthetimeyouspecifywillindicateifdoesntusing
FinishedLate?DataNodeelement
iii.
Cansetpriorityofloop,processortheloopshouldusetoexecute,etc
g. Variableswireisalwayspreferred,raceconditionspossible
i. Local
1. WithinasingleVI
ii. Global
1. VItoVI
2. LookslikeafrontpanelonlyVIthatstoresthevalues
iii.
FunctionalGlobal
1. VItoVI
2. FPandBDuninitializedshiftregisterusedtostoredata
3. Protectsdatafromtwoinstancestryingaccessatsametimeandcausingrace
condition
iv.
Shared
1. VItoVIacrossanetwork
2. DeployedtonetworkforusebymultipleVIsonthenetwork

-15-

Section4:ProgrammingVisandfunctions
1. Numeric,Boolean,string,path,andvariant
a) (seeabove)
2. Conversion,comparison,andmanipulation
a) Functionsspecificallyforconverting:num>string,string>num,path>string,string>path,etc
b) Functionsspecificallyformanipulatingcertaindatatypes:buildpath,strippath,concatenatestring,
bool>numarray,etc
3. Arraysandclusters
a) Bothhaveshells
b) Arrays
1. mustbesamedatatype
2. dimensionanddata
3. indexelementfromarray
c) Clusters
1. Groupingofmanydatatypes(includingarraysandotherclusters)
2. Unbundleandbundleclusterelements
4. Timing
a) Waittimers
1. Wait
1. Willwaituntilthespecifiedtimehaselapsed
2. Wheninaloop,runsinparalleltoothercodeinsideloop(assumingnodependencieson
othercodeinloop)ifcodetakeslongerthanthewaittime,nextloopiterationwillbegin
immediately,otherwisethewaitwillcompleteandthennextloopiterationwillbegin
2. Waituntilnextmillisecondmultiple
-16-

1. Willwaituntilamultipleofthetimespecifiedisreached
2. Wheninaloopandassumingnodependencyonothercodeinloop,itwillruninparallelif20
msiswiredtoit,imaginemarksalongatimelineevery20ms.Ifthecoderuns45ms,the
nextloopiterationcannotbeginuntilthenextmark,whichwouldbeat60ms.
b) tickcount(ms)
1. startsatzero(cannotconvertintorealdate/time)
2. maxvalue=(2^32)1;thereforecanrolloverbacktozeroifallowedtocountpastitsmax>bad
information
c) date/timefunctions
d) Timingfunctionsrelatedtotimedstructures
5. fileI/Oformats
a) ASCII
1. Textfile
2. Goodtousewhenwanttoopenwithanotherprogram(notepad,textedit,word,etc)
b) Binary
1. Takesleastamountofmemory
2. Efficient
3. Cannotbeeasilyreadbyuseroropenedbyanotherprogram
4. Mustknowhowtodecodethefile
c) Datalog
1. Typeofbinaryfile
2. Usedtowriteclustereddatatofile
d) Storage(.tdm)
1. Internalstructurepubliclydocumented(createdbyNI)
2. TypeofbinaryfilewithanindexfileforfasterI/Operformance
3. Abletoapplypropertiestofileatdifferentlevels:file,group,channel
e) Waveform
f) XML(ExtensibleMarkupLanguagestandardized)
1. SetoffunctionsspecificallyforXML
2. Platformindependent
g) Configuration
1. inifile
2. Setoffunctionsspecificallyforconfigfiles
3. Platformindependent
6. WaveformandwaveformfileI/O
a) StorageVIsusedtowritewaveformdatatobinarymeasurementfiles(.tdm)
7. Dynamicanduserevents
-17-

a) (seeabove)

Section5:DataCommunicationandSynchronizationVIsandFunctions
LocalVariables
Localvariablesallowdatatobepassedbetweenparallelloops.Youcanreadorwriteasinglecontrolorindicator
frommorethanonelocationintheprogram.Localvariablesbreakthedataflowparadigmandshouldbeused
sparingly.
Sometimesyoumayneedtoaccessafrontpanelobjectfrommorethanoneplaceontheblockdiagramorto
passdatabetweenstructuresthatyoucannotconnectbyawire.Toaccomplishthesetasks,youwouldusea
localvariable.
LocalvariablesarelocatedontheFunctionspaletteunderProgrammingStructures.
Youusealocalvariablebyfirstselectingtheobjectyouwanttoaccess.Youcaneitherclickonthelocalvariable
withtheOperatingtoolandselecttheobjectyouwanttoaccess,orrightclickonthelocalvariableandchoosethe
objectfromtheSelectItemmenu.
Next,youmustdecidetoeitherreadorwritetotheobject.RightclickonthelocalvariableandchooseChangeto
ReadorChangetoWrite.
GlobalVariables

UseglobalvariablestoaccessandpassdataamongseveralVIs
Differsfromlocalvariablesbecauselocalvariablesareusedtoaccessandpassdatabetweenparallelloops
(withinoneVI).Whenyoucreateaglobalvariable,LabVIEWautomaticallycreatesaspecialglobalVI,whichhas
afrontpanelbutnoblockdiagram.
SharedVariable

-18-

Representsasharedvariableontheblockdiagram.UsesharedvariablestosharedataamongVIsorbetween
locationsontheblockdiagramthatyoucannotconnectwithwires.
DataSocket

UsetheDataSocketVIandfunctionstopassdatabetweenVIsprogrammatically.DataSocketbeusedwith
basicallyanyprotocolthatutilizestheTransmissionControlProtocol(TCP)insomeform.
TouseDataSocketsitisnecessarytosetuptheDataSocketsServer,aprogramthatrunsononeofthemachines
inthenetworkandactsasanintermediary,sothatmultipleclientscanread/writedata.Thedatatransferusesthe
DatasocketTransferProtocol(DSTP).
Protocols

UsetheProtocolsVIsandfunctionstoexchangedatabetweenapplicationsbyusingprotocolssuchasTCP/IP,
UDP,serial,IrDA,Bluetooth,andSMTP.
Notifiers

UsetheNotifierOperationsfunctionstosuspendtheexecutionofablockdiagramuntilyoureceivedatafrom
anothersectionoftheblockdiagramorfromanotherVIrunninginthesameapplicationinstance.
Queues

UsetheQueueOperationsfunctionstocreateaqueueforcommunicatingdatabetweensectionsofablock
diagramorfromanotherVI.
Semaphores

-19-

UsetheSemaphoreVIstolimitthenumberoftasksthatcansimultaneouslyoperateonashared(protected)
resource.Aprotectedresourceorcriticalsectionofcodemightincludewritingtoglobalvariablesor
communicatingwithexternalinstruments.
Section5PracticeQuestions
1.

Whichofthefollowingcannotbeusedtotransferdata?

a.Semaphores
b.Queues
c.Notifiers
d.
Localvariables

2.

Whichofthefollowingillustratesanadvantageofaglobalvariableoveralocalvariable?

a.AglobalvariablecanpassdatabetweentwoindependentVIsrunningsimultaneously
b.Onlytheglobalvariablecanpassarraydata,localvariablescannot
c.Globalvariablesfollowthedataflowmodel,andthereforecannotcauseraceconditions
d.Globalvariablesdonotrequireownedlabelstooperate
Section5Answers
1. A
2. A

-20-

Section6:VIServerandFunctions
InLabVIEWprogramming,aVIServercanbeusetoprogrammaticallycontrolfrontpanelobjects,VIs,
andLabVIEW,andtodynamicallyload,edit,andrunVIsonacomputerorremotelyacrossanetwork.
YoucancontrolbrowseraccesstotheVIsandconfigurewhichVIsremoteapplicationscancontrol.
ConfiguringtheVIServerPage
SelectToolsOptionstodisplaytheOptionsdialogboxandselectVIServerfromtheCategorylistto
displaythispage.IfatargetinaLabVIEWprojectsupportstheVIServer,youalsocanrightclickthe
target,suchasMyComputer,selectPropertiesfromtheshortcutmenu,andselectVIServerfromthe
Categorylisttodisplaythispage.
ToconfigureVIServeroptionsforthe mainapplicationinstance,displaythispagefromthe Options
dialogbox.ToconfigureVIServeroptionsforatarget,displaythispagefromthePropertiesdialogbox
forthetarget.ToconfigureVIServersettingsforaprojectapplicationinstance,rightclickthetargetin
theProjectExplorerwindow.
TheVIServerpageincludesthefollowingcomponents:

ProtocolsUsethissectiontoconfiguretheVIServer.ThedefaultVIServersettingsareActiveX
enabledandTCP/IPdisabled.
o TCP/IPEnablesVIserversupportforTCP/IP.Ifyouallowremoteapplicationstoconnectusing
TCP/IP,youalsoshouldspecifywhich machineaddressescanaccesstheVIServer inthe
MachineAccesssectionofthispage.Thischeckboxdoesnotcontainacheckmarkbydefault.
-21-

PortSets the TCP/IP port at which the VI server listens for requests. From
ToolsOptions thisportnumberis3363,bydefault,whichisaregisteredportnumber
reservedforusebyLabVIEW.Fortargets,thedefaultis0causingtheoperatingsystem
todynamicallyselectaport.Ifyouwanttorunmultiple applicationinstances onthe
machine,eachwithitsownVIServerrunning,youmusthaveauniqueVIServerport
number.Youalsocanusethe Server:Port propertytosettheLabVIEWVIServerport
programmatically.
ServicenameSetstheservicenamefortheVIServerTCPInstance.Toretrievean
applicationreferencewithouttheportnumber,useServicenameinconjunctionwiththe
OpenApplicationReferencefunctionbywiringaServicenametothepolymorphicport
number

or
Service

name
input.

IfyoudisplaythispagefromtheOptionsdialogbox,thisservicenameisMainApplication
Instance/VIServerbydefault.IfyoudisplaythispagefromthePropertiesdialogboxfora
target, the service name is target name/VI Server by default. You can use the
Server:ServiceNamepropertytosettheservicenameprogrammatically.
UsedefaultSets Servicename toitsdefaultvalue.Thischeckboxcontainsa
checkmarkbydefault.Toedit Servicename,removethecheckmarkfromthe
checkbox.
o ActiveX(Windows) Enables VI server support for ActiveX Automation. This checkbox is
available only from the ToolsOptions navigation. This checkbox contains a checkmark by
default.
VIScriptingUsethissectiontoenableVIScripting.
o ShowVIScriptingfunctions,propertiesandmethodsEnablesVIScriptingfunctionsonthe VI
ScriptingpaletteandadditionalVIServerpropertiesandmethods.Allfunctions,properties,and
methodsyouenablethroughVIScriptingdisplayasblue.
DisplayadditionalVIScriptinginformationinContextHelpwindowDisplaysconnector
paneterminalnumbersintheContextHelpwindow.PlaceacheckmarkintheShowVI
Scriptingfunctions,propertiesandmethodscheckboxtoenablethisoption.
AccessibleServerResourcesUsethissectiontoindicatethetasksthatremote
applications can
accomplish.
o VIcallsAllowsremoteapplicationstocallVIsexportedthroughtheVIServer.Ifyouallow
remoteapplicationsaccesstoVIs,specifywhichVIscanbeexported.Thischeckboxcontainsa
checkmarkbydefault.
o VIpropertiesandmethodsAllowsremoteapplicationstoreadandsetthepropertiesofVIsand
tocallmethodsforVIsthroughtheVIServer.IfyouallowremoteapplicationsaccesstoVIs,
specifywhichVIscanbeexported.Thischeckboxcontainsacheckmarkbydefault.
o ApplicationpropertiesandmethodsAllowsremoteapplicationstoreadandsetthepropertiesof
theapplicationinstanceandtocallmethodsfortheapplicationinstancethroughtheVIServer.
Thischeckboxcontainsacheckmarkbydefault.
o ControlpropertiesandmethodsAllowsremoteapplicationstoreadandsetthepropertiesof
-22-

controls and to call methods for controls through the VI Server. This checkbox contains a
checkmarkbydefault.
MachineAccessUsethissectiontocontrolmachineaccesstoVIsthrough theVIServer.
o MachineaccesslistListsmachinesthatdoanddonothaveaccesstotheVIServer.Youalso
can use the Server:TCP/IP Access List property to list programmatically the TCP/IP
addresses of machines that may access the VI server.
Note: If you change the Machine access list, machines that are currently
connectedtotheVIserverwillnotbedisconnectedeveniftheyarenolonger
allowedaccesstotheserver.
o Machinename/addressEnterthenameorIPaddressofthemachineyouwanttoaddtothe
Machineaccesslist.
o AllowaccessAllowsaccesstothemachine(s)selectedinMachineaccesslist.
o DenyaccessDeniesaccesstothemachine(s)selectedinMachineaccesslist.
o AddAddsanewentrytothe Machineaccesslist.Thenewentryappearsbelowtheselected
entryintheMachineaccesslist.
o RemoveRemovestheselectedentryfromtheMachineaccesslist.
ExportedVIsUsethissectiontoadd,edit,andremoveVIsfromtheExportedVIslist.
o ExportedVIslistListstheVIsthatcanbeexported.YoualsocanusetheServer:VIAccessList
propertytolistprogrammaticallytheVIsontheVIServerthatareaccessiblebyremoteclients.
o ExportedVIEnteraVItolistinExportedVIs.YoucanusewildcardsintheVInameordirectory
pathyouenter.
o AllowaccessAllowsaccesstotheVI(s)selectedin ExportedVIs.Thisoptionisselectedby
default.
o DenyaccessDeniesaccesstotheVI(s)selectedinExportedVIs.
o AddAddsanewentrytoExportedVIs.
o RemoveRemovestheselectedentryfromExportedVIs.
UserAccessUsethissectiontocontroluseraccesstoVIsthroughtheVIServer.Youalsocanuse
theDomainAccountManagertomanagedomainusersandgroups.
o UserandgroupaccesslistLists users and groups that can and cannot access the VI
Server. If you do not include users or groups in this list, all users and groups associated
with machines that have access permission can access the VI Server.
Note: If the User and group access list is changed, users that are currently
connected to the server will not be disconnected even if they are no longer
allowedaccesstotheVIServer.
o AllowaccessAllowsaccesstotheusersandgroupsselectedinUserandgroupaccesslist.
o DenyaccessDeniesaccesstotheusersandgroupsselectedinUserandgroupaccesslist.
o AddDisplaysthe AddUsersandGroupsdialogbox,inwhichyoucanselectadomain,user,
andgroup.
o RemoveRemovestheselectedentryfromtheUserandgroupaccesslist.
-23-

-24-

VIServerApplication
CompletethefollowingstepstocreateaVIServerapplication:
1. ConfiguretheVIServertoallowtheTCP/IPprotocol.
2. Use the Open Application Reference function to open a reference to a local or remote
application instance.
Note:Ifyouhavemultipleapplicationinstancesopensimultaneously,suchasifyouare
workingwitha LabVIEWproject ortargetsofaLabVIEWproject,multipleVIServers
can be listening on different ports. Open an application reference to a specific
applicationinstancebystatingthemachinenameandtheportorservicename.
3. UsetheOpenVIReferencefunctiontoopenareferencetoaVIonthelocalorremotecomputer
thatalreadyexistsinmemoryfortheapplicationinstance,ortodynamicallyloadaVIfromdisk.
However,beawarethatiftheinputtovipathisafilepath,thisfunctionwaitsuntiltheuserinterfaceis
idletoloadtheVIfromdisk.
4. UsethePropertyNodetogetorsetpropertiesortheInvokeNodeto

invoke
methods.
5. YoualsocanuseaCallByReferenceNodetocalladynamicallyloaded


VI
.
6. UsetheCloseReferencefunctiontocloseanyopenreferences.

-25-

Section7:ErrorshandlingVIsandFunctions
HaveyoueverwonderwhatisthelowestlineinmostoftheVIs?ThatlineisanspeciallinecalledErrorIn/Out.
ThislineisanspecialclusterTypecalledErrorcluster,whichconsistsof:
1. Boolean:Indicatingifthereisanerror.
2. 32bitInteger:Indicatingthecodeoftheerror.
3. String:Indicatingthesourceoftheerror,i.e.thecauseoftheerror.

Thisclusterhasthesamepropertiesofanyotherclusters,howeverithasotherspecialfeatures.Thefirstofthem
isthatthislineisusuallyusedtoguaranteesequence.FollowingtheLabVIEWrulethatestablishesthatanysubVI
orfunctionneedstohaveallitsinputsinordertorun,iftheoutputerrorlineisconnectedtotheinputofanother
subVI,thesecondsubVIwontrununtilthepreviousends.
Anothercharacteristicoftheerrorclusteristhat,whenconnectedtoacasestructure,itwillcreatetwocases:Error
andNoError,whichcanbeusedtoskipstepsthatcantbeexecutedunlesseverythingelsehasnoerrors.Alsois
usedtoguaranteesequencewhentherearefunctionsorVIsthatdoesnthaveerrorline.

Therearetwodifferentwaysofhandlingerrors,automaticandmanually.
Automatic:WhenLabVIEWisconfiguredtohandletheVIsautomatically(File>VI
Properties>Execution>EnableAutomaticErrorHandling),whenitencountersaunwiredErrorline,itwill
halttheexecutionandhighlightwheretheerroroccurred.
Manual:TohandleerrosmanuallytherearecertainVIsmeanttodoitwhicharepresentatthe
Programming>Dialog&UserInterface:
-26-

SimpleErrorhandlerandGeneralErrorHandler:Displayswhenanerroroccurred,showingthe
causeoftheerrorandoptionallyanerrordialogbox,thedifferencebetweenthesimpleandthe
generalisthatthegeneralalsoacceptscustomerrorcodes.
o Merging,creating,clearingandsearchingerrorVIs:alsotheusermayneedtoclearerrorsifthe
programsolvestheproblembyitself,also,whenbuildingSubVIsitisimportanttoaddthe
previouserrorstotheerrorsthatcanbeaddedfromthesubVI,andafterseveralsubVIsadding
error,isusefultosearchforthefirsterror,sincetheerrorhandlerVIsshowstheerrorwithmost
priority.
o UserinterfaceDialogBoxes:ThisVIsareusedtoinformtheuserwheneveranerroroccurred
andalsotoallowtheusertodecidetheactiontoimplementiftheprogramrequiresit.
o

WhencreatingVIs,wemightproduceerrorsthatLabVIEWdoesntinterpretthemaserrors.Forexample,when
wehaveadivisionby0:

-27-

LabVIEWwillgiveinfiniteasresult,however,forsomeapplicationthatmeansthatanerroroccurred.Forthose
cases,itispossibletocreateyourownerrorcodesandimplementtheminlabVIEW.Todoso,itisnecessaryto
createa*error.txtfile.FortunatelyLabVIEWhasaninterfacemeanttohelpcreatingthisfile:
Tools>Advanced>EditErrorCodes.Itwillaskyouifyouwanttocreateanewfileoreditone,eitherwayyoucan
addorediterrors.

Alltheerrorsaresavedat<NationalInstrumentsLocation>>Shared>Errors.

-28-

Section8:VIDesignPatterns
AgeneralVIdesignpatternconsistsof3mainparts:
1.Startup:Initializehardwareorgettingsignalsordatafromafile.
2.Mainapplication:Analyzetheinputsignalordatacontinuouslyuntilitis
terminatedbyaconditionalterminalorauseraction.
3.Shutdown:Displaysoutputdataorlogintofile.
DesignPatternSelectionFlowChart

-29-

StateMachineDesignPattern
Thestatemachinedesignpatternisusedforalgorithmsthatcanbeexplicitly representedwithastate
diagram.
AstatemachineinLabVIEWconsistoffollowingblockdiagramcomponents:
1.WhileLoop:Executecurrentstatecontinuously.
2.ShiftRegister:Usedtostoreandtransitnextstatetocurrentstate.
3.CaseStructure:Containsprogramcodeforeachstate.
4.StateFunctionalityCode:Programcodeforeachstateincasestructure.
5.TransitionCode:Determinenextstate.

StateMachineDesignPattern
QueuedMessageHandler:
Itisusedtoimplementcodeforauserinterface.Messagesisqueuedandhandledonebyoneinthe
orderofthequeue.Eachsubdiagraminthequeuedmessagehandlerrepresentsahandlingroutine.
Itissimilartoastatemachinedesignbutwiththeshiftregisterholdingontothequeuedmessage.

-30-

ParallelLoop&Master/SlaveDesignPattern

ParallelLoopDesignPattern
Aboveblockdiagramillustratestheparallelloopdesignpattern.Theerror
clusterwiresareusedtoexecute
bothwhileloopsinparallel.However,thisdesignpatternisnotefficientastheremightbearaceconditionwhen
implementingdataaccessingmechanismwheretheremaybemultipleloopsaccessingthedataatthesame
instanceoftime.
Asolutiontothiswouldbeusingthemaster/slavedesignpatternasdepictedin blockdiagrambelow.

Master/SlaveDesignPattern

-31-

Themaster/slavedesignpatternisusedforexecutingtwoormoreprocesses simultaneouslyandpass
dataamongprocesses.Thisdesignpatternmayconsist multiple parallel loops, each running at differentrates.
Therewillbealoopacts
asthemasterwhichcontrolsalltheotherloopsknownastheslaveloops.The
raceconditionisavoidedbyusinganotifiestopassdatafromthemastertothe
slave. Benefits
ofusingnotifiesinmaster/slavedesignpatternisthatallslave loopsaresynchronizedtothemasterloop.Slave
loopexecutesonlywhen
the
masterloopsendsanotification.
Producer/Consumer(Data)DesignPattern

Producer/Consumer(Data)DesignPattern
Thisdesignpatternenhancesthedatasharingamongmultipleloopsrunningatdifferentrates.The
parallel loops are separated into 2 categories: the loop producing data (producer) and the loop
consumingdata(consumer).
Mainbenefits:
Processmultiplesetsofdatainorder.
Queuesdataintheconsumerloop.
Basically,thedataiscontinuouslyqueuedbytheproducerinto theconsumerloopqueueandis
processedbytheconsumerloopatitsownpace.
UserInterfaceEventHandlerDesignPattern
Theeventbaseddesignpatternbenefitsintermsofefficiencyastheyonlyrespondwhenanevent
occurs.
Itconsistsoffollowingblockdiagramcomponents:
-32-

1.EventStructure:Containsprogramcodeforeachdetecteduser
interfaceevent.
2.WhileLoop:Monitoruserinterfaceeventcontinuously.
3.TimeoutTerminal:Controlswhenthetimeouteventexecutes.
4.EventDataNode.

UserInterfaceEventHandlerDesignPattern

-33-

Producer/Consumer(Event)DesignPattern

Producer/Consumer(Event) DesignPattern
Thisdesignpatternissimilartotheproducer/consumer(data)designpattern, however, the consumer
loopexecutesasaneventoccurrenceisdetectedinthe producerloop.
Mainbenefits:
Efficientlyrespondsasynchronouslytotheuserinterface.
Queuescantransferanydatatype.

-34-

FunctionalGlobalVariable
UninitializedshiftregistersinfororwhileloopscanbeusedtoholddataaslongastheVInevergoes
outofmemory.Theshiftregisterholdsthelaststateoftheshiftregister.Thus,aloopwithan
uninitializedshiftregisterisafunctionalglobalvariable.
MainBenefits:
Controlaccesstodatainashiftregister.
Eliminatethepossibilityofaracecondition.

FunctionalGlobalVariable
AboveisaVIexampleofafunctionalglobalvariable,whentheenumeratedinputisSet,theinput
valueisshiftedandstoredintotheshiftregister.Ontheotherhand,whentheenumeratedinputis
Get,itwillretrievedthestoredvaluefromtheshiftregisteranddisplayitattheoutput.

-35-

DesignPatternsTableofComparison
DesignPattern
General
StateMachine

Use
Standardcontrolflow

Pros
Distinctinitialize,run
andstopphases
State sequence Controlssequences
systemcontrol

Queued Message Enhanced state


Handler
machine with storing
of future sequences
toexecute(message)
ParallelLoop
Multiple

task
processinginaVI
Master/Slave

Parallel loops with


synchronization

Producer/Consumer
(Data)
User Interface Event
Handler

Data producing and


processinginparallel
Responds to user
interfaceevent

Producer/Consumer
(Event)

Producer/Consumer
(Data)

which
responds to user
interfaceevent

Stores

sequences
execute

Cons
Unabletoreturntoa
previousstate
Doesnotstorefuture
sequences to
execute
future Does not use
to memoryefficiently

Efficient use of Bad synchronization


computingresources and have race
condition
Passes messages Does not lend itself
and handles loop welltopassingdata
synchronization
Storesdataforlater Does not provide
processing
loopsynchronization
Handles user Does not allow for
interfacemessages
intensive processing
applications
Separates the user Does not integrate
interface from nonuser interface
processorintensive
eventswell
code

-36-

Section9:SubVIDesign
ModularityisthepropertyofscalingaVIinsubmoduleswhichhavespecialfeaturesandcanberecycledinother
VIs.ThesemodulesarecalledsubVIs,and,sinceaSubVIisaVImodifiedintoasmallblockvisualization,double
clickingitwillopenafrontpanelandablockdiagram.
EverySubVIneedsanIconandaConnectorpanetobecalledSubVI:
a. Icon:GraphicalrepresentationofaVI.Customizable(doubleclick)
b. ConnectorPane:MapoftheterminalsofaVI.Inputstotheleft,Outputstotheright(accessing
viarightclick>ShowConnector)
TheiconmustbemodifiedinordertorepresentwhatdoestheSubVIdoes,forthisreasontheIconEditorhasa
builtinpaintwindowtomodifytheimage:

TheconnectorPanerepresentstheInputsandOutputsofaSubVI.Therearemanytypesofconnectorssuitedfor
anyapplication.Itisimportanttonotethat,forconvention,InputsgoesleftandOutputsgoesRight.Tolinkthe
terminalwiththeI/O:
FirstClicktheterminalintheconectorPane
TheclickontheInputorOutput,theterminalwillchangecolorasaconfirmation
FinallychooseiftheconnectorisRequired,RecommendedorOptionalbyRightClickingthe
terminal>ThisConnectionis>

-37-

WhendesigningSubVIs,itisimportanttoconsiderthepreviouserrorsastheerrorsthattheSubVIisadding,one
ofthemostcommonerrorhandlingmethodsinSubVIisthenextone:

ApolymorphicVIisanspecialVIthatacceptsseveralDataTypes,anexamplecouldbethemultiplyfunction,
sinceitcanacceptanydataType.InordertocreateapolymorphicVIisnecessarytocreatealltheVIsthatare
goingtobepartofthepolymorphicVIwiththesameconnectorpaneconfiguration.Afterthatgoto:
File>New>PolymorphicVI.Anewwindowwillprompt,whereyouwillhavetoaddalltheVIs.TheiconofthisVI
willalsoneedtobecreatedbyclickingintotheEditIcon.ThisVIwillautomaticallydecidewhichinstanceofthe
VIsaddedtouse.

-38-

Section10:DebuggingVIs
WhenyourunaVIitmayhappenthatitdoesntevenrunoritdoessomethingyouwerentexpecting.

IftheVIdoesntrun,thefirststepistochecktheBrokenarrowatthetopoftheBlockDiagramortheFrontPanel:

Thenextwindowwillprompt:

-39-

ThemostcommoncausesforaVItobebrokenare:
3. Theblockdiagramcontainsabrokenwire.
4. ArequiredterminalofaSubVIisnotwired
5. ASubVIisbroken.
SooncetheVIisnotbroken,thenextstepistorunit,ifitworksthedebuggingprocessisover!However,itmight
happenthattheVIgivesanunexpectedresultorithaltsatthemiddleoftheexecutionduetoerrors.The
debuggingprocessisthenextone:
1. Checktheerrorsiftheyexist.
2. UsethecontextHelpinSubVItocheckthedefaultvaluesandbesurethatthedefaultvaluecorresponds
towhatyouwant.
3. Eliminateallthewarnings
4. CheckDataTypes,sometimeswhenusingdifferentdatatypes,informationcanbelostduetoDataType
casting.
Ifthatdoesntwork,thenextstepistodebugtheexecutionoftheVIusingthenexttoolsaloneorcombined:
HighlightExecution:AnanimationoftheblockDiagramexecutionwithvaluesattheoutputs.This
methodshowsthemovementofData.

-40-

SingleStepping:ExecutesonlyonestepoftheVI.UsedwiththeHighlightedExecutionprovidesan
incredibledebuggingtool.

ProbingTools:Showsthevalueoverawire.InHighlightingexecutionorSingleStepping.Clickonthe
Wire

Breakpoints:PausetheexecutionwheneverthereisnewDataAtaWire.

-41-

SuspendwhenExecuted:ThisworksasaBreakpoingforSubVIs.OncetheSubVIisexecuteditwill
pausethewholeVI.AndwillopenthefrontpaneloftheSubVI.

-42-

Section11:VIDesignandDocumentation
1. Userinterfaceandblockdiagramlayout
a. UI
i. Onemonitororless
1. Tabstoorganizeandcondenseiftoomanycontrols/indicatorstolimittoone
monitor
ii. Groupcontrolsandindicatorslogically
1. Relateditemsshouldbegroupedtogether
2. Usedecorationstoclarifyoremphasizegroupings
iii.
Fontandcolor
1. Usebrightcolorssparinglyandonlyforthingsthatneedtostandout(i.e.stop
button)
2. Fontshouldbeuniform
3. Boldtextforgroupingtitlesorheading
4. Textsizeshouldbelogical
a. largertextforheadingsorimportantinformation,
b. textshouldbesizedtothecontrolfillbuttons,butnotoverwhelmthe
frontpanel
b. blockdiagram
i. minimizewirecrossingsandbends
ii. dataflowshouldgolefttoright
iii.
terminalsshouldbealigned:inputsontheleft,outputsontheright
2. Modularandhierarchicaldesign
a. UsesubVIswhencodeisrepeated
b. ComplexcodethatachievesasinglefunctioncanbeplacedinasubVI
3. subVIiconsandconnectorpanelayout
a. connectorpanelayout(onlyaccessiblefromfrontpanel)
i. Left=inputs,Right=outputs
ii. Bottomterminalsonsidesareusuallyreservedforerrorwires
iii.
Topterminalsonsideareusuallyreservedforreferencewires
b. Icons
i. PictureshoulddescribewhattheVIdoes
ii. Shouldhavebordernofloatingwireconnectionsconfusesprogrammer
iii.
RelatedsubVIsshouldhavearelatedicons(example:DAQmxhasbarattopthat
saysDAQmx)
4. VIproperties
-43-

a. Documentation
i. Showsupincontexthelp
b. Passwordprotect
i. Ifdistributingcodetoothers,youcanputapasswordontheblockdiagramsotheycant
reuseorrecreateit
c. Windowappearance
i. Basicallyallowsyoutoselectthewindowtypethemaindifferencebetweenthemis
thenumberofmenubarsvisible.
d. Windowsizeusefulifwillberunonamonitorwithdifferentresolutionfromdevelopment
machine
e. RunTimepositionwhenitrunsdoyoualwayswantittoappearinaspecificlocationonthe
monitor?
5. DocumentingVIs
a. Controls/indicators
i. Descriptionandtipstrip
ii. Labels
iii.
Captions
1. UsecaptionsinsteadoflabelstolocalizeaVIwithoutbreakingtheVI.Unlikea
label,acaptiondoesnotaffectthenameoftheobject(whichyoumaybeusing
toaccessthatitemprogrammaticallythroughVIServer),andyoucanusea
captionasamoredescriptiveobjectlabel.Thecaptionappearsonlyinthefront
panelwindow.
b. FPandBD
i. Freelabelstextboxesnotassociated/tiedtoanobject
ii. SelfdocumentingcodeusingclustersandtheUnbundlebyNamesothatthelabelsare
visibleintheunbundle
iii.
Wirelabelsforlongwires(nowavailableinLV2010,otherwiseusefreelabelsto
labelwires)
c. VI
i. DocumentationunderVIProperties
1. ThiswillshowupintheContextHelpWindow
2. RightclickonVIIcon>>VIProperties>>Documentation

-44-

Section12:Memory,Performance,andDeterminism
1. Toolsforidentifyingmemoryandperformanceissues
c. Profilememoryandperformance
i. Tools>>Profile>>ProfilePerformanceandMemory
ii. toolforanalyzinghowyourapplicationusesexecutiontimeandmemory.
iii.
identifythespecificVIsorpartsofVIstooptimize
1. Forexample,ifyounoticethataparticularsubVItakesalongtimetoexecute,
youcanfocusyourattentiononimprovingtheperformanceofthatVI.
iv.
providesaroughestimateoftheaverageexecutiontimeoftheVIsusedinan
application.
1. limitedtomillisecondresolution.
2. Duetothenondeterministicexecution,executiontimeshouldbeaveragedover
severaliterationsforaccuratemeasurements.VITimedisplaysthetotalamount
oftimespendexecutingeachVI.
d. Showbufferallocations
i. Tools>>Profile>>ShowBufferAllocations
1. Showswherebuffersarecreatedontheblockdiagram
2. DoesNOTshowbuffersize,whichisdependentondatatype
3. Fewerbufferallocations(usingwiresinsteadoflocalvariables,whichcreatesa
copy)meansfasterperformance
e. VImetricsVIAnalyzer
i. interactivelyandprogrammaticallytestVIstoidentifyareasforimprovement.
ii. maincategories:

BlockDiagramChecksblockdiagramperformanceandstyleissues,suchas
wiring,loopandstructureusage,coerciondots,andunnecessaryelementsontheblock
diagram.

ComplexityMetricsChecksforVIcomplexity,suchasnesting,codereuse,
andmodularity.
-45-


DocumentationChecksfordocumentationfordevelopersanduserswithina
VI,suchasVIandcontroldescriptionsandblockdiagramcomments.Checksthespelling
onVIs,frontpanels,andblockdiagrams.

FrontPanelChecksfrontpaneldesignanduserinterfaceissues,suchas
controlusage,fontselection,andlabels.

GeneralChecksperformanceandstyleissuesthatdonotfitintotheother
categories,suchasfileproperties,iconsandconnectorpanes,andVIproperties.

VIMetricsChecksblockdiagramandfrontpanelmetrics,suchasthenumber
ofconnectorpaneinputsandoutputs,controlsandindicators,andnodes.
2.

Programmingpractices
a. Enforcingdataflow
i. Helpfultouseanerrorwiretoenforcedataflow
b. UIupdatesandresponsetouserinterfacecontrols
i. NoneedtoupdateUIfasterthan510persecond,becausehumanscantdetecta
changefasterthanthatandmonitorshavealimitedupdateratetoo
ii. WaystoupdateUI
1. Best:wiredirectlytoterminal
2. Better:localvariablemayrequirecopytobemade>slowdown
3. Good:propertynodesmayrequirecopyandtoloadfrontpanelintomemoryif
notalready
iii.
UseEventstructureoverpollingfrontpanelsleepingfunctions(likeevent
structure)aremoreefficient
c. Datatypeselection,coercion,andbufferallocation
i. Fornumbersthatcanonlybeintegers,useI32,U32,I16,U16,I8,U
ii. BitdepththenumberinU8oru16isbasedonhowmanybitsyouneedtorepresentthe
number
1. Forexample,aU8numbercancountfrom0to255,ifyouweretoaddanotherto
aU8whenitisat255itwouldwraparoundto0.
iii.
Avoidcoercioncausestwomemorylocationsforeachversionofthevalueandis
lessefficientonlowlevel
iv.
Tocreatefilesthattaketheleastamountofmemory,usethesmallestnumeric
representationpossibleforyourprecisionneeds.
v. Optimizecodetoallocatefewernumberofbuffers
d. Array,string,andloopoperations
i. BuildingarraysdynamicwillusesignificantlymorememorybecauseLVhastoreallocate
anentirenewmemoryspacewhenanelementisaddeditisbettertoinitializeanarray
tothemaximumsizeandusereplacearraysubset
1. Appendingtoanarrayisbetterthanprependingtoanarraybecauseofbuffer
allocationrequirements
2. AutoindexingisalsobetterbecauseLVcanpredictthebuffersizeaheadoftime
(hastoknowfornumberofloopiterationsanyway)
e. Localandglobalvariables,propertynodes,andreferences
-46-

i. DonotuseavariablewhereawirecanbeusedgoesagainstLVsdataflowparadigm
1. Usingapropertynodetoupdateafrontpanelvaluecausesthefrontpanelofthe
targetVItoloadintomemory=slowsdowncodeiffrontpanelisnotalreadyin
memory
ii. CancallsubVIsbyreferenceinsteadofjustputtingthemontheblockdiagram
1. Onblockdiagram:subVIloadedintomemorywhenmainVIisloaded(everseen
thescreenwhereLVislookingforthesubVIs?itpromptsyoutochooseitifit
cantfindit)
2. Byreference:subVIloadedwhencalled

-47-

Anda mungkin juga menyukai