clad study guide
DESCRIPTION
Guía de estudio para examen CLAD Core I y Core IITRANSCRIPT
-
CLADStudyGuidePreparedbyLabVIEWStudentAmbassadors:
JulianFerrerRiosKristenHeck
FrancescaRamadoriKelvinTang
TableofContentsSection 1: LabVIEW Programming Concepts...........................................................................................2Section 2: LabVIEW Environment............................................................................................................6Section 3: Software Constructs in LabVIEW............................................................................................9Section 4: Programming Vis and functions..............................................................................................16Section 5: Data Communication and Synchronization VIs and Functions..............................................18Section 6: VI Server and Functions.........................................................................................................21Section 7: Errors handling VIs and Functions........................................................................................26Section 8: VI Design Patterns..................................................................................................................29Section 9: SubVI Design..........................................................................................................................37Section 10: Debugging VIs.....................................................................................................................39Section 11: VI Design and Documentation..............................................................................................43Section 12: Memory, Performance, and Determinism.............................................................................45
-1-
-
Section1:LabVIEWProgrammingConcepts
DataFlow
LabVIEWfollowsadataflowmodelforrunningVis.
Ablockdiagramnodeexecuteswhenallitsinputsareavailable.Whenanodecompletesexecution,itsuppliesdatatoitsoutputterminalsandpassestheoutputdatatothenextnodeinthedataflowpath.
VisualBasic,C++,JAVA,andmostothertextbasedprogramminglanguagesfollowacontrolflowmodelofprogramexecution.Incontrolflow,thesequentialorderofprogramelementsdeterminestheexecutionorderofaprogram.
Considertheblockdiagramabove.Itaddstwonumbersandthenmultipliesby2fromtheresultoftheaddition.Inthiscase,theblockdiagramexecutesfromlefttoright,notbecausetheobjectsareplacedinthatorderbutbecauseoneoftheinputsoftheMultiplyfunctionisnotvaliduntiltheAddfunctionhasfinishedexecutingandpassedthedatatotheMultiplyfunction.Rememberthatanodeexecutesonlywhendataareavailableatallofitsinputterminals,anditsuppliesdatatoitsoutputterminalsonlywhenitfinishesexecution.Inthesecondpieceofcode,theSimulateSignalExpressVIreceivesinputfromthecontrolsandpassesitsresulttothegraph.
Youmayconsidertheaddmultiplyandthesimulatesignalcodetocoexistonthesameblockdiagraminparallel.Thismeansthattheybeginexecutingatthesametimeandrunindependentlyofoneanother.Ifthecomputerrunningthiscodehadmultipleprocessors,thesetwopiecesofcodecouldrunindependentlyofoneanother(eachonitsownprocessor)withoutanyadditionalcoding.
-2-
-
Polymorphism
Aprogramminglanguagefeaturethatallowsvaluesofdifferentdatatypestobehandledusingauniforminterface.
InLabVIEW:theabilityofVIsandfunctionstoautomaticallyadapttoacceptinputdataofdifferentdatatypes(i.e.NumericFunctions);Usefulwhenperformingthesameoperationondifferentdatatypes
Section1PracticeQuestions
1. YoudevelopaSubVIthatonlyoutputsavalueandneedtousethisSubVIina(calling)VI.WhichofthefollowingisthebestwaytoenforcedataflowtocontroltheexecutionoftheSubVI?
a.UsetheSubVIinaSequencestructureb.ModifytheSubVItohavedummyinputsthatcanbeusedfromthecallingVIc.ModifytheSubVItohaveErrorclustersthatcanbeusedfromthecallingVId.ModifytheSubVItohaveaglobalvariableanduseitfromthecallingVI
2. Whichofthefollowingdoesnotconformtodataflowprogrammingparadigm?
a.ShiftRegistersb.Tunnelsc.SubVIsd.LocalVariables
-3-
-
3. Inthefigurebelow,whatwillResultequalwhenthiscalculationisexecuted?
a.55b.70c.65d.Indeterminate
4. WhatisthevalueinXORResultafterthefollowingcodehasexecuted?
a.0b.1c.Trued.False
5. WhatdeterminestheprogramorderofexecutionofcodeinLabVIEW?
a.Thetimewhenyouenteredthecodeb.Itgoesfromlefttoright.c.Thedataflow
-4-
-
6. InthefollowingVI,whatwillbetheexecutionorderoffunctions?
a.
b.
c.
d.
Section1Answers1.C2.D3.B4.B5.C6.C
-5-
-
Section2:LabVIEWEnvironment
LabVIEWprogramsarecalledvirtualinstruments(Vis).Controlsareinputsandindicatorsareoutputs.
EachVIcontainsthreemainparts:
FrontpanelHowtheuserinteractswiththeVI
BlockdiagramThecodethatcontrolstheprogram
Icon/connectorThemeansofconnectingaVItootherVis
-6-
-
InLabVIEW,youbuildauserinterfacebyusingasetoftoolsandobjects.Theuserinterfaceisknownasthefrontpanel.Youthenaddcodeusinggraphicalrepresentationsoffunctionstocontrolthefrontpanelobjects.Theblockdiagramcontainsthiscode.Insomeways,theblockdiagramresemblesaflowchart.
Youinteractwiththefrontpanelwhentheprogramisrunning.Youcancontroltheprogram,changeinputs,andseedataupdatedinrealtime.Controlsareusedforinputssuchasadjustingaslidecontroltosetanalarmvalue,turningaswitchonoroff,orstoppingaprogram.Indicatorsareusedasoutputs.Thermometers,lights,andotherindicatorsdisplayoutputvaluesfromtheprogram.Thesemayincludedata,programstates,andotherinformation.
Everyfrontpanelcontrolorindicatorhasacorrespondingterminalontheblockdiagram.WhenyourunaVI,valuesfromcontrolsflowthroughtheblockdiagram,wheretheyareusedinthefunctionsonthediagram,andtheresultsarepassedintootherfunctionsorindicatorsthroughwires.
ControlsPalette
UsetheControlspalettetoplacecontrolsandindicatorsonthefrontpanel.TheControlspaletteisavailableonlyonthefrontpanel.Toviewthepalette,selectViewControlsPalette.YoualsocandisplaytheControlspalettebyrightclickinganopenareaonthefrontpanel.TackdowntheControlspalettebyclickingthepushpinonthetopleftcornerofthepalette.
FunctionsPalette
UsetheFunctionspalettetobuildtheblockdiagram.TheFunctionspaletteisavailableonlyontheblockdiagram.Toviewthepalette,selectViewFunctionsPalette.YoualsocandisplaytheFunctionspalettebyrightclickinganopenareaontheblockdiagram.TackdowntheFunctionspalettebyclickingthepushpinonthetopleftcornerofthepalette.
ToolsPalette
-7-
AutomaticSelectionTool
-
YoucanviewtheToolsPaletteonboththefrontpanelandblockdiagram.Toviewthepalette,selectViewToolsPalette.YoualsocandisplaytheToolspalettebyholdingshift+rightclickinganopenareaonthefrontpanelorblockdiagram.Ifyouenabletheautomaticselectiontoolandyoumovethecursoroverobjectsonthefrontpanelorblockdiagram,LabVIEWautomaticallyselectsthecorrespondingtoolfromtheToolspalette.ToggleautomaticselectiontoolbyclickingtheAutomaticSelectionToolbuttonintheToolspalette.
UsetheOperatingTooltochangethevaluesofacontrolorselectthetextwithinacontrol.UsethePositioningTooltoselect,move,orresizeobjects.ThePositioningToolchangesshapewhenitmovesoveracornerofaresizableobject.UsetheLabelingTooltoedittextandcreatefreelabels.TheLabelingToolchangestoacursorwhenyoucreatefreelabels.UsetheWiringTooltowireobjectstogetherontheblockdiagram.
Section2PracticeQuestions
1. Whichofthefollowingisthebestmethodtoupdateanindicatoronthefrontpanel?
a.UseaValuepropertynodeb.Wiredirectlytotheindicatorterminalc.Usealocalvariabled.Useafunctionalglobalvariable
Section2Answers1.B
-8-
-
Section3:SoftwareConstructsinLabVIEW1. Frontpanelwindowandblockdiagramobjects
a. Controls,indicators,IOcontrolsandrefnumsi. Controlfrontpanelobjectforsimulatinginput,displaysvaluesthatwillbepassedTOfunctionsonblockdiagram
1. Knobs,pushbuttons,etc.2. Usuallyhasawhitebackground
ii. Indicatorfrontpanelobjectforoutput,displaysvaluespassedFROMfunctionsonblockdiagram
1. Graphs,LEDs,etc.2. Usuallyhasagraybackground
iii. I/OControlsiv. Refnums
b. Terminals,constants,nodesi. Terminalsrepresentationoffrontpanel(FP)objects(controlsandindicators)ontheblockdiagram(BD);entryandexitpointsfordataexchangebetweenFPandBD
1. RememberpositionofterminaldoesntmatterlabelanddatatypedefineswhatFPobjecttheterminalisconnectedto
ii. ConstantsonlyonBDiii. Nodes
1. Functiona. Paleyellowbackgroundb. FundamentaloperatingelementsofLV
-9-
-
c. Doubleclickingselectsitem2. subVI
a. VIwithinaVIb. AnyVIhaspotentialtobeasubVIc. DoubleclickonsubVItoopenFPd. ExpressVIs=specialtype
i. Configurationwindow3. Structure
a. Examples:whileloop,forloop,casestructure,sequencestructurec. Palettes,updatemodes,andlegendsofchartsandgraphs
i. Palettes1. Graphpalette
a. Cursormodefocustocursorsocursormovesb. zoommodehorzorvertonlyzoom,boxzoom,zoomin/out(shift+click
forzoomout)c. dragmodeclickanddragplotviewaroundscaleautoupdates
ii. Updatemodes1. Chartaddspointeachiterationmaintainshistory
a. Stripchartentireplotredrawneachiterationinorderforplottoappeartoscrolltotheleft
b. Scopechartpointsplotteduntilendofxscalereached,thenplotclears,andplotbeginsatfarleftagain
c. Sweepchartredlinethatindicatesthefrontedgeofnewdatabeingplottedoverolddata.
2. Graphredrawspoint(s)eachiterationa. Useachartinsidealooptoseefullsetofdata(dynamicallyupdates)b. Useagraphoutsidealooptoseefullsetofdata
iii. Legends1. Plotlegend
a. Showscolorofeachplotandplotname2. Scalelegend
a. Showsxandyscaletitles,canlockscales,showfulldatarange,andedittheformatofthenumbers
3. Cursorlegenda. Onlyavailableforgraphsb. Listscursorsandcoordinatesc. Cancreatecursorsfromhere
-10-
-
d. MechanicalactionofBooleanobjects[reallyhelpfulexampleVI:MechanicalActionofBooleans.viintheExampleFindersearchmechanical]
i. Switch1. Whenpressedvaluechangeondownclickofleftmousebutton2. Whenreleasedvaluechangeonreleaseofleftmousebutton3. Untilreleasedvaluechanceondownclickandreleaseofleftmousebutton
ii. LatchhastobereadbyLVandreturnstoitsoriginalstate1. Whenpressedvaluechangeondownclickofleftmousebutton2. Whenreleasedvaluechangeonreleaseofleftmousebutton3. Untilreleasedvaluechanceondownclickandreleaseofleftmousebutton
e. Propertynodesi. Accesspropertiesofanobject(item)ii. Allowyoutomodifyobjectsappearanceorbehavior(forexample)programmaticallyiii. Operatetoptobottomiv. Bydefault,iferroroccurshalfwaydown,remainingpropertymodificationswillnotexecuteanderrorwillbeoutput
2. Datatypesanddatastructures[formoredetails(morethancoveredonCLAD)>http://zone.ni.com/reference/enXX/help/371361B01/lvexcodeconcepts/manager_data_types/]
a. Numerici. representnumbersii. chooserepresentation=numberofbitsusedtostorethenumber(morebits,moreprecisionpossible);ieI32,U8,DBL
iii. Orange(DBL),Blue(Integer),Gray(FXP)b. String
i. SequenceofASCIIcharactersii. Tables,textentry,labelsareexamplesofstringobjectsiii. Changedisplayformat:Normal,\Codes,Password,Hexiv. Pink
c. Booleani. True/Falseii. Greeniii. Mechanicalaction(seeabove)
d. EnumeratedControl/Constant/Indicator(Enum)i. Pairsofstringandnumericindefinedlistii. Usefulbecauseeasiertomanipulatenumbersthanstringssometimes(statemachines)
e. pathdatatypei. platform(OS)independent;thefilemanager(lowlevelLV)determineshowthedatatype
-11-
-
isdefinedf. Arrayandclusterdatatypes
i. Arrays1. Composedofelements(data)anddimension(size)2. Allelementsmustbeofsamedatatypedefinedwhencreated(placing
numericalcontrolinanarrayshellcontrolcreatesanumericarraycontrol)g. Waveform
i. Threepartstoit1. t0:timezero2. delta_t:timeincrement3. Y:value,intensity,voltage,etc.
h. Timestampdatatypei. timezoneindependentnumberofsecondsthathaveelapsedsince12:00a.m.,Friday,January1,1904,UniversalTime.Ifyearandmonthareoutofrange,theresultsareunpredictable.Ifyearisbefore1904,timestampisnegative.
i. Variantdatatypei. Allowsyoutohandledatainageneralway
3. Workingwithobjectsanddatatypesonfrontpanelwindowsa. Ranges,formats,representation,andscaling
i. Appropriateuse1. Example:ifyouaremeasuringtheangleofahalfrotationtherangeshouldbe0
180b. Customizingcontrols
i. Customcontrol1. Singleinstanceofuniquecontrolorindicator
ii. Typedefinitions1. Linkedtofilesochangestofilewillbeseenineachinstanceoftypedeffed
control/indicator2. Appearanceisnotlinkedtofiledatatype(I32,U8,listofenum,string)
iii. Stricttypedefinitions1. Linkedtofilesochangestofilewillbeseenineachinstanceoftypedeffed
control/indicator2. AppearanceISlinkedsoEVERYTHINGexceptlabel,description,anddefault
valuechanges4. Programcontrolstructuresanddatastorage
a. Loopingstructures(forloopsandwhileloops)i. ForLoop
-12-
-
1. ExecutessetnumberoftimesdefinedbyNterminalorindexedtunnel2. Possibleexecutezerotimes3. Tunnelsautomaticallyoutputanarrayofdata
ii. WhileLoop1. Stopsexecutingbasedonthevalueattheconditionalterminal2. Mustrunatleastonce(dowhileloop)3. Tunnelsautomaticallyoutputlastvalue
iii. Indexingonloopboundaries1. Input:oneelementinthearraywillbepassedinwitheachloopiteration2. Output:anelementisaddedtothearraywitheachloopiteration,theentirearray
willbepassedoutiv. Shiftregisters
1. Pairofterminalsonleftandrightsideofloopforcedtobealigned2. Valuereadfromoutputofshiftregister(leftside)willbethesamevalueasthe
valuepassedtotheshiftregisterinput(rightside).3. 1stiterationofloop:
a. ifinitialized(valuepassedintoshiftregisterfromoutsidetheloop),theinitializingvaluewillbethevaluereadfromtheshiftregister.
b. Ifuninitialized,thevalueintheshiftregisterfromthelasttimetheloopwasexecutedwillbethevaluereadfromtheshiftregister(thisisutilizedinfunctionalglobals)ifneverrunbefore,usesdefaultvalue(usually0)
b. Caseandsequencestructuresi. Flatandstackedsequencestructures
1. Canbeusedtoforceexecutionorder,butusuallyanotherway(errorwire)2. Shouldbeavoidedbecausecannotbestoppedinthemiddle.3. Stackedmeansthatyouonlyseeoneframeatatimescrollthroughtosee
othersii. Caseselectorvaluesanddatatypes
1. Caseselectoracceptsvaluestodeterminewhichcasetoexecute2. Ifvaluecaseselectorreadsdoesnotmatchanyofthecases,defaultcasewill
execute.3. Enumsusefulbecausedonthavetoworryabouttyposwithstrings,andplain
numericsarehardertokeeptrackof.4. Errorwirecanbewiredtocaseselectortoprogrammaticallychoosetoexecute
certaincodewhenthereisorisnotanerrorcasestructureturnsredandgreentoindicateerrorcaseandnoerrorcase.
iii. Datapassingtunnelsandsequencelocals1. Tunnelspassvaluesinoroutofstructures
-13-
-
a. Colorwillmatchdatatypei. Solidallcaseswired,noindexing,normalii. Open(notseenonloops;output/rightsideonly)oneormorecasesisntprovidingavaluetooutput
iii. Smallwhitesquareinsideusedefaultifunwirediv. Whitewithbracketsofdatatypecolor(seenonlyonloops)autoindexingenabled
2. Sequencelocalonlyforstackedsequencestructuresa. Similartoshiftregisterinthatitpassesdatafromoneinstance(loop,
sequenceframe)toanotherb. Arrowtoindicateifinputorouput
c. Eventstructuresi. Notifyandfilterevents(userinterface)
1. Notifya. Leftsideofeventstructureb. eventhappened,getvaluesfromeventc. GreenarrowinEditEventwindow
2. Filtera. eventisabouttohappen,abletochangewhathappensb. rightsideofeventstructurec. redarrowinEditEventwindowandendswith?
ii. Value(signaling)propertiesofcontrols1. Thesepropertiescanbecaughtbyaneventstructure
iii. Dynamiceventsanduserevents1. Dynamicevents
a. usewhenonlywanteventtoberegisteredduringpartoftheapplicationsexecution
b. enableyoutohandleeventsinasubVIc. rightclickoneventstructuretoselectShowDynamicEventTerminals
2. UserEventsa. Programmaticallycreateaneventthatyoudefine(insteadoftheones
alreadyavailablethroughtheeventstructure)b. UseGenerateUserEventtohaveeventoccurandbesenttoevent
structuretobehandledd. Formulanode
i. Allowsyoutousetexttoexecuteafunctionandmathematicalformulas(cos,sin,log,etc)e. Conditionaldisableanddiagramdisablestructures
-14-
-
i. ProgrammaticallyenableanddisablecodeusefulifwantingtomakefileI/Ofunctioncorrectlyinbothdevelopmentandexecutableenvironments
ii. Usefulintroubleshootingcodetonarrowdownproblemspotf. Timedstructuresloopandsequence
i. Moreusefulinarealtimeoperatingsystem(deterministic)ii. EachlooporframewilloperateinthetimeyouspecifywillindicateifdoesntusingFinishedLate?DataNodeelement
iii. Cansetpriorityofloop,processortheloopshouldusetoexecute,etcg. Variableswireisalwayspreferred,raceconditionspossible
i. Local1. WithinasingleVI
ii. Global1. VItoVI2. LookslikeafrontpanelonlyVIthatstoresthevalues
iii. FunctionalGlobal1. VItoVI2. FPandBDuninitializedshiftregisterusedtostoredata3. Protectsdatafromtwoinstancestryingaccessatsametimeandcausingrace
conditioniv. Shared
1. VItoVIacrossanetwork2. DeployedtonetworkforusebymultipleVIsonthenetwork
-15-
-
Section4:ProgrammingVisandfunctions1. Numeric,Boolean,string,path,andvariant
a) (seeabove)2. Conversion,comparison,andmanipulation
a) Functionsspecificallyforconverting:num>string,string>num,path>string,string>path,etcb) Functionsspecificallyformanipulatingcertaindatatypes:buildpath,strippath,concatenatestring,
bool>numarray,etc3. Arraysandclusters
a) Bothhaveshellsb) Arrays
1. mustbesamedatatype2. dimensionanddata3. indexelementfromarray
c) Clusters1. Groupingofmanydatatypes(includingarraysandotherclusters)2. Unbundleandbundleclusterelements
4. Timinga) Waittimers
1. Wait1. Willwaituntilthespecifiedtimehaselapsed2. Wheninaloop,runsinparalleltoothercodeinsideloop(assumingnodependencieson
othercodeinloop)ifcodetakeslongerthanthewaittime,nextloopiterationwillbeginimmediately,otherwisethewaitwillcompleteandthennextloopiterationwillbegin
2. Waituntilnextmillisecondmultiple
-16-
-
1. Willwaituntilamultipleofthetimespecifiedisreached2. Wheninaloopandassumingnodependencyonothercodeinloop,itwillruninparallelif20
msiswiredtoit,imaginemarksalongatimelineevery20ms.Ifthecoderuns45ms,thenextloopiterationcannotbeginuntilthenextmark,whichwouldbeat60ms.
b) tickcount(ms)1. startsatzero(cannotconvertintorealdate/time)2. maxvalue=(2^32)1;thereforecanrolloverbacktozeroifallowedtocountpastitsmax>bad
informationc) date/timefunctionsd) Timingfunctionsrelatedtotimedstructures
5. fileI/Oformatsa) ASCII
1. Textfile2. Goodtousewhenwanttoopenwithanotherprogram(notepad,textedit,word,etc)
b) Binary1. Takesleastamountofmemory2. Efficient3. Cannotbeeasilyreadbyuseroropenedbyanotherprogram4. Mustknowhowtodecodethefile
c) Datalog1. Typeofbinaryfile2. Usedtowriteclustereddatatofile
d) Storage(.tdm)1. Internalstructurepubliclydocumented(createdbyNI)2. TypeofbinaryfilewithanindexfileforfasterI/Operformance3. Abletoapplypropertiestofileatdifferentlevels:file,group,channel
e) Waveformf) XML(ExtensibleMarkupLanguagestandardized)
1. SetoffunctionsspecificallyforXML2. Platformindependent
g) Configuration1. inifile2. Setoffunctionsspecificallyforconfigfiles3. Platformindependent
6. WaveformandwaveformfileI/Oa) StorageVIsusedtowritewaveformdatatobinarymeasurementfiles(.tdm)
7. Dynamicanduserevents
-17-
-
a) (seeabove)
Section5:DataCommunicationandSynchronizationVIsandFunctions
LocalVariables
Localvariablesallowdatatobepassedbetweenparallelloops.Youcanreadorwriteasinglecontrolorindicatorfrommorethanonelocationintheprogram.Localvariablesbreakthedataflowparadigmandshouldbeusedsparingly.Sometimesyoumayneedtoaccessafrontpanelobjectfrommorethanoneplaceontheblockdiagramortopassdatabetweenstructuresthatyoucannotconnectbyawire.Toaccomplishthesetasks,youwouldusealocalvariable.
LocalvariablesarelocatedontheFunctionspaletteunderProgrammingStructures.Youusealocalvariablebyfirstselectingtheobjectyouwanttoaccess.YoucaneitherclickonthelocalvariablewiththeOperatingtoolandselecttheobjectyouwanttoaccess,orrightclickonthelocalvariableandchoosetheobjectfromtheSelectItemmenu.Next,youmustdecidetoeitherreadorwritetotheobject.RightclickonthelocalvariableandchooseChangetoReadorChangetoWrite.
GlobalVariables
UseglobalvariablestoaccessandpassdataamongseveralVIsDiffersfromlocalvariablesbecauselocalvariablesareusedtoaccessandpassdatabetweenparallelloops(withinoneVI).Whenyoucreateaglobalvariable,LabVIEWautomaticallycreatesaspecialglobalVI,whichhasafrontpanelbutnoblockdiagram.
SharedVariable
-18-
-
Representsasharedvariableontheblockdiagram.UsesharedvariablestosharedataamongVIsorbetweenlocationsontheblockdiagramthatyoucannotconnectwithwires.
DataSocket
UsetheDataSocketVIandfunctionstopassdatabetweenVIsprogrammatically.DataSocketbeusedwithbasicallyanyprotocolthatutilizestheTransmissionControlProtocol(TCP)insomeform.
TouseDataSocketsitisnecessarytosetuptheDataSocketsServer,aprogramthatrunsononeofthemachinesinthenetworkandactsasanintermediary,sothatmultipleclientscanread/writedata.ThedatatransferusestheDatasocketTransferProtocol(DSTP).Protocols
UsetheProtocolsVIsandfunctionstoexchangedatabetweenapplicationsbyusingprotocolssuchasTCP/IP,UDP,serial,IrDA,Bluetooth,andSMTP.
Notifiers
UsetheNotifierOperationsfunctionstosuspendtheexecutionofablockdiagramuntilyoureceivedatafromanothersectionoftheblockdiagramorfromanotherVIrunninginthesameapplicationinstance.
Queues
UsetheQueueOperationsfunctionstocreateaqueueforcommunicatingdatabetweensectionsofablockdiagramorfromanotherVI.
Semaphores
-19-
-
UsetheSemaphoreVIstolimitthenumberoftasksthatcansimultaneouslyoperateonashared(protected)resource.Aprotectedresourceorcriticalsectionofcodemightincludewritingtoglobalvariablesorcommunicatingwithexternalinstruments.
Section5PracticeQuestions
1. Whichofthefollowingcannotbeusedtotransferdata?
a.Semaphoresb.Queuesc.Notifiersd. Localvariables
2. Whichofthefollowingillustratesanadvantageofaglobalvariableoveralocalvariable?
a.AglobalvariablecanpassdatabetweentwoindependentVIsrunningsimultaneouslyb.Onlytheglobalvariablecanpassarraydata,localvariablescannotc.Globalvariablesfollowthedataflowmodel,andthereforecannotcauseraceconditionsd.Globalvariablesdonotrequireownedlabelstooperate
Section5Answers1. A2. A
-20-
-
Section6:VIServerandFunctions
InLabVIEWprogramming,aVIServercanbeusetoprogrammaticallycontrolfrontpanelobjects,VIs,andLabVIEW,andtodynamicallyload,edit,andrunVIsonacomputerorremotelyacrossanetwork.YoucancontrolbrowseraccesstotheVIsandconfigurewhichVIsremoteapplicationscancontrol.
ConfiguringtheVIServerPageSelectToolsOptionstodisplaytheOptionsdialogboxandselectVIServerfromtheCategorylisttodisplaythispage.IfatargetinaLabVIEWprojectsupportstheVIServer,youalsocanrightclickthetarget,suchasMyComputer,selectPropertiesfromtheshortcutmenu,andselectVIServerfromtheCategorylisttodisplaythispage.ToconfigureVIServeroptionsforthe mainapplicationinstance,displaythispagefromthe Optionsdialogbox.ToconfigureVIServeroptionsforatarget,displaythispagefromthePropertiesdialogboxforthetarget.ToconfigureVIServersettingsforaprojectapplicationinstance,rightclickthetargetintheProjectExplorerwindow.TheVIServerpageincludesthefollowingcomponents: ProtocolsUsethissectiontoconfiguretheVIServer.ThedefaultVIServersettingsareActiveXenabledandTCP/IPdisabled.o TCP/IPEnablesVIserversupportforTCP/IP.Ifyouallowremoteapplicationstoconnectusing
TCP/IP, youalsoshould specify which machineaddressescanaccess theVI Server in theMachineAccesssectionofthispage.Thischeckboxdoesnotcontainacheckmarkbydefault.
-21-
-
PortSets the TCP/IP port at which the VI server listens for requests. FromToolsOptions thisportnumberis3363,bydefault,whichisaregisteredportnumberreservedforusebyLabVIEW.Fortargets,thedefaultis0causingtheoperatingsystemtodynamically select aport. If youwant to runmultiple application instances on themachine,eachwithitsownVIServerrunning,youmusthaveauniqueVIServerportnumber.Youalsocanusethe Server:PortpropertytosettheLabVIEWVIServerportprogrammatically.
ServicenameSetstheservicenamefortheVIServerTCPInstance.Toretrieveanapplicationreferencewithouttheportnumber,useServicenameinconjunctionwiththeOpenApplicationReference functionbywiringa Servicename tothepolymorphicportnumber or Service name input.
IfyoudisplaythispagefromtheOptionsdialogbox,thisservicenameisMainApplicationInstance/VIServerbydefault.IfyoudisplaythispagefromthePropertiesdialogboxforatarget, the service name is target name/VI Server by default. You can use theServer:ServiceNamepropertytosettheservicenameprogrammatically.
UsedefaultSets Servicename toitsdefaultvalue.Thischeckboxcontainsacheckmarkbydefault.Toedit Servicename,removethecheckmarkfromthecheckbox.
o ActiveX(Windows) Enables VI server support for ActiveX Automation. This checkbox isavailable only from the ToolsOptions navigation. This checkbox contains a checkmark bydefault.
VIScriptingUsethissectiontoenableVIScripting.o ShowVIScriptingfunctions,propertiesandmethodsEnablesVIScriptingfunctionsonthe VI
ScriptingpaletteandadditionalVIServerpropertiesandmethods.Allfunctions,properties,andmethodsyouenablethroughVIScriptingdisplayasblue.
DisplayadditionalVIScriptinginformationinContextHelpwindowDisplays connectorpaneterminalnumbersintheContextHelpwindow.PlaceacheckmarkintheShowVIScriptingfunctions,propertiesandmethodscheckboxtoenablethisoption.
AccessibleServerResourcesUsethissectiontoindicatethetasksthatremote applications canaccomplish.
o VIcallsAllowsremoteapplications to call VIs exported through theVI Server. If youallowremoteapplicationsaccesstoVIs,specifywhichVIscanbeexported.Thischeckboxcontainsacheckmarkbydefault.
o VIpropertiesandmethodsAllowsremoteapplicationstoreadandsetthepropertiesofVIsandtocallmethodsforVIsthroughtheVIServer.If youallowremoteapplicationsaccesstoVIs,specifywhichVIscanbeexported.Thischeckboxcontainsacheckmarkbydefault.
o ApplicationpropertiesandmethodsAllowsremoteapplicationstoreadandsetthepropertiesoftheapplicationinstanceandtocallmethodsfortheapplicationinstancethroughtheVIServer.Thischeckboxcontainsacheckmarkbydefault.
o ControlpropertiesandmethodsAllowsremoteapplicationstoreadandsetthepropertiesof
-22-
-
controls and to call methods for controls through the VI Server. This checkbox contains acheckmarkbydefault.
MachineAccessUsethissectiontocontrolmachineaccesstoVIsthrough theVIServer.o MachineaccesslistListsmachinesthatdoanddonothaveaccesstotheVIServer.Youalso
can use the Server:TCP/IP Access List property to list programmatically the TCP/IPaddresses of machines that may access the VI server.Note: If you change the Machine access list, machines that are currentlyconnectedtotheVIserverwill notbedisconnectedevenif theyarenolongerallowedaccesstotheserver.
o Machinename/addressEnterthenameorIPaddressofthemachineyouwanttoaddtotheMachineaccesslist.
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.YoualsocanusetheDomainAccountManagertomanagedomainusersandgroups.o Userandgroupaccess listLists 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 associatedwith machines that have access permission can access the VI Server.Note: If the User and group access list is changed, users that are currentlyconnected to the server will not be disconnected even if they are no longerallowedaccesstotheVIServer.
o AllowaccessAllowsaccesstotheusersandgroupsselectedinUserandgroupaccesslist.o DenyaccessDeniesaccesstotheusersandgroupsselectedinUserandgroupaccesslist.o AddDisplaysthe AddUsersandGroupsdialogbox,inwhichyoucanselectadomain,user,
andgroup.o RemoveRemovestheselectedentryfromtheUserandgroupaccesslist.
-23-
-
-24-
-
VIServerApplication
CompletethefollowingstepstocreateaVIServerapplication:1. ConfiguretheVIServer toallowtheTCP/IPprotocol.2. Use the OpenApplication Reference function to open a reference to a local or remote
application instance. Note:Ifyouhavemultipleapplicationinstancesopensimultaneously,suchasifyouareworkingwitha LabVIEWproject ortargetsofaLabVIEWproject,multipleVIServerscan be listening on different ports. Open an application reference to a specificapplicationinstancebystatingthemachinenameandtheportorservicename.3. UsetheOpenVIReferencefunctiontoopenareferencetoaVIonthelocalorremotecomputerthatalreadyexists in memory for theapplication instance, or to dynamically loadaVI fromdisk.However,beawarethatiftheinputtovipathisafilepath,thisfunctionwaitsuntiltheuserinterfaceisidletoloadtheVIfromdisk.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.Thefirstofthemisthatthislineisusuallyusedtoguaranteesequence.FollowingtheLabVIEWrulethatestablishesthatanysubVIorfunctionneedstohaveallitsinputsinordertorun,iftheoutputerrorlineisconnectedtotheinputofanothersubVI,thesecondsubVIwontrununtilthepreviousends.
Anothercharacteristicoftheerrorclusteristhat,whenconnectedtoacasestructure,itwillcreatetwocases:ErrorandNoError,whichcanbeusedtoskipstepsthatcantbeexecutedunlesseverythingelsehasnoerrors.AlsoisusedtoguaranteesequencewhentherearefunctionsorVIsthatdoesnthaveerrorline.
Therearetwodifferentwaysofhandlingerrors,automaticandmanually. Automatic:WhenLabVIEWisconfiguredtohandletheVIsautomatically(File>VI
Properties>Execution>EnableAutomaticErrorHandling),whenitencountersaunwiredErrorline,itwillhalttheexecutionandhighlightwheretheerroroccurred.
Manual:TohandleerrosmanuallytherearecertainVIsmeanttodoitwhicharepresentattheProgramming>Dialog&UserInterface:
-26-
-
o SimpleErrorhandlerandGeneralErrorHandler:Displayswhenanerroroccurred,showingthecauseoftheerrorandoptionallyanerrordialogbox,thedifferencebetweenthesimpleandthegeneralisthatthegeneralalsoacceptscustomerrorcodes.
o Merging,creating,clearingandsearchingerrorVIs:alsotheusermayneedtoclearerrorsiftheprogramsolvestheproblembyitself,also,whenbuildingSubVIsitisimportanttoaddthepreviouserrorstotheerrorsthatcanbeaddedfromthesubVI,andafterseveralsubVIsaddingerror,isusefultosearchforthefirsterror,sincetheerrorhandlerVIsshowstheerrorwithmostpriority.
o UserinterfaceDialogBoxes:ThisVIsareusedtoinformtheuserwheneveranerroroccurredandalsotoallowtheusertodecidetheactiontoimplementiftheprogramrequiresit.
WhencreatingVIs,wemightproduceerrorsthatLabVIEWdoesntinterpretthemaserrors.Forexample,whenwehaveadivisionby0:
-27-
-
LabVIEWwillgiveinfiniteasresult,however,forsomeapplicationthatmeansthatanerroroccurred.Forthosecases,itispossibletocreateyourownerrorcodesandimplementtheminlabVIEW.Todoso,itisnecessarytocreatea*error.txtfile.FortunatelyLabVIEWhasaninterfacemeanttohelpcreatingthisfile:Tools>Advanced>EditErrorCodes.Itwillaskyouifyouwanttocreateanewfileoreditone,eitherwayyoucanaddorediterrors.
Alltheerrorsaresavedat>Shared>Errors.
-28-
-
Section8:VIDesignPatterns
AgeneralVIdesignpatternconsistsof3mainparts:
1.Startup:Initializehardwareorgettingsignalsordatafromafile.2.Mainapplication:Analyzetheinputsignalordatacontinuouslyuntilitis
terminatedbyaconditionalterminalorauseraction.3.Shutdown:Displaysoutputdataorlogintofile.
DesignPatternSelectionFlowChart
-29-
-
StateMachineDesignPatternThestatemachinedesignpatternisusedforalgorithmsthatcanbeexplicitly representedwithastate
diagram.
AstatemachineinLabVIEWconsistoffollowingblockdiagramcomponents:1.WhileLoop:Executecurrentstatecontinuously.2.ShiftRegister:Usedtostoreandtransitnextstatetocurrentstate.3.CaseStructure:Containsprogramcodeforeachstate.4.StateFunctionalityCode:Programcodeforeachstateincasestructure.5.TransitionCode:Determinenextstate.
StateMachineDesignPattern
QueuedMessageHandler:Itisusedtoimplementcodeforauserinterface.Messagesisqueuedandhandledonebyoneintheorderofthequeue.Eachsubdiagraminthequeuedmessagehandlerrepresentsahandlingroutine.Itissimilartoastatemachinedesignbutwiththeshiftregisterholdingontothequeuedmessage.
-30-
-
ParallelLoop&Master/SlaveDesignPattern
ParallelLoopDesignPattern
Aboveblockdiagramillustratestheparallelloopdesignpattern.Theerror clusterwiresareusedtoexecutebothwhileloopsinparallel.However,thisdesignpatternisnotefficientastheremightbearaceconditionwhenimplementingdataaccessingmechanismwheretheremaybemultipleloopsaccessingthedataatthesameinstanceoftime.
Asolutiontothiswouldbeusingthemaster/slavedesignpatternasdepictedin blockdiagrambelow.
Master/SlaveDesignPattern
-31-
-
Themaster/slavedesignpatternisusedforexecutingtwoormoreprocesses simultaneouslyandpassdataamongprocesses.Thisdesignpatternmayconsist multiple parallel loops, each running at different rates.Therewillbealoopacts asthemasterwhichcontrolsalltheotherloopsknownastheslaveloops.The
raceconditionisavoidedbyusinganotifiestopassdatafromthemastertothe slave. Benefitsofusingnotifiesinmaster/slavedesignpatternisthatallslave loopsaresynchronizedtothemasterloop.Slaveloopexecutesonlywhen the masterloopsendsanotification.
Producer/Consumer(Data)DesignPattern
Producer/Consumer(Data)DesignPatternThisdesignpatternenhancesthedatasharingamongmultipleloopsrunningatdifferentrates.Theparallel loops are separated into 2 categories: the loop producing data (producer) and the loopconsumingdata(consumer).Mainbenefits:Processmultiplesetsofdatainorder.Queuesdataintheconsumerloop.Basically, thedata is continuously queuedby theproducer into theconsumer loopqueueand isprocessedbytheconsumerloopatitsownpace.
UserInterfaceEventHandlerDesignPattern
Theeventbaseddesignpatternbenefitsintermsofefficiencyastheyonlyrespondwhenaneventoccurs.
Itconsistsoffollowingblockdiagramcomponents:
-32-
-
1.EventStructure:Containsprogramcodeforeachdetecteduserinterfaceevent.2.WhileLoop:Monitoruserinterfaceeventcontinuously.3.TimeoutTerminal:Controlswhenthetimeouteventexecutes.4.EventDataNode.
UserInterfaceEventHandlerDesignPattern
-33-
-
Producer/Consumer(Event)DesignPattern
Producer/Consumer(Event) DesignPattern
Thisdesignpatternissimilartotheproducer/consumer(data)designpattern, however, the consumerloopexecutesasaneventoccurrenceisdetectedinthe producerloop.
Mainbenefits:Efficientlyrespondsasynchronouslytotheuserinterface.Queuescantransferanydatatype.
-34-
-
FunctionalGlobalVariable
UninitializedshiftregistersinfororwhileloopscanbeusedtoholddataaslongastheVInevergoesoutofmemory.Theshiftregisterholdsthelaststateoftheshiftregister.Thus,aloopwithanuninitializedshiftregisterisafunctionalglobalvariable.
MainBenefits:
Controlaccesstodatainashiftregister.
Eliminatethepossibilityofaracecondition.
FunctionalGlobalVariable
AboveisaVIexampleofafunctionalglobalvariable,whentheenumeratedinputisSet,theinputvalueisshiftedandstoredintotheshiftregister.Ontheotherhand,whentheenumeratedinputisGet,itwillretrievedthestoredvaluefromtheshiftregisteranddisplayitattheoutput.
-35-
-
DesignPatternsTableofComparison
DesignPattern Use Pros ConsGeneral Standardcontrolflow Distinct initialize,run
andstopphasesUnabletoreturntoapreviousstate
StateMachine State sequencesystemcontrol
Controlssequences Doesnotstorefuturesequences toexecute
Queued MessageHandler
Enhanced statemachine with storingof future sequencestoexecute(message)
Stores futuresequences toexecute
Does not usememoryefficiently
ParallelLoop Multiple taskprocessinginaVI
Efficient use ofcomputingresources
Bad synchronizationand have racecondition
Master/Slave Parallel loops withsynchronization
Passes messagesand handles loopsynchronization
Does not lend itselfwelltopassingdata
Producer/Consumer(Data)
Data producing andprocessinginparallel
Storesdata for laterprocessing
Does not provideloopsynchronization
User Interface EventHandler
Responds to userinterfaceevent
Handles userinterfacemessages
Does not allow forintensive processingapplications
Producer/Consumer(Event)
Producer/Consumer(Data) whichresponds to userinterfaceevent
Separates the userinterface fromprocessorintensivecode
Does not integratenonuser interfaceeventswell
-36-
-
Section9:SubVIDesign
ModularityisthepropertyofscalingaVIinsubmoduleswhichhavespecialfeaturesandcanberecycledinotherVIs.ThesemodulesarecalledsubVIs,and,sinceaSubVIisaVImodifiedintoasmallblockvisualization,doubleclickingitwillopenafrontpanelandablockdiagram.
EverySubVIneedsanIconandaConnectorpanetobecalledSubVI:a. Icon:GraphicalrepresentationofaVI.Customizable(doubleclick)b. ConnectorPane:MapoftheterminalsofaVI.Inputstotheleft,Outputstotheright(accessing
viarightclick>ShowConnector)
TheiconmustbemodifiedinordertorepresentwhatdoestheSubVIdoes,forthisreasontheIconEditorhasabuiltinpaintwindowtomodifytheimage:
TheconnectorPanerepresentstheInputsandOutputsofaSubVI.Therearemanytypesofconnectorssuitedforanyapplication.Itisimportanttonotethat,forconvention,InputsgoesleftandOutputsgoesRight.TolinktheterminalwiththeI/O:
FirstClicktheterminalintheconectorPane TheclickontheInputorOutput,theterminalwillchangecolorasaconfirmation FinallychooseiftheconnectorisRequired,RecommendedorOptionalbyRightClickingthe
terminal>ThisConnectionis>
-37-
-
WhendesigningSubVIs,itisimportanttoconsiderthepreviouserrorsastheerrorsthattheSubVIisadding,oneofthemostcommonerrorhandlingmethodsinSubVIisthenextone:
ApolymorphicVIisanspecialVIthatacceptsseveralDataTypes,anexamplecouldbethemultiplyfunction,sinceitcanacceptanydataType.InordertocreateapolymorphicVIisnecessarytocreatealltheVIsthataregoingtobepartofthepolymorphicVIwiththesameconnectorpaneconfiguration.Afterthatgoto:File>New>PolymorphicVI.Anewwindowwillprompt,whereyouwillhavetoaddalltheVIs.TheiconofthisVIwillalsoneedtobecreatedbyclickingintotheEditIcon.ThisVIwillautomaticallydecidewhichinstanceoftheVIsaddedtouse.
-38-
-
Section10:DebuggingVIs
WhenyourunaVIitmayhappenthatitdoesntevenrunoritdoessomethingyouwerentexpecting.
IftheVIdoesntrun,thefirststepistochecktheBrokenarrowatthetopoftheBlockDiagramortheFrontPanel:
Thenextwindowwillprompt:
-39-
-
ThemostcommoncausesforaVItobebrokenare:3. Theblockdiagramcontainsabrokenwire.4. ArequiredterminalofaSubVIisnotwired5. ASubVIisbroken.
SooncetheVIisnotbroken,thenextstepistorunit,ifitworksthedebuggingprocessisover!However,itmighthappenthattheVIgivesanunexpectedresultorithaltsatthemiddleoftheexecutionduetoerrors.Thedebuggingprocessisthenextone:
1. Checktheerrorsiftheyexist.2. UsethecontextHelpinSubVItocheckthedefaultvaluesandbesurethatthedefaultvaluecorresponds
towhatyouwant.3. Eliminateallthewarnings4. CheckDataTypes,sometimeswhenusingdifferentdatatypes,informationcanbelostduetoDataType
casting.
Ifthatdoesntwork,thenextstepistodebugtheexecutionoftheVIusingthenexttoolsaloneorcombined: HighlightExecution:AnanimationoftheblockDiagramexecutionwithvaluesattheoutputs.This
methodshowsthemovementofData.
-40-
-
SingleStepping:ExecutesonlyonestepoftheVI.UsedwiththeHighlightedExecutionprovidesanincredibledebuggingtool.
ProbingTools:Showsthevalueoverawire.InHighlightingexecutionorSingleStepping.ClickontheWire
Breakpoints:PausetheexecutionwheneverthereisnewDataAtaWire.
-41-
-
SuspendwhenExecuted:ThisworksasaBreakpoingforSubVIs.OncetheSubVIisexecuteditwillpausethewholeVI.AndwillopenthefrontpaneloftheSubVI.
-42-
-
Section11:VIDesignandDocumentation
1. Userinterfaceandblockdiagramlayouta. UI
i. Onemonitororless1. Tabstoorganizeandcondenseiftoomanycontrols/indicatorstolimittoone
monitorii. Groupcontrolsandindicatorslogically
1. Relateditemsshouldbegroupedtogether2. Usedecorationstoclarifyoremphasizegroupings
iii. Fontandcolor1. Usebrightcolorssparinglyandonlyforthingsthatneedtostandout(i.e.stop
button)2. Fontshouldbeuniform3. Boldtextforgroupingtitlesorheading4. Textsizeshouldbelogical
a. largertextforheadingsorimportantinformation,b. textshouldbesizedtothecontrolfillbuttons,butnotoverwhelmthe
frontpanelb. blockdiagram
i. minimizewirecrossingsandbendsii. dataflowshouldgolefttorightiii. terminalsshouldbealigned:inputsontheleft,outputsontheright
2. Modularandhierarchicaldesigna. UsesubVIswhencodeisrepeatedb. ComplexcodethatachievesasinglefunctioncanbeplacedinasubVI
3. subVIiconsandconnectorpanelayouta. connectorpanelayout(onlyaccessiblefromfrontpanel)
i. Left=inputs,Right=outputsii. Bottomterminalsonsidesareusuallyreservedforerrorwiresiii. Topterminalsonsideareusuallyreservedforreferencewires
b. Iconsi. PictureshoulddescribewhattheVIdoesii. Shouldhavebordernofloatingwireconnectionsconfusesprogrammeriii. RelatedsubVIsshouldhavearelatedicons(example:DAQmxhasbarattopthatsaysDAQmx)
4. VIproperties
-43-
-
a. Documentationi. Showsupincontexthelp
b. Passwordprotecti. Ifdistributingcodetoothers,youcanputapasswordontheblockdiagramsotheycantreuseorrecreateit
c. Windowappearancei. Basicallyallowsyoutoselectthewindowtypethemaindifferencebetweenthemisthenumberofmenubarsvisible.
d. Windowsizeusefulifwillberunonamonitorwithdifferentresolutionfromdevelopmentmachine
e. RunTimepositionwhenitrunsdoyoualwayswantittoappearinaspecificlocationonthemonitor?
5. DocumentingVIsa. Controls/indicators
i. Descriptionandtipstripii. Labelsiii. Captions
1. UsecaptionsinsteadoflabelstolocalizeaVIwithoutbreakingtheVI.Unlikealabel,acaptiondoesnotaffectthenameoftheobject(whichyoumaybeusingtoaccessthatitemprogrammaticallythroughVIServer),andyoucanuseacaptionasamoredescriptiveobjectlabel.Thecaptionappearsonlyinthefrontpanelwindow.
b. FPandBDi. Freelabelstextboxesnotassociated/tiedtoanobjectii. SelfdocumentingcodeusingclustersandtheUnbundlebyNamesothatthelabelsarevisibleintheunbundle
iii. Wirelabelsforlongwires(nowavailableinLV2010,otherwiseusefreelabelstolabelwires)
c. VIi. DocumentationunderVIProperties
1. ThiswillshowupintheContextHelpWindow2. RightclickonVIIcon>>VIProperties>>Documentation
-44-
-
Section12:Memory,Performance,andDeterminism
1. Toolsforidentifyingmemoryandperformanceissuesc. Profilememoryandperformance
i. Tools>>Profile>>ProfilePerformanceandMemoryii. toolforanalyzinghowyourapplicationusesexecutiontimeandmemory.iii. identifythespecificVIsorpartsofVIstooptimize
1. Forexample,ifyounoticethataparticularsubVItakesalongtimetoexecute,youcanfocusyourattentiononimprovingtheperformanceofthatVI.
iv. providesaroughestimateoftheaverageexecutiontimeoftheVIsusedinanapplication.
1. limitedtomillisecondresolution.2. Duetothenondeterministicexecution,executiontimeshouldbeaveragedover
severaliterationsforaccuratemeasurements.VITimedisplaysthetotalamountoftimespendexecutingeachVI.
d. Showbufferallocationsi. Tools>>Profile>>ShowBufferAllocations
1. Showswherebuffersarecreatedontheblockdiagram2. DoesNOTshowbuffersize,whichisdependentondatatype3. Fewerbufferallocations(usingwiresinsteadoflocalvariables,whichcreatesa
copy)meansfasterperformancee. VImetricsVIAnalyzer
i. interactivelyandprogrammaticallytestVIstoidentifyareasforimprovement.ii. maincategories: BlockDiagramChecksblockdiagramperformanceandstyleissues,suchaswiring,loopandstructureusage,coerciondots,andunnecessaryelementsontheblockdiagram. ComplexityMetricsChecksforVIcomplexity,suchasnesting,codereuse,andmodularity.
-45-
-
DocumentationChecksfordocumentationfordevelopersanduserswithinaVI,suchasVIandcontroldescriptionsandblockdiagramcomments.ChecksthespellingonVIs,frontpanels,andblockdiagrams. FrontPanelChecksfrontpaneldesignanduserinterfaceissues,suchascontrolusage,fontselection,andlabels. GeneralChecksperformanceandstyleissuesthatdonotfitintotheothercategories,suchasfileproperties,iconsandconnectorpanes,andVIproperties. VIMetricsChecksblockdiagramandfrontpanelmetrics,suchasthenumberofconnectorpaneinputsandoutputs,controlsandindicators,andnodes.
2. Programmingpracticesa. Enforcingdataflow
i. Helpfultouseanerrorwiretoenforcedataflowb. UIupdatesandresponsetouserinterfacecontrols
i. NoneedtoupdateUIfasterthan510persecond,becausehumanscantdetectachangefasterthanthatandmonitorshavealimitedupdateratetoo
ii. WaystoupdateUI1. Best:wiredirectlytoterminal2. Better:localvariablemayrequirecopytobemade>slowdown3. Good:propertynodesmayrequirecopyandtoloadfrontpanelintomemoryif
notalreadyiii. UseEventstructureoverpollingfrontpanelsleepingfunctions(likeeventstructure)aremoreefficient
c. Datatypeselection,coercion,andbufferallocationi. Fornumbersthatcanonlybeintegers,useI32,U32,I16,U16,I8,Uii. BitdepththenumberinU8oru16isbasedonhowmanybitsyouneedtorepresentthenumber
1. Forexample,aU8numbercancountfrom0to255,ifyouweretoaddanothertoaU8whenitisat255itwouldwraparoundto0.
iii. Avoidcoercioncausestwomemorylocationsforeachversionofthevalueandislessefficientonlowlevel
iv. Tocreatefilesthattaketheleastamountofmemory,usethesmallestnumericrepresentationpossibleforyourprecisionneeds.
v.Optimizecodetoallocatefewernumberofbuffersd. Array,string,andloopoperations
i. BuildingarraysdynamicwillusesignificantlymorememorybecauseLVhastoreallocateanentirenewmemoryspacewhenanelementisaddeditisbettertoinitializeanarraytothemaximumsizeandusereplacearraysubset
1. Appendingtoanarrayisbetterthanprependingtoanarraybecauseofbufferallocationrequirements
2. AutoindexingisalsobetterbecauseLVcanpredictthebuffersizeaheadoftime(hastoknowfornumberofloopiterationsanyway)
e. Localandglobalvariables,propertynodes,andreferences
-46-
-
i. DonotuseavariablewhereawirecanbeusedgoesagainstLVsdataflowparadigm1. Usingapropertynodetoupdateafrontpanelvaluecausesthefrontpanelofthe
targetVItoloadintomemory=slowsdowncodeiffrontpanelisnotalreadyinmemory
ii. CancallsubVIsbyreferenceinsteadofjustputtingthemontheblockdiagram1. Onblockdiagram:subVIloadedintomemorywhenmainVIisloaded(everseen
thescreenwhereLVislookingforthesubVIs?itpromptsyoutochooseitifitcantfindit)
2. Byreference:subVIloadedwhencalled
-47-
Section 1: LabVIEW Programming ConceptsSection 2: LabVIEW EnvironmentSection 3: Software Constructs in LabVIEWSection 4: Programming Vis and functionsSection 5: Data Communication and Synchronization VIs and FunctionsSection 6: VI Server and FunctionsSection 7: Errors handling VIs and FunctionsSection 8: VI Design PatternsSection 9: SubVI DesignSection 10: Debugging VIsSection 11: VI Design and DocumentationSection 12: Memory, Performance, and Determinism