+ All Categories
Home > Documents > Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4...

Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4...

Date post: 05-Aug-2020
Category:
Upload: others
View: 3 times
Download: 0 times
Share this document with a friend
28
4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series of nine activities. These activities are designed to be done either on one’s own outside of the laboratory or under the instructor’s direction in the lab. We first explore the LabVIEW environment with its graphical controls, indicators and functions. We then continue with the structures of G: the WHILE loop, the FOR loop, the Graph and file I/O. These activities are preparation for Chapter 5. Our Intent Our intent in this chapter is to survey the most important elements of G as quickly as possible. These elements include the usual constructs of any program- ming language: data types, representation, precision, logic, simple arithmetic, loops and arrays, strings, reading and writing files and dealing with errors. Because of our objective and the time available to us, we can not be as systematic or as comprehensive in detail as might be the norm in a course in Computer Science. In fact, the Computer Science major taking this course might sense that we are cutting corners by sacrificing depth for breadth. If our strategy is successful in teaching G as we intend, we shall make no apology for it. The LabVIEW Environment LabVIEW’s programming language is called G, which stands for “Graphical”. You may already have opera- ted LabVIEW demonstrations in your reading of the previous three chapters, so you should have a flavour of how it works. You know how to boot LabVIEW on the lab computers, how to open a virtual instrument (or VI) and how to make the VI “go” by clicking on buttons on the VI’s panel. In this short introduction to G we shall not have a lot to say about the history of G or the philosophy behind LabVIEW. This you can read about from the recommended text for the course. 1 Suffice us to say that G has the functionality and power of PASCAL or C, with the advantage over conventional line-oriented languages in enabling the programmer to build a working program in a fraction of the time that would otherwise be required. This speed is the result of being able to lay down code with graphical devices or icons called virtual instruments (VIs). VIs can be functions, operations or subprograms. The VIs are connected together with wires—yes, with wires—on a computer screen. It is not surprising that the business of coding in G has been likened to the wiring of a virtual electronic circuit because the code ends up resembling an electronic circuit diagram. We shall assume here that you know enough about the operating system of your computer to be able to run LabVIEW. When LabVIEW boots it presents the programmer with two windows called “Untitled 1” and “Untitled 1 Diagram”. The former we shall refer to simply as the Panel (Figure 4-1a), the latter the Diagram (Figure 4-1b). The Panel is the workspace where you construct the panel or “front face” of your virtual instrument—that part you want the user to see—using controls from the Controls Palette. A control might be an ON/OFF button, a container for a numeric or string input and the like. The Diagram is where you assemble the program code using functions from the Functions palette. Functions might be arithmetic functions, comparison functions and so forth. You can switch from the Panel to the Diagram by clicking in a window bar in the usual Mac/Windows fashion or by selecting the window you wish to be uppermost from the Window menu. You can move these windows anywhere on the screen as was, in fact, done to produce Figures 4-1 on the next page.
Transcript
Page 1: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

4-1

Chapter 4Introduction to G

We begin our study of the G programming language with a series of nine activities. Theseactivities are designed to be done either on one’s own outside of the laboratory or under theinstructor’s direction in the lab. We first explore the LabVIEW environment with its graphicalcontrols, indicators and functions. We then continue with the structures of G: the WHILE loop,the FOR loop, the Graph and file I/O. These activities are preparation for Chapter 5.

Our Intent

Our intent in this chapter is to survey the mostimportant elements of G as quickly as possible. Theseelements include the usual constructs of any program-ming language: data types, representation, precision,logic, simple arithmetic, loops and arrays, strings,reading and writing files and dealing with errors.Because of our objective and the time available to us,

we can not be as systematic or as comprehensive indetail as might be the norm in a course in ComputerScience. In fact, the Computer Science major takingthis course might sense that we are cutting corners bysacrificing depth for breadth. If our strategy issuccessful in teaching G as we intend, we shall makeno apology for it.

The LabVIEW Environment

LabVIEW’s programming language is called G, whichstands for “Graphical”. You may already have opera-ted LabVIEW demonstrations in your reading of theprevious three chapters, so you should have a flavourof how it works. You know how to boot LabVIEW onthe lab computers, how to open a virtual instrument(or VI) and how to make the VI “go” by clicking onbuttons on the VI’s panel.

In this short introduction to G we shall not have alot to say about the history of G or the philosophybehind LabVIEW. This you can read about from therecommended text for the course.1 Suffice us to saythat G has the functionality and power of PASCAL orC, with the advantage over conventional line-orientedlanguages in enabling the programmer to build aworking program in a fraction of the time that wouldotherwise be required. This speed is the result ofbeing able to lay down code with graphical devices oricons called virtual instruments (VIs). VIs can befunctions, operations or subprograms. The VIs areconnected together with wires—yes, with wires—on acomputer screen. It is not surprising that the businessof coding in G has been likened to the wiring of avirtual electronic circuit because the code ends up

resembling an electronic circuit diagram.We shall assume here that you know enough about

the operating system of your computer to be able torun LabVIEW. When LabVIEW boots it presents theprogrammer with two windows called “Untitled 1”and “Untitled 1 Diagram”. The former we shall referto simply as the Panel (Figure 4-1a), the latter theDiagram (Figure 4-1b).

The Panel is the workspace where you construct thepanel or “front face” of your virtual instrument—thatpart you want the user to see—using controls fromthe Controls Palette. A control might be an ON/OFFbutton, a container for a numeric or string input andthe like.

The Diagram is where you assemble the programcode using functions from the Functions palette.Functions might be arithmetic functions, comparisonfunctions and so forth. You can switch from the Panelto the Diagram by clicking in a window bar in theusual Mac/Windows fashion or by selecting thewindow you wish to be uppermost from theWindow menu. You can move these windowsanywhere on the screen as was, in fact, done toproduce Figures 4-1 on the next page.

Page 2: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-2

Figure 4-1a. The LabVIEW Panel with the default name “Untitled 1”. This is the workspace where you place buttons andcontrols (from the Controls Palette at the right) to build the front panel of your virtual instrument. An asterix placed next tothe name indicates this document has yet to be saved.

Figure 4-1b. The LabVIEW Diagram with the default name “Untitled 1 Diagram”. This is where you assemble the programcode using functions from the Functions palette at the right.

Page 3: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-3

The LabVIEW Menubar

For your convenience in following what goes on here as you read this should you not have a computer in front ofyou, we have reproduced the Mac version of the LabVIEW menubar in Figure 4-2a. On a PC running Windows95/98/NT a similar menu appears at the top of each Panel and Diagram window. In Figures 4-2b through 4-2ethe File, Edit, Help and Window menus are shown pulled down. These menus have many more items than youwill ever have need of in this course. The items you will likely use are pointed out in the figure captions.

Figure 4-2a. LabVIEW’s menu bar as it appears along the top of the screen on a Macintosh.

Figure 4-2b. LabVIEW’s File menu. The most important

items here are New VI, Open, Save, Save As and Quit. On

a PC, Quit is replaced by Exit.

Figure 4-2c. LabVIEW’s Edit menu. The most important

items here are Paste and Remove Broken Wires.

Figure 4-2d. LabVIEW’s Help menu. The most important

items here are Show Context Help and VI, Function, &

How-To Help....

Figure 4-2e. LabVIEW’s Window menu. The most import-

ant items here are Show Panel or Diagram, Show Function

or Controls Palette and Show Tools Palette. The check mark

shows that the Panel window “Untitled 1 Diagram” is

currently uppermost.

