Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lesson 7 Using Sequential and State Machine Algorithms

Similar presentations


Presentation on theme: "Lesson 7 Using Sequential and State Machine Algorithms"— Presentation transcript:

0 Course Learning Map Lesson # Lesson Title
Navigating LabVIEW Lesson 2 Troubleshooting & Debugging VIs Lesson 3 Implementing a VI Lesson 4 Developing Modular Applications Lesson 5 Creating and Leveraging Data Structures Lesson 6 Managing File and Hardware Resources Lesson 7 Using Sequential and State Machine Algorithms Lesson 8 Solving Dataflow Challenges with Variables

1 Lesson 7 Using Sequential and State Machine Algorithms
Using Sequential Programming Using State Programming State Machines 1

2 A. Using Sequential Programming
Flow-Through Parameters Sequence Structures Error Case Structures 2

3 Using Sequential Programming
Many of the VIs you write accomplish sequential tasks. By default, LabVIEW does not force sequential programming. Example: Nothing forces the execution order of these tasks. Any one of these tasks could happen first. 3

4 Flow-Through Parameters Force Execution Order
Use error clusters and refnums to force order of execution. Use flow-through parameters, such as refnums and error clusters, to control execution order when natural data dependency does not exist. Not all LabVIEW nodes have flow-through parameters to ensure data dependency. For example, the One Button Dialog function does not have an error cluster input or output. 4

5 Sequence Structures Force Execution Order
Sequence structures are a structure with frames, where each frame executes in order. The second frame cannot begin execution until everything in the first frame completes execution. Without flow-through parameters, such as error clusters and refnums, you can use sequence structures to the force execution order. Sequence structures are not ideal and should be used sparingly. They do not take advantage of nodes that do support flow-through parameters. They do not guarantee that the update of terminals will happen before a dialog. There are appropriate situations for Sequence structures, but in general, Sequence structures are not considered good LabVIEW programming. 5

6 Avoid Overuse of Sequence Structures
You cannot stop the execution in the middle of a sequence. Single frame sequence structures are better than multi-sequence frames shown on previous slide. In this diagram, the One Button Dialog functions pop-up even if the DAQ Assistant results in an error. What can we replace the sequence structures with? 6

7 Better to Use Error Case Structures
The best way to write this VI is to enclose the dialog boxes in Case structures, wiring the error cluster to the case selectors. 7

8 B. Using State Programming
State Transition Diagrams 8

9 State Programming State programming helps you solve the following issues that sequential programming or flow-through parameters do not: What if you need to change the order of the sequence? What if you need to repeat one item in the sequence more often than other items? What if some items in the sequence execute only when certain conditions are met? What if you need to stop the program immediately, rather than waiting until the end of the sequence? 9

10 State Transition Diagram
A state transition diagram is a type of flowchart that indicates the states of a program and transitions between states. State – Part of a program that satisfies a condition, performs an action or waits for an event Transition – Condition, action, or event that causes the program to move to the next state 10

11 State Transition Diagram
Furnace Example: 11

12 C. State Machines Common Uses Infrastructure Transitions 12

13 State Machines The state machine design pattern implements a state diagram or flow chart. Common uses of state machines: To create user interfaces, where different user actions send the user interface into different states. For process tests, where a state represents each segment of the process. 13

14 State Machines – Infrastructure
A state machine consists of a set of states and a transition function that maps to the next state. Each state can lead to one or multiple states or end the process flow. While Loop Type-Defined Enum Case Structure Shift Register 14

15 State Machines – Default Transition
Point out here that a type defined enumerated control is a good method for controlling a state machine. 15

16 State Machines – Transition Between Two States
16

17 State Machines – Case Structure Transition
17

18 State Machines – Transition Array Transition
18

19 Course Project Transition Diagram
19

20 Course Project Demonstrate an implementation of a state machine. <Solution>\LabVIEW Core 1\Exercise7-1 Open the weather station to demonstrate a state machine implemented in a project file using a type-defined enumerated control. Point out the mapping between the state transition diagram and the state machine. Indicate that this is what the students will build in their next exercise. Demonstrate creating and/or editing the typedef enum. Demonstrate making copies of the enum constant using control-drag. This course project uses the Weather Data.ctl type definition and the Temperature Warnings.vi that students have built in previous exercises. Rather than have students copy their files, the exercise includes a pre-built copy of these files. If students are confident they completed previous exercises completely and they want to user their own copies of these files, they can copy over the files on disk. It is recommended that slower students just use the copies that are provided.

21 Exercise 7-1 Weather Station Project
Create a Weather Station application using a state machine design pattern. Practice skills learned throughout this course. Students are given the front panel of a Weather Station application. Students need to complete the block diagram by implementing a state machine. Students also use a copy of the Weather Data.ctl and the Temperature Warnings.VI created earlier. The copies are provided for them. If they want to use their own versions of the .ctl and .vi files, they can replace the ones in the Weather Station folder.

