Robotics and Embedded Systems

Lesson 3: Sensors, Motors and ActuatorsNew-age

A robot lives or dies by the loop sense, decide, act. Lessons 1 and 2 covered the electricity and the code; this lesson covers the two ends of the loop that touch the physical world: sensors, which turn light, distance, temperature and motion into numbers, and actuators, which turn numbers back into motion. Both ends fail in predictable ways, and both reward the same discipline: read the datasheet, calibrate against something you know, budget the power, and test each part alone before you combine them.

Sensors: measuring the world

SensorMeasuresTypical useWatch out for
Ultrasonic (HC-SR04)Distance to the nearest surfaceObstacle avoidanceStruggles with soft, angled surfaces
Infrared reflectanceSurface brightness (line or no line)Line following, proximityAmbient sunlight can swamp it
Temperature/humidity (DHT22)Air temperature and humidityGreenhouses, weather stationsSlow: one reading every 2 seconds at best
Light (LDR divider)Light levelDay/dusk detectionCoarse — fine for thresholds, poor for precision
IMU (accelerometer + gyroscope)Acceleration, tilt, rotationBalance, orientationGyroscopes drift over time
Wheel encoderWheel rotationsDistance travelled, speed controlCounts motion of the wheel, not the ground — slipping lies
GPSPosition outdoorsNavigationMetres of error; nothing indoors

The ultrasonic sensor shows the general pattern: it emits a pulse of sound and times the echo. Sound travels at about 343 m/s, which is 0.0343 cm per microsecond, and the pulse makes a round trip, so distance = (echo time × 0.0343) / 2. An echo time of 1166 µs gives 1166 × 0.0343 / 2 ≈ 20.0 cm; 2915 µs gives ≈ 50.0 cm. Two details separate users from victims: the sensor needs a short trigger pulse (10 µs) before it answers, and if nothing is in range it eventually gives up — so code must handle a timeout, typically about 25 ms, which corresponds to roughly 4 m, its maximum rated range.

That last fact came from the datasheet, and reading one is a core skill. Key lines from the HC-SR04 datasheet: operating voltage 5 V; range 2 cm to 400 cm; accuracy about ±3 mm; working current 15 mA. Each line drives a design decision: 5 V fixes your supply rail; 2 cm minimum means the sensor is blind to anything closer — a robot can touch a wall its sensor swears is not there; ±3 mm accuracy means you should not build a control rule that depends on 1 mm differences. The DHT22's datasheet hides its trap in the sampling period: 2 seconds. Code that reads it every 100 ms is not getting fresher data, just the same data ten times — or, on some units, an error.

Calibration: from raw counts to real units

Sensors report counts, microseconds or volts — never the quantity you actually care about. Calibration is the measured mapping from raw output to physical units, and the workhorse method is two-point calibration: record the raw output at two known conditions and draw the straight line between them.

Worked example. A temperature probe in a divider reads 210 counts in ice water (0 °C) and 820 counts in boiling water (100 °C). The slope is (100 − 0) / (820 − 210) = 100 / 610 ≈ 0.164 °C per count. A reading of 500 counts is therefore (500 − 210) × 0.164 ≈ 47.5 °C. The same method fits any roughly linear sensor. A light sensor that reads 120 counts at 50 lux (a dim room, measured with a reference meter) and 880 counts at 1000 lux has a slope of 950 / 760 = 1.25 lux per count, so 500 counts means 50 + (500 − 120) × 1.25 = 525 lux.