Page 4: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-4

The Panel Menubar

We continue our survey of the LabVIEW environmentwith a study of the menubar of the Panel. The Paneland Diagram have similar menubars (Figure 4-3a). Atthe left end of each menubar is the Run button; youclick this button when you wish to start a VI running.Next come the Run Continuously, Abort Execution andPause buttons. These buttons resemble the buttons ona VCR and function in ways that should be self-evident. The next, long button gives the Text Settingspulldown menu (Figure 4-3b). The next three buttons

provide edit functionality and enable you to changecertain attributes of objects on the Panel that happento be selected at the time: Align Objects (Figure 4-3c),Distribute Objects (Figure 4-3d) and Reorder (Figure 4-3e). What these selections do is briefly explained inthe captions accompanying the figures below. Theirvalue will become more evident to you in thefollowing activities in this chapter when you come toconstruct the Panel of your own VI.

Figure 4-3a. The Panel menubar. The name of a button is displayed when the mouse pointer is held over the button.

Figure 4-3b. A portion of the Text Settings pulldown menu.This menu resembles a text menu in a wordprocessor andhas roughly the same functionality.

Figure 4-3c. The Align Objects palette. Objects on the Panelcurrently selected can be aligned in various ways asexplained symbolically by the icons.

Figure 4-3d. The Distribute Objects palette. Objects on thePanel currently selected can be distributed or separated invarious ways explained symbolically by the icons.

Figure 4-3e. The Reorder palette. Objects on the Panelcurrently selected can be reordered (moved on top orbeneath one another) in the ways stated.

Page 5: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-5

Activity #1. Getting Acquainted with Tools, Controls and FunctionsHere we examine the three palettes, the Tools Palette, Controls Palette and Functions Palette. Hereyou will learn how to take your first steps in building a VI—how to select a Control and anIndicator from the Controls Palette, how to place them on the Panel and how to navigate throughLabVIEW menus to examine some of the properties of a Control and an Indicator. To give ameasure of guidance we begin by providing a number of detailed instructions, which you maychoose to follow …or not. We expect that as you become more experienced with LabVIEWselecting from palettes and switching between windows you will need to follow such explicitinstructions less closely.

The Tools PaletteWhether you are working on the Panel or the Dia-gram you will need some kind of tool from the ToolsPalette (Figure 4-4a). If the Tools Palette is not visiblethen make it visible by selecting Window >> ShowTools Palette.

Figure 4-4a. The Tools Palette showing the “Operate Value”tool selected with its “help name” showing. To show helpnames just move the mouse pointer over the tool of interest;the help name appears automatically.

From this palette you select the tool you need toperform a specific task—to place a Control on thepanel, to place a function on the Diagram, to inserttext, to move icons around on the Panel or Diagramand to wire VIs together. We shall examine most ofthese tasks in this chapter. But first we examine howto use the Operate Value tool and how to navigatesubmenus of the Controls and Functions Palettes.

You should be able to interpret the meaning of thetools in the Tools Palette from their icons. The item ofinterest to us here is the first item in the second row—the tool with the icon of a hand called the “OperateValue” tool. This tool is used to pick a Control and anIndicator and to place them on the panel.

The Controls PaletteA Control serves as an input to a section of code andan Indicator holds or displays the output. The Con-trols Palette contains Indicators as well as Controls.For the moment we concentrate on Controls. Do thefollowing:

¬ Ensure the Panel is the uppermost window andthe Controls Palette is visible.

Á Ensure the Operate Value tool in the Tools Palette(Figure 4-4a) is selected.

 Move the mouse pointer slowly over the variousitems in the Controls Palette (Figure 4-4b) to seetheir names printed at the top of the palette.

Figure 4-4b. The Controls Palette. The pointer is currentlyheld over the Numeric item and its name is printed abovethe Controls area of the palette.

à With the mouse pointer over the Numeric item onthe Controls Palette, click the (left) mouse buttononce. The Controls Palette will now be replacedby the Numeric subpalette (Figure 4-5).

° Place the mouse pointer over the item DigitalControl and click the (left) mouse button once to

Page 6: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-6

select it.

Figure 4-5. The Numeric subpalette that replaces the Con-trols palette when the pointer is moved over the Numericitem on the Controls Palette and then clicked once.

Å You should now spot a digital control “attached”to your cursor. Move the cursor over the Paneland click the (left) mouse button in a convenientlocation to drop the Control on the Panel. TheControl should appear as is shown in Figure 4-6.

Figure 4-6. The Panel showing the Control in position andthe Operate Value tool placed over its bottom edge.

LabVIEW gives this Control the name “Numeric” bydefault and assigns it a value of zero with a precisionof two. This brings us in the next section to the topicsof numeric type, representation, format and precision.

Numeric Type, RepresentationFormat and Precision

You can see from the number (0.00) LabVIEW hasplaced in the Control (Figure 4-6) that the Control hasthe default representation of floating point. But to findout exactly the variety of floating point number do thefollowing:

¬ Place the Operate Value tool on the bottom edgeof the Control (Figure 4-6), hold down the com-

mand (z) key and the mouse button together.(From now on we shall call this action a z-click;on a PC click the right mouse button.) If you dothis correctly a menu and submenu will dropdown as shown in Figure 4-7. You may have topractice this a few times to get the menu youwant.

Figure 4-7. The numeric control dropdown menus.

Á Navigate down through the menu and stop atRepresentation. You can see from the subpal-ette that the representation is double precisionfloating point (LabVIEW calls this a DBL).

To find out the format and precision of the number,do the following:

 Repeat step Á but this time stop at Format &Precision… and release the mouse button. Adialog box will appear (Figure 4-8). You can seethat the format is numeric, notation is floatingpoint, and precision is 2 digits. By this time youmay have guessed that you could have changedthe Representation and Precision if you wantedjust by making your own choices from this dialog.(But to avoid possible confusion in the nextactivity, don’t change anything.)

Page 7: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-7

Figure 4-8. The Format and Precision dialog box.

Controls vs IndicatorsNow we come to the subject of Indicators. All pro-gramming languages have inputs and outputs—toand from subroutines, for example. In G, a Controlserves as an input and an Indicator serves as an out-put. You might input a number to a function via aControl on the Panel and you might output the resultof the function (a calculation, an operation or what-ever) in an Indicator—also on the Panel. Controls andIndicators handle data of a type set by default whenyou select them—boolean, numeric or string amongothers.

Selecting and Placing an IndicatorAn Indicator is selected and placed on the Panel muchlike a Control. But for some reason, LabVIEW groupsIndicators with Controls on the same Controls Palette.To place an indicator do the following:

¬ Ensure the Panel is the uppermost window andthe Controls Palette is visible. Select the OperateValue tool.

Á Move the mouse pointer over the Numeric item inthe Controls Palette and select a Digital Indicator.Digital Indicator is the icon next to Digital Control(look back to Figure 4-5).

 Move the mouse pointer slowly over the Paneland click the (left) mouse button somewhere tothe right of the Control you placed earlier. ThePanel should resemble Figure 4-9.

Figure 4-9. The Control and Indicator on the Panel aregiven default names by LabVIEW.

Notice that the Indicator resembles a Control but isnot a Control. The two icons differ in that the Controlhas “up” and “down” arrow bottons attached to itsleft edge whereas the Indicator has no such buttons.

The Function PaletteTo prepare for Activity #2 we turn our attention tofunctions, the Function Palette and placing the func-tion on the Diagram.

