Example 2.1 explained, Example 2.1 explained -6 – Rockwell Automation 2098-IPD-xxx Ultra5000 C Programming using the Motion Library User Manual

Page 18

Advertising
background image

Publication 2098-PM001E-EN-P — July 2002

1-6

Programming Motion Control in C

Example 2.1 Explained

The program still consists of a single function main. However, it
introduces several new ideas, including comments, declarations,
variables, arithmetic expressions, and loops. The two lines

/* Increment through the 10 index positions

1000, 2000, etc. until target > endpoint */

are a comment, which in this case briefly explains what the program
does. Any characters between the /* and */ are ignored by the
compiler. Comments of this type may be multi-line and should be
used freely to make a program easier to read and understand.

In C, all variables must be declared before they are used, usually at
the beginning of the function in front of any executable statements. A
declaration announces the properties of variables; it consists of a type
name and a list of variables such as

long target, index, endpoint;

The type long means that the variables listed are long integers, by
contrast the type float means floating point, i.e., numbers that may
have a fractional part. On the Ultra5000, a long integer is a 32-bit
quantity that contains a value in the range ±2,147,483,647; a floating
point is a 32-bit quantity that contains a value in the range 10

-38

to

10

+38

.

Computation begins in the motion program with the assignment
statements

index = 1000;

target = index;

endpoint = index * 10;

which set the variables to their initial values. Semicolons terminate
individual statements.

In the example, each move is calculated and executed the same way,
and the loop repeats once per index; this is the purpose of the while
loop

while (target <= endpoint) {

. . .

}

The while loop tests whether a statement is true or false, and then
performs one of two possible paths. The example operates as follows:
The condition in parentheses is tested. If it is true (target is less than
or equal to endpoint), the body of the loop (the statements enclosed
by braces) is executed. Then the condition is re-tested, and if true, the
body is executed again. When the test becomes false (target exceeds

Advertising