6.algo introlabview ii.r13.4 - la.epfl.ch · • data paces the program execution ... • two...

49
Introduction partie 2 LabVIEW ME 2 e semestre rev. 13.4 Christophe Salzmann Photo Martin Klimas

Upload: truongdien

Post on 02-May-2018

226 views

Category:

Documents


1 download

TRANSCRIPT

Introduction partie 2

LabVIEW

ME 2e semestre

rev. 13.4

Christophe Salzmann���

Photo Martin Klimas

Summary part 1

LabVIEW concepts Front panel / diagram / connector pane

Data flow programming

Parallelism

Control and indicator

Basic functions and structures Types, for and while loops, case

Basic editor/environment manipulations Watch execution

Breakpoint

Probe

My first and second VIs

3

Virtual Instrument (VI)

Front Panel (UI)

Diagram (Program)

Connector Pane (Interface)

•  Data paces the program execution

•  Data flows from sources to sinks

•  Data flows in parallel

•  Wires are like variables' name

float function A_B(float A, float B) {

return A*B; }

A VI is like a function with its parameters defined in the connector pane

4

Virtual instrument

int main (void) {

double R;

int slider, stop;

do {

cin>> Slider;

R=(double)(rand()%100)/100.0;

cout << A_B(slider,R);

usleep(100*1000); // 100 ms

cin>>stop;

} while (!stop);

return 0;

}

•  The main VI consists generally of a loop doing some action until the user stops it.

•  Sub-VI are VIs with a connector pane. They are like c's function. They should not have a potential infinite loop inside.

5

Dataflow

6

•  To be executed, a node needs to have all its inputs (wires) defined/known •  Two independent nodes can be ran in parallel

Dataflow

7

•  To be executed, a node needs to have all its inputs (wires) defined/known •  Two independent nodes can be ran in parallel

Dataflow

A containing structure (loop, sequence, case, etc.) is like the { } in c:

It defines a scope. It is like inputs are copied in temporary variables, outputs are copied from internal temporary variable.

temp. var.! Internal temp. var.!

A!

B!

C!D!

E!

int tmpA = A;

int tmpB = B;

int tmpC = n/a;

do {

E = D * tmpA;

tmpC = E + i;

} while (!tmpB);

C = tmpC;

8

Dataflow – auto-indexing

Auto indexing enable access to the ie element of the connected input (array).

Similarly for outputs, it internally stores the nth elements in a temporary array.

auto-indexing!

A! C!

P!

int A[]= {5,2,7};

int B,P,I;

int e,tmpi,tmpP, tmpB;

int tmpC[],C[];

boolean F, tmpF;

tmpB=B;

for(i=0;i<sizeof(A);i++){

e = A[i];

tmpi=i;

tmpC[i]=e;

tmpF= (e == tmpB);

if (tmpF) break;

}

P = tmpP;

C[] = tmpC[];

F = tmpF;

e!

B!F!

For dth dimensions array auto-indexing indexes one dimension at a time

5 2

7

5 5 5

2 2 7

break!

i = 0!!

1!!

2!

9

Dataflow

LabVIEW will generate an error if I try to connect the output to the input,

Why ? Causality

You cannot mix (add) current values with values that come from the future (i.e. values that are computed based on current values)!

≡ Feedback node!

10

tmpL(k-1)!

Dataflow

If no default value are connected, the last store value is used!

J!

L!

int tmpJ_k_1 = 0; // default

// tmpJ_k_2 = 0;

int tmpJ, J, Stop;

do {

J = tmpJ_k_1;

tmpJ = i;

tmpJ_k_1 = tmpJ;

} while (!Stop);

tmpL(k)!

tmp(k-1)! tmp(k)!

default!when k=0

J = 0,0,1,2,3, ...

Shift registers are time dependent temporary variables that store previous value(s)

NO default! =>!keep the value of the previous run!

L = 0 L = 1

tmp(k-1)"tmp(k-2)"

double tmpL_k_1; // NO default

double tmpL, L;

do {

L = tmpL_k_1 + 1;

tmpL = L;

tmpL_k_1 = tmpL;

} while (!Stop);

L = 2

11

Quick test

crt increase at each iteration infinite loop, False connected to the stop condition

crt =0 at each iteration, N=0, the for loop is never executed

Fibonacci suite Sum input 2D array, #row, #col

factorial

12

Virtual Instrument (VI)

•  Main VI does not have connected connector pane

•  Sub-VI (i.e. VI with connected connector pane) are like functions

- Default values are used for un-connected entries

•  Visually in the diagram sub-Vis are identified by their icon

•  Internally sub-VIs are differentiated by their names (and path)

- For LabVIEW two VIs with the same name are "identical"