22 Exercise 7-1 Weather Station Project
How would you change the diagram to add an Initialize and Shutdown state? How would you change the diagram to add an Initialize and Close state? Add an Initialize item and a Close item to the Weather Station States.ctl typedef. Set the Beginning State to Initialize. Add an Initialize case to the Case structure. Move the File Dialog and Open/Create/Replace function to the Initialize case. Add a transition to Acquisition state. Add a Close case to the Case structure. Move the Close File to the Close case. In the Time Check case, add code to transition to the Close case if the Stop button is pressed.

23 Summary—Quiz When using a Sequence structure, you can stop the execution in the middle of a sequence. True False Answer if False. 23

24 Summary—Quiz Answer When using a Sequence structure, you can stop the execution in the middle of a sequence. True False You cannot stop the execution in the middle of a sequence. 24

25 Summary—Quiz Which of the following are benefits of using a state machine instead of a sequential structure? You can change the order of the sequence. You can repeat individual items in the sequence. You can set conditions to determine when an item in the sequence should execute. You can stop the program at any point in the sequence. Answer is a, b, c, and d. 25

26 Summary—Quiz Answers Which of the following are benefits of using a state machine instead of a sequential structure? You can change the order of the sequence. You can repeat individual items in the sequence. You can set conditions to determine when an item in the sequence should execute. You can stop the program at any point in the sequence. 26

27 Lesson 8 Solving Dataflow Challenges with Variables
Communicating Between Parallel Loops Writing to Controls & Reading from Indicators Variables Local Variables Race Conditions 1

28 A. Communicating Between Parallel Loops
2

29 Communicating Between Parallel Loops
Dual chart example: Execute multiple tasks at the same time. 3

30 How do the loops stop in this example?
Passing data among parallel loops is a challenge. 4

31 How do the loops stop in this example?
Ask students what other ways they can communicate between loops? Another possible solution: Read the Stop button from a file. Each loop independently accesses the file. However, reading and writing to files can consume much processor time You cannot pass data between parallel loops with a wire. 5

32 B. Writing to Controls & Reading from Indicators
6

33 Writing to Controls & Reading from Indicators
How would you handle the following dataflow challenges? Initialize front panel controls with values from a configuration file? Copy a “Ship To” address to a “Bill To” address? Initialize indicators that will be written to later in your code? Write to an indicator in two cases of a Case structure without writing to it in all cases? Sometimes you need to write to a control or read from an indicator. 7

34 C. Variables 8

35 Variables Variables – Block diagram elements that allow you to access or store data in another location Variables can be of the following types: Local—Stores data in front panel controls and indicators. Global —Stores data in special repositories that can be accessed from multiple VIs. Functional Global—Stores data in While Loop shift registers. Shared—Transfers data between various distributed targets connected together over a network. Variables allow you to circumvent normal dataflow by passing data from one place to another without connecting the two places with a wire. In this course, you learn about and practice with Local variables. For a brief introduction to Global and Shared Variables, refer to the LabVIEW Core 1 Concepts Manual. For extended information on Global variables, refer to LabVIEW Help or LabVIEW examples. You learn about Functional Global variables in LV Core 2. You learn about Shared variables in courses like LabVIEW Real-Time. 9

36 D. Local Variables When To Use Local Variables
Local Variables and Boolean Mechanical Actions How To Create Local Variables 10

37 Local Variables Use local variables to pass data within a single VI.
11

38 Local Variables Use local variables to modify front panel control values. 12

39 Use Switch Mechanical Action
Boolean controls with associated local variables must use switch mechanical action. Boolean latch action is incompatible with local variables. Boolean latch action is incompatible with local variables. If a Boolean control has an associated local variable, it cannot use a latch mechanical action because the first local variable to read the Boolean control with latch action would reset its value to the default, which is not the expected behavior. 13

40 Creating Local Variables
Create and use local variables. <Exercises>\LabVIEW Core 1\Demonstrations\Local Variables Demonstration should include: Stopping two While Loops running at different rates using only one Stop button. Changing the mechanical action so that the Boolean Stop button can be used with local variables. Re-creating the latch behavior by writing to the local variable after the While Loops stop.

41 Exercise 8-1 Weather Station UI with Local Variable VI
Use a local variable to write to and read from a control.

42 Exercise 8-1 Weather Station UI with Local Variable VI
What functionality does the local variable provide for this application? What functionality does the local variable provide for this application? If Upper Limit is less than Lower Limit, this VI uses a local variable to change the value of Lower Limit to match the value of Upper Limit.

