Make the robot react. Drive until something happens.
if, else if, else 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."
= 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++.
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();
}
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();
}
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.
Two programs with intentional errors. Spot the bug.
bool isPressed = FrontBumper.pressing();
if (isPressed = true) {
LeftMotor.stop();
RightMotor.stop();
}
LeftMotor.spin(forward, 50, percent);
RightMotor.spin(forward, 50, percent);
while (DistanceSensor.objectDistance(mm) < 100) {
wait(20, msec);
}
LeftMotor.stop();
RightMotor.stop();