116
University College of Southeast Norway http://home.hit.no/~hansha Introduction to LabVIEW Hans-Petter Halvorsen, 2016-09-07

Introduction to LabVIEW - HiT

  • Upload
    vudan

  • View
    243

  • Download
    2

Embed Size (px)

Citation preview

Page 1: Introduction to LabVIEW - HiT

UniversityCollegeofSoutheastNorway

http://home.hit.no/~hansha

IntroductiontoLabVIEWHans-PetterHalvorsen,2016-09-07

Page 2: Introduction to LabVIEW - HiT

ii

PrefaceThisdocumentexplainsthebasicconceptsofLabVIEW.

Youfindadditionalresources,code,etc.here:

http://home.hit.no/~hansha/?tutorial=labview

YouneedtoinstalltheLabVIEWProfessionalDevelopmentSystem.

FormoreinformationaboutLabVIEW,visitmyBlog:http://home.hit.no/~hansha/

LabVIEWBasicsVideos:

http://home.hit.no/~hansha/video/labview_basics.php

LabVIEWTrainingandResources:

http://home.hit.no/~hansha/?training=labview

Page 3: Introduction to LabVIEW - HiT

iii

TableofContentsPreface......................................................................................................................................ii

TableofContents.....................................................................................................................iii

1 Introduction......................................................................................................................1

1.1 DataflowProgramming...............................................................................................1

1.2 GraphicalProgramming..............................................................................................1

1.3 Benefits.......................................................................................................................2

2 StartusingLabVIEW..........................................................................................................4

2.1 TheLabVIEWEnvironment.........................................................................................4

2.2 FrontPanel.................................................................................................................5

2.3 BlockDiagram.............................................................................................................7

2.4 ControlsPalette........................................................................................................10

2.4.1 NumericSubPalette..........................................................................................12

2.4.2 BooleanSubPalette..........................................................................................12

2.4.3 String&PathSubPalette..................................................................................13

2.5 FunctionPalette........................................................................................................13

2.6 ToolsPalette.............................................................................................................14

2.7 Wiring.......................................................................................................................16

2.8 Toolbar......................................................................................................................16

2.9 Execution..................................................................................................................17

2.10 TheObjectsshort-cutmenu.................................................................................18

2.11 DataflowProgramming.........................................................................................19

2.12 Help.......................................................................................................................20

Exercises..............................................................................................................................20

Page 4: Introduction to LabVIEW - HiT

iv TableofContents

Tutorial:AnIntroductiontoLabVIEW

3 SubVIs.............................................................................................................................24

3.1 CreateNewSubVIfromScratch...............................................................................25

3.1.1 InputandOutputSubVIConnectors.................................................................26

3.1.2 IconEditor.........................................................................................................28

3.2 CreateSubVIfromexistingcode..............................................................................29

3.3 UsingSubVIs............................................................................................................30

Exercises..............................................................................................................................31

4 CustomizeLabVIEW.........................................................................................................33

Exercises..............................................................................................................................34

5 LoopsandStructures.......................................................................................................35

5.1 Loops.........................................................................................................................35

5.1.1 ForLoop.............................................................................................................36

5.1.2 WhileLoop........................................................................................................37

5.2 Structures.................................................................................................................38

5.2.1 CaseStructure...................................................................................................38

5.2.2 SequenceStructure...........................................................................................39

5.2.3 EventStructure..................................................................................................40

Exercises..............................................................................................................................42

6 TroubleshootingandDebugging.....................................................................................45

6.1 Howtofinderrors....................................................................................................45

6.2 HighlightExecution...................................................................................................45

6.3 Probes.......................................................................................................................46

6.4 Breakpoints...............................................................................................................47

6.5 Stepinto/over/outdebugging..................................................................................48

Exercises..............................................................................................................................48

Page 5: Introduction to LabVIEW - HiT

v TableofContents

Tutorial:AnIntroductiontoLabVIEW

7 WorkingwithData..........................................................................................................50

7.1 Arrays........................................................................................................................50

7.1.1 Auto-Indexing....................................................................................................50

7.1.2 ArrayFunctions.................................................................................................51

7.2 Cluster.......................................................................................................................53

7.2.1 ClusterOrder.....................................................................................................54

7.2.2 ClusterElements................................................................................................55

Exercises..............................................................................................................................56

8 WorkingwithStrings.......................................................................................................58

Exercises..............................................................................................................................60

9 ErrorHandling.................................................................................................................62

9.1 FindingError.............................................................................................................62

9.2 ErrorWiring..............................................................................................................62

9.3 ErrorHandlinginSubVIs...........................................................................................63

9.4 ErrorHandling...........................................................................................................64

Exercises..............................................................................................................................65

10 WorkingwithProjects..................................................................................................66

10.1 ProjectExplorer.....................................................................................................66

10.2 Deployment...........................................................................................................67

Exercises..............................................................................................................................69

11 DesignTechniques........................................................................................................71

11.1 ForceProgramFlow..............................................................................................71

11.2 ShiftRegister.........................................................................................................72

11.3 StateProgrammingArchitecture..........................................................................73

11.4 MultipleLoops/Parallelprogramming..................................................................75

Page 6: Introduction to LabVIEW - HiT

vi TableofContents

Tutorial:AnIntroductiontoLabVIEW

11.5 Templates..............................................................................................................77

Exercises..............................................................................................................................78

12 UserInterface...............................................................................................................80

12.1 VIProperties.........................................................................................................81

Exercises..............................................................................................................................84

13 PlottingData.................................................................................................................85

13.1 Customizing...........................................................................................................87

Exercises..............................................................................................................................89

14 Tips&Tricks.................................................................................................................91

14.1 10functionsyouneedtoknowabout..................................................................91

14.2 The10mostusefulShort-cuts..............................................................................96

15 ExampleApplication.....................................................................................................97

16 AdditionalExercises...................................................................................................101

17 What’sNext?..............................................................................................................106

17.1 MyBlog...............................................................................................................106

17.2 Tutorials..............................................................................................................106

17.3 AdditionalResources..........................................................................................106

17.4 Examples.............................................................................................................107

QuickReference....................................................................................................................108

Page 7: Introduction to LabVIEW - HiT

1

1 IntroductionLabVIEW(shortforLaboratoryVirtualInstrumentationEngineeringWorkbench)isaplatformanddevelopmentenvironmentforavisualprogramminglanguagefromNationalInstruments.Thegraphicallanguageisnamed"G".OriginallyreleasedfortheAppleMacintoshin1986,LabVIEWiscommonlyusedfordataacquisition,instrumentcontrol,andindustrialautomationonavarietyofplatformsincludingMicrosoftWindows,variousflavorsofUNIX,Linux,andMacOSX.ThelatestversionofLabVIEWisversionLabVIEW2011.VisitNationalInstrumentsatwww.ni.com.

Thecodefileshavetheextension“.vi”,whichisanabbreviationfor“VirtualInstrument”.LabVIEWofferslotsofadditionalAdd-OnsandToolkits.

1.1 DataflowProgrammingTheprogramminglanguageusedinLabVIEW,alsoreferredtoasG,isadataflowprogramminglanguage.Executionisdeterminedbythestructureofagraphicalblockdiagram(theLV-sourcecode)onwhichtheprogrammerconnectsdifferentfunction-nodesbydrawingwires.Thesewirespropagatevariablesandanynodecanexecuteassoonasallitsinputdatabecomeavailable.Sincethismightbethecaseformultiplenodessimultaneously,Gisinherentlycapableofparallelexecution.Multi-processingandmulti-threadinghardwareisautomaticallyexploitedbythebuilt-inscheduler,whichmultiplexesmultipleOSthreadsoverthenodesreadyforexecution.

1.2 GraphicalProgrammingLabVIEWtiesthecreationofuserinterfaces(calledfrontpanels)intothedevelopmentcycle.LabVIEWprograms/subroutinesarecalledvirtualinstruments(VIs).EachVIhasthreecomponents:ablockdiagram,afrontpanel,andaconnectorpanel.ThelastisusedtorepresenttheVIintheblockdiagramsofother,callingVIs.Controlsandindicatorsonthefrontpanelallowanoperatortoinputdataintoorextractdatafromarunningvirtualinstrument.However,thefrontpanelcanalsoserveasaprogrammaticinterface.Thusavirtualinstrumentcaneitherberunasaprogram,withthefrontpanelservingasauserinterface,or,whendroppedasanodeontotheblockdiagram,thefrontpaneldefinestheinputsandoutputsforthegivennodethroughtheconnectorpane.ThisimplieseachVIcanbeeasilytestedbeforebeingembeddedasasubroutineintoalargerprogram.

Page 8: Introduction to LabVIEW - HiT

2 Introduction

Tutorial:AnIntroductiontoLabVIEW

Thegraphicalapproachalsoallowsnon-programmerstobuildprogramssimplybydragginganddroppingvirtualrepresentationsoflabequipmentwithwhichtheyarealreadyfamiliar.TheLabVIEWprogrammingenvironment,withtheincludedexamplesandthedocumentation,makesitsimpletocreatesmallapplications.Thisisabenefitononeside,butthereisalsoacertaindangerofunderestimatingtheexpertiseneededforgoodquality"G"programming.Forcomplexalgorithmsorlarge-scalecode,itisimportantthattheprogrammerpossessanextensiveknowledgeofthespecialLabVIEWsyntaxandthetopologyofitsmemorymanagement.ThemostadvancedLabVIEWdevelopmentsystemsofferthepossibilityofbuildingstand-aloneapplications.Furthermore,itispossibletocreatedistributedapplications,whichcommunicatebyaclient/serverscheme,andarethereforeeasiertoimplementduetotheinherentlyparallelnatureofG-code.

1.3 BenefitsOnebenefitofLabVIEWoverotherdevelopmentenvironmentsistheextensivesupportforaccessinginstrumentationhardware.Driversandabstractionlayersformanydifferenttypesofinstrumentsandbusesareincludedorareavailableforinclusion.Thesepresentthemselvesasgraphicalnodes.Theabstractionlayersofferstandardsoftwareinterfacestocommunicatewithhardwaredevices.Theprovideddriverinterfacessaveprogramdevelopmenttime.ThesalespitchofNationalInstrumentsis,therefore,thatevenpeoplewithlimitedcodingexperiencecanwriteprogramsanddeploytestsolutionsinareducedtimeframewhencomparedtomoreconventionalorcompetingsystems.Anewhardwaredrivertopology(DAQmxBase),whichconsistsmainlyofG-codedcomponentswithonlyafewregistercallsthroughNIMeasurementHardwareDDK(DriverDevelopmentKit)functions,providesplatformindependenthardwareaccesstonumerousdataacquisitionandinstrumentationdevices.TheDAQmxBasedriverisavailableforLabVIEWonWindows,MacOSXandLinuxplatforms.