43 E. Race Conditions Definition How To Avoid Race Conditions
Controlling Shared Resources 17

44 Race Conditions Race Condition – A situation where the timing of events or the scheduling of tasks may unintentionally affect an output or data value Race conditions are a common problem for programs that execute multiple tasks in parallel and share data between the tasks. 18

45 What is the final value of the Value variable?
Four possible outcomes: Value = (Value * 5) +2 Value = (Value + 2) * 5 Value = Value * 5 Value = Value +2 Explain all the potential outcomes of this section of code, and how the outcome uncertainty could be avoided by properly sequencing the code. Optional: Build the code and demonstrate the results using execution highlighting. 19

46 Race Conditions Race conditions are very difficult to identify and debug. Often, code with a race condition can return the same result thousands of times in testing, but still be capable of returning a different result. Avoid race conditions by: Controlling shared resources. Use one writer, multiple readers. Properly sequencing instructions. Reducing use of variables. 20

47 Controlling Shared Resources
Bad Race conditions are most common when two tasks have both read and write access to a resource. A resource is any entity that is shared between the processes. Most common resources, such as variables, share data storage. Most race conditions occur only when a resource has multiple writers. Therefore, to avoid race conditions, minimize shared resources and limit the number of writers to the remaining shared resources. In top image, the reader reads whichever was the last value written to the resource. In bottom image, all readers read value A. Good! 21

48 Summary—Quiz You should use variables in your VI whenever possible.
True False Answer is False. 22

49 Summary—Quiz Answer You should use variables in your VI whenever possible. True False You should use variables only when necessary. Use wires to transfer data whenever possible. 23

50 Summary—Quiz When controlling resources, which combination of writers and readers reduces chance of race conditions? One writer, one reader One writer, multiple readers Multiple writers, one reader Multiple writers, multiple readers Answer is a and b. 24

51 Summary—Quiz Answer When controlling resources, which combination of writers and readers reduces chance of race conditions? One writer, one reader One writer, multiple readers Multiple writers, one reader Multiple writers, multiple readers 25

52 End of LabVIEW Core 1

53 Certified LV Associate Developer Exam Certified LabVIEW Developer Exam
Lesson # Lesson Title New User Experienced User Advanced User Managing Software Engineering in LabVIEW Advanced Architectures in LabVIEW LabVIEW Core 1 LabVIEW Core 2 LabVIEW Core 3 LabVIEW Connectivity Object-Oriented Design and Programming in LabVIEW LabVIEW Performance Certifications Certified LV Associate Developer Exam Certified LabVIEW Developer Exam Certified LabVIEW Architect Exam <Remove this slide if your class is not in the LabVIEW series.> Other Courses LabVIEW Real-Time 1 LabVIEW Real-Time 2 LabVIEW Instrument Control LabVIEW Modular Instruments LabVIEW FPGA DAQ & Signal Conditioning

54 Lesson # Lesson Title LabVIEW Core 2

55 What You Need To Get Started
Lesson # Lesson Title What You Need To Get Started LabVIEW Core 2 Course Manual LabVIEW Core 2 Exercise Manual LabVIEW Core 2 Course Kit Computer running: LabVIEW or later Windows XP or later

56 Exercises <or> Solutions
Lesson # Lesson Title File Locations Root Directory Exercises <or> Solutions LabVIEW Core 2 The course installer places the course files in the following location:

57 Course Goals This course prepares you to:
Lesson # Lesson Title Course Goals This course prepares you to: Use event programming effectively. Apply common design patterns that use queues and events. Programmatically control user interface objects. Evaluate file I/O formats and use them in applications. Modify existing code for improved usability. Prepare, build, and deploy stand-alone applications.

58 Configuring Your LabVIEW Environment
Change the LabVIEW environment in the Options dialog box. Front Panel page Set Control Style for New VIs to Silver style. Block Diagram page Uncheck Place front panel terminals as icons Enable automatic error handling in new VIs Enable automatic error handling dialogs Configure Block Diagram Cleanup to customize your block diagram. The settings noted in the slide are suggested changes. Although chaining error wires together effectively disables Automatic Error Handling, it is possible to forget once in a while. To ensure that LabVIEW does not resort to Automatic Error Handling you should disable it for all new VIs. To do this, you need to change a configuration setting in the Tools»Options dialog box. Students can complete exercises using any control style or terminal style. However, to match the solutions, select Silver style for controls and uncheck Place front panel terminals as icons. Other possible suggested changes based on instructor discretion: Check Environment » General » Skip Getting Started window on launch

59 Configuring Your LabVIEW Environment
Functions Palette Tack the Functions palette and select Customize»Change Visible Palettes then click Select All. Controls Palette Tack the Controls palette and select Customize»Change Visible Palettes then click Select All.

