Trailblazer Robotics
Unit 2 · Week 3

If / Else & First Sensor

Make the robot react. Drive until something happens.

You'll learn

The if pattern

if (DistanceSensor.objectDistance(mm) < 100) {
  LeftMotor.stop();
  RightMotor.stop();
} else {
  LeftMotor.spin(forward, 50, percent);
  RightMotor.spin(forward, 50, percent);
}

Read it like a sentence: "If the distance to the closest object is less than 100 mm, stop both motors. Otherwise, drive forward."

Common bug: = assigns, == compares. if (x = 5) sets x to 5; if (x == 5) checks if it equals 5. Mixing these up is the most common bug in C++.

Drive until the bumper hits

One last reminder before we stop calling it out: the motors and the bumper are added by the Robot Configuration menu, and vexcodeInit() is auto-inserted at the top of main. From the next lesson on, we'll show only the part you actually write yourself.

int main() {
  vexcodeInit();   // VEXcode IQ adds this for you, leave it alone

  LeftMotor.spin(forward, 50, percent);
  RightMotor.spin(forward, 50, percent);

  // Loop until the bumper is pressed
  while (FrontBumper.pressing() == false) {
    wait(20, msec);  // small wait so we don't hog the CPU
  }

  LeftMotor.stop();
  RightMotor.stop();
}

Logical operators

You can combine conditions with && (and) and || (or).

if (FrontBumper.pressing() || DistanceSensor.objectDistance(mm) < 50) {
  // stop if either the bumper is pressed OR the wall is close
  LeftMotor.stop();
  RightMotor.stop();
}

Try it

Write a program that drives forward until a bumper is pressed, then backs up for 0.5 seconds, then stops. Two if-statements (or one while loop and one wait) is enough.

Curated references

Find the Bug

Two programs with intentional errors. Spot the bug.

Problem 3A
This program is supposed to stop the motors when the bumper is pressed. Instead, the motors stop instantly every time you run the program. Why?
bool isPressed = FrontBumper.pressing();

if (isPressed = true) {
  LeftMotor.stop();
  RightMotor.stop();
}
Problem 3B
This program is supposed to drive forward until the wall is closer than 100 mm. Instead, the robot drives forever. The wall is clearly closer than 100 mm. What's broken?
LeftMotor.spin(forward, 50, percent);
RightMotor.spin(forward, 50, percent);

while (DistanceSensor.objectDistance(mm) < 100) {
  wait(20, msec);
}

LeftMotor.stop();
RightMotor.stop();
← Week 2 Next: Loops & Functions →