Tải bản đầy đủ (.pdf) (117 trang)

Giáo trình Introduction to LabVIEW

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.16 MB, 117 trang )

g







IntroductiontoLabVIEW
Hans-PetterHalvorsen



g/documents/programming/labview/




IntroductiontoLabVIEW


Hans-PetterHalvorsen
Copyright©2017


E-Mail:
Web:g



g








Preface
ThisdocumentexplainsthebasicconceptsofLabVIEW.

Youfindadditionalresources,code,etc.here:

g/documents/programming/labview/






iii





TableofContents
Preface.....................................................................................................................................iii
TableofContents.....................................................................................................................iv
1

2


Introduction......................................................................................................................1
1.1

DataflowProgramming...............................................................................................1

1.2

GraphicalProgramming..............................................................................................1

1.3

Benefits.......................................................................................................................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
iv



v
3



TableofContents

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

Tutorial:AnIntroductiontoLabVIEW


vi



7


TableofContents

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

Tutorial:AnIntroductiontoLabVIEW


vii




11.5

TableofContents

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


Tutorial:AnIntroductiontoLabVIEW




1 Introduction
LabVIEW(shortforLaboratoryVirtualInstrumentationEngineeringWorkbench)isa
platformanddevelopmentenvironmentforavisualprogramminglanguagefromNational
Instruments.Thegraphicallanguageisnamed"G".OriginallyreleasedfortheApple
Macintoshin1986,LabVIEWiscommonlyusedfordataacquisition,instrumentcontrol,and
industrialautomationonavarietyofplatformsincludingMicrosoftWindows,variousflavors
ofUNIX,Linux,andMacOSX.ThelatestversionofLabVIEWisversionLabVIEW2011.Visit
NationalInstrumentsatwww.ni.com.
Thecodefileshavetheextension“.vi”,whichisanabbreviationfor“VirtualInstrument”.
LabVIEWofferslotsofadditionalAdd-OnsandToolkits.

1.1 DataflowProgramming
TheprogramminglanguageusedinLabVIEW,alsoreferredtoasG,isadataflow
programminglanguage.Executionisdeterminedbythestructureofagraphicalblock

diagram(theLV-sourcecode)onwhichtheprogrammerconnectsdifferentfunction-nodes
bydrawingwires.Thesewirespropagatevariablesandanynodecanexecuteassoonasall
itsinputdatabecomeavailable.Sincethismightbethecaseformultiplenodes
simultaneously,Gisinherentlycapableofparallelexecution.Multi-processingandmultithreadinghardwareisautomaticallyexploitedbythebuilt-inscheduler,whichmultiplexes
multipleOSthreadsoverthenodesreadyforexecution.

1.2 GraphicalProgramming
LabVIEWtiesthecreationofuserinterfaces(calledfrontpanels)intothedevelopmentcycle.
LabVIEWprograms/subroutinesarecalledvirtualinstruments(VIs).EachVIhasthree
components:ablockdiagram,afrontpanel,andaconnectorpanel.Thelastisusedto
representtheVIintheblockdiagramsofother,callingVIs.Controlsandindicatorsonthe
frontpanelallowanoperatortoinputdataintoorextractdatafromarunningvirtual
instrument.However,thefrontpanelcanalsoserveasaprogrammaticinterface.Thusa
virtualinstrumentcaneitherberunasaprogram,withthefrontpanelservingasauser
interface,or,whendroppedasanodeontotheblockdiagram,thefrontpaneldefinesthe
inputsandoutputsforthegivennodethroughtheconnectorpane.ThisimplieseachVIcan
beeasilytestedbeforebeingembeddedasasubroutineintoalargerprogram.
1



2



Introduction

Thegraphicalapproachalsoallowsnon-programmerstobuildprogramssimplybydragging
anddroppingvirtualrepresentationsoflabequipmentwithwhichtheyarealreadyfamiliar.
TheLabVIEWprogrammingenvironment,withtheincludedexamplesandthe

documentation,makesitsimpletocreatesmallapplications.Thisisabenefitononeside,
butthereisalsoacertaindangerofunderestimatingtheexpertiseneededforgoodquality
"G"programming.Forcomplexalgorithmsorlarge-scalecode,itisimportantthatthe
programmerpossessanextensiveknowledgeofthespecialLabVIEWsyntaxandthe
topologyofitsmemorymanagement.ThemostadvancedLabVIEWdevelopmentsystems
offerthepossibilityofbuildingstand-aloneapplications.Furthermore,itispossibletocreate
distributedapplications,whichcommunicatebyaclient/serverscheme,andaretherefore
easiertoimplementduetotheinherentlyparallelnatureofG-code.