60 Course Learning Map Lesson # Lesson Title Lesson 1 Lesson 2 Lesson 3
Moving Beyond Dataflow Lesson 2 Implementing Design Patterns Lesson 3 Controlling the User Interface Lesson 4 File I/O Techniques Lesson 5 Improving an Existing VI Lesson 6 Creating & Distributing Applications

61 Lesson 1 Moving Beyond Dataflow
Asynchronous Communication Queues Event-Driven Programming

62 A. Asynchronous Communication

63 Asynchronous Communication
LabVIEW is a dataflow language. Functions depend on other functions for data. Dependent functions do not execute until their dependencies have completed execution. Wires transfer data between functions. However, sometimes you need break dataflow and program using asynchronous communication.

64 Asynchronous Communication
Asynchronous Communication — Transfer information without using wires Asynchronous communication is between the following: Parallel loops UI and Block Diagram VIs Application instances (LabVIEW projects, executables, etc.) Information includes the following: Data Notification that something happened This course focuses on the first two scenarios: Parallel loops UI and Block Diagram LV Core 3 explores more advanced ways of communicating between loops and VIs.

65 B. Queues Queues Queue Operations
Producer/Consumer (Data) Design Pattern

66 Queues Are used for communicating data between parallel loops.
Store multiple pieces of data (i.e. buffer data). Work in a FIFO (first in, first out) manner by default. Can hold data of any type. REVIEW: Reasons to use parallel loops: Execute tasks simultaneously Execute tasks at different rates Other ways of communicating between multiple loops: Variables (already seen) Notifiers (covered in LabVIEW Core 3) User Events (covered in LabVIEW Core 3) Queues (covered in this course) If students are advanced, then you can also cover the following information: Queues ensure that data is not lost unless: The data is explicitly discarded. The queue is destroyed. The queue is configured to be lossy. The system runs out of memory.

67 Drawbacks of Variables
Drawbacks of using variables to communicate between loops: It’s possible to read duplicate data. It’s possible to miss data. You can create read-modify-write race conditions. The diagram shows how it is possible to read duplicate data or miss data. The instructor should mention that the most commonly accepted use of local variables is to update a control or indicator. Occasionally it is OK to use a local variable to read the value of a control when the terminal is already in use. It is also OK to occasionally use a local variable to read the value of an indicator. Instructor should downplay the use of variables (local, global and shared) as a means of communicating between parallel loops. However, an acceptable use of variables for communicating between parallel loops is when: It is OK to occasionally read duplicate data in the loop receiving data. It is OK to occasionally miss data in the loop receiving the data. There are no read-modify-write race conditions.

68 Queue Operations Use the Queue Operations functions to create and use a queue for communicating data between: Different sections of a VI. Different VIs.

69 Producer/Consumer Design Pattern (Data)
You learn more about design patterns in the next lesson. The focus here is on use of queues to pass data between the top loop (producing loop) and the bottom loop (consuming loop).

70 Producer/Consumer (Data) Design Pattern
Demonstrate use of queues to transfer data between parallel loops. <Exercises>/LabVIEW Core 2/Demonstrations/ Producer Consumer - Data <Optional slide and demo> Instructor: If your class is small and you have fast students, consider taking the time to demonstrate the Producer/Consumer (Data) Design Pattern. Focus on the queue behavior. Design patterns are not officially covered until the next lesson. Point out the following aspects of demo: Enqueue and Dequeue elements Loops running at two different rates Demonstrate how to change the datatype of the queue element.

71 Exercise 1-1 Concept: Comparing Queues with Local Variables
Run and examine a producer/consumer design pattern VI that transfers data that a producer loop generates to consumer loops using local variables and queues.

72 Exercise 1-1 Concept: Comparing Queues with Local Variables
What is the data type associated with the queue? What function determines the number of elements in the queue? What is the purpose of the While Loop before the Release Queue? What is the data type associated with the Queue? Double precision floating point. This is specified by the Obtain Queue function. What function determines the number of elements in the queue? Get Queue Status. What is the purpose of the While Loop before the Release Queue? In this particular application, we want to wait for the queue to clear before stopping the application. This is an application design choice. In other applications, you might want to terminate before the queue is clear. Other possible discussion questions: Why do we need to re-initialize the Stop button? Because we want to simulate a latch operation, but local variables are not compatible with Booleans with a latch mechanical action. Why do we need a single frame sequence structure around the Stop button? To force execution order. The sequence frame is a convenient way of forcing the re-initialization of stop button after the producer loop AND local variable consumer loop stop.

73 Lesson # Lesson Title End of Week 6


Download ppt "Lesson 7 Using Sequential and State Machine Algorithms"

Similar presentations


Ads by Google