Skip to content
RoboLearn
Not completed

Functions

ProgrammingBeginner25 minWrite robot functions ↓Before this: Variables and data

What you’ll learn

  • How to write your own functions
  • Parameters (inputs) and return values (outputs)
  • How functions make robot code readable

Functions

A function is a named block of code you can run whenever you want. You’ve already used some: digitalWrite(), delay(), setup(), loop().

void beep() {
tone(8, 1000, 100);
}

void means it doesn’t give anything back. Call it with beep();.

Parameters

Inputs that change what the function does:

void blink(int pin, int times) {
for (int i = 0; i < times; i++) {
digitalWrite(pin, HIGH); delay(200);
digitalWrite(pin, LOW); delay(200);
}
}
blink(13, 3);

Return values

A function can calculate something and give it back:

float toCm(long microseconds) {
return microseconds * 0.0343 / 2;
}
float d = toCm(1160); // 19.9

Why bother?

  • Readable: forward(); turnLeft(); reads like the plan.
  • No repeated code: fix a bug once, in one place.
  • Testable: check each function on its own.

Finished this lesson?