Thisdocumentintroducingthefollowingthemes:

• StartusingLabVIEWo TheLabVIEWEnvironmento FrontPanelandBlockDiagramo Palettes:ControlPalette,FunctionsPalette,ToolsPaletteo DataTypeso PropertyNodes

• SubVIs• LoopsandStructures• TroubleshootingandDebugging• WorkingwithData

Page 9: Introduction to LabVIEW - HiT

3 Introduction

Tutorial:AnIntroductiontoLabVIEW

o Arrays§ ArrayFunctions

o Cluster• WorkingwithStrings• ErrorHandling• WorkingwithProjectsusingProjectExplorer• DesignTechniques

o ShiftRegistero StateMachineo MultipleLoops

• UserInterface• PlottingData• Deployment:BuildingExecutableApplications(.exe)• IntroductiontoAdd-OnsandToolkits

o Brieflyexplanations…o MoredetailaboutControlandSimulationModuleinlater

• IntroductiontoDAQ-DataAcquisitiono MAX–MeasurementandAutomationExplorero NI-DAQmx

• QuickReferencewithKeyboardShort-cuts

FormoreinformationaboutLabVIEW,visitmyBlog:http://home.hit.no/~hansha/

Page 10: Introduction to LabVIEW - HiT

4

2 StartusingLabVIEWThischapterexplainsthebasicconceptsinLabVIEW.

Thetopicsareasfollows:

• TheLabVIEWEnvironment• FrontPanelandBlockDiagram• Palettes:ControlPalette,FunctionsPalette,ToolsPalette• DataTypes• PropertyNodes

2.1 TheLabVIEWEnvironmentLabVIEWprogramsarecalledVirtualInstruments,orVIs,becausetheirappearanceandoperationimitatephysicalinstruments,suchasoscilloscopesandmultimeters.LabVIEWcontainsacomprehensivesetoftoolsforacquiringanalyzing,displaying,andstoringdata,aswellastoolstohelpyoutroubleshootyourcode.

WhenopeningLabVIEW,youfirstcometothe“GettingStarted”window.

Page 11: Introduction to LabVIEW - HiT

5 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

InordertocreateanewVI,select“BlankVI”orinordertocreateanewLabVIEWproject,select“Emptyproject”.

WhenyouopenablankVI,anuntitledfrontpanelwindowappears.ThiswindowdisplaysthefrontpanelandisoneofthetwoLabVIEWwindowsyouusetobuildaVI.Theotherwindowcontainstheblockdiagram.Thesectionsbelowdescribethefrontpanelandtheblockdiagram.

2.2 FrontPanelWhenyouhavecreatedanewVIorselectedanexistingVI,theFrontPanelandtheBlockDiagramforthatspecificVIwillappear.

InLabVIEW,youbuildauserinterface,orfrontpanel,withcontrolsandindicators.Controlsareknobs,pushbuttons,dials,andotherinputdevices.Indicatorsaregraphs,LEDs,andotherdisplays.

Youbuildthefrontpanelwithcontrolsandindicators,whicharetheinteractiveinputandoutputterminalsoftheVI,respectively.Controlsareknobs,pushbuttons,dials,andotherinputdevices.Indicatorsaregraphs,LEDs,andotherdisplays.Controlssimulateinstrument

Page 12: Introduction to LabVIEW - HiT

6 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

inputdevicesandsupplydatatotheblockdiagramoftheVI.Indicatorssimulateinstrumentoutputdevicesanddisplaydatatheblockdiagramacquiresorgenerates.

E.g.,a“Numeric”caneitherbea“NumericControl”ora“NumericIndicator”,asseenbelow.

Iyouselecta“NumericControl”,itcaneasybechangedtoan“NumericIndicator”byrightclickontheobjectanselect“ChangetoIndicator”

Oropposite,Iyouselecta“NumericIndicator”,itcaneasybechangedtoan“NumericControl”byrightclickontheobjectanselect“ChangetoControl”

Page 13: Introduction to LabVIEW - HiT

7 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

Thedifferencebetweena“NumericControl”anda“NumericIndicator”isthatfora“NumericControl”youmayenteravalue,whilethe“NumericIndicator”isread-only,i.e.,youmayonlyreadthevalue,notchangeit.

Theappearanceisalsoslightlydifferent,the“NumericControl”hasanincrementandandecrementbuttoninfront,whilethe“NumericIndicator”hasadarkerbackgroundcolorinordertoindicatethatitsread-only.

2.3 BlockDiagramAfteryoubuildtheuserinterface,youaddcodeusingVIsandstructurestocontrolthefrontpanelobjects.Theblockdiagramcontainsthiscode.Insomeways,theblockdiagramresemblesaflowchart.

Page 14: Introduction to LabVIEW - HiT

8 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

Afteryoubuildthefrontpanel,youaddcodeusinggraphicalrepresentationsoffunctionstocontrolthefrontpanelobjects.Theblockdiagramcontainsthisgraphicalsourcecode.Frontpanelobjectsappearasterminals,ontheblockdiagram.Blockdiagramobjectsincludeterminals,subVIs,functions,constants,structures,andwires,whichtransferdataamongotherblockdiagramobjects.

TheFigurebelowshowsafrontpanelanditscorrespondingblockdiagramwithfrontpanelandblockdiagramcomponents.

Page 15: Introduction to LabVIEW - HiT

9 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

Thedifferentcomponentsareasfollows:

1. Toolbar2. OwnedLabel3. NumericControl4. FreeLabel5. NumericControlTerminal6. KnobTerminal7. NumericConstant8. MultiplyFunction9. Icon10. KnobControl11. PlotLegend 12. XYGraph

Page 16: Introduction to LabVIEW - HiT

10 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

13. WireDataPath14. XYGraphTerminal15. BundleFunction16. SubVI17. ForLoopStructure

2.4 ControlsPaletteTheControlsandFunctionspalettescontainsubpalettesofobjectsyoucanusetocreateaVI.Whenyouclickasubpaletteicon,theentirepalettechangestothesubpaletteyouselected.Touseanobjectonthepalettes,clicktheobjectandplaceitonthefrontpanelorblockdiagram.TheControlspaletteisavailableonlyonthefrontpanel.TheControlspalettecontainsthecontrolsandindicatorsyouusetobuildthefrontpanel.

ThemostusedSubPalettesaretheNumericSubPalette,theBooleanSubPaletteandtheString&PathSubPalette.

YoumaychangetheappearanceandthecontentsoftheControlspalette:

Page 17: Introduction to LabVIEW - HiT

11 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

YoumayPinthepalette,soitisalwaysvisible,justclickthelittlepinbutton intheupperleftcornerofthepalette:

Ifyouwanttochangethecontentandappearanceofthepalette,clickthe“View”button.

Hereyoumaychangethewaythepaletteshouldlook.

Ifyouclick“ChangeVisibleCategories…”youmaychangewhichCategoriesyouwanttohavevisible.

Page 18: Introduction to LabVIEW - HiT

12 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

2.4.1 NumericSubPalette

“NumericalControl”and“NumericalIndicator”arethemostusedobjectsinthenumericsubpalette.

2.4.2 BooleanSubPalette

Thispalettehaslotsofdifferentbuttonsyoumayuse.OK,CancelandStopbuttonsareuseful.

Page 19: Introduction to LabVIEW - HiT

13 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

2.4.3 String&PathSubPalette

IntheStringandPathpalettewehaveStringControls,ComboBox,etc.

2.5 FunctionPaletteTheFunctionspaletteisavailableonlyontheblockdiagram.TheFunctionspalettecontainstheVIsandfunctionsyouusetobuildtheblockdiagram.

Page 20: Introduction to LabVIEW - HiT

14 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

2.6 ToolsPaletteYoucancreate,modify,anddebugVIsusingthetoolslocatedonthefloatingToolspalette.TheToolspaletteisavailableonboththefrontpanelandtheblockdiagram.Atoolisaspecialoperatingmodeofthemousecursor.ThecursorcorrespondstotheiconofthetoolselectedintheToolspalette.Usethetoolstooperateandmodifyfrontpanelandblockdiagramobjects.

Page 21: Introduction to LabVIEW - HiT

15 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

TheToolspaletteisavailablefromtheViewmenu:

Ifyoumakesure“Automaticwiring”isdisabled(Irecommendyoudoso!)youmayusetheTabkeyonyourkeyboardinordertoswitchbetweenthemostcommontools.

Themostusedtoolsare:

UsetheOperatingtool,shownatleft,tochangethevaluesofacontrolorselectthetextwithinacontrol.TheOperatingtoolchangestotheiconshownatleftwhenitmovesoveratextcontrol,suchasanumericorstringcontrol.

UsethePositioningtool,shownatleft,toselect,move,orresizeobjects.ThePositioningtoolchangestoresizinghandleswhenitmovesovertheedgeofaresizableobject.

UsetheLabelingtool,shownatleft,toedittextandcreatefreelabels.The

Labelingtoolchangestothefollowingicon whenyoucreatefreelabels.

UsetheWiringtool,shownatleft,towireobjectstogetherontheblockdiagram.

Page 22: Introduction to LabVIEW - HiT

16 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

2.7 WiringInordertocreatethelogicalflowbetweentheobjectontheBlockDiagram,youneedtousetheWiringtoolinordertoconnectthedifferentobjectstogether.

UsetheWiringtooltowireobjectstogetherontheblockdiagram.

AvailableKeyboardShortcutswhendealingwithWiring:

Ctrl-Bisveryuseful.Thisshort-cutremovesallbrokenwiresontheBlockDiagram.

2.8 ToolbarBelowweseetheLabVIEWToolbar:

Thebehaviorsofthedifferentbuttonsareasfollows:

Page 23: Introduction to LabVIEW - HiT

17 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

ClicktheRunbuttontorunaVI.LabVIEWcompilestheVI,ifnecessary.YoucanrunaVIiftheRunbuttonappearsasasolidwhitearrow.Thesolidwhitearrow,shownabove,alsoindicatesyoucanusetheVIasasubVIifyoucreateaconnectorpanefortheVI.

