Functions
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.9Why 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.
Example: robot moves as functions (simulator)
function forward() { motors(50, 50); }function turnLeft() { motors(-40, 40); }function stop() { motors(0, 0); }
function loop() { if (distance() < 25) turnLeft(); else forward();}Example: a function that decides
bool pathClear() { return readCm(3, 2) > 25;}
void loop() { if (pathClear()) forward(); else turnLeft();}Try it
Robot commands
motors(left, right): wheel power, −100 to 100lineLeft(),lineRight():trueover the black linedistance(): cm to the nearest thing ahead (max 200)distanceLeft(),distanceRight(): cm to the sideslinePosition(): where the line is, −1 (left) to 1 (right), ornullmillis(): milliseconds since Runprint(value): show a message belowsetup()runs once;loop()runs 50 times a second
Add a reverseEasy
Write backward(speed) and use it when something is closer than 10 cm.
function backward(s) { motors(-s, -s); } and in loop(): if (distance() < 10) backward(40); else if (distance() < 25) spin(); else forward(60);
A helper that returnsMedium
Write isBlocked() that returns true when anything is within 25 cm in front, and use it in loop().
function isBlocked() { return distance() < 25; } then if (isBlocked()) spin(); else forward(60);
Smart turn functionHard
Write turnToOpenSide() that spins towards whichever side has more space.
Show an answer
function turnToOpenSide() { if (distanceLeft() > distanceRight()) motors(-40, 40); else motors(40, -40);}Quick check
Finished this lesson?