Stage 00 · Lesson 05/10

Robotics Orientation · Lesson 05

The Robot Brain

Est. 40–55 min

Why

Why the “brain” choice matters

People say “robot brain”, but in the lab you choose a controller based on very practical questions: How many pins do I need? How fast and how regularly must my loop run? Do I need a camera, Wi-Fi or Linux? Choosing wrong means jittery servos, missed sensor readings, or a board that simply can’t run your software.

Concept

The big idea: microcontrollers vs single-board computers

Two kinds of brains

Microcontroller (MCU)Single-board computer (SBC)
ExampleArduino Uno (ATmega328P chip)Raspberry Pi 4
Speed and memory16 MHz, 32 KB program flash, 2 KB RAMQuad-core 64-bit ARM processor, gigabytes of RAM
Operating systemNone: your program is the only thing runningLinux (many programs share the CPU)
SuperpowerPrecise, predictable timing; direct pin control (PWM, ADC); starts instantlyCameras, Wi-Fi, Python libraries, ROS 2, AI models
WeaknessToo small for cameras, maps or AITiming can jitter because Linux may pause your program
Human analogySpinal reflexes (pull your hand off a hot tawa)Thinking brain (planning what to cook)

Real-time does not mean “very fast”. It means on time, every time. A loop that runs exactly every 20 ms is real-time; one that is usually 5 ms but sometimes 200 ms is not, even though it is faster on average.

Firmware vs software

  • Firmware runs on the microcontroller and talks directly to pins, timers and hardware buses. Your Arduino sketch is firmware.
  • High-level software runs on a computer or SBC and works with files, networks, cameras and messages. Your Python scripts and (later) ROS 2 nodes.
  • A common robot design uses both: the SBC decides “move the elbow to 60°”, then sends that over a USB cable to the MCU, which generates the exact servo pulses.
NoteAlso good to know: factories often use PLCs (programmable logic controllers), rugged controllers with their own programming tools, built for reliability. Out of scope here.

How it works

How an Arduino actually runs your code

  1. Power on / reset

    A small built-in program (the bootloader) checks whether new code is arriving over USB, then jumps to your sketch.

  2. setup() runs once

    Set pin modes, start Serial, attach servos.

  3. loop() runs forever

    As soon as loop() ends, it starts again. Each pass is one heartbeat: read sensors → decide → write outputs.

  4. Time is a budget

    If you want 50 updates per second, each loop gets 1000 ÷ 50 = 20 ms. Every sensor read, calculation, print and delay() spends part of that budget.

  5. millis() is the clock

    millis() returns milliseconds since power-on. Comparing it with a saved time lets you do things “every 1000 ms” without stopping the loop. That’s the non-blocking style used by every serious robot sketch.

Visual

Visualise it: does your loop finish on time?

Set a target loop rate, then add sensor time, compute time, serial printing and delay(). See how much of the time budget each task uses and what rate you really get.

Interactive · Loop timing budget

Too slow: loop misses its target rate
0 mstarget period 20.0 ms
Sensor read 3.00 msCompute 1.00 msSerial print 31.25 msdelay() 0.00 ms deadline

Wanted rate

50 Hz

Time used / loop

35.25 ms

CPU budget used

176 %

Actual rate

28.4 Hz

Serial time here = characters × 10 bits ÷ baud. On an Arduino Uno, Serial.print() returns at once while its small transmit buffer (64 bytes) has room; when you print more than the line can carry, print() waits — so in steady state each loop pays roughly this time.

Worked example

Worked example: the 20 ms budget

You want your arm controller to update 50 times per second (50 Hz). The budget per loop is 20 ms. Let’s spend it:

Time used per loop
TaskTimeHow we know
Read a sensor3 msExample value; measure your own with micros()
Compute the next servo angles1 msExample value
Print 30 characters at 9600 baud31.25 ms30 chars × 10 bits ÷ 9600 bits/s
Total35.25 msOver budget: the loop only manages ≈ 28 Hz

