tutorial_ for loops and while loops - national instruments

8
Tutorial: For Loops and While Loops Publish Date: Apr 01, 2015 Overview This tutorial explores some of the basic functions and uses of For Loops and While Loops. You will learn how to create For Loops and While Loops and when the appropriate time would be to use them in your program. Table of Contents A while loop is a control flow statement you use to execute a block of the subdiagram code repeatedly until a given Boolean condition is met. First, you execute the code within the subdiagram, and then the conditional terminal is evaluated. Unlike a for loop, a while loop does not have a set iteration count; thus, a while loop executes indefinitely if the condition never occurs. A for loop is a control flow statement you use to execute a block of the subdiagram code a set number of times, but a while loop stops executing the subdiagram only if the value at the conditional terminal exists. Building a While Loop 1. Open a new VI. You can open a blank VI by selecting File»New VI 2. If the Functions palette is not visible, rightclick any blank space on the block diagram to display a temporary version of the palette. Click the thumbtack in the upper left corner of the Functions palette to pin the palette so it is no longer temporary. 3. Select the while loop from the Structures palette under the Functions palette.

Upload: raja-rahman-way

Post on 18-Dec-2015

48 views

Category:

Documents


4 download

DESCRIPTION

labview

TRANSCRIPT

  • Tutorial:ForLoopsandWhileLoopsPublishDate:Apr01,2015

    OverviewThistutorialexploressomeofthebasicfunctionsandusesofForLoopsandWhileLoops.YouwilllearnhowtocreateForLoopsandWhileLoopsandwhentheappropriatetimewouldbetousetheminyourprogram.

    TableofContents

    AwhileloopisacontrolflowstatementyouusetoexecuteablockofthesubdiagramcoderepeatedlyuntilagivenBooleanconditionismet.First,youexecutethecodewithinthesubdiagram,andthentheconditionalterminalisevaluated.Unlikeaforloop,awhileloopdoesnothaveasetiterationcountthus,awhileloopexecutesindefinitelyiftheconditionneveroccurs.

    Aforloopisacontrolflowstatementyouusetoexecuteablockofthesubdiagramcodeasetnumberoftimes,butawhileloopstopsexecutingthesubdiagramonlyifthevalueattheconditionalterminalexists.

    BuildingaWhileLoop

    1.OpenanewVI.YoucanopenablankVIbyselectingFileNewVI2.IftheFunctionspaletteisnotvisible,rightclickanyblankspaceontheblockdiagramtodisplayatemporaryversionofthepalette.ClickthethumbtackintheupperleftcorneroftheFunctionspalettetopinthepalettesoitisnolongertemporary.3.SelectthewhileloopfromtheStructurespaletteundertheFunctionspalette.

  • 4.Usethecursortodragaselectionrectanglearoundthesectionoftheblockdiagramyouwanttorepeat.

    5.Whenyoureleasethemousebutton,awhileloopboundaryenclosesthesectionyouhaveselected.

    6.PlaceaStopbuttononthefrontpanel.YoucanfindthisunderControlsPaletteBooleanStop.

    7.AddtheStopbuttonfromtheblockdiagramtothewhileloopbydragginganddroppingitinsidethewhileloop.

    8.Theconditionalterminal,shownbelow,defineswhentheloopstops.Therearetwosettingsfortheconditionalterminal:ContinueifTrueandStopifTrue.WhensettoContinueifTrue,thewhilelooprunsonlyifaBooleanvalueoftrueissenttotheterminal.IftheconditionalterminalissettoStopifTrue,andaBooleanvalueoftrueissenttotheconditionalterminal,theloophaltsexecution.

    StopifTrue

  • ContinueifTrue

    9.ToswitchtheconditionalterminalbetweenContinueifTrueandStopifTrue,rightclickontheconditionalterminalandcheckthecorrespondingsetting.

    10.WiretheStopbuttontotheconditionalterminalsothatyoucancontroltheexecutionofthewhileloop.WhentheStopbuttonispressed,atruevalueispassedtotheconditionalterminalcausingthewhilelooptostopexecution.YoucanwireanyBooleandatatotheconditionalterminaltocontroltheexecutionofawhileloop.

    11.Theiterationterminalisanoutputterminalthatcontainsthenumberofcompletediterations.Theiterationcountalwaysstartsatzero.Duringthefirstiteration,theiterationterminalreturns0.

    12.YouhavejustcreatedasimplewhileloopthatgeneratesrandomnumbersanddisplaysthemuntiltheStopbuttonispressed.

    StructureTunnels

    Usestructuretunnelstofeeddataintoandoutofstructureslikethewhileloop.Ifyouwanttosenddataintoyourwhileloop,youneedtocreatestructuretunnels.DatasentintotheWhileLoopissentonlyonthefirstiteration,anddatasentoutofthewhileloopissentonlyafterthelastiteration.Nowcreateastructuretunneltodisplaythenumberofiterationsexecuted.

    1.Createanumericindicatoronthefrontpanel.

  • 2.Dragadatawirefromtheiterationcounterintotheborderofthewhilelooptocreateastructuretunnel.

    3.Thetunnelappearsasasolidblockontheborderofthewhileloop.Theblockisthecolorofthedatatypewiredtothetunnel.Datapassoutofaloopaftertheloopterminates.Whenatunnelpassesdataintoaloop,theloopexecutesonlyafterdataarriveatthetunnel.

    4.Dragadatawirefromthestructuretunnelintothenumericindicatortopassthenumberofiterationstoyourdisplay.

    5.Inthefollowingblockdiagram,theiterationterminalisconnectedtoatunnel.Thevalueinthetunneldoesnotgetpassedtotheiterationindicatoruntilthewhileloopfinishesexecuting.

    ManipulatingtheConditionalTerminal

    ByusingBooleanfunctions,youcanimplementmultipleconditionstoaffectyourwhileloopconditionalterminal.YoucanuseanorfunctiontocompareanerrorwirestatusandaStopbuttoncontrolsothatifeitherisTRUE,theconditionalterminalreceivesaTRUEsignal,andthewhileloopstops.

    1.Createawhileloopasoutlinedpreviously.

    2.PlaceanErrorIn3D.ctlcontrolonthefrontpanel.YoucanfindthisunderControlsPaletteArray,Matrix&ClusterErrorIn3D.ctl.

  • 3.RemovetheconnectionwirebetweentheStopbuttonandtheconditionalterminal.4.MakesuretheErrorIn3D.ctlisoutsideofthewhileloop.5.PlaceaSimpleErrorHandleroutsideofthewhileloop.YoucanfindthisunderFunctionsPaletteDialog&UserInterfaceSimpleErrorHandler.vi.Thisfunctionreportsanyerrorsencounteredwhencalled.

    6.LinktheerrorincontrolwiththeSimpleErrorHandlerthroughthewhileloopviastructuretunnels.Dragawirefromtheoutputoftheerrorincontroltotheborderofthewhileloop,andthendragtheerrorwirefromthetunnelcreatedtotheoppositeborderofthewhileloopandintotheinputoftheSimpleErrorHandler.

    7.PlaceanUnbundleByNamefunctioninsideofthewhileloop.YoucanfindthisunderFunctionsPaletteProgrammingCluster,Class,&Variant.ThisfunctionseparatestheBooleanportionoftheerrordatawire.

    8.Placeanorfunctioninsideofthewhileloop.YoucanfindthisunderFunctions

  • PaletteProgrammingBoolean.

    9.Linkthedatawiresasshownbelow.ThissimpleVIstopsexecutionofthewhileloopifeithertheStopbuttonispressedoranerrorisdetectedinsideofthewhileloop.

    BuildingaForLoop

    1.OpenanewVI.YoucanopenablankVIbyselectingFileNewVI.2.IftheFunctionspaletteisnotvisible,rightclickanyblankspaceontheblockdiagramtodisplayatemporaryversionoftheFunctionspalette.ClickthethumbtackintheupperleftcorneroftheFunctionspalettetopinthepalettesoitisnolongertemporary.3.SelecttheforloopfromtheStructurespaletteundertheFunctionspalette.

    4.Youalsocanplaceawhileloopontheblockdiagram.RightclicktheborderofthewhileloopandselectReplacewithForLoopfromtheshortcutmenutochangeawhilelooptoaforloop.

  • 5.Aforloopcontainsacountterminal.Thecountterminaldictateshowmanytimesthesubdiagramisexecuted.6.RightclickonthecountterminalandCreateConstanttolinkthecountterminalwithanumericvalue.

    7.Byinserting100intothenumericconstant,theforloopexecutes100timesbeforestopping.

    8.Theiterationterminal,shownasfollows,isanoutputterminalthatcontainsthenumberofcompletediterations.Theexamplebelowwouldupdateanindicatoronthefrontpanelwiththecurrentiterationnumber.

    AddingaConditionalTerminaltoaForLoop

    Ifnecessary,youcanaddaconditionalterminaltoconfigureaforlooptostopwhenaBooleanconditionoranerroroccurs.1.RightclickontheedgeoftheforloopandselectConditionalTerminal.

    2.Aforloopwithaconditionalterminalexecutesuntiltheconditionoccursoruntilalliterationsarecomplete,whicheverhappensfirst.3.Forloopsyouconfigureforaconditionalexithavearedglyphinthecountterminalaswellasaconditionalterminalinthelowerrightcorner.

  • 4.Afteryouconfiguretheforlooptoexitconditionally,theloopappearssimilartothefigurebelow.Thefollowingforloopgeneratesarandomnumbereveryseconduntil100secondshaspassedortheuserclickstheStopbutton.

    Formoreinformationontheusesofforloopsandwhileloops,refertotheContextHelp.YoucanaccessContextHelpfromHelpShowContextHelporusingtheshortcut.

    VideoExerciseLoopsModulesHomeFIRSTCommunity