WhiletheVIruns,theRunbuttonappearsasshownatleftiftheVIisatop-levelVI,meaningithasnocallersandthereforeisnotasubVI.

IftheVIthatisrunningisasubVI,theRunbuttonappearsasshownatleft.

TheRunbuttonappearsbroken,shownatleft,whentheVIyouarecreatingoreditingcontainserrors.IftheRunbuttonstillappearsbrokenafteryounishwiringtheblockdiagram,theVIisbrokenandcannotrun.ClickthisbuttontodisplaytheErrorlistwindow,whichlistsallerrorsandwarnings.

ClicktheRunContinuouslybutton,shownatleft,toruntheVIuntilyouabortorpauseexecution.Youalsocanclickthebuttonagaintodisablecontinuousrunning.

WhiletheVIruns,theAbortExecutionbutton,shownatleft,appears.ClickthisbuttontostoptheVIimmediatelyifthereisnootherwaytostoptheVI.Ifmorethanonerunningtop-levelVIusestheVI,thebuttonisdimmed.

Note:AvoidusingtheAbortExecutionbuttontostopaVI.EitherlettheVIcompleteitsdataowordesignamethodtostoptheVIprogrammatically.Bydoingso,theVIisataknownstate.Forexample,placeabuttononthefrontpanelthatstopstheVIwhenyouclickit.

ClickthePausebutton,shownatleft,topausearunningVI.WhenyouclickthePausebutton,LabVIEWhighlightsontheblockdiagramthelocationwhereyoupausedexecution,andthePausebuttonappearsred.ClickthebuttonagaintocontinuerunningtheVI.

2.9 ExecutionInadditiontotheToolbarbuttonsabovethefollowingKeyboardShortcutsareavailablewhendealingwithExecution:

Page 24: Introduction to LabVIEW - HiT

18 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

2.10 TheObjectsshort-cutmenuThemostoften-usedmenuistheobjectshortcutmenu.AllLabVIEWobjectsandemptyspaceonthefrontpanelandblockdiagramhaveassociatedshortcutmenus.Usetheshortcutmenuitemstochangethelookorbehavioroffrontpanelandblockdiagramobjects.Toaccesstheshortcutmenu,right-clicktheobject,frontpanel,orblockdiagram.

TheNumericcontrolhasthefollowingshort-cut/right-clickmenu:

Theshort-cutmenuwillbedifferentforthedifferentcontrolsorobjects.

Page 25: Introduction to LabVIEW - HiT

19 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

2.11 DataflowProgrammingLabVIEWfollowsadataflowmodelforrunningVIs.Ablockdiagramnodeexecuteswhenallitsinputsareavailable.Whenanodecompletesexecution,itsuppliesdatatoitsoutputterminalsandpassestheoutputdatatothenextnodeinthedataflowpath.

VisualBasic,C++/C#,Java,andmostothertext-basedprogramminglanguagesfollowacontrolflowmodelofprogramexecution.Incontrolflow,thesequentialorderofprogramelementsdeterminestheexecutionorderofaprogram.

Example:DataflowProgramming

TheExampleshowsablockdiagramthataddstwonumbersandthensubtracts50.00fromtheresultoftheaddition.Inthiscase,theblockdiagramexecutesfromlefttoright,notbecausetheobjectsareplacedinthatorder,butbecausetheSubtractfunctioncannotexecuteuntiltheAddfunctionfinishesexecutingandpassesthedatatotheSubtractfunction.Rememberthatanodeexecutesonlywhendataareavailableatallofitsinputterminals,anditsuppliesdatatoitsoutputterminalsonlywhenitfinishesexecution.

Example:DataflowProgramming

Inthisexample,considerwhichcodesegmentwouldexecutefirst-theAdd,RandomNumber,orDividefunction.YoucannotknowbecauseinputstotheAddandDividefunctionsareavailableatthesametime,andtheRandomNumberfunctionhasnoinputs.Inasituationwhereonecodesegmentmustexecutebeforeanotherandnodatadependency

Page 26: Introduction to LabVIEW - HiT

20 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

existsbetweenthefunctions,useotherprogrammingmethods,suchaserrorclusters,toforcetheorderofexecution.

2.12 HelpTheContextHelpwindow(Ctrl+H)displaysbasicinformationaboutLabVIEWobjects

whenyoumovethecursorovereachobject.TheContextHelpwindowisvisiblebydefault.TotoggledisplayoftheContextHelpwindow,selectHelp-ShowContextHelp,presstheCtrl-Hkeys,orclicktheShowContextHelpWindowbuttononthetoolbar.

Whenyoumovethecursoroverfrontpanelandblockdiagramobjects,theContextHelpwindowdisplaystheiconforsubVIs,functions,constants,controls,andindicators,withwiresattachedtoeachterminal.Whenyoumovethecursoroverdialogboxoptions,theContextHelpwindowdisplaysdescriptionsofthoseoptions.Inthewindow,requiredconnectionsarebold,recommendedconnectionsareplaintext,andoptionalconnectionsaredimmedordonotappear.TheFigurebelowshowsanexampleoftheContextHelpwindow.

ExercisesExercise:CreateyourfirstLabVIEWapplication(VI)

CreateasimpleLabVIEWapplication(VI)withaFrontPanelwithsomeControlsandIndicators.CreatethelogicbyconnectingtheTerminalsontheBlockDiagram

TheFrontPanelcouldlooksomethinglikethis:

Page 27: Introduction to LabVIEW - HiT

21 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

TheBlockDiagramcouldlooksomethinglikethis:

StarttheprogramwiththeRunbutton.

Exercise:CreateasimpleCalculator

CreateasimplecalculatorthatAddandSubtract2numberslikethis:

Page 28: Introduction to LabVIEW - HiT

22 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

StarttheprogramwiththeRunbutton.

Exercise:WriteDatatoFile

CreateaVIthatwritesdatatoaTextFile.

UseVisorfunctionsfromtheFileI/Opalette

Theprogramcouldlooksomethinglikethis:

Page 29: Introduction to LabVIEW - HiT

23 StartusingLabVIEW

Tutorial:AnIntroductiontoLabVIEW

Exercise:ReadDatafromFile

CreateanotherVIthatreadthetextfileyoucreatedinthepreviousVI.

Page 30: Introduction to LabVIEW - HiT

24

3 SubVIsThischapterexplainsthebasicconceptsofcreatingandusingSubVIsinLabVIEW.

Topics:

• CreateNewSubVIfromScratch• CreateSubVIfromexistingcode• UsingSubVIs

WhenyouplaceaVIontheblockdiagram,LabVIEWconsiderstheVItobeasubVI.Whenyoudouble-clickasubVI,itsfrontpanelandblockdiagramappear,ratherthanadialogboxinwhichyoucanconfigureoptions.Thefrontpanelincludescontrolsandindicators.Theblockdiagramincludeswires,frontpanelicons,functions,possiblysubVIs,andotherLabVIEWobjects.Theupperrightcornerofthefrontpanelandblockdiagramdisplays.

BelowweseeanexampleofabadBlockDiagram.ThisexampledoesnotmakeuseoftheSubVIfunctionalityinLabVIEWatall!ThismakestheBlockdiagramhardtoreadandunderstand.Thesizeofthediagramisalsotoolarge!TheBlockDiagramshouldalwaysfitintothescreen.BoththeFrontPanelandtheBlockDiagramshouldfitintoascreenresolutionof1024x768.

Page 31: Introduction to LabVIEW - HiT

25 SubVIs

Tutorial:AnIntroductiontoLabVIEW

WithuseofSubVIs,theexampleabovecouldturninto,e.g.:

Asyoucansee,muchofthecodeintheMainVIhavebeenreplacedandputintoSubVIs.Theprogramisnowmorereadable.

Anotherapproachistouseaso-calledStateMachineprinciple(moreaboutthisinchapter11-DesignTechniques).

AvailableKeyboardShortcutswhendealingwithSubVis:

3.1 CreateNewSubVIfromScratch

Page 32: Introduction to LabVIEW - HiT

26 SubVIs

Tutorial:AnIntroductiontoLabVIEW

Select“BlankVI”inthe“GettingStarted”windowwhenopeningLabVIEW,orwhenLabVIEWisalreadyopenedselectFile→NewV”orusetheshort-cutCtrl+N.

3.1.1 InputandOutputSubVIConnectors

MostSubVIswillhaveinputandoutput“connectors”.Thisissimilarwithfunctionsormethodsinotherprogramminglanguagethathaveinputargumentsandanoutput/result.

Inordertocreateconnectors,Right-clickontheiconintheupperrightcorneroftheVIandselect“ShowConnector”.

YoumayselectdifferentPatterns,i.e.,howmanyinputandoutputconnectorsyouneed.

Page 33: Introduction to LabVIEW - HiT

27 SubVIs

Tutorial:AnIntroductiontoLabVIEW

MakesureyouselectaPatternwithenoughconnectorsevenifyoudon’tneedalltheconnectorsatthemoment.IrecommendthatyoustandardizeonthepatternintheFigureabove.

SelecttheWiretoolandclickonthewantedconnector,thenclickontheControlorIndicatorontheFrontPanelyouwanttoconnecttothisconnector.

Youshouldalwaysfollowtheseconnectorrules:

• Upperleftconnector:“Reference”In• Upperrightconnector:“Reference”Out• Lowerleftconnector:ErrorInCluster• Lowerrightconnector:ErrorOutCluster

Example:SubVIConnectors

Seeexamplebelowabouttheseconnectorrules:

Page 34: Introduction to LabVIEW - HiT

28 SubVIs

Tutorial:AnIntroductiontoLabVIEW

MostcommonVIsthatexitsfollowtheserules,seeexamplebelow.

Ifyoufollowtheseconnectorrulesit’smucheasiertocreateacleanandneatcodelikethis:

Bydoingthisit’salsoclearhowtheDataflowsintheprogram.Itshouldalwaysflowfromlefttoright.

3.1.2 IconEditor

YoushouldalsocreateasuitableiconforyourSubVI.

InordertoopentheIconEditor,double-clickontheiconintheupperrightcornerofyourVI.

Page 35: Introduction to LabVIEW - HiT

29 SubVIs

Tutorial:AnIntroductiontoLabVIEW

