Lab .2(d) While Loop / For Loop / Shift Register / Selectors


More than often, we would like an action to repeat until a condition is satisfied; for example, we may want to accept data from the user until the datum provided is of a particular value, at which point we stop processing any further data. This is where loop structures such as the While Loop come in handy.

A While Loop executes the functions it contains until the conditional terminal receives a specific Boolean value (True or False). By default, the conditional terminal is Stop If True( ); this means that, when we connect a Boolean control (a control that returns either True or False) to the terminal, the While Loop will stop iterating as soon as the Boolean control returns True. Another kind of conditional terminal, called Continue If True, is available by right-clicking on the conditional terminal.

There is another terminal called the iteration terminal, which is an output terminal ( ). Every run of the While Loop is considered one iteration. During, and after, execution, this terminal returns the number of iterations completed. The iteration terminal starts off at 0; as a result, during the first iteration, the iteration terminal returns 0.

Example VI
The following exercise will demonstrate the use of a While Loop structure in a VI. This VI will keep generating a random integer between 0 and 100 in a loop until it matches a number defined by the user. An indicator will be used to count the number of iterations used to attain this match.

1. Open LabVIEW.

2. Open a new VI by clicking on Blank VI in the LabVIEW Getting Started window.

3. Save the VI as Number to Match.vi.

4. Create a random number generator, to generate integers between 0 and 100 inclusive, in a While
Loop.

• From the Functions palette, place a While Loop from the Programming → Structures subpalette.

• Using the random number generator found in the Programming → Numeric subpalette, gen-
erate a random integer between 0 and 100. Since the random number generator generates
random floating-point values between 0 and 1, use appropriate functions in the Functions palette to multiply the values by 100 and round them to an integer. You may find the Round to Nearest function useful, but you will need to look for it using the provided search functionality.

5. Create a control on the front panel that will be used to compare the results of the random number to a user-defined value, and display the number of iterations that were required to attain this match.

• From the Controls palette, place a numeric control on the front panel and label it Number to
Match.

• From the Controls palette, place a numeric indicator on the front panel and label it Iterations.

• Create an Equal? function from the Programming → Comparison subpalette and place it on the block diagram to compare the random number generated with the number present in Number to Match, as shown in Figure .

6. Create stop conditions for the While Loop.

• It is good programming practice to allow users the ability to exit a loop structure using a control on the front panel. To this effect, create a stop button control on the front panel from the Modern → Boolean subpalette.


• To also allow the While Loop to terminate when a match has been found, use the appropriate
logic functions from the Programming → Boolean subpalette to construct the necessary logic
for the stop terminal of the loop. The overall block diagram should look similar to that shown in Figure.

Notice, in the block diagram, that 1 has been added to the iteration terminal (i); this is done because iteration counts for loop structures in LabVIEW begin at 0, whereas we need to start counting iterations from 1. To create a constant (in this case, 1), right-click on the terminal and select Create → Constant.


7. Run Number to Match.vi and verify its operation. Run the VI again with the Highlight Execution button selected.

For Loop

A For Loop, like a While Loop, is a loop structure and functions similarly; the sole exception is that a For Loop performs as many iterations as determined by the count terminal).

Example
The following exercise will demonstrate the use of a For Loop structure in a VI. This VI will generate a random floating-point number between 0 and 1 every second and repeat for a finite number of iterations specified by the user. The VI will then return the largest number generated. An indicator will be used to count the number of iterations elapsed.

1. Open LabVIEW.

2. Open a new VI by clicking on Blank VI on the LabVIEW Getting Started window.

3. Save the VI as Max Search.vi.

4. Create a random number generator to generate floating-point numbers between 0 and 1 in a For
Loop and display it on the front panel. Have this loop repeat every second.

• In the block diagram, place a For Loop from the Programming → Structures subpalette.

• Also in the block diagram, place a random number generator found in the Programming → Numeric subpalette.

• Create a numeric indicator labeled Random Number on the front panel, from the Modern → Numeric subpalette, to display the random numbers. In the block diagram, wire the random number generated to this indicator.

• Back in the block diagram, place a Wait (ms) function into the For Loop and wire it to
a constant of 1000. You can do this by right-clicking on the left terminal (the one labeled
milliseconds to wait) and selecting Create → Constant. Again, use either the search functionality or the available categories to determine where the function itself is located in the Functions palette.

What have you just done? By adding the Wait (ms) block, you ensure that every iteration waits 1000 milliseconds, or 1 second, after completion before the next iteration starts.

5. Create a control on the front panel which will be used to define the number of iterations for the For Loop and place a numeric indicator to display the current iteration value.