¬ Switch to the Diagram, select the Operate Valuetool and ensure the Functions Palette is visible(Figure 4-10).

Figure 4-10. The Functions Palette.

Á Move the mouse pointer over the various items inthe Functions Palette to see their names printed atthe top of the palette. For example, in Figure 4-10the pointer is shown positioned over the Numericitem.

Page 8: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-8

 With the pointer over the Numeric item, click the(left) mouse button once; the numeric subpalettewill then appear (Figure 4-11). Select the functionAdd. You should see a function Add “attached” toyour cursor.

Figure 4-11. The Numeric subpalette.

à Move the pointer over the Diagram and place thefunction Add somewhere between the Control andIndicator you placed earlier. The result shouldresemble Figure 4-12.

Figure 4-12. The Diagram at this stage of construction of aVI. A Control can be distinguished from an Indicator by itsboldface border; an Indicator has a normal border.

You can label your VI as follows:

¬ Switch to the Panel and select the Edit Text tool.Á Move the Edit Text tool over the Panel and some-

where convenient above the control and indicator,click the mouse button to insert the cursor. Thentype your name and the date. To terminate your

entry of text, click the text tool anywhere outsidethe text area or click once on the Position/Size/Select tool..

® Select the Position/Size/Select tool and click onthe text you have just entered to select it. Nowexperiment with the Text Settings Palette to getthe text size and style you want. Try to make yourPanel resemble what is shown in Figure 4-13.

Figure 4-13. The Panel of your VI at this stage shouldresemble what is shown here.

Printing and Saving WorkPrintingIn order to document your participation in labs, youwill be asked to either print out your results or save iton a floppy. To print do the following:

à Select Edit >> Print Window. The Panel of yourVI with your name on it will then print on theLaserWriter printer in the physics lab.

SavingIf you are doing this as part of Lab #2 you will beasked to save your work on a floppy. To save your VIdo the following:

¬ Select File >> Save As. In the dialog box thatappears type in a name of your choice (wesuggest MyFirst.vi) and navigate to the floppy. (Ifyou are rusty at saving files on a Macintosh pleaseask your instructor to show you how to do this.)

Á Then click Save.

We now continue with a little arithmetic.

Page 9: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-9

Activity #2. A Little ArithmeticArithmetic lies at the heart of all programming languages. In this activity you will code a VI toperform the operations of addition and division. You will learn how to wire VIs together andhow to deal with some aspects of LabVIEW error checking.

AdditionOur objective is to add two numbers together andplace the result in an indicator, so do the following:

¬ Begin with the Numeric Control, Indicator andfunction Add you laid down in Activity #1. If yousaved your work as a VI then load it. Otherwiseyou will have to lay down the controls, etc., again.

Á Place a second digital control directly beneath thefirst. You should now have two digital controlsand one Indicator (with default names) on yourPanel (resembling Figure 4-14).

Figure 4-14. At this stage your Panel should show a digitalindicator to the right of the two digital controls.

 Now for practice typing, select the Edit Text tooland carefully replace the default labels on thecontrols and indicators with your own labels. Toplace the cursor in a text area you need to care-fully position the cursor at the end of a text areaand then click the (left) mouse button once toinsert the cursor. Delete the old text then type inthe new. One result of this effort is shown inFigure 4-15.

Figure 4-15. One result of editing the labels of the controlsand indicators of Figure 4-14.

à Now switch to the Diagram. You should see twocontrols and one indicator (Figure 4-16). As wehave seen in a previous section they are definedby default as double precision floating pointnumbers (DBLs).

Figure 4-16. How the controls and indicator of Figure 4-15appear on the Diagram.

Coding and Wiring and Making MistakesYou will now wire the function Add to the controlsand indicators. Getting the hang of wiring is tricky forbeginners, so try the following:

¬ Select the Wiring tool. This is the tool on the Toolspalette whose icon resembles a spool of wire.Move the wiring tool over the right end of thecontrol First Number. The control blinks whenLabVIEW senses that the wiring tool is over avalid contact point for wiring. While the contactpoint is blinking, click the (left) mouse buttononce to initiate the wiring action and drag themouse over to the upper input contact point onthe function Add. As you move the mouse along,you should see a dashed wire form and expand.When you reach the input of the function Addclick the (left) mouse button a second time to fixthe wire in place. If you do this correctly the resultwill appear as is shown in Figure 4-17. Otherwiseyou will end up with a “bad” wire (Figure 4-18).

Á If you do get a bad wire you can remove it byselecting Edit >> Remove Broken Wires . Youcan also remove the broken wire by selecting it by(left) clicking on it with the pointer tool and thenpressing the <Delete> key.

 Go ahead and wire the two controls to the twoinputs on the function Add and wire the output of

Page 10: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-10

the function Add (its tip) to the indicator Result.The end product should appear as is shown inFigure 4-19.

Figure 4-17. The control First Number is shown correctlywired to the top input of the function Add.

Figure 4-18. An unsuccessful attempt to do the above hasleft a broken wire.

Figure 4-19. The items wired correctly.

On Precision and the Use of ColorNotice on the figures above that the controls andindicator and the wires themselves are of one color—orange. (Colors are visible only in the electronic ver-sion of these notes.) This is G’s way of telling you thatthe datatypes are numeric and of type double precis-ion floating point. As already stated you can changethe precision of controls and indicators if you like.LabVIEW indicates other datatypes with different

colors, as we shall see in later sections in this chapter.

LabVIEW Error CheckingLabVIEW checks for errors during the programmingstage; notice in Figure 4-17 that the Run button isgreyed out. LabVIEW greys out the Run button aslong as a wire remains to be connected, or some otherdefect is detected while you are laying down code. Assoon as you connect the last remaining wire or correctthe last remaining flaw in the code, LabVIEW clearsthe Run button (Figure 4-19).

Running Your ProgramYou can now run your program to see what LabVIEWdoes with it. Do the following:

¬ Switch to the Panel.Á Select the Edit Text tool and type numbers of your

choice into the two control spaces. Run the VI. Examine the indicator Result. Has

your program worked as expected? A typicalresult is shown in Figure 4-20. Notice that each ofthe numbers are shown to two decimal places bydefault (and as expected).

Figure 4-20. The program appears to work correctly. Theprecision of Result (number of decimal places) is consistentwith the precision of the numbers input.

PolymorphismMany functions in G are described as polymorphic inthe sense that, unlike functions in many otherprogramming languages, they accept data of differentrepresentation. The function Add above is an exampleof this. To illustrate try the following:

¬ Switch to the Diagram.Á Select the Operate Value tool and place the finger

of the tool over the control First Number. Now z-click (right-click) and select from the

menu that drops down: representation >>I32. The Diagram should now appear as shown

Page 11: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-11

in Figure 4-21.

Figure 4-21. The function Add is polymorphic in that itaccepts an I32 and a DBL at its two inputs.

Notice that the representation of the control FirstNumber is now an I32 (32-bit integer). The color of thecontrol and the wire connecting it to the top input ofthe function Add is now blue, indicating an integertype. But a small dot now appears at the top inputcontact point (look for it) indicating a type coersion. Gautomatically converts a 32-bit integer to a floating-point DBL at the input of an arithmetic function. Thisis one manifestation of polymorphism. Polymorphismmeans, among other things, that you can input an I32to the function Add if you like; but if you do, G con-verts it to a DBL at the input point. Since G requiresextra processing time (more CPU cycles) to do this, itis more efficient to avoid coersions of this kind if youcan.