BelowweseeablockdiagramwithSubVIsiconappearancecreatedwiththeIconEditor.

3.2 CreateSubVIfromexistingcodeIfyoufindoutthatyoucodeisgettingmessy,youcouldconsiderputsomecodeintoaSubVI.

Theprocedureisasfollows:

1. SelectthepartofyourcodeyouwanttoturnintoaSubVI2. FromtheEditmenu,select“CreateSubVI”

Page 36: Introduction to LabVIEW - HiT

30 SubVIs

Tutorial:AnIntroductiontoLabVIEW

3. LabVIEWwillautomaticallycreateaSubVIfortheselectedcode.4. Cleanupautomaticallycreatedwires,etc.5. CreateasuitableiconforyourSubVI

Althoughthisisquiteeasytodothis,Idonotrecommendthatyouusethisfunctionalitytomuch.ThisisbecauseyoushouldcreateanduseSubVIsfromthefirstmomentyoustartcreatingyourapplicationandnotafterwardswhenyoufindoutthatyouhavebeencreatingamessycode.

SoyoushouldstructureanddesignyourcodewiththeuseofSubVIsfromthebeginning!

3.3 UsingSubVIsBelowweseeanexampleofhowtouseSubVIsinaprogram(TopVIorSubVIs):

YoumayopenaSubVIfromtheFilemenu,selectaSubVIfromtheFunctionspaletteorusedraganddropindifferentways,e.g.,youmaydragaVIfromtheFileExplorerinWindowsdirectlyintoanexistingVIyouhavealreadyopenedinLabVIEW

Page 37: Introduction to LabVIEW - HiT

31 SubVIs

Tutorial:AnIntroductiontoLabVIEW

ExercisesExercise:ConvertCtoFVI

CreateaSubVIthatconvertaTemperatureinCelsiustoaTemperatureinFahrenheit

1. CreatetheSubVI2. CreatetheFrontPanelandtheBlockDiagramasshownabove3. CreatenecessaryConnectors4. Createasuitableicon,e.g.:

5. UsetheSubVIinanotherVI6. Runtheprogramtoseeifitworks7. ExpandtheprogramsoyoucanselectifyouwanttoconvertfromCelsiusto

FahrenheitorfromFahrenheittoCelsius

Exercise:ConvertexistingcodeintoaSubVI

Page 38: Introduction to LabVIEW - HiT

32 SubVIs

Tutorial:AnIntroductiontoLabVIEW

ConvertapartofyourapplicationintoaSubVIbyusingtheCreateSubVIfunctioninLabVIEW.

Page 39: Introduction to LabVIEW - HiT

33

4 CustomizeLabVIEWLabVIEWhaslotsofpossibilitiesforcustomizingtheappearanceandtheuseoftheLabVIEWenvironment.Select“Options…”fromtheToolsmenu.

Thedefaultsettingsisnotnecessarythebest,herearesomerecommendationsforsettinguptheLabVIEWenvironment.

Category:BlockDiagram

Page 40: Introduction to LabVIEW - HiT

34 CustomizeLabVIEW

Tutorial:AnIntroductiontoLabVIEW

• Disable“Enableautowiring”option.ThispreventsLabVIEWfromautomaticallyconnectingadjacentblocks.Althoughitseemsusefultohaveautowiringenables,itismyexperiencethattheautowiringisalittleannoyingsinceittendstodrawwiresbetweenblockswhenyoudonotwantanywire.

• Disable“Placefrontpanelelementsasicons”option.ThiscausesLabVIEWtousesmallterminaliconsontheblockdiagram.Ifyou,instead,activatethisoption,theterminaliconsarelarger,withamimicoftheelementasitappearsatthefrontpanel.

Category:Controls/FunctionsPalettes

• IntheFormatlist: select“Category(IconsandText)”

Category:AlignmentGrid

• Turnoff“ShowFrontPanelGrid”and“ShowBlockDiagramGrid”

ExercisesExercise:CustomizeLabVIEW

Trythedifferentsettingsexplainedinthischapter.Turnthemonandoffandwatchthedifferent.

Page 41: Introduction to LabVIEW - HiT

35

5 LoopsandStructuresThischapterexplainsthebasicconceptsofLoopsandStructuresinLabVIEW.

Thetopicsareasfollows:

• ForLoop• WhileLoop• CaseStructure• SequenceStructure• EventStructure

ThedifferentLoopsandStructuresavailablearelocatedinthe“Structures”subpaletteintheFunctionspaletteontheBlockDiagram.

5.1 LoopsThemostimportantloopsare:

• ForLoop• WhileLoop

Page 42: Introduction to LabVIEW - HiT

36 LoopsandStructures

Tutorial:AnIntroductiontoLabVIEW

Theseloopswillbeexplainedindetailbelow.

5.1.1 ForLoop

AForLoopexecutesasubdiagramasetnumberoftimes.TheFigurebelowshowsanemptyForLoopinLabVIEW.

AForloopexecutesitssubdiagramntimes,wherenisthevaluewiredtothecount( )terminal.Theiteration( )terminalprovidesthecurrentloopiterationcount,whichrangesfrom0ton-1.

AfteryoucreateaForLoop,youcanuseshiftregisterstopassvaluesfromoneiterationtothenext.IfyouwireanarraytoaForLoop,youcanreadandprocesseveryelementinthatarraybyenablingauto-indexing.Youalsocanenableauto-indexingbyconfiguringaForLooptoreturnanarrayofeveryvaluegeneratedbytheloop.

YoucanaddaconditionalterminaltoconfigureaForLooptostopwhenaBooleanconditionoranerroroccurs.AForLoopwithaconditionalterminalexecutesuntiltheconditionoccursoruntilalliterationscomplete,whicheverhappensfirst.ToaddaconditionalterminaltoaForLoop,right-clicktheForLoopborderandselectConditionalTerminalfromtheshortcutmenu.Youmustwiretheconditionalterminalandeitherwirethecountterminalorauto-indexaninputarrayforthelooptoexecuteandfortheVItorun.

ToconvertaForLooptoaWhileLoop,right-clicktheForLoopandselectReplacewithWhileLoopfromtheshortcutmenu.

Example:ForLoop

ThefollowingexampleusesaForLoopinordertocreateanarraywith10elementsandfillitwithrandomnumbers.

Page 43: Introduction to LabVIEW - HiT

37 LoopsandStructures

Tutorial:AnIntroductiontoLabVIEW

5.1.2 WhileLoop

AWhilelooprepeatsthesubdiagraminsideituntiltheconditionalterminal,aninputterminal,receivesaparticularBooleanvalue.TheBooleanvaluedependsonthecontinuationbehavioroftheWhileLoop.Right-clicktheconditionalterminalandselectStopifTrueorContinueifTruefromtheshortcutmenu.Youalsocanwireanerrorclustertotheconditionalterminal,right-clicktheterminal,andselectStoponErrororContinuewhileErrorfromtheshortcutmenu.TheWhileLoopalwaysexecutesatleastonce.

BelowweseeanemptyWhileloop:

AfteryoucreateaWhileLoop,youcanuseshiftregisterstopassvaluesfromoneiterationtothenext.IfyouwireanarraytoaWhileLoop,youcanreadandprocesseveryelementinthatarraybyenablingauto-indexing.

InordertoconvertaWhileLoopintoaForLoop,right-clicktheWhileLoopandselect“ReplacewithForLoop”fromtheshortcutmenu.ToconvertaWhileLoopintoaTimedLoop,right-clicktheWhileLoopandselect“ReplacewithTimedLoop”fromtheshortcutmenu.

Example:WhileLoop

Page 44: Introduction to LabVIEW - HiT

38 LoopsandStructures

Tutorial:AnIntroductiontoLabVIEW

Thisexamplerununtileithertheuserclicksthestopbuttonornumberofiterationsisgreaterthan10.

5.2 Structures

5.2.1 CaseStructure

TheCaseStructurehasoneormoresubdiagrams,orcases,exactlyoneofwhichexecuteswhenthestructureexecutes.ThevaluewiredtotheselectorterminaldetermineswhichcasetoexecuteandcanbeBoolean,string,integer,orenumeratedtype.Youmayright-clickthestructurebordertoaddordeletecases.UsetheLabelingtooltoentervalue(s)inthecaseselectorlabelandconfigurethevalue(s)handledbyeachcase.

BelowweseeanemptyCasestructure:

BelowweseeanexampleofaCasestructurewith2cases,a“True”caseanda“False”case.DependingoftheBooleaninputvalue,theNumeric1andNumeric2iseitherAddedorSubtracted.

Page 45: Introduction to LabVIEW - HiT

39 LoopsandStructures

Tutorial:AnIntroductiontoLabVIEW

5.2.2 SequenceStructure

ASequencestructureConsistsofoneormoresubdiagrams,orframes,thatexecutesequentially.Right-clickthestructurebordertoaddanddeleteframesortocreatesequencelocalstopassdatabetweenframes.UsetheStackedSequencestructuretoensureasubdiagramexecutesbeforeorafteranothersubdiagram.

BelowweseeanemptySequencestructure.

Page 46: Introduction to LabVIEW - HiT

40 LoopsandStructures

Tutorial:AnIntroductiontoLabVIEW

Belowweseeanexamplewhereweuse“SequenceLocal”,i.e.,wepassavaluefromone

sequencetothenext

Note!TotakeadvantageoftheinherentparallelisminLabVIEW,avoidoverusingSequencestructures.Sequencestructuresguaranteetheorderofexecution,butprohibitparalleloperations.AnothernegativetousingSequencestructuresisthatyoucannotstoptheexecutionpartwaythroughthesequence.

5.2.3 EventStructure

AnEventstructurehasoneormoresubdiagrams,oreventcases,exactlyoneofwhichexecuteswhenthestructureexecutes.TheEventstructurewaitsuntilaneventhappens,thenexecutestheappropriatecasetohandlethatevent.Right-clickthestructurebordertoaddneweventcasesandconfigurewhicheventstohandle.WireavaluetotheTimeoutterminalatthetopleftoftheEventstructuretospecifythenumberofmillisecondstheEventstructureshouldwaitforaneventtooccur.Thedefaultis–1,indicatingnevertotimeout.

Belowweseeanexample:

Page 47: Introduction to LabVIEW - HiT

41 LoopsandStructures

Tutorial:AnIntroductiontoLabVIEW

Right-clickontheborderinordertoAdd/EditEventCases,seethedialogboxbelow.