- LabVIEW will search for missing/misplaced Vis

- LabVIEW will inform you about modified sub-VIs paths

13

Demo 2

The famous Jean-Hubert’s images selection problem

14

staring: •  Sub-vi creation •  Files access •  Image raw data •  Graph •  Cursor

Module 2

• Error handling • Strings • Files • Arrays • Talk to the OS

15

Error handling

Error cluster

Status: true error false no error Code: 0 no error >0 warning code <0 error code Source: additional info

Handling errors is as important in LabVIEW as in other languages/environments.

Right-click on the edge of an error cluster show additional information regarding current error.

LabVIEW standardizes error handling using an error cluster.

16

Error handling

By convention errors clusters are connected at the bottom left and right.

Ensure that by default the input error cluster is set to no error .

If there is an error on the input cluster pass it through, and set outputs accordingly.

If no error, do the work and cook your own error, if any.

in! out!

17

Error handling Chain VIs with errors wires to control the order of execution. Use shift-registers in loops (for, while) to update the error state at each iteration.

Note: Error can directly be mixed with boolean or connected to the loop termination condition.

18

Error handling

Similarly to c++'s exception, LabVIEW has an automatic way of displaying errors if nothing is connected to the output error cluster.

Can be turned off in the VI properties dialog (right click on the VI's icon)

Nothing!!

From previous slide 19

Strings

typedef struct LVString {

long size;

char[] string;

}

•  Strings can be seen as an array (vector) of chars, like in c.

•  Strings are resizable. LabVIEW handles the associated memory operations.

•  Single char does not exist in LabVIEW, it's a string with 1 element.

•  Single char can be expressed as a Byte, i.e. Unsigned 8bits Integer or [U8].

•  Strings are sometimes used as stream of bytes.

•  LabVIEW's strings contains its size, max 232 ~4Billion chars.

20

String functions

String S[] = '\r';

String S[] = 'Hello World';

UInt8 A[] = {1,2,4,3};

String S[] = (String)A;

array of Bytes

A

normal

'\' code

password

hexadecimal

Initialize Strings

Display formats

21

String functions

Length = sizeof("Hello World");

S = S + "Hello " + "World";

strcat(S,"Hello ");

strcat(S,"World");

S = StrSubset("Hello World",3,5);

S[2] = SplitStr("Hello World","\s");

S = ReplaceStr("Hello World","\s","\r");

Length = 11

S = "Hello World"

S = "lo Wo"

S1 = "Hello"

S2 = "World"

S = "Hello World"

String Length!

Concatenate!

String Subset!

Match Pattern!

Search & Replace!

space

return 22

spaceß

String functions

sprintf(S,"Result :%d, %6f",

135,32.089);

S = "Result : 135, 32.089000"

Right – click the Format into String node to edit precisely the string format

String format will be automatically added to the node

Format Into String!

23

String functions

cin >> D >> S >> B >> I;

If (cin.fail()) ...

sscanf(S,"%f %[ A-Za-z] %s %d",

&D, S, &B, &i);

Error = "Scan From String (arg 4) in Strings.vi"

D = 3.14

S = "is pi"

B = FALSE

I = 0

Right – click the Format into String node to edit precisely the string format

Default values

Use %s for a single string (no delimiter like \s, \r, etc) otherwise specify the allowed characters in [], in the above example [\s A-Za-z]

'\s'

Error because the last two elements are inverted

Scan from String!

24

String functions

Double A = {{4.3, 5.6} {1.8, 2.2}};

String F = "%.3f";

S = ArrayToSpreadSheetStr(A,F);

String S = "4.3, 5.6\r1.8,2.2";

String F = "%d";

String D = ',';

A = SpreadSheetStrToArray(S,F,D);

S = "4.300 5.600

1.800 2.200"

A = {{ 4 5 }

{ 2 2 }}

delimiter!format!

format!

%d -> convert into integer

%.3f -> double with 3 digits after '.'

Array to Spreadsheet String!

Spreadsheet String to Array!

25

String functions

String LS = "long blabla before the interesting part that needs to be removed first!!\rtime: 12.1.2012 - 15:13\rc: green\ri: 123" MatchPattern(LS, "time:\s", NULL,NULL,After); MatchPattern(After, "c:\s", S,NULL,After2); MatchPattern(After2, "i:\s", C,NULL,After3); B = (C=="green");

atoi(After3,I)

S = "12.1.21012 -15:13"

Example of string parsing

Decimal String to number!

C = "green"

B = TRUE

I = 123

26

String functions

// -- c++ version -- string LS = "long blabla before the interesting part that needs to be removed first!!\rtime: 12.1.2012 - 15:13\rc: green\ri: 123" int P, I, B; string T,S,C; P = LS.find("time: "); T = LS.substr(P + 6,LS.size());

P = T.find("c: "); S = T.substr(0,P); T = T.substr(P + 3,T.size());

P = T.find("i: "); C = T.substr(0,P);

B = C.compare(0,5,"green"); T = T.substr(P+3,T.size());

I =atoi(T.c_str());

S = "12.1.21012 -15:13"

Example of string parsing

Decimal String to number!

C = "green"

B = TRUE

I = 123

27

Files I/O

•  LabVIEW uses underneath standard OS calls •  Same structure, file reference, file pointer, etc. •  Same rules: access, permission, quota, flush •  Same way of doing files I/O •  Files can be text or binary

File path "HD/myfiles/a.txt"

String to File path "HD/myfiles/b.txt"

File reference 0x2486172920

LabVIEW files handling is the same as in c/c++, only simplier J!

28

Files I/O

Open/create/replace file!

Must specify a path or a dialog is displayed Different options can be selected (create/replace/etc.)

Close file!

Write to text file!

Read from text file!Specify the number of Bytes, -1 -> whole file

Will convert end of line to platform specific format

Will convert end of line to platform specific format

ofstream f; f.open ("a.txt"); f.close() f<<"Hello World!"; f.read(buffer,lenght); f.seekg (0, ios::end); length = f.tellg(); f.seekg (0, ios::beg);

Path Reference

Note: all vi carries error handling, which is not displayed 29

Files I/O

Write to binary file!

Read from binary file!Specify the binary format to be read

Will write the array size(s) (3) before writing the array elements. Will write 2 sizes for an 2D array, etc.

f.open("b.txt",fstream::bin); double A[]= {142.7, 121.8, -23.3}; f<<A; f.read(A,lenght);

Data format

Prepend array size

0000 0003 3 elements 4061 D666 6666 6666 142.7 405E 7333 3333 3333 121.8 C037 4CCC CCCC CCCD -23.3

30

Files I/O – format & endianess •  Endianness has been invented by mad computer scientists to annoy freshman students

- and others as well. •  It is a source of bugs, we should not have to care about such an issue… •  Endianness defines how data is ordered in memory and thus on disk. •  It is similar to writing: some languages write from left to right and others from right to

left. There is no issue as long as direction is known! •  Big endian goes from right to left, the Most Significant Byte first •  Little endian goes from right to left (most used, x86), the Least Significant Byte first •  The smallest unit a processor reads/write is (generally) a byte/char.

•  When the processor writes a longer value, ex. an integer (4 bytes), the order of the writing matters.

A!

A! B! C! D!

little endian big endian

little endian

big endian

little endian: A big endian: A

little endian: CDBA big endian: ABCD

A!

B!

C!

A" B" C" D"

7" D" E" 2"

A" F" 8" 4"4 Bytes memory access

1 Byte memory access

31

Files I/O

Format into (text) File!

Scan from (text) file!Read the file and try to interpret the inputs according to the given format.

Default values will be used in case of error.

Convert the inputs to a string according to the given format and write it to a file

f.open("a.txt"); f<<"sinus"<<100<<2.5; a.txt sinus, 100, 2.5 double D = NaN; string S; boolean B; int I=-1; f>>D>>S>>B>>I;

Default values

String format

String format

32

Files I/O

Write Spreadsheet to File!

Read from Spreadsheet File!Read the spreadsheet file and interpret the values according to the selected format.

Convert the inputs double array to a string according to the given format and write it to a file

double A = {3.4, 2.1, 6.8};

string F = "%.3f";

string P = "a.txt";

S = WriteSpreadSheetToFile

(P,A,F,',');

double A[];

String D = ',';

string P = "a.txt";

A = ReadFromSpreadSheetFile

(P,'double',D);

Double format

format

delimiter

delimiter

33

Files I/O

Build path!

List all the folders and files of a given path

Additional utilities libraries

File/Dir info!

Folders list"

Files list"

Is a directory ?"

Lastest modif."

Strip path!

home/me/myFiles/Prj/LV1.vi

This VI" Default" Temporary"

Path constants!

Get System Directory"

List folders!

Return File/Folder info of a given path

Preferences" XML" ZIP" Image"

34

Files I/O

Build the file path relative to the current VI location

Create a new file or replace and existing one, open the file

Get the current date as a string, write it to the file add '\r' after

Write "sinus 100 2.5" into the file

Close the file

Display error if any

home/me/myFiles/demo.txt

This VI path" string path = LV_GetCrtVIPath(); path += "demo.txt"; ofstream f; f.open (path.c_str()); time_t t; time (&t); f<< ctime(&t)<<"\r"; f << "sinus" << 100 << 2.5; f.close() if (f.fail()) ...

error"

35

Talking to the Unix OS

•  System Exec provides access to almost all underlying Unix functions

•  It is similar to typing a command in the terminal

•  Standard result and standard error are returned

Standard result"

Standard error"

Applications Developer Library Network System Users … private sbin tmp usr var

36 Note: on Windows, prepend 'cmd /c to you call, ex: 'cmd /c dir C:'

Talking to the Unix OS

// -- myPrg.c --

#include <iostream>

using namespace std

int main (int argc, char* const argv[])

{

cout << "argv[1]: '"<<argv[1]<<"'\n";

cerr << "no error!\n";

return 0;

}

> cd my/vi/path

> ./myPrg 123

argv[1]: 123

no error!

>

argv[1]: 123

no error!

The VI directory"

Launch a program called "myPrg" with '123' as parameter.

The program and the calling VI are located in the same directory.

37

Array

Array -> structure with all elements having the same type

•  Arrays can be of any dimension (up to 64) •  Arrays can be of any types •  Array are dynamically allocated & expended •  Width of ‘[]’ visually informs about dimension •  Many array primitives exists, even more linear

algebra functions •  Waveforms are specific 1D array type •  Matrix (real or complex) are specific 2D array types

Bool[];

long[];

long[][];

long[][][];

float[][][][][]..

struct[];

Str[];

waveform;

matrix; array indexes

array element

38

Array functions

Initialize arrays

const dbl cst_array[2][3] =

{{1,2,3} , {4,5,6}};

dbl dbl_array [2][3] =

{{-1,-1,-1},{-1,-1,-1}};

dbl rnd_array[][];

for (r=0; r<2; r++)

for (c=0;c<3;c++)

rand_array[r][c]=rand();

39

How big an array ?

100’000’000 pts x 8 Bytes ~ 800 MBytes

•  Use in place structure primitives where possible •  Check the Buffer Allocations, Tools»Profile»Show Buffer Allocations

40

Array functions

LabVIEW’s array stores its size int A1[3] = {1,2,3};

elem = ArraySize(A1);

int A2[3] = {{1,2,3},

{4,5,6}};

row = Get(ArraySize(A2),0);

Colum = Get(ArraySize(A2),1);

int A3[3] = {1,2,3};

elem = ArraySize(A3);

A4= BuildArray(A3,4);

elem_1 = ArraySize(A4);

LabVIEW’s array can be dynamically extended

A4

A3

A2

A1

Build array 41

Array functions

int Array[6] = {{1,2,3},

{4,5,6}};

A = GetSubArray(Array,def,all,

1,3);

B = GetIndexArray(Array, 1, all);

e = GetIndexElem(Array, 1, 2);

f = GetIndexElem(Array, def, 2);

Access/Select array elements

grow

Unconnected inputs are set to default (see help window for default values)

B[]={4,5,6}

e = 6

f = 0

A[]={{2,3}, {5,6}}

0

1 3

42

Array functions

int Array[4] = {1,2,3,4};

Delete(Array,2,1,C,D);

Insert(C,1,9.0,E);

Replace(E,0,8.0,F);

Replace(F,3,7.0,F);

C[] = {1,4} D[] = {2,3} E[] = {1,9,4} F[] = {8,9,4}

delete

insert

replace

Delete/insert/replace array elements

43

Array functions

double Pos[] = {};

double Neg[] = {};

double _A[];

for (i=0; r<1000; i++)

_A[i]=rand() * 2 - 1;

for (j=0; j<size(_A),j++) {

if (_A[j]≥ 0)

AppendArray(Pos, _A[j]);

else

AppendArray(Neg, _A[j]);

Ex: sort in 2 arrays positive from negative values

_A[]

44

Array functions

double A[100];

double B[100];

double Neg[], Pos[];

Double T=0;

int i;

GenRand(100, &A);

Sort(A, &B);

for (i=0, i<SizeArray(B), i++){

if (B[i]<T) && (B[i+1]>=T))

break;

i++;

}

Split(B, i, &Neg, &Pos);

Ex: sort positive from negative values, alternative solution

45

G data types - Matrix

? ? B = C = D

46

Matrix functions

47

Waveform

t0 time instant of the first point dt delta t, time between sample Y data points, start at t0 and separated by dt

Data with associated timing information

48

Waveform

generation basic measurement filter

. . .

Waveforms

Set waveform attribute

49

Class 2 - recap

•  Error handling –  It is important!

•  Strings –  Easy, same as in c

•  Files –  Easy, same as in c, be aware about endianess

•  External code –  I can call any UNIX commands

•  Arrays –  easy, same as in c

50