04

Robotics · Step 4 of 8 · 6 min

Programming robots: loops and state machines

You can structure robot code so it reacts quickly and stays readable.

The control loop

Robot code is a loop: read sensors, decide, set the motors, repeat. A small robot might run this loop 50 to 100 times a second. The faster and steadier the loop, the smoother the robot.

Avoid blocking delays

delay() pauses everything. While it waits, the robot cannot see the wall coming. Beginners hit this wall, literally, very often.

Instead, check the clock. On Arduino, millis() tells you how long the board has been running. Do a task only when enough time has passed, and the loop keeps reading sensors in between.

State machines

A state machine names the modes a robot can be in, such as SEARCHING, FOLLOWING_LINE, AVOIDING and STOPPED. In each state the robot does one simple thing. Clear rules say when to switch.

This keeps code readable. Instead of a tangle of if statements, you can draw the robot's behaviour as circles and arrows, then turn the drawing into code.

Using AI to write code

Chatbots write decent robot code, but they guess at pin numbers, libraries and wiring. Test in a simulator first. Read each line. A wrong pin on real hardware can drive a motor into a wall or short a board.

Try it

Design a state machine

  1. 1.Pick a behaviour: a robot that drives forward, backs up and turns when something is closer than 15 cm.
  2. 2.List the states and the events that move between them.
  3. 3.Ask a chatbot to turn your list into Arduino code that uses millis() and no delay().
  4. 4.Run it in Wokwi with LEDs standing in for the motors.
Here are my robot states and transitions: [paste]. Write Arduino code as a state machine using an enum and a switch statement. Use millis(), not delay(). Explain how each transition happens.
Why is calling delay(2000) inside a robot's main loop risky?

Check yourself

Why is calling delay(2000) inside a robot's main loop risky?

Read alongside