Page 48: Introduction to LabVIEW - HiT

42 LoopsandStructures

Tutorial:AnIntroductiontoLabVIEW

ExercisesExercise:ForLoop

CreateaVIwithaForLoop.Createthelogictofindoutifanumberinanarrayisgreaterthan10.SeeFrontPanelbelow:

Page 49: Introduction to LabVIEW - HiT

43 LoopsandStructures

Tutorial:AnIntroductiontoLabVIEW

Exercise:WhileLoop

CreateaVIwithaWhileLoop.Createthelogictofindoutwhich(thefirst)indexinthearraythathaveanumbergreaterthan30.SeeFrontPanelbelow:

Exercise:CaseStructure

CreateaVIwithaCaseStructure.

UseaCasestructureinsideaForLooptowritethetext“TheNumberisgreaterthan10”ifvalueisgreaterthan10.SeeFrontPanelbelow:

Page 50: Introduction to LabVIEW - HiT

44 LoopsandStructures

Tutorial:AnIntroductiontoLabVIEW

Exercise:SequenceStructure

CreateaVIwithaSequenceStructure.SeeFrontPanelbelow:

Exercise:EventStructure

CreateaVIwithanEventStructure.SeeFrontPanelbelow:

Page 51: Introduction to LabVIEW - HiT

45

6 TroubleshootingandDebugging

ThischapterexplainsthebasicconceptsoftroubleshootinganddebugginginLabVIEW.

Topics:

• Howtofinderrors• HighlightExecution• Probes• Breakpoints• Stepinto/over/outdebugging

6.1 Howtofinderrors IfaVIdoesnotrun,itisabroken,or“nonexecutable”,VI.TheRunbuttonoften

appearsbroken,shownatleft,whenyoucreateoreditaVI.Ifitisstillbrokenwhenyoufinishwiringtheblockdiagram,theVIisbrokenandwillnotrun.Generally,thismeansthatarequiredinputisnotwired,orawireisbroken.

ClickthebrokenRunbuttontodisplaytheErrorlistwindow,whichlistsalltheerrors.Double-clickanerrordescriptiontodisplaytherelevantblockdiagramorfrontpanelandhighlighttheobjectthatcontainstheerror.

6.2 HighlightExecution ViewananimationoftheexecutionoftheblockdiagrambyclickingtheHighlight

Executionbutton.Executionhighlightingshowstheflowofdataontheblockdiagramfromonenodetoanotherusingbubblesthatmovealongthewires.Note!ExecutionhighlightinggreatlyreducesthespeedatwhichtheVIruns.

Page 52: Introduction to LabVIEW - HiT

46 TroubleshootingandDebugging

Tutorial:AnIntroductiontoLabVIEW

6.3 Probes UsetheProbetooltocheckintermediatevaluesonawireasaVIruns.

Whenexecutionpausesatanodebecauseofsingle-steppingorabreakpoint,youalsocanprobethewirethatjustexecutedtoseethevaluethatflowedthroughthatwire.Youalsocancreateacustomprobetospecifywhichindicatoryouusetoviewtheprobeddata.Forexample,ifyouareviewingnumericdata,youcanchoosetoseethatdatainachartwithintheprobe.Tocreateacustomprobe,right-clickawireandselectCustomProbe-Newfromtheshortcutmenu.

Page 53: Introduction to LabVIEW - HiT

47 TroubleshootingandDebugging

Tutorial:AnIntroductiontoLabVIEW

6.4 Breakpoints

UsetheBreakpointtooltoplaceabreakpointonaVI,node,orwireontheblockdiagramandpauseexecutionatthatlocation.Whenyousetabreakpointonawire,executionpausesafterdatapassthroughthewire.Placeabreakpointontheblockdiagramworkspacetopauseexecutionafterallnodesontheblockdiagramexecute.WhenaVIpausesatabreakpoint,LabVIEWbringstheblockdiagramtothefrontandusesamarqueetohighlightthenodeorwirethatcontainsthebreakpoint.LabVIEWhighlightsbreakpointswithredbordersfornodesandblockdiagramsandredbulletsforwires.Whenyoumovethecursoroveranexistingbreakpoint,theblackareaoftheBreakpointtoolcursorappearswhite.UsetheBreakpointtooltoclickanexistingbreakpointtoremoveit.

Youmayalsoright-clickonthewireinordertosetabreakpointoropentheBreakpointManager.

BreakpointManagerisatoolforenable,disableanddeletebreakpoints.

Page 54: Introduction to LabVIEW - HiT

48 TroubleshootingandDebugging

Tutorial:AnIntroductiontoLabVIEW

6.5 Stepinto/over/outdebuggingAvailableKeyboardShortcutswhenDebugging:

ExercisesExercise:HighlightExecution

Enable“HighlightExecution”inoneofyourprograms,andseehowitworks.

Exercise:Probes

SetSeveralProbesaroundinyourapplicationandwatchhowitworks.UsetheProbewatchWindowandcheckoutthefunctionalitythistooloffers.

Alsocheckoutthe“CustomProbe”andthe“FindProbe”functionality.

Page 55: Introduction to LabVIEW - HiT

49 TroubleshootingandDebugging

Tutorial:AnIntroductiontoLabVIEW

Exercise:Breakpoints

SetsomeBreakpointaroundinyourcodeandcheckouthowitworks.UsetheBreakpointManagertool.

Example:

Exercise:Stepinto/over/outdebugging

UsetheStepinto/over/outfunctionalitytogetherwithyourBreakpointsandlearnhowyoucanusethemandseewhatthedifferencebetweenthemis.

Page 56: Introduction to LabVIEW - HiT

50

7 WorkingwithDataThischapterexplainsthebasicconceptsofcreatingandusingSubVisinLabVIEW.

Topics:

• Arrays• ArrayFunctions• Cluster

7.1 ArraysArraysareverypowerfultouseinLabVIEW.InallyourapplicationsyouwouldprobablyusebothOne-DimensionalArraysandTwo-DimensionalArrays.

7.1.1 Auto-Indexing

LabVIEWusesapowerfulmechanismcalled“Auto-indexing”.

ForExampleyoumayuseaForlooptocreateArraydatalikethis:

OryoumayuseanArraylikethisinordertoautomaticallyspecifynumberofiterations:

Page 57: Introduction to LabVIEW - HiT

51 WorkingwithData

Tutorial:AnIntroductiontoLabVIEW

7.1.2 ArrayFunctions

LabVIEWhaslotsofbuilt-infunctionsformanipulatingarrays.

ThemostusefulArrayfunctionsare:

ArraySize

IndexArray

Page 58: Introduction to LabVIEW - HiT

52 WorkingwithData

Tutorial:AnIntroductiontoLabVIEW

DeletefromArray

Search1DArray

InitializeArray

BuildArray

ArraySubset

ArrayConstant

Allthesefunctionsarebasic(butveryuseful)arrayfunctionsyouwillprobablybeusinginallyourapplicationsandVIs.

Example:Arrayfunctions

InthisexampleweseehowwecanusetheseArrayfunctionsandwhattheydo.

TheresultingFrontPanelisasfollows:

Page 59: Introduction to LabVIEW - HiT

53 WorkingwithData

Tutorial:AnIntroductiontoLabVIEW

7.2 ClusterClustersgroupdataelementsofmixedtypes,suchasabundleofwires,asinatelephonecable,whereeachwireinthecablerepresentsadifferentelementofthecluster.Aclusterissimilartoarecordorastructintext-basedprogramminglanguages.BundlingseveraldataelementsintoclusterseliminateswireclutterontheblockdiagramandreducesthenumberofconnectorpaneterminalsthatsubVIsneed.Theconnectorpanehas,atmost,28terminals.Ifafrontpanelcontainsmorethan28controlsandindicatorsthatyouwanttouseprogrammatically,groupsomeofthemintoaclusterandassigntheclustertoaterminalontheconnectorpane.Likeanarray,aclusteriseitheracontroloranindicator.Aclustercannotcontainamixtureofcontrolsandindicators.

Page 60: Introduction to LabVIEW - HiT

54 WorkingwithData

Tutorial:AnIntroductiontoLabVIEW

Althoughclusterandarrayelementsarebothordered,youmustunbundleallclusterelementsatonceratherthanindexoneelementatatime.Youalsocanusethe“UnbundleByName”functiontoaccessspecificclusterelements.

ExampleofaClusterinLabVIEW:

7.2.1 ClusterOrder

Youmaysortthedifferentelementsintheclusterbyright-clickontheclusterborderandselect“ReorderControlsinCluster…”

Page 61: Introduction to LabVIEW - HiT

55 WorkingwithData

Tutorial:AnIntroductiontoLabVIEW

7.2.2 ClusterElements

InordertomanipulateandworkwithclusterLabVIEWofferslotsoffunctions,suchasthe“Bundle”and“Unbundle”functions.

Inordertowritetoaclusterfromthecode,youmayusethe“Bundle”functionorthe“BundleByName”function.Seeexamplebelow:

Example:Clusters

Page 62: Introduction to LabVIEW - HiT

56 WorkingwithData

Tutorial:AnIntroductiontoLabVIEW

Inordertogetaccesstothedifferentelementsinthecluster,youneedto“Unbundle”byusingthe“Unbundle”functionorthe“UnbundleByName”.Seeexamplebelow:

ExercisesExercise:Arrays

CreatesomesimpleVIswhereyouusethesearrayfunctionstomanipulatearraydata:

ArraySize

IndexArray

DeletefromArray

Search1DArray

InitializeArray

BuildArray

ArraySubset

Exercise:Arrays

CreateaSubVIthatfindthe“peaks”intheinputarrayregardingtoaninputpeaklevel.

Page 63: Introduction to LabVIEW - HiT

57 WorkingwithData

Tutorial:AnIntroductiontoLabVIEW

Exercise:Clusters

CreateaClusterandgetthedifferentvaluesfromthecontrolsintheCluster.SeeFrontPanelbelow:

Page 64: Introduction to LabVIEW - HiT

58

8 WorkingwithStringsWorkingandmanipulatingwithstringsisanimportantpartinLabVIEWdevelopment.

OntheFrontpanelwehavethefollowingStringcontrolsandindicatorsavailablefromtheControlpalette:

OntheBlockDiagramwehavethefollowingStringfunctionsavailablefromtheFunctionspalette:

SomeofthemostimportantStringfunctionsare:

ConcatenateStrings

Page 65: Introduction to LabVIEW - HiT

59 WorkingwithStrings

Tutorial:AnIntroductiontoLabVIEW

Thisfunctionconcatenatesseveralstringsintoonstring:

SearchandReplaceString

Usethiswhenyouwanttoreplaceorremoveacertaintextinastring.

MatchPattern

Page 66: Introduction to LabVIEW - HiT

60 WorkingwithStrings

Tutorial:AnIntroductiontoLabVIEW

Thisisthemostusefulfunctionwhenitcomestostringmanipulation.

FormatIntoString

Example:

ExercisesHerearesomeexercisesusingsomeoftheStringfunctionsthatareavailableinLabVIEW.

Exercise:SubVI:Removeleadingzerosinstring.vi

CreateaSubVIwhichremovesleadingzerosinastring.CreateaTestVIthatusestheSubVI.

Page 67: Introduction to LabVIEW - HiT

61 WorkingwithStrings

Tutorial:AnIntroductiontoLabVIEW

Exercise:SubVI:Removespacefromendofstring.vi

CreateaSubVIwhichremovesallspacesfromtheendofthestring.CreateaTestVIthatusestheSubVI.

Exercise:SubVI:Add2String.vi

CreateaSubVIwhichadds2stringsintoone.CreateaTestVIthatusestheSubVI.

Page 68: Introduction to LabVIEW - HiT

62

9 ErrorHandlingThischapterexplainsthebasicconceptsofhandleerrorsinyourcode.

Topics:

• FindingErrors• ErrorWiring• ErrorHandling

9.1 FindingErrorIfaVIdoesnotrun,itisabroken,or“nonexecutable”,VI.TheRunbuttonoftenappears

broken,shownatleft,whenyoucreateoreditaVI.Ifitisstillbrokenwhenyoufinishwiringtheblockdiagram,theVIisbrokenandwillnotrun.Generally,thismeansthatarequiredinputisnotwired,orawireisbroken.ClickthebrokenRunbuttontodisplaytheErrorlistwindow,whichlistsalltheerrors.Double-clickanerrordescriptiontodisplaytherelevantblockdiagramorfrontpanelandhighlighttheobjectthatcontainstheerror.

9.2 ErrorWiringErrorhandlingisimportantinallprogramminglanguages.LabVIEWhaspowerfulmechanismforhandlingerrorsanderrorwiring.

YoushouldalwayswiretheErrorclusterbetweenallSubVIs,nodes,etc.thatsupportthis,seeexamplebelow.

TheErrorclusterislocatedintheControlspalettehere:

Page 69: Introduction to LabVIEW - HiT

63 ErrorHandling

Tutorial:AnIntroductiontoLabVIEW

TheErrorCluster:

TheErrorclustercontainsofthefollowingparts:

• Status–True/False.False:NoError,True:Error• Code–ErrorCode• Source–TextualErrormessage

9.3 ErrorHandlinginSubVIsWhencreatingSubVIsyoushouldalwayscreateanErrorInandanErrorOut.IntheSubVIcodeyoushouldalsouseaCasestructureandwiretheErrorinclustertotheCaseSelectorasshownbelow.

Page 70: Introduction to LabVIEW - HiT

64 ErrorHandling

Tutorial:AnIntroductiontoLabVIEW

9.4 ErrorHandlingLabVIEWhasseveralusefulSubVIs,etc.forErrorHandling:

Page 71: Introduction to LabVIEW - HiT

65 ErrorHandling

Tutorial:AnIntroductiontoLabVIEW

Theseare:

Ingeneralyoushouldalwaysshowtheerrortotheuser.SeeLabVIEWHelpformoredetailsofhowtousetheseSubVIs.

ExercisesExercise:ErrorHandling

CheckoutthedifferentErrorVisinLabVIEW.UsetheminsomeofyourpreviousVis.

Page 72: Introduction to LabVIEW - HiT

66

10 WorkingwithProjectsThischapterexplainsthebasicconceptsoftheprojectExplorerinLabVIEW.

Topics:

• ProjectExplorer• Building.exe(executable)applications• Deployment:CreateanInstaller

10.1 ProjectExplorerItisnotnecessarytousetheProjectExplorerwhendevelopingyourLabVIEWcode,butitisaneasywaytostructureyourcode,especiallyforlargerprojects.

TheprojectExplorerisnecessarywhenyouwanttodeployyourcodeinto,e.g.,anexecutable(.exe)application,buildasetup,etc.

Page 73: Introduction to LabVIEW - HiT

67 WorkingwithProjects

Tutorial:AnIntroductiontoLabVIEW

TheProjectExplorerisalsoveryusefulwhenyouintegrateasourcecontroltool,suchasTeamFoundationServer,VisualSourceSafe,etc.Thenyoumayeasilycheckfilesinandoutofthesourcecodesystem.

InordertocreateanewProjectinLabVIEW,simplyselect“EmptyProject”fromtheGettingStartedwindowwhenyouopenLabVIEW.

10.2 DeploymentWhenyourapplicationisfinished,youmaywanttodistributeordeployyourapplicationandshareitwithothers.

TheProjectExplorergivesyouseveralchoiceswhenitcomestodistributeanddeployyourapplication.Someoftheoptionsare:

• Createanexecutableapplication(.exe)–thismeansthatthetargetdoesn’tneedtohaveLabVIEWinstalledontheircomputer.AllthetargetneedisLabVIEWRun-Rime,whichisasmallinstallationpackage.

• Youmaycreateyourowninstaller,soallthetargetneedistorunasetup.exeinordertouseyourapplication

• OtherpossibilitiesistocreateaWebServiceoraSharedLibrary(DLL)ofyourapplication

Page 74: Introduction to LabVIEW - HiT

68 WorkingwithProjects

Tutorial:AnIntroductiontoLabVIEW

AlltheseoptionsareavailablefromtheProjectExplorer,justright-clickonyour“BuildSpecifications”node.

Wewillgothroughhowwecreateanexecutableapplication.ClickBuildSpecifications→New→Application(EXE).

InthePropertieswindowfillinyournameoftheapplication.

Page 75: Introduction to LabVIEW - HiT

69 WorkingwithProjects

Tutorial:AnIntroductiontoLabVIEW

MakesureyouselectaStartupVI.

Therearelotsofpropertiesandsettingyoumayuseinordertocreateyourapplication,gothroughalltheCategoriesinthePropertieswindow.

Whenyouhavefinishedallthesteps,justselect“Build”inordertocreateyourapplication.

Whenyoumakechangesinyourapplication,itiseasytorebuildyourapplication:

ExercisesExercise:ProjectExplorer

CreateanewProjectandputonofyourexistingapplicationintotheproject

Page 76: Introduction to LabVIEW - HiT

70 WorkingwithProjects

Tutorial:AnIntroductiontoLabVIEW

Exercise:Deployment

Createanexecutableapplication

Page 77: Introduction to LabVIEW - HiT

71

11 DesignTechniquesThischapterexplainssomeusefultechniquestousewhencreatingyourapplication.

Topics:

• ForcetheProgramFlowusinganErrorcluster• ShiftRegister• StateMachine• MultipleLoops• Templates

11.1 ForceProgramFlowAsmentionedearlier,LabVIEWfollowsadataflowmodelforrunningVIs.Ablockdiagramnodeexecuteswhenallitsinputsareavailable.Whenanodecompletesexecution,itsuppliesdatatoitsoutputterminalsandpassestheoutputdatatothenextnodeinthedataflowpath.

IntheexamplebelowwecannotbesurethattheDAQmxWrite.viexecutesbeforetheDAQmxStopTask.viexecutes.LabVIEWwillinthiscaserandomlyexecuteoneofthesefirst.IftheStopVIhappenstoexecutefirstthentheWriteVIwillfailedbecausetaskhasbeenstopped.

IntheexamplebelowwewiretheErrorclusterthroughalltheVIs,andtherewillbenodoubtthattheWriteVIwillexecutebeforetheStopVI.

Page 78: Introduction to LabVIEW - HiT

72 DesignTechniques

Tutorial:AnIntroductiontoLabVIEW

Thisapproachwillalsotakecareoftheerrorhandlinginyourprogram,whichisveryimportantinreal-worldapplications.

11.2 ShiftRegisterUseshiftregistersonForLoopsandWhileLoopstotransfervaluesfromoneloopiterationtothenext.Shiftregistersaresimilartostaticvariablesintext-basedprogramminglanguages.Ashiftregisterappearsasapairofterminals,directlyoppositeeachotherontheverticalsidesoftheloopborder.Therightterminalcontainsanuparrowandstoresdataonthecompletionofaniteration.LabVIEWtransfersthedataconnectedtotherightsideoftheregistertothenextiteration.Createashiftregisterbyright-clickingtheleftorrightborderofaloopandselectingAddShiftRegisterfromtheshortcutmenu.

Ashiftregistertransfersanydatatypeandautomaticallychangestothedatatypeofthefirstobjectwiredtotheshiftregister.Thedatayouwiretotheterminalsofeachshiftregistermustbethesametype.

Toinitializeashiftregister,wireanyvaluefromoutsidethelooptotheleftterminal.Ifyoudonotinitializetheshiftregister,theloopusesthevaluewrittentotheshiftregisterwhenthelooplastexecutedorthedefaultvalueforthedatatypeiftheloophasneverexecuted.

UsealoopwithanuninitializedshiftregistertorunaVIrepeatedlysothateachtimetheVIruns,theinitialoutputoftheshiftregisteristhelastvaluefromthepreviousexecution.UseanuninitializedshiftregistertopreservestateinformationbetweensubsequentexecutionsofaVI.Aftertheloopexecutes,thelastvaluestoredintheshiftregisterremainsattherightterminal.Ifyouwiretherightterminaloutsidetheloop,thewiretransfersthelastvaluestoredintheshiftregister.Youcanaddmorethanoneshiftregistertoaloop.Ifyouhavemultipleoperationswithinaloop,usemultipleshiftregisterstostorethedatavaluesfromthosedifferentprocessesinthestructure.

Page 79: Introduction to LabVIEW - HiT

73 DesignTechniques

Tutorial:AnIntroductiontoLabVIEW

11.3 StateProgrammingArchitectureCreatingVIsusingtheStateMachineapproachisveryusefulwhencreating(large)applications.