Some sensors do half the work in the component itself. A TMP36 temperature sensor outputs a voltage: 500 mV at 0 °C plus 10 mV per degree. Read by a 10-bit ADC with a 5 V reference, a count of 154 means 154 × 5000 / 1023 ≈ 752.7 mV, hence (752.7 − 500) / 10 ≈ 25.3 °C. Notice the chain again — physical quantity, voltage, count, back to physical quantity (Lesson 1's chain, run in both directions). Calibration is not optional polish: an uncalibrated robot does not know less precisely where the wall is, it knows *wrongly*, with confidence.

Taming noise: the median filter

Real readings jump. A single ultrasonic measurement can spike when the pulse grazes an edge. Averaging helps against random jitter but a spike pulls the mean with it; the median (middle value) simply ignores one-off spikes:

float readDistanceCm() {
  float r[5];
  for (int i = 0; i < 5; i++) {
    r[i] = pingOnceCm();        // one timed echo, or -1 on timeout
    delay(10);
  }
  // simple sort of 5 values
  for (int i = 0; i < 4; i++)
    for (int j = i + 1; j < 5; j++)
      if (r[j] < r[i]) { float t = r[i]; r[i] = r[j]; r[j] = t; }
  return r[2];                  // the median
}

Given readings 20.1, 19.8, 55.0, 20.3, 20.0 cm, the sorted list is 19.8, 20.0, 20.1, 20.3, 55.0 and the function returns 20.1 cm — the 55.0 spike, probably an echo off a door frame, vanishes. But this code has a flaw worth spotting: if pingOnceCm returns −1 for "no echo", a median full of timeouts can hide the fact that the sensor sees nothing at all. Robust code counts the timeouts and reports "no obstacle detected" separately from "obstacle at 20 cm" — Lesson 4's fail-safe behaviour depends on exactly that distinction.

Actuators: making it move

ActuatorWhat it doesControl signalTypical job
DC motorSpins continuouslyPWM for speed, H-bridge for directionWheels, fans, pumps
ServoMoves to a set angle, 0–180°Pulse 1 ms → 0°, 1.5 ms → 90°, 2 ms → 180°, repeated every 20 msGrippers, steering, camera tilt
Stepper motorRotates in exact steps (200 steps per turn = 1.8° per step)Step pulses; 16× microstepping gives 3200 steps per turn3D printers, precision positioning

A microcontroller pin supplies at most about 20 mA safely. A small DC motor draws 600 mA running and over 1 A stalled (held still). Connecting a motor to a pin is not optimistic, it is destructive. Motors are driven through an H-bridge driver (such as the L298N): the pins send *signals*, the driver passes *power* from the motor supply, and the H-bridge arrangement also reverses the motor by swapping polarity. Speed comes from PWM on the driver (Lesson 2): an average of 6 V from a 9 V rail at 170/255 duty.

Power budgeting: the calculation that prevents melting

Every actuator decision is also a power decision. Budget our example robot honestly, at 7.4 V from a battery pack:

LoadTypical currentPeak current
Microcontroller + logic50 mA60 mA
Two DC drive motors600 mA each1200 mA each (stall)
Steering servo250 mA600 mA (starting a move)
Ultrasonic sensor15 mA15 mA

Total while driving: about 1,515 mA. A 2200 mAh pack at an average draw of 1.2 A lasts roughly 2200 / 1200 ≈ 1.8 hours — call it 1 hour 50 minutes before the design review, not during the demo. The peaks matter as much as the average: the driver must survive the stall sum of its own channel (1.2 A, within the L298N's 2 A per-channel rating), and the battery and wiring must deliver the total peak without the voltage sagging so far that the microcontroller resets. Brown-out resets — the board rebooting every time the motors start — are the signature symptom of a skipped power budget. Supporting habits: a separate supply for motors with a common ground shared with the logic (no shared ground, no shared signal reference, nothing works), a capacitor across the motor supply to absorb noise spikes, and driver chips chosen with rating to spare.

Where this runs in the real world

Warehouse robots glide between shelves on exactly this stack: ultrasonic and infrared sensors for obstacles, encoders for distance, DC motors through drivers, and a power budget that decides whether a robot finishes its shift. Agricultural robots read soil moisture and temperature, then dose water through pumps — a sensor reading becomes an action with money attached to its accuracy, which is why calibration matters commercially, not just in class. Medical devices are the strictest version: an infusion pump is a stepper motor, an encoder and a control loop whose calibration and fail-safes are regulated, because a 5% error is not a wobble, it is a dose. Same ideas, higher stakes.

Common mistakes

  • Powering a motor or servo from the 5 V pin. The pin's 20 mA budget and a servo's 250 mA appetite differ by a factor of twelve. The board will reset, brown out or die.
  • No common ground between the motor supply and the logic supply, then wondering why control signals behave randomly.
  • Trusting raw readings. No calibration, no filtering, no timeout handling — three separate ways to be confidently wrong.
  • Reading the datasheet after the smoke. Range, sampling period, accuracy and current draw are all printed before you buy, let alone build.
  • Testing everything at once. Sense, then act, then combine. A robot assembled in one step fails in ways that cannot be localised.
Key idea. Calibrate against something you know, filter what the sensor gives you, budget the power before you spend it — and never let a pin do a driver's job.
Try it. An encoder counts 48 pulses per wheel revolution, and the wheel is 20 cm in circumference. The robot logs 240 pulses. How far has it travelled, and what assumption about the wheel could make the true distance different?

Real-World Challenge

The task. Specify the sensing and power system for a greenhouse inspection rover that drives between plant benches. Requirements: (a) it must detect benches up to 3 m away with an HC-SR04 — calculate the echo timeout your code should use for that range; (b) its light sensor has been calibrated at two points, 120 counts at 50 lux and 880 counts at 1000 lux — find the lux value of a 500-count reading, and state whether a grower who wants the rover to work only above 400 lux should accept that reading; (c) the power budget is: controller 60 mA, two drive motors averaging 500 mA each, a camera servo 200 mA, sensors 40 mA. The rover must run for 2 hours between charges. Calculate the total average current and the minimum battery capacity, and recommend a pack size with sensible margin.

Worked solution. (a) Distance = (time × 0.0343) / 2, so time = 2 × distance / 0.0343 = 2 × 300 / 0.0343 ≈ 17,493 µs ≈ 17.5 ms. Set the timeout to about 17.5 ms: waiting longer wastes control-loop time staring at empty air; waiting less throws away benches that are really there. (b) Slope = (1000 − 50) / (880 − 120) = 950 / 760 = 1.25 lux per count. At 500 counts: 50 + (500 − 120) × 1.25 = 50 + 475 = 525 lux. That is above the grower's 400 lux threshold, so yes, the rover works in this light — with 125 lux of margin, enough to trust despite a few counts of sensor noise. (c) Total average current = 60 + 500 + 500 + 200 + 40 = 1,300 mA = 1.3 A. Two hours needs 1.3 × 2 = 2.6 Ah = 2,600 mAh as an absolute minimum. Batteries deliver less than their label as they age and discharge, so choose a 3,000 mAh pack (or larger): the roughly 15% margin is the difference between a specification and a hope. Note what the budget also tells you: the motors are 77% of the draw — any runtime problem is a motor problem, which the extension exploits.

Extension. The rover's motors only actually drive for about half of each patrol (the rest is spent stopped, photographing plants). Recalculate the average current with the motors duty-cycled to 50%, and work out how long the 3,000 mAh pack now lasts. Then name the trade-off: what does the rover give up for that extra runtime, and in what kind of greenhouse would that trade be unacceptable?

✅ Check your understanding

Quick recall check, generated from this lesson’s key terms. It is practice only and is not graded.

Keep reading to complete this lesson