Try exactly these numbers in the visualisation above: 50 Hz, sensor 3 ms, compute 1 ms, 30 characters, then toggle 9600 ↔ 115200 baud.

Code lab

Code lab: the frozen robot vs the responsive robot

Both sketches blink the built-in LED once a second and watch a push button on pin 2 (button between pin 2 and GND). Upload the first one and press the button quickly. Most presses are missed.

blink_delay.ino · Arduino C++
// blink_delay.ino — the "frozen robot" version. Don't build robots like this!
const int LED = LED_BUILTIN;
const int BUTTON = 2;   // push button to GND (uses the internal pull-up)

void setup() {
  pinMode(LED, OUTPUT);
  pinMode(BUTTON, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(LED, HIGH);
  delay(1000);                       // CPU does NOTHING else for 1 second
  digitalWrite(LED, LOW);
  delay(1000);                       // ...and again
  if (digitalRead(BUTTON) == LOW) {  // checked only once every 2 seconds!
    Serial.println("Button pressed (noticed late)");
  }
}

What you will see

Button pressed (noticed late)
(only if you happen to be holding the button at the moment it is checked, once every 2 seconds)

Now the non-blocking version. It does three jobs “at the same time” by never waiting:

blink_millis.ino · Arduino C++
// blink_millis.ino — non-blocking loop: blink AND watch the button at the same time.
const int LED = LED_BUILTIN;
const int BUTTON = 2;              // push button to GND (uses the internal pull-up)
const unsigned long BLINK_MS = 1000;

unsigned long lastBlink = 0;
bool ledOn = false;
bool lastButton = HIGH;
unsigned long loops = 0;
unsigned long lastReport = 0;

void setup() {
  pinMode(LED, OUTPUT);
  pinMode(BUTTON, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  unsigned long now = millis();

  // Task 1: blink without blocking
  if (now - lastBlink >= BLINK_MS) {
    lastBlink = now;
    ledOn = !ledOn;
    digitalWrite(LED, ledOn ? HIGH : LOW);
  }

  // Task 2: react to the button within microseconds
  bool b = digitalRead(BUTTON);
  if (b == LOW && lastButton == HIGH) {
    Serial.println("Button pressed (noticed immediately)");
  }
  lastButton = b;

  // Task 3: once a second, report how many times loop() ran
  loops++;
  if (now - lastReport >= 1000) {
    lastReport = now;
    Serial.print("loop() ran ");
    Serial.print(loops);
    Serial.println(" times in the last second");
    loops = 0;
  }
}

What you will see (the loop count is in the thousands per second; the exact number depends on your board)

loop() ran … times in the last second
Button pressed (noticed immediately)
loop() ran … times in the last second

Real world

Real robot brains

Arduino Uno R3: a blue circuit board with a USB-B socket, a barrel power jack, black header strips along the edges and a long ATmega328P chip.
Arduino Uno R3, the classic microcontroller board used in Stage 6. Header pins along the edges give direct access to digital I/O (some with PWM), analogue inputs, 5 V and GND.Photo: SparkFun Electronics · CC BY 2.0 · Source: Wikimedia Commons · resized, converted to WebP
Raspberry Pi 4 Model B single-board computer seen from above, with a 40-pin GPIO header, USB and Ethernet ports, and two micro-HDMI ports.
Raspberry Pi 4 Model B, a credit-card-sized Linux computer. Great for cameras, Python and ROS 2. Its GPIO pins are 3.3 V, not 5 V.Photo: Laserlicht · CC BY-SA 4.0 · Source: Wikimedia Commons · resized, converted to WebP
  • Stage 6 arm: Arduino generates the servo pulses; your laptop can optionally send target angles over USB serial.
  • ROS 2 robots (Stage 10): a Linux computer runs navigation and vision; a microcontroller handles motors and encoders.
  • Hobby drones: a dedicated flight-controller MCU runs the fast stabilisation loop; a companion computer may handle the camera.

Mistakes

Common mistakes and debugging

Hardware & safety

Hardware lab and safety notes

Prove the difference between delay() and millis() on a real Uno.

  • Push button between pin 2 and GND (sketch uses INPUT_PULLUP).
  • Built-in LED on pin 13 — no extra wiring.
  • Upload blink_delay.ino, press the button quickly many times, then upload blink_millis.ino and repeat.

Debugging

Debugging: when it doesn’t work

Symptom → likely cause → fix
SymptomLikely causeFix
Button presses are missedCode is stuck inside delay()Use the millis() pattern
One press prints 2–3 timesSwitch bounceIgnore changes for ~20 ms after a press (debounce)
Blink timing goes wrong after a long timeUsing int for timesStore times in unsigned long and use now - last >= interval
Serial Monitor shows nothingWrong baud or wrong portSet 9600 baud; pick the right port in Tools → Port
NoteChange one thing at a time and write down what happened. Most first-day problems are wiring, power or the wrong port, not the code.

Think

Think about it

Think

You want 30 Hz vision and 200 Hz joint PWM. One Raspberry Pi alone — good idea?

Experiment

Try it in the lab: pick the brain for the job

Experiment

Controller choice card

You will need

  • Notebook
  • The loop-timing visualisation above
  • Optional: Arduino Uno, push button, USB cable

Steps

  1. For a line follower, a camera arm, and a ROS 2 demo, pick MCU / SBC / both.
  2. Write the one responsibility you would NOT put on the SBC alone.
  3. In the loop-timing lab, set 100 Hz, sensor 3 ms, compute 1 ms, 20 characters at 9600 baud. Is it on time? Now fix it two different ways.
  4. With hardware: upload both blink sketches and count how many of 10 quick button presses each one notices.

Knowledge check

Check your understanding

Knowledge check

1. A common robust pattern is…

2. MCU strengths for hobby robots include…

3. Firmware primarily…

4. How long does it take to send 30 characters at 9600 baud (10 bits per character)?

5. “Real-time” in robotics mainly means…

Practice quiz

Loading practice quiz…

Mini assignment

Hands-on assignment

Mini assignment

Interface sketch

Draw boxes: Sensors → MCU → (optional) SBC → Actuators. Label two messages that cross the MCU↔SBC link (e.g. joint targets, telemetry).

Deliverables

  • Block diagram
  • Two interface notes

Stretch (code): add a fourth task to blink_millis.ino that prints “tick” every 250 ms using its own lastTick variable. All four tasks should run without any delay().

Do this, step by step

  1. Upload blink_delay.ino. Press the button 10 times quickly and count how many presses get noticed.
  2. Upload blink_millis.ino and repeat. Note the “loop() ran … times” number.
  3. Draw the interface sketch: Sensors → MCU → (optional) SBC → Actuators, and label two messages that cross the MCU↔SBC link.

Stuck? Hints, one at a time

NoteTry the task first. Read one hint, try again, and only then read the next one.
  1. Hint 1: With delay(1000) the board is blind for a full second, so short presses are lost.
  2. Hint 2: The loop count tells you how many times per second your robot could check its sensors.
  3. Hint 3: Typical MCU↔SBC messages: joint targets going down, sensor readings / battery voltage coming up.

Challenges (pick by level)

  • 🟢 Easy: Change BLINK_MS to 250 and confirm the button still works.
  • 🟡 Medium: Add a fourth task that prints “tick” every 250 ms with its own lastTick, with no delay().
  • 🟠 Hard: Add a 20 ms debounce so each press prints exactly once.

Next step

Next, Lesson 6: Power & Communication. Related: microcontrollers in depth in Stage 4 — Electronics, Linux on an SBC in Stage 3 — Linux & Dev Environment, Python in Stage 2.

Sources

Self-attested for now — keep artifacts in your lab notebook.

Complete

Today's goal

0 of 1 done today

0-day streak
Daily goal:lessons, quizzes or assignments a day

Mark this lesson complete when you have worked the experiment, knowledge check, and assignment (even roughly).

Stuck somewhere?

Ask a doubt about this lesson

Saved with this lesson's id and your email so we can reply. Privacy · or email contact@aihubstation.in