DivisionIt is useful to know how to change the VI you havejust constructed to perform other arithmetic opera-tions, for example, division. This will enable you tosee how easy it is to change functions in G and howfriendly G is in dealing with results that in otherprogramming languages might result in a fatal error.Do the following:

¬ Switch to the Diagram.Á Select the Operate Value tool and place the finger

of the tool over the function Add. Now z-click (right-click) and select from the

menu that drops down: Replace >> Numeric>> Divide.

à Switch to the Panel and type an arbitrary numberinto the control First Number. Leave the controlSecond Number zero (or type in 0.00 if anothernumber occupies the space). Now click the Runbutton. The result might resemble Figure 4-22.What has happened?

Figure 4-22. The First Number divided by the SecondNumber yields infinity, indicated by “inf” in G.

G interprets an impossibly large number (23 dividedby zero) as infinity and places the special type “Inf” inthe indicator Result. In most other programminglanguages you would have been issued a far lessfriendly error message!

IncompatibilitiesWhen typing at the keyboard one can easily make themistake of typing a letter instead of a number. To seehow LabVIEW reacts if you try this on a numericcontrol try the following:

¬ Enter a String into a Numeric Control. Try typingsomething other than a DBL into the controlSecond Number—like the letter “a”. What happens?G refuses to accept a string type into a control thathas been predefined a numeric type.

Á Wire a String and a Numeric to a Function. Tryreplacing the control First Number with a stringcontrol. We explained how to perform a Replaceearlier in this chapter. How does LabVIEW res-pond? Do wires break? Is the Run button greyedout? Polymorphism is one thing, but trying towire a string and a numeric to an arithmeticfunction makes no sense in any programminglanguage! LabVIEW is smart enough to preventyou from doing this.

If you are doing this as part of Lab #2 save your workas MyDivide.vi on your floppy.

We now continue in Activity #3 with aspects of logic,another prerequisite of a programming language.

Page 12: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-12

Exercise #3. Logic, the WHILE Loop and Getting HelpIn G, as in other programming languages, the beginner can learn from reading and decipheringthe programs of others. Here you will decipher an existing VI, learn a little about the WHILE loopstructure in G, and how to get various kinds of LabVIEW help.

DecipheringTo get the VI to decipher do the following:

¬ Navigate to LabVIEW Demos >> Chapter 04 andload AND gate.vi. Its Panel and Diagram are repro-duced in Figures 4-23.

Figure 4-23a. The panel of the AND gate.vi from Chapter 3.

Figure 4-23b. The Diagram of the AND gate.vi.

IdentificationYou should be able to identify on the Diagram thethree boolean button controls A, B and stop and theone boolean indicator Q. A boolean Control and aboolean Indicator are selected in a manner similar to anumeric control and a numeric Indicator. A booleancontrol and indicator can be either ON (TRUE) or OFF(FALSE). (Normally, button indicators display thelabels ON or OFF. Here they have been edited todisplay a “1” or a “0”.)

You should be able to spot the function AND on theDiagram and the function invert (to the right of thecontrol stop). What is new to you in this figure is theWHILE loop which resembles a kind of rectangular

ring structure.

Understanding the VIBefore explaining the operation of this VI we firsthave you run it. So

¬ Run the VI. The VI will continue to run until youclick the stop button.

Á Click on the A and B buttons to change the statesof the inputs and convince yourself that the VIperforms the task of an AND gate.

 When you have had enough stop the VI.

The code in Figure 4-23b is simple enough to be des-cribed in a few words. When the Run button isclicked, G starts executing the code. The WHILE loopis entered from the left side of the loop and the codewithin the loop is executed from left to right and fromtop down. At the same time the stop button is tested.(G executes both groups of code in the WHILE loop inparallel.) If this button has not been clicked then thebutton reads FALSE. This FALSE state is inverted to aTRUE state by the inversion operation and passed tothe WHILE loop control in the lower right hand cor-ner of the loop. Since the Control reads TRUE the loopcontinues to execute. Thus the code for the AND gate isexecuted repetitively. The VI continues to execute solong as the stop button is not pressed. But as soon asyou press the stop button a logic FALSE is passed tothe WHILE loop Control and the loop is terminated.(The “i” in the lower left hand corner of the loop is theloop iteration counter which is not used here.)

Highlighting ExecutionLabVIEW has various kinds of help. One kind of helpis a tool called highlight. Highlight is useful whendebugging and in following how a VI works. Whenyou turn on highlight you can see the program flowby watching the movement of little dots along theconnecting wires in your code (on the Diagram). Touse highlight do the following:

¬ Start from the beginning with AND gate.vi loadedand its Panel and Diagram both visible.

Á Click on the light bulb icon in the menubar of the

Page 13: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-13

Diagram. This turns highlight ON. Run the VI.à As the VI runs, try following the dots in the

Diagram and the printing of the logic states at theoutput of controls and indicators. Figure 4-24shows the VI at one stage in its operation.

Figure 4-24. The Diagram of the AND gate.vi running withhighlight turned ON. You have to look closely to see the“T” and the “F”.

You should be able to spot the “T”s which are printedat the output of the boolean controls and the “F”printed at the output of the boolean control stop. Lookfor similar kinds of things on the VI as you run it.

Getting Simple HelpLabVIEW provides help on specific functions. Thehelp window for the function And is reproduced inFigure 4-25.

Figure 4-25. The help for the And gate function on the ANDgate.vi Diagram.

To get the help window for the function AND do the

following:

¬ Ensure the VI is stopped.­ With the Diagram visible select Help >> Simple

Help. Then move the pointer over the item ofinterest. Doing this for AND brings up the infor-mation in Figure 4-25. When you don’t need theHelp window anymore click on its Close box. Thiscloses the help window and turns help off.

Getting More HelpSometimes you will need more help than that pro-vided by Simple Help. For example, you may needhelp on a general topic or in a wide area of LabVIEWnot yet covered in these notes. In this case you canselect Help >> Online Help. A window will appearas is shown in Figure 4-26. You can choose to viewContents, Index, a Glossary etc. etc.

If you have used a web browser you should have notrouble navigating your way through the HelpContents. QuickLinks are underlined; just click onthem. When you have no more need of help simplyclick in the window Close box.

Figure 4-26. The Online Help window.

Page 14: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-14

Replace:Creating an OR Gate VI from an And Gate.vi

LabVIEW has a very useful Replace functionality youshould know about. To get a little practice using it tryreplacing an AND gate with an OR gate as follows:

¬ Switch to the AND gate.vi Diagram, move themouse pointer over the function AND on the Dia-gram, z-click (right-click) and navigate downthrough Replace and the drop down Booleanmenu and stop at Or (Figure 4-27). When yourelease the mouse button (and the z key), a func-

tion OR should be in place of the function AND.Á Now switch to the Panel, run the VI and satisfy

yourself that the VI performs the OR function.When you are satisfied stop the VI.

 With the Panel uppermost, replace the text on thePanel with something like: MyORGate.vi.

à If you are doing this as part of Lab #2 save the VIwith this new name to your floppy.

We now continue with Activity #4 and the topics ofloops and arrays.

Figure 4-27. Performing a Replacement.

Activity #4. Loops and ArraysOne important function of any programming language is the ability to access and operate onelements of an array. The FOR loop and the WHILE loop makes this possible in G.