1.3 Benefits
OnebenefitofLabVIEWoverotherdevelopmentenvironmentsistheextensivesupportfor
accessinginstrumentationhardware.Driversandabstractionlayersformanydifferenttypes
ofinstrumentsandbusesareincludedorareavailableforinclusion.Thesepresent
themselvesasgraphicalnodes.Theabstractionlayersofferstandardsoftwareinterfacesto
communicatewithhardwaredevices.Theprovideddriverinterfacessaveprogram
developmenttime.ThesalespitchofNationalInstrumentsis,therefore,thatevenpeople
withlimitedcodingexperiencecanwriteprogramsanddeploytestsolutionsinareduced
timeframewhencomparedtomoreconventionalorcompetingsystems.Anewhardware
drivertopology(DAQmxBase),whichconsistsmainlyofG-codedcomponentswithonlya
fewregistercallsthroughNIMeasurementHardwareDDK(DriverDevelopmentKit)
functions,providesplatformindependenthardwareaccesstonumerousdataacquisition
andinstrumentationdevices.TheDAQmxBasedriverisavailableforLabVIEWonWindows,
MacOSXandLinuxplatforms.
Thisdocumentintroducingthefollowingthemes:








StartusingLabVIEW
o TheLabVIEWEnvironment
o FrontPanelandBlockDiagram
o Palettes:ControlPalette,FunctionsPalette,ToolsPalette
o DataTypes
o PropertyNodes
SubVIs
LoopsandStructures
TroubleshootingandDebugging
WorkingwithData
Tutorial:AnIntroductiontoLabVIEW


3


















o Arrays
§ ArrayFunctions
o Cluster
WorkingwithStrings
ErrorHandling
WorkingwithProjectsusingProjectExplorer
DesignTechniques
o ShiftRegister
o StateMachine
o MultipleLoops
UserInterface
PlottingData
Deployment:BuildingExecutableApplications(.exe)
IntroductiontoAdd-OnsandToolkits
o Brieflyexplanations…
o MoredetailaboutControlandSimulationModuleinlater
IntroductiontoDAQ-DataAcquisition
o MAX–MeasurementandAutomationExplorer
o NI-DAQmx
QuickReferencewithKeyboardShort-cuts



FormoreinformationaboutLabVIEW,visitmyBlog:

g

Tutorial:AnIntroductiontoLabVIEW


Introduction




2 StartusingLabVIEW
ThischapterexplainsthebasicconceptsinLabVIEW.
Thetopicsareasfollows:






TheLabVIEWEnvironment
FrontPanelandBlockDiagram
Palettes:ControlPalette,FunctionsPalette,ToolsPalette
DataTypes
PropertyNodes

2.1 TheLabVIEWEnvironment
LabVIEWprogramsarecalledVirtualInstruments,orVIs,becausetheirappearanceand
operationimitatephysicalinstruments,suchasoscilloscopesandmultimeters.LabVIEW
containsacomprehensivesetoftoolsforacquiringanalyzing,displaying,andstoringdata,as
wellastoolstohelpyoutroubleshootyourcode.
WhenopeningLabVIEW,youfirstcometothe“GettingStarted”window.


4




5



StartusingLabVIEW

InordertocreateanewVI,select“BlankVI”orinordertocreateanewLabVIEWproject,
select“Emptyproject”.
WhenyouopenablankVI,anuntitledfrontpanelwindowappears.Thiswindowdisplays
thefrontpanelandisoneofthetwoLabVIEWwindowsyouusetobuildaVI.Theother
windowcontainstheblockdiagram.Thesectionsbelowdescribethefrontpanelandthe
blockdiagram.

2.2 FrontPanel
WhenyouhavecreatedanewVIorselectedanexistingVI,theFrontPanelandtheBlock
DiagramforthatspecificVIwillappear.


InLabVIEW,youbuildauserinterface,orfrontpanel,withcontrolsandindicators.Controls
areknobs,pushbuttons,dials,andotherinputdevices.Indicatorsaregraphs,LEDs,and
otherdisplays.
Youbuildthefrontpanelwithcontrolsandindicators,whicharetheinteractiveinputand
outputterminalsoftheVI,respectively.Controlsareknobs,pushbuttons,dials,andother
inputdevices.Indicatorsaregraphs,LEDs,andotherdisplays.Controlssimulateinstrument

Tutorial:AnIntroductiontoLabVIEW



6



StartusingLabVIEW

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


Iyouselecta“NumericControl”,itcaneasybechangedtoan“NumericIndicator”byright
clickontheobjectanselect“ChangetoIndicator”


