Trailblazer Robotics
Unit 1 · Week 2

Variables and Types

Store numbers, give them names, and use them to control the robot.

You'll learn

What is a variable?

A variable is a labeled box that holds a value. You can read it, change it, do math with it. The label is the name you choose. The value is what's inside.

int   driveSpeed = 50;        // whole number (percent)
double turnPower  = 35.5;     // decimal number
bool  isHolding  = true;     // true or false

The three types you'll use most

Using variables in real code

Compare these two versions of the same program. Both drive forward at 50% for 1.5 seconds. Which is easier to tweak later?

Bad, magic numbers:

LeftMotor.spin(forward, 50, percent);
RightMotor.spin(forward, 50, percent);
wait(1.5, seconds);
LeftMotor.stop();
RightMotor.stop();

Better, variables with meaningful names:

int main() {
  vexcodeInit();   // IDE-supplied setup, leave this alone

  int    speedPct = 50;
  double driveSec = 1.5;

  LeftMotor.spin(forward, speedPct, percent);
  RightMotor.spin(forward, speedPct, percent);
  wait(driveSec, seconds);
  LeftMotor.stop();
  RightMotor.stop();
}
Reminder: the motor and sensor objects (LeftMotor, RightMotor) are still generated for you by the Robot Configuration menu. You only write what goes after vexcodeInit();.
Why this matters: when you write a 200-line autonomous routine and you need to change the speed in 12 places, the variable version takes one second to update. The magic-number version is a nightmare.

Naming rules

Curated references

Find the Bug

Two programs with intentional errors. Spot the bug.

Problem 2A
This program is supposed to drive forward for 1.5 seconds. Instead, it drives for exactly 1 second. The compiler shows no errors. What's wrong?
int    speedPct = 50;
int    driveSec = 1.5;

LeftMotor.spin(forward, speedPct, percent);
RightMotor.spin(forward, speedPct, percent);
wait(driveSec, seconds);
LeftMotor.stop();
RightMotor.stop();
Problem 2B
This program will not compile. The compiler says "assignment of read-only variable". What needs to change?
const int MAX_SPEED = 80;

int main() {
  MAX_SPEED = 100;
  LeftMotor.spin(forward, MAX_SPEED, percent);
}
← Week 1 Next: If / Else →