Algorithms and sequences
What you’ll learn
- What an algorithm is
- Why robots need precise, ordered instructions
- The three building blocks: sequence, selection and repetition
Algorithms
An algorithm is a precise list of steps that solves a problem. Recipes and directions are algorithms. A robot follows its algorithm exactly, with no common sense, so every step must be clear and in the right order.
“Make a sandwich” is vague. “Take two slices of bread. Spread butter on one side of each slice…” is an algorithm.
The building blocks
| Block | Means | Example |
|---|---|---|
| Sequence | Do steps in order | Drive forward, then turn, then stop |
| Selection | Choose based on a condition | If the path is blocked, turn |
| Repetition | Repeat steps | Do this 4 times; or keep going until the line ends |
Almost every robot program is these three blocks combined.
Good algorithms are
- Precise: “turn right 90°”, not “turn a bit”.
- Ordered: steps in the right sequence.
- Finite: they end, or repeat on purpose.
- Tested: you walk through them before trusting them.
Example: drive a square
repeat 4 times: drive forward 50 cm turn right 90°stopExample: the “human robot” game
One person is the robot and only follows exact commands: “step forward 1 step”, “turn right 90°”. Another writes an algorithm to get them to the door. Missing or vague steps show up immediately: the “robot” walks into a chair.
Example: the same idea in robot code
// sequence by time: 0–1 s forward, 1–1.6 s turn, then stopfunction loop() { const t = millis(); if (t < 1000) motors(50, 50); else if (t < 1600) motors(50, -50); else motors(0, 0);}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
Write a morning algorithmEasy
Write an 8-step algorithm for getting ready for school. Swap with a friend: can they find a missing or vague step?
Zig-zagMedium
Make the robot drive in a zig-zag: forward, left turn, forward, right turn, repeating.
Use millis() % 3200 to repeat a 3.2-second pattern.
Show an answer
function loop() { const t = millis() % 3200; if (t < 1000) motors(50, 50); else if (t < 1600) motors(-50, 50); // left else if (t < 2600) motors(50, 50); else motors(50, -50); // right}Find the bugHard
This algorithm should get a robot through a door: “turn right 90°; drive forward until the wall; drive through the door”. What’s missing? There’s no step to find the door: after reaching the wall, the robot needs to turn and drive along it until there’s a gap, then turn through it. The last step is also vague: how far?
Quick check
Finished this lesson?