Oropposite,Iyouselecta“NumericIndicator”,itcaneasybechangedtoan“Numeric
Control”byrightclickontheobjectanselect“ChangetoControl”

Tutorial:AnIntroductiontoLabVIEW


7



StartusingLabVIEW




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


Theappearanceisalsoslightlydifferent,the“NumericControl”hasanincrementandan
decrementbuttoninfront,whilethe“NumericIndicator”hasadarkerbackgroundcolorin
ordertoindicatethatitsread-only.

2.3 BlockDiagram
Afteryoubuildtheuserinterface,youaddcodeusingVIsandstructurestocontrolthefront
panelobjects.Theblockdiagramcontainsthiscode.Insomeways,theblockdiagram
resemblesaflowchart.

Tutorial:AnIntroductiontoLabVIEW


8



StartusingLabVIEW



Afteryoubuildthefrontpanel,youaddcodeusinggraphicalrepresentationsoffunctionsto
controlthefrontpanelobjects.Theblockdiagramcontainsthisgraphicalsourcecode.Front
panelobjectsappearasterminals,ontheblockdiagram.Blockdiagramobjectsinclude
terminals,SubVIs,functions,constants,structures,andwires,whichtransferdataamong
otherblockdiagramobjects.

TheFigurebelowshowsafrontpanelanditscorrespondingblockdiagramwithfrontpanel
andblockdiagramcomponents.

Tutorial:AnIntroductiontoLabVIEW


9



StartusingLabVIEW


Thedifferentcomponentsareasfollows:
1. Toolbar
2. OwnedLabel
3. NumericControl
4. FreeLabel
5. NumericControlTerminal
6. KnobTerminal
7. NumericConstant
8. MultiplyFunction
9. Icon
10. KnobControl
11. PlotLegend
12. XYGraph
Tutorial:AnIntroductiontoLabVIEW


10




StartusingLabVIEW

13. WireDataPath
14. XYGraphTerminal
15. BundleFunction
16. SubVI
17. ForLoopStructure

2.4 ControlsPalette
TheControlsandFunctionspalettescontainsubpalettesofobjectsyoucanusetocreatea
VI.Whenyouclickasubpaletteicon,theentirepalettechangestothesubpaletteyou
selected.Touseanobjectonthepalettes,clicktheobjectandplaceitonthefrontpanelor
blockdiagram.TheControlspaletteisavailableonlyonthefrontpanel.TheControlspalette
containsthecontrolsandindicatorsyouusetobuildthefrontpanel.


ThemostusedSubPalettesaretheNumericSubPalette,theBooleanSubPaletteandthe
String&PathSubPalette.
YoumaychangetheappearanceandthecontentsoftheControlspalette:

Tutorial:AnIntroductiontoLabVIEW


11




StartusingLabVIEW

YoumayPinthepalette,soitisalwaysvisible,justclickthelittlepinbutton
upperleftcornerofthepalette:

inthe


Ifyouwanttochangethecontentandappearanceofthepalette,clickthe“View”button.


Hereyoumaychangethewaythepaletteshouldlook.


Ifyouclick“ChangeVisibleCategories…”youmaychangewhichCategoriesyouwanttohave
visible.



Tutorial:AnIntroductiontoLabVIEW


12

2.4.1



StartusingLabVIEW


NumericSubPalette

“NumericalControl”and“NumericalIndicator”arethemostusedobjectsinthenumericsub
palette.



2.4.2

BooleanSubPalette

Thispalettehaslotsofdifferentbuttonsyoumayuse.OK,CancelandStopbuttonsare
useful.

Tutorial:AnIntroductiontoLabVIEW


13



StartusingLabVIEW



2.4.3

String&PathSubPalette

IntheStringandPathpalettewehaveStringControls,ComboBox,etc.




2.5 FunctionPalette
TheFunctionspaletteisavailableonlyontheblockdiagram.TheFunctionspalettecontains
theVIsandfunctionsyouusetobuildtheblockdiagram.

Tutorial:AnIntroductiontoLabVIEW


14



StartusingLabVIEW



2.6 ToolsPalette
Youcancreate,modify,anddebugVIsusingthetoolslocatedonthefloatingToolspalette.
TheToolspaletteisavailableonboththefrontpanelandtheblockdiagram.Atoolisa
specialoperatingmodeofthemousecursor.Thecursorcorrespondstotheiconofthetool
selectedintheToolspalette.Usethetoolstooperateandmodifyfrontpanelandblock
diagramobjects.

Tutorial:AnIntroductiontoLabVIEW


