Programming instructions

Reference
Project Lead The Way
©
and Carnegie Mellon Robotics Academy
©
/ For use with VEX
®
Robotics Systems
Variables 1
task main()
{
int speed;
speed = 50;
startMotor(port3,speed);
startMotor(port2,speed);
wait1(2.0);
}
Variables with Natural Language
Variables are places to store values (such as sensor readings) for later use, or for use in
calculations. There are three main steps involved in using a variable:
task main()
{
int speed;
speed = 75;
startMotor(port3,speed);
startMotor(port2,speed);
wait1(2.0);
}
Declaration
The variable is created by announcing its type,
followed by its name. Here, it is a variable
named speed that will store an integer.
1. Introduce (create or “declare”) the variable
2. Give (“assign”) the variable a value
3. Use the variable to access the stored value
Assignment
The variable is assigned a value. The variable
speed now contains the integer value 75.
Use
The variable can now “stand in” for any value of the appropriate
type, and will act as if its stored value were in its place.
Here, both startMotor commands expect integers for power
settings, so the int variable speed can stand in. The commands
set their respective motor powers to the value stored in speed,
75.
In the example above, the variable “speed” is used to store a number, and then retrieve and use
that value when it is called for later on. Specically, it stores a number given by the programmer,
and retrieves it twice in the two different places that it is used, once for each of the startMotor
commands. This way both motors are set to the same value, but more interestingly, you would
only need to change one line of code to change both motor powers.
One line changed
The value assigned to speed is now 50 instead of 75.
Changed without being changed
No change was made to the program here, but
because these lines use the value contained in
the variable, both lines now tell their motors to
run at a power level of 50 instead of 75.
This example shows just one way in which variables can be used, as a convenience for
the programmer. With a robot, however, the ability to store sensor values (values that are
measured by the robot, rather than set by the programmer) adds invaluable new capabilities.
It gives the robot the ability to take measurements in one place and deliver them in another,
or even do its own calculations using stored values. The same basic rules are followed, but
the possibilities go far beyond just what you’ve seen so far!
Go to Reference Links