Trailblazer Robotics
Unit 2 · Week 4

Loops & Functions

Repeat actions cleanly. Group code into reusable chunks.

You'll learn

The while loop

"Keep doing this as long as the condition is true."

while (Brain.timer(msec) < 3000) {
  LeftMotor.spin(forward, 50, percent);
  RightMotor.spin(forward, 50, percent);
  wait(20, msec);
}
LeftMotor.stop();
RightMotor.stop();

The for loop

"Do this a specific number of times."

for (int i = 0; i < 4; i++) {
  // drive forward then turn 90°, repeats 4 times for a square
  driveForward(12);  // 12 inches (we'll write this function below)
  turnRight(90);
}

Your first function

Functions are reusable blocks. Write once, call anywhere.

// A function that turns the robot right by a given angle.
void turnRight(int degrees) {
  LeftMotor.spinFor(forward,  degrees, deg, false);  // false = don't wait
  RightMotor.spinFor(reverse, degrees, deg, true);   // true  = wait until done
}

int main() {
  turnRight(90);
  turnRight(45);
  turnRight(180);
}
The DRY rule (Don't Repeat Yourself): if you find yourself copy-pasting the same 5 lines of code more than twice, turn it into a function. Your code shrinks, bugs get easier to find, and changes happen in one place.

Parameters and return values

// Returns the average of two numbers
double average(double a, double b) {
  return (a + b) / 2.0;
}

double avgEncoder = average(LeftMotor.position(deg), RightMotor.position(deg));

Try it

Write a function driveDistance(int inches) that drives forward a given number of inches (you can convert inches to motor degrees using the wheel circumference, we'll do this properly in Week 6). Then use a for-loop to drive in a square: 4 sides of 24 inches with 90° turns.

Curated references

Find the Bug

Two programs with intentional errors. Spot the bug.

Problem 4A
This loop is supposed to drive the robot in a square (4 sides). Instead, it makes 5 sides and ends up rotated 90° off. Why?
for (int i = 0; i <= 4; i++) {
  driveInches(12);
  turnRight(90);
}
Problem 4B
This function is supposed to return the average of two numbers, but the value it returns is always wrong by a lot. What's going on?
int average(int a, int b) {
  return (a + b) / 2;
}

int main() {
  double result = average(7, 4);
  Brain.Screen.print("avg = %.2f", result);
  // prints 5.00 instead of 5.50
}
← Week 3 Next: Sensors →