15




StartusingLabVIEW


TheToolspaletteisavailablefromtheViewmenu:


Ifyoumakesure“Automaticwiring”isdisabled(Irecommendyoudoso!)youmayuse
theTabkeyonyourkeyboardinordertoswitchbetweenthemostcommontools.
Themostusedtoolsare:
UsetheOperatingtool,shownatleft,tochangethevaluesofacontrolorselect
thetextwithinacontrol.TheOperatingtoolchangestotheiconshownatleftwhenit
movesoveratextcontrol,suchasanumericorstringcontrol.
UsethePositioningtool,shownatleft,toselect,move,orresizeobjects.The
Positioningtoolchangestoresizinghandleswhenitmovesovertheedgeofaresizable
object.
UsetheLabelingtool,shownatleft,toedittextandcreatefreelabels.The
Labelingtoolchangestothefollowingicon

whenyoucreatefreelabels.

UsetheWiringtool,shownatleft,towireobjectstogetherontheblockdiagram.

Tutorial:AnIntroductiontoLabVIEW


16




StartusingLabVIEW

2.7 Wiring
InordertocreatethelogicalflowbetweentheobjectontheBlockDiagram,youneedtouse
theWiringtoolinordertoconnectthedifferentobjectstogether.
UsetheWiringtooltowireobjectstogetherontheblockdiagram.
AvailableKeyboardShortcutswhendealingwithWiring:


Ctrl-Bisveryuseful.Thisshort-cutremovesallbrokenwiresontheBlockDiagram.

2.8 Toolbar
BelowweseetheLabVIEWToolbar:

Thebehaviorsofthedifferentbuttonsareasfollows:

Tutorial:AnIntroductiontoLabVIEW


17



StartusingLabVIEW

ClicktheRunbuttontorunaVI.LabVIEWcompilestheVI,ifnecessary.YoucanrunaVI
iftheRunbuttonappearsasasolidwhitearrow.Thesolidwhitearrow,shownabove,also
indicatesyoucanusetheVIasasubVIifyoucreateaconnectorpanefortheVI.
WhiletheVIruns,theRunbuttonappearsasshownatleftiftheVIisatop-levelVI,

meaningithasnocallersandthereforeisnotasubVI.
IftheVIthatisrunningisasubVI,theRunbuttonappearsasshownatleft.
TheRunbuttonappearsbroken,shownatleft,whentheVIyouarecreatingorediting
containserrors.IftheRunbuttonstillappearsbrokenafteryoufinishwiringtheblock
diagram,theVIisbrokenandcannotrun.ClickthisbuttontodisplaytheErrorlistwindow,
whichlistsallerrorsandwarnings.
ClicktheRunContinuouslybutton,shownatleft,toruntheVIuntilyouabortorpause
execution.Youalsocanclickthebuttonagaintodisablecontinuousrunning.
WhiletheVIruns,theAbortExecutionbutton,shownatleft,appears.Clickthisbutton
tostoptheVIimmediatelyifthereisnootherwaytostoptheVI.Ifmorethanonerunning
top-levelVIusestheVI,thebuttonisdimmed.
Note:AvoidusingtheAbortExecutionbuttontostopaVI.EitherlettheVIcompleteitsdata
owordesignamethodtostoptheVIprogrammatically.Bydoingso,theVIisataknown
state.Forexample,placeabuttononthefrontpanelthatstopstheVIwhenyouclickit.
ClickthePausebutton,shownatleft,topausearunningVI.WhenyouclickthePause
button,LabVIEWhighlightsontheblockdiagramthelocationwhereyoupausedexecution,
andthePausebuttonappearsred.ClickthebuttonagaintocontinuerunningtheVI.

2.9 Execution
InadditiontotheToolbarbuttonsabovethefollowingKeyboardShortcutsareavailable
whendealingwithExecution:


Tutorial:AnIntroductiontoLabVIEW


18




StartusingLabVIEW



2.10

TheObjectsshort-cutmenu

Themostoften-usedmenuistheobjectshortcutmenu.AllLabVIEWobjectsandempty
spaceonthefrontpanelandblockdiagramhaveassociatedshortcutmenus.Usethe
shortcutmenuitemstochangethelookorbehavioroffrontpanelandblockdiagram
objects.Toaccesstheshortcutmenu,right-clicktheobject,frontpanel,orblockdiagram.
TheNumericcontrolhasthefollowingshort-cut/right-clickmenu:


Theshort-cutmenuwillbedifferentforthedifferentcontrolsorobjects.

Tutorial:AnIntroductiontoLabVIEW


×