The ArrayIn science, the data received from an instrument or asensor is conventionally stored in a numeric array. Anexample is shown in Figure 4-28, an array of datafrom a typical thermistor (Thermistor Data). The firstcolumn contains temperatures in Celsius, the secondthe corresponding resistances (in kΩ) of the ther-mistor’s semiconductor element (recall from Chapters1 and 2 and Lab #1 that a thermistor is an elementwhose resistance varies markedly with temperature).

In any programming language one typically needs tobe able to select specific elements in an array and tochange or operate on them. To give you experience indoing this we consider the arbitrary task of adding aconstant factor to each of the elements in the secondcolumn of Thermistor Data.

Do the following:

¬ Navigate to LabVIEW Demos >> Chapter 04 >>

Page 15: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-15

Data Folder and locate Thermistor Data.vi inside.Load the VI. Its Panel should appear as in Figure4-28. This VI is a single numeric 2D array controlwith data already inserted into it.

Figure 4-28. The array Thermistor Data in ThermistorData.vi.

Your task is to add a constant factor, say 1, to each ofthe numbers in the second column.

Á Switch to the Diagram and code the VI as shownin Figure 4-29a. When you choose the FOR loopyou will have to enlarge it to accommodate thefunction +1. When you have done this, switch tothe Panel and tidy up the Panel so it resemblesFigure 4-29b. We now take a few moments toexplain what we have done.

Figure 4-29a. The Diagram of the VI at this stage.

Notice that the icon for a FOR loop resembles thepages of a book (one page for each iteration of theloop). The “N” in the upper left hand corner of theloop sets the number of iterations to be executed.Sometimes, as in this case, with an array wired to theFOR loop, the “N” can be left unwired. This isbecause the loop will continue to iterate over allelements in the array until it gets to the last one. The

“i” in the lower left corner of the loop is the iterationcounter; this starts from zero.

Figure 4-29b. The Panel of the VI at this stage.

Starting from the original array Thermistor Data on theleft, the function Index Array “slices off” the whole ofthe second column. To make this function work asintended, you have to enlarge Index Array to include anextra dimension, and then you have to disable theindexing to the top (row) index. Wiring a constant “1”to the second (column) index will give you the secondcolumn (LabVIEW uses “zero indexing” so the firstcolumn has an index of “0”).

The second column then goes as a whole to the leftedge of the FOR loop. At the left edge of the FOR loopthe wire changes from array size to element size. Ifyou pop up on the tunnel on the left edge of the FORloop you can see that indexing is enabled; this meansthat the FOR loop will automatically access eachelement in the column array one after the other, onefor each iteration of the loop. Iteration will stop oncethe last element in the array has been accessed.

The function +1 inside the loop performs theoperation we want on the element indexed at the leftedge of the loop. The changed element then goes tothe right edge of the loop and ultimately to the outputarray. The right edge automatically takes eachelement fed to it and produces an array. This meansthat on the right edge of the loop the wire changesfrom single element size to array size.

Do the following:

¬ Run the VI. Does it work as expected?

Questions:How would you modify the VI to operate on the firstcolumn of the array?

Page 16: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-16

How would you modify the VI to operate on the firstor second rows of the array?

If you are doing this as part of Lab #2, save your work

as MyArray.vi on your floppy.

We now continue in the next activity with a first lookat strings.

Activity #5. A Few Good String FunctionsIn any programming language, string functions are equal in importance to arithmetic, loops andarrays. After all, responses from instruments take the form of strings. In this activity you willpractice parsing the kind of string returned by a typical low-cost digital multimeter, the RadioShack DMM. G has a number of string functions ready made for this purpose.

Coding the VITo set yourself up do the following:

¬ If LabVIEW is currently running then bring up afresh Panel by selecting New. If you have oldPanels and Diagrams open, then Save them if youneed to—otherwise just close their windows. Ifyou are booting LabVIEW then use the defaultPanel.

Á Building on what you have learned in earlieractivities in this chapter, construct the Panelshown in Figure 4-30. The panel has one StringControl, two String Indicators and two NumericIndicators. Label the string Indicators Mode andUnit respectively, and the Numeric IndicatorsValue and Length. This will enable you to followour description of them in what follows.

Figure 4-30. The Panel showing the one String Control andthe two String Indicators and the two Numeric Indicatorslabelled. The Align Objects Palette was used here to alignthe left edges of Mode, Value and Length.

 You now need to enter a typical response string.Scan ahead to the description of the Radio ShackDMM in Appendix A and locate the first exampleof a typical response string from the instrument.

NOTE: The last character in the string is <CR>, orcarriage return. The Radio Shack DMM interprets avoltage transition on its RxD line as a “send data”command.2 And it terminates the data string it sub-sequently returns with a <CR>. This means you mustsomehow enter a <CR> character into the string fromthe keyboard. If you try to do this now you might findthat the <CR> doesn’t show. So do the following:

à Select the Operate Value tool, place the fingerpointer over the lower edge of the indicatorResponse, z-click (right-click) and change thedisplay from Normal to ‘\’ Codes Display (Figure4-31). If you do this correctly a space will appearas the character group “\s”. You can now type a<CR> as the character group “\r”. The string youhave typed into the String Control shouldresemble what is shown in Figure 4-32.

Figure 4-31. Changing the Display Mode of a Control.

Page 17: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-17

Figure 4-32. A response string entered correctly. Note thespaces “\s” and the carriage return “\r”.

Ä Switch to the Diagram. Using what you learned inprevious activities code the Diagram shown inFigure 4-33. To assist you in deciphering the code,the help windows for the functions String Length,String Subset and Scan From String are reproducedin Figures 4-34, 4-35 and 4-36. Do you understandwhy the values indicated were chosen for theinteger inputs of the functions (shown in blue ona color monitor to the left of the functions)?

Figure 4-33. The Diagram after the functions have beenplaced and wired. The diagram has been tidied up for easierreading using tools from the Align Objects Palette.

Figure 4-34. Help for the String Length function.

Question: Why was it OK to leave the Offset input tothe first function String Subset at the top of theDiagram unwired?

Figure 4-35. Help for the function String Subset.

Figure 4-36. Help for the function Scan From String.

Å Switch to the Panel and run the VI. The outputshould resemble what is shown in Figure 4-37.The reason you were asked to label the indicatorsthe way you were should now be clear.

Figure 4-37. The completed Panel showing expected output.

Save Your WorkIf you are doing this as part of Lab #2 save your workas MyRSDecoder.vi on your floppy. You are going touse it again in the next activity.

This activity has illustrated a typical, extremely use-ful, LabVIEW task—the extraction from the responsestring of a typical instrument the subparts of measure-ment mode, numeric value and unit. Knowing how todo this will be useful when you actually come tocontrol this DMM (and other instruments) in Chapter5.

Page 18: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-18

Activity #6. The Sub-VIIn LabVIEW there are VIs and sub-VIs. VIs and sub-VIs are essentially the same, though the wordsub-VI is used specifically to describe a VI that serves as a subroutine. The VI you coded in theprevious activity is an ideal candidate for a sub-VI, for you will use it again in Chapter 5. A sub-VI is called from a main program. The main program sends it inputs and collects from it thesubsequent outputs. In LabVIEW you can create a sub-VI two ways: from a VI that already exists,or from a portion of code in your main program. Here we illustrate how to do this for a VI thatalready exists.

Creating a Sub-VITo create a sub-VI do the following:

¬ Load the VI you coded in the previous activity. Ifyou followed the suggestion it will be calledMyRSDecoder.vi.

The first step in preparing a VI for use as a sub-VI isto set up the connectors on the icon. Therefore…

Á Place the mouse pointer over the icon in the upperright hand corner of the Panel window, z-click(right-click) and select Show Connector fromthe drop down menu (Figure 4-38). If you do thiscorrectly the icon will change from icon view toconnector view (Figure 4-39).

Figure 4-38. The drop down menu for the VI icon.

In this example, LabVIEW automatically chooses aconnector style with five terminals, consistent withthe existence of the five Control/Indicators on thePanel. One of these terminals (the left one) can serve

as the input to your sub-VI, the remaining four (on theright) can serve as outputs. It is considered goodpractice to wire inputs to terminals on the left of anicon, outputs to terminals on the right.

Figure 4-39. The connector view of the VI icon. In thisexample, LabVIEW automatically chooses five connectors.There is one input (left) and four outputs (right).

 You must now “assign” each Control and Indi-cator on the panel to a specific terminal on theicon. This is done with the Wiring tool. Select thewiring tool from the Tools Palette, move it overthe control Response and click the mouse buttononce to select the control. If you do this correctly amarqee will run around the control (Figure 4-40).

Figure 4-40. To assign a Control to a terminal on the iconfirst click the wiring tool on the Control so as to select it.

à Now move the wiring tool so that its hot spot (thetip of the wire) is over the left hand terminal ofthe icon and click once (Figure 4-41). If you dothis correctly the terminal will change color toshow that a Control/Indicator has been assignedto it.

Page 19: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-19

Figure 4-41. The control Response has been assigned to theleft hand terminal of the icon.

Ä Now carry on and repeat this procedure for theIndicators, assigning each one to one of the fourremaining terminals of the icon. It doesn’t matterwhich indicator goes to which terminal sinceLabVIEW keeps track of their names. The endresult might resemble Figure 4-42.

Figure 4-42. The last of the indicators has been assigned to aterminal on the icon.

Å If you are doing this as part of Lab #2, save yourwork as MyRSDecoder.vi on your floppy and Closethe VI. You are now ready to learn in the nextsection how to use the sub-VI in a program.

Using a Sub-VITo learn how to use the sub-VI you have just createddo the following:

¬ Open a new VI and switch to the Diagram.Á Select Functions Palette >> Select a VI…

(in the lower right hand corner of the Palette).This will call up a dialog box for you to select afile. In the dialog box select MyRSDecoder.vi.

 Place the sub-VI in a convenient location on theDiagram. If you wish you can z-click (right-click)over the icon and select Show >> Label from thepulldown menu. The result might resembleFigure 4-43.

à Now that you have the sub-VI in place, you needto create the necessary controls and indicators.Figure 4-43 shows the icon view. But we need theterminal view to do this. To change to terminal

view place the cursor over the icon, z-click (right-click) and select Show >> Terminals. The resultshould resemble Figure 4-44.

Figure 4-43. MyRSDecoder.vi placed on a new Diagramand shown after a Show >> Label was performed.

Figure 4-44. Terminal view of MyRSDecoder.vi.

Ä LabVIEW has a useful shortcut for creatingcontrols and indicators for a sub-VI when theterminals of the icon are visible. To see this short-cut, place the mouse pointer over the left handterminal, z-click (right-click) and select CreateControl from the pulldown menu (Figure 4-45).A control should appear on the Diagram (Figure4-46).

Figure 4-45. Creating a Control by z-clicking (right-clicking) over the left terminal.

Page 20: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-20

Å Now repeat step Ä (Create Indicator) for each ofthe four indicators. The result should resembleFigure 4-47. Notice that when controls and indica-tors are created in this way, LabVIEW automatic-ally takes their names from the icon.

Figure 4-46. A control automatically labelled “Response”results from the menu selection Create Control (Figure 4-45).

Figure 4-47. The diagram after performing Create >>Indicator four times.

Æ If you don’t like the positioning of the controlsand indicators you can select them and movethem either by dragging with the mouse or byusing the arrow keys on the keyboard. Figure 4-48shows the Diagram of Figure 4-47 tidied up foreasier readability.

Figure 4-48. The Diagram of Figure 4-47 tidied up for easierreadability.

³ You might also find that when you switch to the

Panel (Figure 4-49) you don’t like the positioningof the controls and indicators either. You canposition them also by dragging or using the arrowkeys on the keyboard. One result of doing this isshown in Figure 4-50.

Figure 4-49. The panel of Figure 4-47 before the controls andindicators were repositioned.

Figure 4-50.The Panel of Figure 4-47 after positioning thecontrols and indicators. The Panel has been modified tomake it easier to read.

To continue…´ Run the VI to convince yourself the subVI does its

job. If you are doing this as part of Lab #2, savethe VI as MyFirstProg.vi on the floppy.

We now leave the subject of the sub-VI to continuewith another look at strings. Don’t lose what you havedone here; you will have a real use for the sub-VI youhave created in Chapter 5.

Page 21: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-21

Activity #7. Unravelling a CSV StringThe data that an instrument sends over an interface is in the form of a string. Some instrumentsreturn strings wrapped within double quotation marks, others do not. Some instruments returnstrings in ASCII form which are readable directly from an indicator on a panel. Some instruments(oscilloscopes) return their waveform data as numbers (integers or floating point numbers)delimited by commas. Other instruments return data in binary or hex format. In any case, aresponse is usually (though not always) terminated by an EOS (end-of-string) character. In thisactivity you will write a VI to unravel a very common type of string and to place the numericdata contained within it into an array. This array will then serve as the source of data for thegraphing you will do in the next activity.

The CSV StringA string in which the data (numbers) are delimited bycommas is called a CSV string (CSV stands forComma Separated Value). A CSV string has in factbeen prepared for you for this activity. To load it dothe following:

¬ Navigate to Physics >> PSCB01S >> LabVIEWDemos >> Chapter 04 and load CSV Example.viinside. This VI consists of just one string controlcontaining a long string (Figure 4-51). The controlhas been equipped with a scrollbar to enable youto scan through it.

Figure 4-51. The control CSVString on the panel of CSV

Example.vi.

This string was, in fact, returned from a Tek TDS210digital oscilloscope in response to SCPI commands.(Some of these commands are described in AppendixA.) The data consists of 2500 8-bit (I8) integersseparated by commas.3

Á You might wish to use the Operate Value tool toscroll down to the end of the string. There youwill find (Figure 4-52) the EOS character, a <CR>,indicated by “\r”. This is the default EOScharacter on the Macintosh. If you are doing thison a PC the EOS character might be a <CR><LF>

(indicated by “\r\n”).

Figure 4-52. Another view of CSVString showing the EOScharacter “\r”.

Unravelling the StringBy unravelling the string is meant extracting thecomma-delimited integers contained within it andplacing them into an array. You can do this using aspecial function for the purpose, Spreadsheet String toArray. Therefore...

® Switch to the Diagram and place the functionSpreadsheet String to Array just to the right of thecontrol CSVString. For your convenience the helpwindow for this function is reproduced in Figure4-53. For convenience in creating the controls itrequires, you may also wish to change the viewfrom icon view to terminal view.

This function takes a maximum of four controls:spreadsheet string, delimiter (Tab), format string , and arraytype (2D Dbl). The control spreadsheet string takes thestring we wish to unravel, i.e., CSVString, so…

¯ Wire the control CSVString directly to the inputcontrol spreadsheet string.

If the control delimiter (Tab) is left unwired, a <Tab> isassumed by default. Since we know the delimiter is a

Page 22: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-22

comma here...

° Pop-up on the delimiter terminal, select createconstant and type a comma into the constantspace.

Figure 4-53. The help for Spreadsheet String to Array.

You are going to extract decimal integer values fromthe string and place them into an array, so…

± Pop-up on the terminal format string , selectCreate Constant and type “%d” into the con-stant space. Popup on the control array type (2D Dbl)and select Create Constant. A 2D constantarray will be created by default. But since youwant a 1D array, place the Operate Value Toolover the lower edge of the array constant andz–click and select Remove Dimension. Thisshould leave you with a 1D array constant thatresembles the one shown at the bottom of Figure4-54.

² Finally popup on the terminal array and selectCreate Indicator. This completes the wiring ofFigure 4-54.

When you are ready…

³ Run the VI. At completion the panel shouldresemble Figure 4-55. The string has been neatlyunravelled and the integers placed into the array.You have achieved your objective.

Figure 4-54. The diagram at this stage of construction.

Figure 4-55. The array on the front panel. The integers inthe string control on the left are neatly placed in the arrayon the right.

If you are doing this as part of Lab #2 save your workas MyCSVExample.vi on your floppy. You will be usingit in the next activity.

Eventually, the data transferred from an instrument

must be graphed. We continue now with the subject

of graphing.

Page 23: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-23

Activity #8. Bundling, Clustering and GraphingGraphing is one of the more non-intuitive activities in LabVIEW. It probably has much to do withthe unusual datatype called a cluster that many graphs require. In this activity you will graph thedata from prepared arrays in two ways, one not requiring a cluster and one that does.

Simple GraphingThe simplest type of graph is one that is fed a 1Darray of numbers as was generated in the previousactivity. Do the following:

¬ Load your MyCSVExample.vi you prepared in theprevious activity. Add a Waveform Graph to thePanel and wire up the Diagram as shown inFigure 4-56a.

Figure 4-56a. The Diagram of MyCSVExample.vi showingthe Waveform Graph wired.

Note first that the wiring did not produce a brokenwire! To continue…

Á Switch to the Panel and run the VI. The resultshould resemble Figure 4-56b.

It should be evident immediately that the data in theCSV string is a sinewave. You can see how quicklyyou can produce a graph in LabVIEW. All you need todo is get your data in the form of an array and thenwire the array to a Waveform Graph. The graph herereally does resemble the screen of the Tek oscilloscopefrom which the data was transferred. The graphdisplays all the 2500 data points the oscilloscopeoriginally collected.

However, this kind of graph has a major failing.Since the array is a 1D array, it lacks X-value (timevalue) information. You could revise this VI if youknew the time for the beginning X-value (zero, per-haps) and the time increment XIncr-value. Then witha little programming you could wire up an XY graphthat would show the time information along the x

axis. This you shall do in a little different way in thenext section.

Figure 4-56b. The Panel of the VI after being run.

A Better Data ArrayAs we have stated in a previous activity in this chap-ter, in the sciences, the data one measures is usuallyplaced into a two dimensional array or table. Tablesmost often take the form of ordered pairs (Xi, Y i) orbetter, quartets (X i, ∆Xi, Y i, ∆Yi), if the uncertainties inthe measurements are included. Here we shall showyou how to produce a graph when your data is in theform of a 2D array of values (Xi, Yi). Unfortunately,LabVIEW at the present time does not support aneasy way of graphing error bars. Do the following:

Page 24: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-24

¬ Navigate to LabVIEW Demos >> Chapter 04 andload the ThermistorData.vi you used in a previousactivity. (This is the data that is plotted in Figure2-10.)

Figure 4-57. The 2D array Thermistor Data. The data is inthe form (Ti, Ri) where T is in ˚C and R in kΩ.

Á Switch to the Diagram and wire up the VI shownin Figure 4-58.

Figure 4-58a. The Diagram of a VI to plot Thermistor Dataon an XY Graph.

Notice the use of the functions Index Array. LabVIEWindexes the columns in an array starting from zero,meaning that the columns are numbered “0”, “1” etc.The two functions Index Array pick an element from the“zeroth” (first) column and from the “first” (second)column and pass them to the function Bundle; thefunction Bundle places the two numbers into astructure called a cluster.

You might think that a FOR loop or a WHILE loopwould be needed to work through all the elements inthe array. But a loop is not necessary here. When yourun the VI, the first pair of data is extracted from thecontrol Thermistor Data and then bundled. Then thesecond pair of data is extracted and bundled, and so

on until all the data have been extracted and bundled.When the bundling is complete, the cluster is passedto the graph.

The bundle function is wired to an XY Graphbecause we want the data in the second column of thearray (resistance in kΩ) to be plotted vs the data in thefirst column (temperature in ˚C).

When you are ready…

® Run the VI. The graph should appear as is shownin Figure 4-58b.

Figure 4-58b. The Panel after running the VI. The graph isshown in its default form.

Page 25: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-25

Changing Graph AttributesThe graphs shown in Figures 4-56b and 4-58b areLabVIEW defaults. Among other things, the back-ground color is black and the foreground color white.LabVIEW defaults will not always be to your liking.Graph defaults can be changed with something calledan attribute node. Do the following:

¬ Switch to the Diagram, place the Operate Valuetool on the control XY-Graph.

Á z–click and select Create >> attribute node.Wire the attribute node as shown in Figure 4-59.

® Rerun the VI. The graph should change to reflectyour selections in the attribute node.

If you are doing this as part of Lab #2 save your VI asMyGraphExample.vi on your floppy.

Figure 4-59. An XY Graph attribute node.

Activity #9. File I/OAn important requirement of any programming language is the ability to write and read experi-mental data to and from files. LabVIEW makes these tasks easy to implement.

File TypesLabVIEW supports the writing and reading of a num-ber of types of files. To explore this subject completelywould take us beyond the intended scope of thesenotes. The file type of most interest to a beginner is anASCII file where the data is delimited by a specialcharacter, say a comma or a <Tab>. Most spreadsheetand curvefit programs, like Microsoft Excel and proFit,read these kinds of files.

Saving an ASCII FileAs we have stated in the previous activity, a VI dedi-cated to the collection of data usually produces anarray at some stage in its execution. If the array is inconventional form (meaning the x- and y-values are incolumns), it is easy to save it in LabVIEW as a tab-delimited ASCII file. The VI Write to Spreadsheet File.vi(Figure 4-59) will do this for you.

Figure 4-59. The help for Write to Spreadsheet File.vi.

You need a file to write so to get one do the following:¬ Navigate to LabVIEW Demos >> Chapter 04 and

load Thermistor Data.vi. As we have seen, Thermistor

Data.vi contains just an array of data, nothing else.Á Drop a Write To Spreadsheet File.vi on the Diagram

and wire it as shown in Figure 4-60. Before yourun it, we spend a few moments describing it.

Figure 4-60. A VI to save an array of data.

This VI takes a maximum of five controls. If thecontrol format (%.3f) is left unwired, then the data willbe saved by default as floating point numbers with 3digits of precision. This format is very often perfectlyfine, and it certainly is here since the data in the arrayThermistor Data has 3 digits of precision. If the controlfile path (dialog if empty) is left unwired then a dialogbox will be presented when the VI is run, requestingyou to enter the name of the file you want your datasaved to. Since this file will be a new file we leave thecontrol append to file? (new file F) unwired. And sincethe data array is in conventional form we can leavethe control transpose? (no F) unwired, since a transposeis not required.

To continue...® Run the VI. In the dialog box that appears, type in

the name you wish and navigate to the volumeyou wish to save your file to. If you are doing this

Page 26: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-26

in the physics lab you can navigate to youraccount space on FISSURE, the Student TempSave area on the hard drive of the computer or afloppy. Don’t forget the name as you will bereading this file in the next section.

¯ Click Save.

You have just saved a file in the form of a two-dimen-sional tab-delimited numeric array. You can quicklyconfirm that the file was saved in that form byopening it with a spreadsheet such as Microsoft Excelor a text reader such as Notepad (Windows) orSimpleText (Macintosh).

Reading a FileReading a file from disk and placing the data into anarray is just as easy as saving a file. (Though in thiscourse you will probably be saving data files moreoften than reading them.) The file you shall read inthis exercise is the one you have just saved. Do thefollowing:

¬ Run LabVIEW, and when it has finished booting,switch to the Diagram.

Á Drop a Read From Spreadsheet File.vi on the Dia-gram (its help is shown in Figure 4-61, we shalldiscuss it in a moment). Pop up on the terminal allrows and create an indicator. The finishedDiagram is shown in Figure 4-62a.

Figure 4-61. The help for Read From Spreadsheet File.vi.

As can be seen, Read From Spreadsheet File.vi takes amaximum of 4 controls. The control format (%.3f) canbe left unwired since we know the data in the file youhave just saved is in floating point format with 3digits of precision. The control file path (dialog if empty)can be left unwired. This means that when the VI isrun a dialog box will be presented requesting you toselect the file you wish to read. The control number ofrows (all: -1) can be left unwired, since we want to readthe whole file. And finally, the control transpose (no: F)

can be left unwired since a transpose is not requiredhere. To continue…

® Switch to the Panel and run the VI. In the dialogbox that appears navigate to the file you wish toread. Click OK.

Figure 4-62a. The Diagram of ReadFileExample.vi.

You should see the data pop into the indicator all rows(Figure 4-62b). Reading data when you know exactlywhat its format is, is as easy as this.

Figure 4-62b. The Panel of ReadFileExample.vi.

This completes our first look at some of the basicfeatures of LabVIEW and the G programming lang-uage. We continue with G in Chapter 5 and its use incontrolling an instrument.

Page 27: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-27

Practice ProblemsThe following programs are to be written in G.

1. Write a program to• Add A to B• Add C to the Sum of A and B• Divide the Sum of A, B and C by 3• Subtract A from C

2. Solve problem 1 using a formula node.

3. Write a program to calculate the square root of thesum of squares of two input DBLs.

4. The following program is written in pseudo-BASIC. Write the equivalent program in G.

if (x >= 0) theny = sqrt(x)

elsey = -99

end if

5. The following program is written in pseudo-BASIC. Write the equivalent program in G.

for i = 0 to 99x = i*(π/10)y = sin(x)array [i] = y

next iGraph (array)

6. Write a program to create a 1D array of 100random numbers between 0 and 1.

7. Write a program to create a 2D array (4 rows x 6columns) of random numbers between 0 and 10.

8. Write a program to evaluate the factorial of aninput I32. (Recall n! = n(n-1)(n-2)... 1.)

9. Write a program to generate a 1D array of I32integers whose elements range from 25 to 100.

10. Write a program to take an input I32. If thenumber is less than 0 print “Too low !” into anindicator. If the number is greater than 10 print“Too high !”. If the number is in the range 0 – 10

print “OK !”.

11. Some instruments (viz. the E3640A programmablepower supply) sometimes respond to a query byreturning a string enclosed within double quota-tion marks, for example,

“8.00000,3.00000”Write a program that takes this string in a control,extracts the two floating point numbers anddisplays them in numeric indicators.

12. Using the array control ThermistorData.vi find theaverage resistance value. Solve this problem inthree distinctively different ways.

13. Write a program to calculate the square root of thesum of squares of two input DBLs (problem 3).Make this a sub-VI and use it in a program tocalculate the square root of the sum of squares oftwo numbers plus a third input number.

14. Suppose that due to some systematic error inmeasuring resistance, the value of the resistancesin the array ThermistorData.vi are all 2% too low.Write a program to output the (whole) array withthe data corrected.

15. Suppose that the systematic error described in theprevious problem applies to only the first 10 resis-tances in the array. Write a program to output the(whole) array with the data corrected.

16. Solve the previous problem using the functionReplaceArrayElement.vi.

17. The array ThermistorData.vi contains values of resis-tance measured at intervals of 5 ˚C. Write a pro-gram to search for the temperature of, say, 20 ˚Cand output the corresponding resistance.

18. The array ThermistorData.vi contains values of resis-tance measured at intervals of 5 ˚C. Write a pro-gram to take any value of resistance as input andoutput the interpolated value of temperature.

19. Starting with the 1D array ThermistorData1.vi write

Page 28: Chapter 4 Introduction to G - University of Torontoquick/PSCB01H3S/Manual/Ch04.pdf · 4-1 Chapter 4 Introduction to G We begin our study of the G programming language with a series

Introduction to G

4-28

a program to graph the data in a waveform graph.Set the following attributes for the graph:

• Background color white• Foreground color black

20. Starting with the 2D array ThermistorData.vi write aprogram to graph the data in an XY-graph. Set thefollowing attributes for the graph:

• Background color white• Foreground color blackProvide your program with a dynamic readout ofthe cursor positions.

21. The response of a Tek TDS210 digital oscilloscopeto a WFMPre? SCPI command (meaning sendwaveform preamble) is a string containing thecalibration parameters necessary for convertingthe I8 CSV (waveform) data string into values ofvoltage vs time. Starting from the controlWFMPre.vi in the Data folder write a program toextract the calibration parameters.

22. Interpolation problem using KTypeTC.dat.

23. Write a program to function as a simple calcula-tor, providing the mean, standard deviation of thesample and standard deviation of the samplemean of a series of numbers input at thekeyboard.

24. Locate in the Data folder SerialBuffer.vi. This array

is designed to represent the contents of a serialport buffer. The elements in the array are thevalues in a typical string returned from a RadioShack DMM. Write a program to read this arrayone element at a time and to place the recon-structed string into an indicator.

25. Locate PowerDiode.vi in the Data folder. This VI isjust an array control of data obtained using theHP programmable power supply. Plot this data inan XY graph and determine from the graph theapproximate value of the diode’s turn-on voltage.

26. Locate WeatherArray.vi in the Data folder. This VIconsists of just an array control of data down-loaded from the UTSC weather station. Write aprogram to display this data in a table indicator.

27. Using WeatherArray.vi (previous problem) write aprogram to add the constant factor 100 to the datain the 6 th column (the column containing atmos-pheric pressure data). Display the results in atable indicator.

28. Using the control WeatherArray.vi (previous prob-lems) write a program to calculate the mean andstandard deviation of the data in the 7th column.

29. There exists an array of seven 32-bit integers[8,6,7,5,3,0,9] on a panel. Write a program toreverse the order of the elements.

EndNotes for Chapter 41 R. H. Bishop, Learning With LabVIEW (Addison-Wesley, 1999).2 The manual which accompanies the Radio Shack DMM states that the send command is the ASCII character “D”terminated by a <CR>. However, in actual fact, we have found that any character works just as well, including no string, just a<CR>. The conclusion to be drawn is that the DMM sends data in response to any voltage transition on its RxD line.3 The most efficient mode for transferring data in terms of speed and memory requirements is binary, in which case theintegers would not be comma delimited. For pedagogical reasons we shall stick with ASCII transfers in this course. Anexample of binary transfer can be found in the source code of the application Oscar (Appendix B).


Recommended