Ingeneral,astatemachineisamodelofbehaviorcomposedofafinitenumberofstates,transitionsbetweenthosestates,andactions.Itissimilartoa"flowgraph"wherewecaninspectthewayinwhichthelogicrunswhencertainconditionsaremet.

Sometimes,youmaywanttochangetheorderofthesequence,repeatoneiteminthesequencemoreoftenthantheotheritems,stopasequenceimmediately,orhaveitemsinthesequencethatmayexecuteonlywhencertainconditionsaremet.Althoughyourprogrammaynothaveanysuchrequirements,thereisalwaysthepossibilitythattheprogrammustbemodifiedinthefuture.Therefore,astateprogrammingarchitectureisagoodchoice,evenifasequentialprogrammingstructureissufficient.Thefollowinglistdescribesmorecomplexprogrammingrequirementsthatjustifytheuseofastateprogrammingarchitectureforanapplication.

Page 80: Introduction to LabVIEW - HiT

74 DesignTechniques

Tutorial:AnIntroductiontoLabVIEW

• Youneedtochangetheorderofthesequence• Youmustrepeataniteminthesequencemoreoftenthanotheritems• Youwantsomeitemsinthesequencetoexecuteonlywhencertainconditionsare

met

TheStateMachineapproachinLabVIEWusesaCasestructureinsideaWhilelooptohandlethedifferentstatesintheprogram,andthetransitionsbetweenthem.TheShiftRegisterisusedtosavedatafromandbetweenthedifferentstates.

BelowweseeexamplesofastatemachineprincipleimplementedinLabVIEW.

SimpleStateMachineprinciple

StateMachinewithmultipletransitionsdependingontheState:

Page 81: Introduction to LabVIEW - HiT

75 DesignTechniques

Tutorial:AnIntroductiontoLabVIEW

MoreadvancedStateMachineusingShiftRegisters:

11.4 MultipleLoops/Parallelprogramming

Often,youneedtoprogrammultipletaskssothattheyexecuteatthesametime.InLabVIEWtaskscanruninparalleliftheydonothaveadatadependencybetweenthem,and

Page 82: Introduction to LabVIEW - HiT

76 DesignTechniques

Tutorial:AnIntroductiontoLabVIEW

iftheyarenotusingthesamesharedresource.Anexampleofasharedresourceisafile,oraninstrument.

UsingmultipleWhileloopsissometimesusefulinapplicationsthatneedtohandleUserinteractionsinparallelwith,e.g.,DAQoperations,etc.

Belowweseeanexampleofhowthisstructurecouldlooklike.Theupperloopcouldhandleinteractionwiththeuser,whilethelowerloopcouldhandleDAQoperations,suchasreadingandwritingtosomeI/Oequipments.

Page 83: Introduction to LabVIEW - HiT

77 DesignTechniques

Tutorial:AnIntroductiontoLabVIEW

Inordertopassdatabetweentheloops,youmaye.g.uselocalvariables.Theloopmayhavedifferenttimecycles.TheI/OmayrequirefastercyclesthantheUserinteractionloop.

11.5 TemplatesYoushouldcreateyourowntemplatesforsuchVIyouusealot.Itiseasytocreateyourowntemplatesforscratch,justcreateaVIasyounormallydoandthensaveitasatemplatewiththeending“.vit”.YoumayalsoconvertaVIyoualreadymadejustbychangingtheextensionto“.vit”.

YoushouldcopyyourtemplatestotheLabVIEWtemplatefolderwhichisdefaultlocatedin“C:\ProgramFiles\NationalInstruments\LabVIEWX.X\Templates\”.

TheTemplateswillthenbeavailablefromtheGettingStartedWindoworFile→New…inLabVIEW.

ImaycaseIhavecreatedasubfoldercalled“MyTemplates”whereIplaceallmytemplates.

Page 84: Introduction to LabVIEW - HiT

78 DesignTechniques

Tutorial:AnIntroductiontoLabVIEW

ExercisesHerearesomeexercisesaboutshift-registers,StateMachinesandparallelprogramming.

Exercise:Shift-register

CreateaVI(seeexamplebelow)whereyouhavethefollowingstates:

• Initialize• Write• Read• Close

IntheVIyouwilluseashift-registerasatemporarystorage.IntheWritestateyouWriteDatatothestorage(shift-register)whileyouintheReadstatewillreadtheDatafromtheStorage.

SeeExamplebelow:

Page 85: Introduction to LabVIEW - HiT

79 DesignTechniques

Tutorial:AnIntroductiontoLabVIEW

WriteaTestprogramthattesttheSubVI,e.g.,

Thisexampleshowshowyoucanuseashift-registerasatemporarystorage,whichisveryusefulinmanysituations.

Exercise:StateMachine

UsetheStateMachineprincipleononeofyourpreviousexercises.

Exercise:ParallelProgramming

CreateaVIthatconsistsof2parallelloops.Uselocalvariablesandothermechanismsinordertosharedatabetweenthe2loops.

Exercise:Templates

StripsomeofyourspreviousVisandsavethemasreusableTemplates.

Page 86: Introduction to LabVIEW - HiT

80

12 UserInterfaceThischapterexplainsthebasicconceptsofcreatinguser-friendlyGraphicalUserInterfaces(GUI)inLabVIEW.

Topics:

• Decorations• TabControl• Splitter• SubPanel• Etc.

BelowweseeaFrontPanel(GUI)witha“poor”design.

Theinformation(ControlsandIndicators)ontheFrontPanelisnotstructured.Youshouldgroupelementsthatnaturallybelongtogetherandusedifferentcolorswithcare.

WhencreatingGraphicalUserInterfaces(GUI)youshouldusethecontrolsfromtheSystempaletteandnotfromtheModernorClassicpalettes.ModernControlsmaybeusedinSubViswithnovisibleUserInterface(fortheuser).

Page 87: Introduction to LabVIEW - HiT

81 UserInterface

Tutorial:AnIntroductiontoLabVIEW

TheappearanceofthecontrolsintheSystempaletteisstandardMSWindowslookandfeelingandthislookisfamiliarformostusers.Thesecontrolsalsochangeappearanceduetochangesintheappearanceintheoperationsystem.

12.1 VIPropertiesInordertomaketheappearanceoftheWindowthathostsyourapplication,youshouldalwaysmakesomechangesinthe“VIProperties”.

Youfindthe“VIProperties”byright-clickontheiconintheupperrightcornerofyourVI.

Page 88: Introduction to LabVIEW - HiT

82 UserInterface

Tutorial:AnIntroductiontoLabVIEW

Thefirstthingyoushouldchangeisthe“Windowtitle”.HereyoumaytypeappropriatenameofyourapplicationorSubVI.

Thenextyoushoulddoistothe“Customize”buttoninordertocustomizetheWindowappearance.

BelowweseeanapplicationwithasimpleandneatUserInterfaceandwithaCustomizedWindowsappearance.

Page 89: Introduction to LabVIEW - HiT

83 UserInterface

Tutorial:AnIntroductiontoLabVIEW

BelowweseeaprofessionalapplicationcreatedinLabVIEWthatimplementcommonGUIobjectssuchasaToolbar,aTreeview,aListview,etc..

Page 90: Introduction to LabVIEW - HiT

84 UserInterface

Tutorial:AnIntroductiontoLabVIEW

ExercisesExercise:UserInterface

CreateaDialogBoxwhereyouusesomeoftheControlsfromtheSystempalette.MakethenecessarysettingsinVIPropertiesinordertohidemenus,buttons,createaTitle,etc.

CreateaTestVIfromwhereyouopenthisDialogBox,entersomedataintheDialogBox,andthenretrievethesedatainthecallingVI.

Example:

Page 91: Introduction to LabVIEW - HiT

85

13 PlottingDataThischapterexplainsthebasicconceptswhenplottingdatainLabVIEW.

LabVIEWofferspowerfulfunctionalityforplottingdata.IntheGraphpalettewehavelotsofusefulcontrolsforplottingandvisualizationofdata.

Themostusefulare:

• WaveformChart• WaveformGraph• XYGraph

Example:

Thissimpleexamplecreatesagraphwithsomerandomvalues.

Page 92: Introduction to LabVIEW - HiT

86 PlottingData

Tutorial:AnIntroductiontoLabVIEW

Theexamplebelowshowthebasicdifferencebetweena“Chart”anda“Graph”.

Page 93: Introduction to LabVIEW - HiT

87 PlottingData

Tutorial:AnIntroductiontoLabVIEW

Youusethe“Graph”ifyouwanttoplotasetofdata,e.g.,anarraywithdata,plotdatafromafile,etc.Usethe“Chart”ifyouwanttoplotonedatapointatatime,e.g.,insidealoop,etc.

13.1 CustomizingThedifferentChartcomponentsinLabVIEWofferagreatdealofcustomizing.

Youmayclickonthe“PlotLegend”inordertosetcolors,differentlinestyles,etc.

Ifyouright-clickontheGraph/Chart,youmaysetpropertiessuchasauto-scaling,etc.

Page 94: Introduction to LabVIEW - HiT

88 PlottingData

Tutorial:AnIntroductiontoLabVIEW

IfyouselectProperties,yougetthefollowingdialog:

Youmayalsoselectwhichitemsthatshouldbevisibleornot.

Page 95: Introduction to LabVIEW - HiT

89 PlottingData

Tutorial:AnIntroductiontoLabVIEW

The“GraphPalette”letsyouzoominandoutontheGraph,etc.

ExercisesExercise:Graph

CreateaVIthatreadsdatafromafileandplotthedatainaGraphcomponent.

Exercise:Chart

CreateaVIwhereyouuseDataBindinginordertoretrievedatafromanOPCdemo.

DataBindingissetintheProperties→DataBindingtab:

Page 96: Introduction to LabVIEW - HiT

90 PlottingData

Tutorial:AnIntroductiontoLabVIEW

Exercise:Customizing

CustomizetheGraphandtheChartintheexamplesaboveinordertosetcolors,linethickness,etc.

Page 97: Introduction to LabVIEW - HiT

91

14 Tips&TricksThischaptergivesyousomeusefulTips&TricksregardingLabVIEW.

14.1 10functionsyouneedtoknowabout

Thesearethe10mostusefulfunctionsinLabVIEW,soyoucouldalreadynowlearnhowtousethemandwheretofindthem!

BuildArray

ThisexampleusingtheBuildArrayfunctioninsideaForloopinorderbuildanarraywith10elements.