• From the Controls palette, place a numeric control on the front panel and label it Number of
Iterations. Since this value can only be an integer, change the data representation of this
control from DBL (which stores double precision floating-point numbers) to I32 (which stores
integers) by right-clicking on the control in the block diagram, selecting Representation and
choosing I32, as shown in Figure. Connect this control to the iteration value N of the For
Loop.
Fig. How to Change the Data Representation
• From the Controls palette, place a numeric indicator on the front panel and label it Iterations. Wire the iteration index i to this indicator in the block diagram.

We now need to keep track of the maximum number generated in the iterations that have completed, but this involves maintaining history. In other words, we need a way to remember past values. Before we continue with this exercise, we will explore the concept of a shift register.

Shift Register
A shift register will be one of the most useful and ubiquitous constructs that we will use in the labs to come. In order to understand how a shift register works, we draw the following analogy: Notice how the For Loop looks like a finite sheaf of papers. This represents the fact that whatever is present on the topmost sheet is duplicated onto the other sheets. As the VI runs, each of these sheets are ‘run’ one after the other: in effect, we are thus repeatedly running the code on the topmost sheet, as a For Loop must.

Essentially, a shift register is like a data pipeline connecting two adjacent sheets, or iterations, together; the right square saves the result of the current iteration so that the next iteration can use it, while the left one uses the result of the previous iteration. Formally, during the ith iteration, data sent forward from the (i − 1)th iteration can be obtained from the left square of the shift register, manipulated or used in some way during the current iteration, and then sent forward to the (i + 1)th iteration using the right square of the shift register. As a result, the shift register allows us to remember values from previous iterations. We will use this property for the current task.

In other words, the left square of the shift register can be seen as an input from the previous iteration, and the right square of the shift register can be treated as an output for the current iteration.

6. Find the largest random number generated.

• Right-click on the left border of the For Loop and select Add Shift Register. You should now see a square on either side of the For Loop: the left one pointing down ( ), and the right one pointing up ( ); together, they constitute a shift register.


Figure. How to Add a Shift Register

• Outside the For Loop but near the left square of the shift register, drag a numeric constant from the Programming → Numeric subpalette and initialize this constant to 0. Then, connect this constant to the left square.

Notice that the left square now has a constant attached to it (in this case, that constant is 0). This is because, in the first iteration, there is no data from a previous iteration to be used, so an initial value must be attached to the left shift register; in this case, during the first iteration, the left shift register will produce the value 0.
If this initial value is not present, then running the VI the first time will cause LabVIEW to use a default initial value (usually 0 for numeric data), but running the VI subsequently will cause LabVIEW to use, as initial values, the values obtained from the previous runs of the VI, which is usually unintended behavior.

• Create a numeric indicator labeled Max on the front panel from the Modern → Numeric subpalette to display the maximum number.

• Using the necessary logic functions from the Programming → Comparison subpalette, implement an algorithm that will compare the random number with the previous maximum value and update the new maximum value. Figure shows the final block diagram for Max Search.vi.
Figure 6. Max Search.vi Block Diagram


Wait, what is that large triangular block in the block diagram?

Selectors

A selector acts as a sluice gate, and as such, allows us to choose which data should flow through a wire. It is analogous to the if-construct in programming languages. A selector has three input terminals: t, s, and f. The s terminal accepts a wire carrying Boolean data, which is data that is either True or False. If the datum is True, then the data contained in the wire connected to the t terminal is allowed to flow through; if the datum is False, then the data contained in the wire connected to the f terminal is allowed to flow through.

In the example shown in Figure 6, the Greater Than comparison block produces a True Boolean value, if the value flowing into its upper terminal is strictly greater than the value flowing into its lower terminal. This Boolean value feeds into the s terminal of the selector. With this in mind, we interpret the block diagram as follows: if a past value, provided by the shift register, is greater than the number randomly generated in this iteration, then that number is propagated to the next iteration; otherwise, the new random number is propagated. As a result, the shift register remembers the maximum value generated so far.

7. Run Max Search.vi and verify its operation. Run the VI again with the Highlight Execution
button selected.

Self-Exercise
Now that we learned how to use a For Loop, implement the following VI which generates two random numbers between −0.5 and 0.5 for a set amount of time defined by the user. Denote the first random number as Random Number A and the second as Random Number B. Points are attributed to a random number whenever its value is greater than the other. Write a VI that keeps track of the points for each random number generator and displays the winner, with the help of Boolean indicators. Also, include an indicator in the event of a tie. Note that the winner should only be displayed at the end of the competition (once all iterations have finished). Save this VI as Random Competition.vi.

You will probably need two shift registers and two selectors to achieve this task, one each for A and for B. Think about what each shift register should remember, and how these values should be updated; for instance, if A gets a higher score than B, which shift register should be updated? How about the other shift register?

Also, using the analogy of data flow, where would you obtain the final scores of A and of B, and how would you use this information to determine the winner?

Figure. Random Competition.vi Front Panel

No comments:

Post a Comment