IndexArray

Page 98: Introduction to LabVIEW - HiT

92 Tips&Tricks

Tutorial:AnIntroductiontoLabVIEW

Itisalwaysusefultofindaspecificvalueinanarray:

TheIndexArrayisextendible,soyoucandragitouttofindmorethanoneelements:

ArraySize

Findthesizeofanarbitraryarray:

Select

Page 99: Introduction to LabVIEW - HiT

93 Tips&Tricks

Tutorial:AnIntroductiontoLabVIEW

Dependingontheinputdata,gototheAlarmcaseortheWriteDatacase.

ConcatenateStrings

Thisfunctionconcatenateseveralstringsintoonstring:

SearchandReplaceString

Page 100: Introduction to LabVIEW - HiT

94 Tips&Tricks

Tutorial:AnIntroductiontoLabVIEW

Usethiswhenyouwanttoreplaceorremoveacertaintextinastring.

MatchPattern

Thisisthemostusefulfunctionwhenitcomestostringmanipulation.

FormatIntoString

Page 101: Introduction to LabVIEW - HiT

95 Tips&Tricks

Tutorial:AnIntroductiontoLabVIEW

Example:

Fract/ExpStringtoNumber

Thisfunctionconvertsastringintoanumber:

Example:NumberToFractionalString

Example:

Page 102: Introduction to LabVIEW - HiT

96 Tips&Tricks

Tutorial:AnIntroductiontoLabVIEW

14.2 The10mostusefulShort-cutsThesearethe10mostusefulshort-cutsinLabVIEW,soyoucouldalreadynowlearnhowtousethem!

Short-Cut DescriptionCtrl+B DeletesallbrokenwiresinaVICtrl+. StopstheRunningVICtrl+E TogglebetweentheFrontPanelandBlockDiagramTab CyclesthroughthemostcommonTools(AutomaticToolSelection

shouldbedisabled!)Ctrl+Mousewheel

ScrollsthroughsubdiagramsinCase,EventorSequencestructures

Ctrl+H DisplaystheContextHelpwindowCtrl+MouseDouble-clickonaSubVI

OpenstheBlockDiagramdirectly

Ctrl+Arrows(→←←↓)

Movefaster.YoufirsthavetoselectaSubVI,aFunction,Object,etc

Ctrl+W ClosetheSubVIDouble-clickonawire

Selectstheholewire

Page 103: Introduction to LabVIEW - HiT

97

15 ExampleApplicationInthisexamplewewillgothroughanexampleapplication.TheapplicationusesmostoftheLabVIEWfeaturesyouhavelearnedinthisTutorial.

Theapplicationiscalled“Glossary”.Itisasimpleapplicationthatlearnskid’swordsinEnglish.Sincetheapplicationisforkids,theuserinterfaceiscreatewitha“childish”lookandfeel.

Thisisanexampleofhowtocreateauser-friendlyapplicationinLabVIEWthatusesmostofthefunctionalityinLabVIEW,suchasState-machineprinciples,readingandwritingtofiles,dialogboxes,graphicsandsoundeffects.Basicfunctionsforstringandarraymanipulation,andofcoursewhileloops,casestructures,subVIs,etc.TheexamplealsousestheProjectExplorertocollectallthefilesinoneplaceandtocreateanexecutablefileofthesolution.FinallyitusestheProjectExplorertocreateasetuppackageyoucanusetoinstalltheapplicationeasilyonothercomputers.

Page 104: Introduction to LabVIEW - HiT

98 ExampleApplication

Tutorial:AnIntroductiontoLabVIEW

IcreatedthisapplicationformykidsinthePrimaryschoolwhohadproblemswithlearningtheirhomeworkinEnglish.

UsethecodeasanexampleforcreatingyourownstunningLabVIEWapplications.Thecodeisavailablefordownloadatmyblog:http://home.hit.no/~hansha.

BelowweseetheGlossaryList:

Ifyouclickonthelittlebooksymbolinyourapplication,thiswindowwillpopup:

Clicktissymbolandyoucanenternewwords:

Page 105: Introduction to LabVIEW - HiT

99 ExampleApplication

Tutorial:AnIntroductiontoLabVIEW

TheapplicationusestheProjectExplorer:

Page 106: Introduction to LabVIEW - HiT

100 ExampleApplication

Tutorial:AnIntroductiontoLabVIEW

Thismakesiteasytokeepanoverviewofallyourfilesinyourproject.YoumayalsousetheProjectExplorertocreateanexecutablefileofyourapplication.Inadditionyoumayalsocreateaninstallationpackagesoyoucaneasilyinstalltheapplicationonothercomputers.AspartoftheinstallationtheLabVIEWRun-timeenginewillbeinstalled.

BlockDiagram:

Theapplicationusesthestatemachineprinciple,whichmakesiteasytocreatelargeapplications:

Page 107: Introduction to LabVIEW - HiT

101

16 AdditionalExercisesThischapterlistslotsofadditionalexercisesyoucouldtryoutinordertoimproveyourLabVIEWskills.

Exercise:vCardReader

CreateanapplicationthatreadsinformationfromavCard.

vCardisafileformatstandardforelectronicbusinesscards.vCardsareoftenattachedtoe-mailmessages,butcanbeexchangedinotherways,suchasontheWorldWideWeb.Theycancontainnameandaddressinformation,phonenumbers,URLs,logos,photographs,andevenaudioclips.

Example:

BEGIN:VCARD VERSION:2.1 N:Gump;Forrest FN:Forrest Gump ORG:Bubba Gump Shrimp Co. TITLE:Shrimp Man TEL;WORK;VOICE:(111) 555-1212 TEL;HOME;VOICE:(404) 555-1212 ADR;WORK:;;100 Waters Edge;Baytown;LA;30314;United States of America LABEL;WORK;ENCODING=QUOTED-PRINTABLE:100 Waters Edge=0D=0ABaytown, LA 30314=0D=0AUSA ADR;HOME:;;42 Plantation St.;Baytown;LA;30314;United States of America LABEL;HOME;ENCODING=QUOTED-PRINTABLE:42 Plantation St.=0D=0ABaytown, LA 30314=0D=0AUSA EMAIL;PREF;INTERNET:[email protected] REV:20080424T195243Z END:VCARD

FormoreinformationaboutthevCardformat,seehttp://en.wikipedia.org/wiki/VCard.

Theapplicationshouldlooksomethinglikethis:

WhentheuserclickOpen,thenadialogboxlikethisshouldappear:

Page 108: Introduction to LabVIEW - HiT

102 AdditionalExercises

Tutorial:AnIntroductiontoLabVIEW

Requirements:

• UsetheProjectExplorer• UsetheStateMachineprinciple• UsetheEventStructure• UseSystemControls• SettheappropriatesettingsintheVIProperties.• Createaexecutableapplication(vCard.exe)

Exercise:vCardWrite&Read

Extendtheapplicationinthepreviousexample.YoushouldnowbeabletobothwriteandreadvCardfiles.Theapplicationcouldlooksomethinglikethis:

Page 109: Introduction to LabVIEW - HiT

103 AdditionalExercises

Tutorial:AnIntroductiontoLabVIEW

WhentheuserclicksNew,thedialogboxinthepreviousexerciseappears.TheusermayenteranewvCard.IftheuserclicksEdit,adialogboxwiththeselectedcontactshouldappear.

Exercise:Read/Writefrom.inifiles

Read/Writefrom.inifiles.UsetheConfigurationFileVIs:

Exercise:ActiveX

CreateasimpleWebBrowserusingActiveXandtheInternetExplorerActiveXcontrol(MicrosoftWebBrowser)

UsetheActiveXContainerfromtheContainerscontrolpalette:

Page 110: Introduction to LabVIEW - HiT

104 AdditionalExercises

Tutorial:AnIntroductiontoLabVIEW

UsetheActiveXfunctionpalette:

Theapplicationcouldlooksomethinglikethis:

Exercise:Themes

Page 111: Introduction to LabVIEW - HiT

105 AdditionalExercises

Tutorial:AnIntroductiontoLabVIEW

Ine.g.,ASP.NETwehavesomethingcalledThemes.Themesareusedtochangetheappearanceofyourwholeapplicationregardingtocolor,font,pictures,etc.

LabVIEWdonotoffersuchafunctionality,buttrytocreateyourownThemeConfigurator,soyoucanchangetheappearanceofyourVIinstantly.

HereisanexampleofhowWindowsXPhandlesdifferentThemes:

CreateasimilarThemeConfiguratorsoyoumayeasilychangetheappearanceofyourVis.

Page 112: Introduction to LabVIEW - HiT

106

17 What’sNext?

17.1 MyBlogFormoreinformationaboutLabVIEW,visitmyBlog:http://home.hit.no/~hansha/

LabVIEWBasics:

http://home.hit.no/~hansha/video/labview_basics.php

LabVIEWTrainingandResources:

http://home.hit.no/~hansha/?training=labview

17.2 TutorialsThisTutorialisapartofaserieswithotherTutorialsIhavemade,suchas:

• IntroductiontoLabVIEW• DataAcquisitioninLabVIEW• ControlandSimulationinLabVIEW• LabVIEWMathScript• LinearAlgebrainLabVIEW• DataloggingandSupervisoryControlinLabVIEW• ModelPredictiveControlinLabVIEW• WirelessDataAcquisitioninLabVIEW• etc.

TheseTrainingKitsareavailablefordownload(.pdffiles,sourcecode,additionalresources,etc.)frommyblog:http://home.hit.no/~hansha

17.3 AdditionalResourcesYoufindlotsofinformationaboutLabVIEWinNationalInstrumentswebsite:

www.ni.com

Page 113: Introduction to LabVIEW - HiT

107 What’sNext?

Tutorial:AnIntroductiontoLabVIEW

17.4 ExamplesIntheNIexampleFinder(Help→FindExamples…)youfindlotsofusefulexamplesthatyoucanplaywithoruseasastartwhencreatingyourownapplications.

Page 114: Introduction to LabVIEW - HiT

108

QuickReference

Page 115: Introduction to LabVIEW - HiT

QuickReference

Tutorial:AnIntroductiontoLabVIEW

Page 116: Introduction to LabVIEW - HiT

Hans-PetterHalvorsen,M.Sc.

E-mail:[email protected]

Blog:http://home.hit.no/~hansha/

UniversityCollegeofSoutheastNorway

www.usn.no