Power, Safety and Building Your First Robot

Robotics Fundamentals

Course 1 · Chapter 10 · Power, Safety and Building Your First Robot

Nine chapters have designed the parts of a robot one at a time: the frame (Robotics Fundamentals 2), the motors and wheels (Robotics Fundamentals 3), the drive and its kinematics (Robotics Fundamentals 4), the sensors (Robotics Fundamentals 5), position and feedback (Robotics Fundamentals 6), control (Robotics Fundamentals 7), behaviour (Robotics Fundamentals 8) and arms (Robotics Fundamentals 9). None of it runs without a power system, and none of it should be switched on near people without safety built in. This final chapter does both, then brings everything together. It covers the batteries (chemistry, capacity, voltage sag, runtime), the power budget and the choice of regulator, the low-voltage cutoff and how to charge and store a LiPo pack without starting a fire, the wiring (wire gauge, voltage drop, connectors, fuses, a main switch, a common ground, a star layout), the emergency stop and the habits of safe testing, and a short look at the ethics of building machines that act in the world. Then comes the build: a complete plan for a small two-wheel line-following, obstacle-avoiding robot, with a specification, a parts list, design calculations that reuse every earlier chapter, a block diagram, a wiring table, an assembly order, a test plan with expected readings, and a troubleshooting table. The chapter ends with a recap of the whole course and the path on to Programming for Robotics.

Nothing here was built or tested by the author
This is a plan, worked out on paper. The author has not built this robot, measured its current, or run its code on a board. Every number below is either a calculation you can repeat (and that was recomputed with a script) or a typical or approximate value for a part (marked as such) taken from memory or from Basic Electronics 9 and Basic Electronics 11. The pin numbers are an example for one board, to be checked against your own board's pinout. Where your measurements disagree with a figure here, trust your meter and the data sheet of the part in your hand, and treat the disagreement as the interesting result. Prices are approximate pounds sterling and change often.

The same caution applies to safety. This chapter teaches habits and arithmetic for hobby-scale robots (batteries of a few watt-hours, motors of a few watts). It is not a safety certification and does not replace the manufacturer's instructions for a charger, a battery or a motor, or the law for anything you sell or use at work. Where lithium batteries are concerned, the manufacturer's instructions win over this chapter.

1. Batteries: the chemistries

A robot's battery decides how long it works, how fast it can start, how much it weighs and how dangerous it is. Basic Electronics 9 section 8 introduced the four numbers that describe any battery (nominal voltage, capacity, maximum discharge current expressed as a C-rate, and internal resistance) and the main cell types. Here is the comparison again for robot use, with lead-acid added because larger robots use it.

ChemistryCell voltage (nominal; full to empty)Energy per kg (approximate)Internal resistance (typical)Good forWatch for
NiMH (AA, rechargeable)1.2 V; 1.4 to 1.0 V60 to 120 Wh/kg20 to 50 mΩ per cellA first robot: safe, forgiving, replaceable AA cells, simple chargersVoltage falls slowly with charge, so the gauge is hard to read; ordinary cells lose charge in weeks, low-self-discharge types hold it far longer; heavy for the energy
Li-ion (18650 and similar)3.6 or 3.7 V; 4.2 to 3.0 V150 to 250 Wh/kg20 to 60 mΩ per cellLong runtime in a small space; good cells deliver 10 A or moreNeeds a protection circuit and a proper lithium charger; a short or a puncture can start a fire; buy genuine cells from a known seller
LiPo (pouch pack)3.7 V; 4.2 to 3.0 V; 2S 7.4 V, 3S 11.1 V150 to 200 Wh/kg5 to 30 mΩ per cellLight packs with very high C-rates: fast robots, drones, anything needing strong burstsThe most dangerous in everyday use: swelling, fire after a puncture, a short or a deep discharge; needs a balance charger and care in storage (section 5)
LiFePO43.2 V; 3.65 to 2.5 V; 4 cells 12.8 V90 to 160 Wh/kgLowA safer lithium chemistry with a very long cycle life; good for robots that are charged dailyHeavier than LiPo; the very flat discharge curve means voltage says little about the charge left; needs its own charger profile
Lead-acid (sealed, SLA)2.0 V; about 2.1 to 1.75 V; 6 cells 12 V30 to 40 Wh/kgLow in a large battery, rising with ageBig, heavy robots (ride-on, lawn, workshop carts): cheap, rugged, huge surge current, forgiving chargerVery heavy for the energy; harms itself if left discharged; must stay upright; vents hydrogen if overcharged

The energy-per-kg figures are typical orders of magnitude from memory and vary a lot between products; the pattern is what matters. Weight is the robot's enemy: every gram of battery has to be accelerated, carried up slopes and braked (Robotics Fundamentals 3 section 6), so a small mobile robot usually wants lithium, while a large slow one can afford lead-acid, and a beginner who wants forgiveness takes NiMH. The build in section 9 uses a 2S LiPo pack to show the careful handling it needs, and notes a NiMH alternative.

2. Sizing a battery: capacity, C-rate, sag and runtime

Four calculations size a battery, and they are the ones from Basic Electronics 9 and Robotics Fundamentals 1 section 5 written in one place. Energy is voltage times capacity. Runtime is usable energy divided by average power. The C-rate checks that the pack can supply the peak current. The voltage sag checks what the robot sees at the moment of a start or a stall, which is what resets the board. A simple derating then covers the real-world losses without needing the Peukert exponent (a refinement for lead-acid that this chapter leaves out).

Energy: E = V x C E in Wh, V in volts, C in Ah 1000 mAh at 7.4 V: E = 7.4 x 1.0 = 7.40 Wh Usable energy: E(usable) = 0.8 x E (the 0.8 of Robotics Fundamentals 1 section 5) 0.8 x 7.40 = 5.92 Wh Runtime: t = E(usable) / P = 0.8 V C / P P = the AVERAGE power drawn from the pack, in W C-rate: I(max) = (C-rate) x C a "20C" 1.0 Ah pack can give 20 x 1.0 = 20 A; the C-rate needed = I(peak) / C Voltage sag: V(terminal) = V(open) - I x R(internal) (the pack voltage under load; the robot sees THIS) Simple derating: t = 0.8 x k(cold) x k(age) x V C / P one plain multiplier per effect (typical, approximate: k(cold) about 0.8 near 0 C; k(age) about 0.9 after a year or two of use) Worked example 1, sag: a 2S LiPo pack of about 60 mohm (Basic Electronics 9 section 8) supplies the build's stall current of 5.03 A (section 3). V(drop) = 5.03 x 0.060 = 0.30 V: a pack that rests at 8.40 V (full) gives about 8.10 V under that load. Six AA NiMH cells of about 40 mohm each (0.24 ohm in all) at the same current: 5.03 x 0.24 = 1.21 V lost. A weak or tired pack that sags by a volt at every start resets the board (the brown-out of Basic Electronics 9 section 10), so check the sag at the START, not only the average. Worked example 2, runtime: the 1000 mAh 2S pack of the build at the budget of section 3, P(average) = 2.58 W: E(usable) = 0.8 x 7.4 x 1.0 = 5.92 Wh t = 5.92 / 2.58 = 2.29 h = 137.6 min (using the unrounded power) Cold and aged: k(cold) = 0.8, k(age) = 0.9, so 0.8 x 0.9 = 0.72: E = 5.92 x 0.72 = 4.26 Wh, t = 4.26 / 2.58 = 1.65 h = 99.0 min Pessimistic: the robot at its peak working power the whole time, 4.18 W: t = 5.92 / 4.18 = 1.42 h = 84.9 min. The honest claim is "about 1.5 to 2 hours", not "2.3". Worked example 3, C-rate: the 1000 mAh pack must supply a worst-case (stall) current of 5.03 A: C-rate = 5.03 / 1.0 = 5.03C, well inside a 20C pack. The working peak of 0.57 A is only 0.57C.

Two more points about runtime. First, a pack that is quoted at a high C-rate is not the same as a pack that is good at that rate: look at the internal resistance and test the sag. Second, the capacity on the label is measured at a gentle current at room temperature; a heavy load, a cold day and an old pack each take a share, which is why the simple multipliers above exist. Measure the real runtime once the robot works, and keep that figure rather than the calculated one.

3. The power budget: average against peak

A power budget lists every load, with an average current (which sets the runtime) and a peak current (which sets the size of the regulator, the wire, the fuse and the pack's C-rate). Basic Electronics 11 section 2 built one for a phone-driven robot; here is the full budget for the robot of section 9. The motors use the sizing recipe of Robotics Fundamentals 3 section 6 (a 0.8 kg robot, 0.3 m/s cruise, the typical 6 V gearmotor of that chapter: 2.0 Ω, k = 0.006, I0 = 0.15 A, 50:1 gearbox of efficiency 0.729). The currents of the sensors and the board are typical figures from memory; replace them with the data sheets of your parts.

Power budget of the build: 2S LiPo (7.4 V nominal); 5 V logic rail from a 90 % buck converter; motors from the pack through the driver. Typical or assumed values. A. The 5 V logic rail average peak working Raspberry Pi Pico (on VSYS) 30 mA 50 mA 5-channel IR line module (5 x 20 mA, LEDs always on) 100 mA 100 mA HC-SR04 ultrasonic sensor 15 mA 20 mA 2 x encoders (10 mA each) 20 mA 20 mA Driver logic and status LEDs 5 mA 25 mA Total on the 5 V rail 170 mA 215 mA Drawn from the pack (5 V x I / 0.90 / 7.4 V) 0.128 A 0.161 A B. The two motors, from the pack each motor duty from the pack (both) Flat cruise at 0.3 m/s (no margin) 0.167 A 42 % 0.141 A Working average (assumed 1.5 x cruise) 0.211 A Worst working: 10 deg slope, a = 0.8 m/s^2, margin 1.5 0.399 A 48 % 0.385 A Stall: rotor held, duty capped at 81 % (6 V of 7.4 V) 3.00 A 81 % 4.865 A Driver, wire and connector losses (5 % of motor current, assumed) 0.011 A avg, 0.019 A peak C. Totals at the pack average peak working fault (stall) Logic (A) 0.128 A 0.161 A 0.161 A Motors (B) 0.211 A 0.385 A 4.865 A Losses (B) 0.011 A 0.019 A - Total current (sum of the unrounded values) 0.349 A 0.565 A 5.026 A Power at 7.4 V 2.58 W 4.18 W 37.2 W How the motor rows were found (the recipe of Robotics Fundamentals 3 section 6, m = 0.8 kg, wheel radius 0.0325 m, Crr = 0.03): Cruise: F = m Crr g = 0.8 x 0.03 x 9.81 = 0.235 N; tau(wheel) = 0.235 x 0.0325 / 2 = 0.00383 N m; tau(motor) = 0.00383 / (50 x 0.729) = 0.000105 N m; I = 0.000105 / 0.006 + 0.15 = 0.167 A wheel speed 0.3 / 0.0325 = 9.23 rad/s, motor 50 x 9.23 = 461.5 rad/s; V(need) = 0.006 x 461.5 + 0.167 x 2.0 = 3.10 V; duty = 3.10 / 7.4 = 42 %; pack current per motor = duty x I = 0.070 A (both 0.141 A) Worst: F = 0.8 x (0.8 + 9.81 sin 10 + 0.03 x 9.81 cos 10) = 0.8 x 2.793 = 2.235 N; tau(wheel) = 0.0363 N m; tau(motor) = 1.5 x 0.0363 / (50 x 0.729) = 0.00149 N m (8.3 % of the 0.018 N m stall torque); I = 0.399 A V(need) = 2.769 + 0.399 x 2.0 = 3.57 V; duty 48 %; pack current per motor 0.192 A (both 0.385 A) Stall: the driver applies at most 6 V (duty capped at 6 / 7.4 = 81 %), so each motor draws 6 / 2.0 = 3.0 A and the pack supplies 0.81 x 3.0 = 2.43 A per motor, 4.865 A for both. Runtime from the average: 2.58 W gives 137.6 min on the 1000 mAh pack (section 2).
The motors are 5 amps in a fault and a quarter of an amp at work
Look at the three columns of table C. The average is 0.35 A, so a small pack lasts hours. The peak working figure, 0.57 A, sets the fuse. The stall figure, 5.03 A, is more than ten times the working peak: it is what the wire, the switch, the connectors and the driver must survive (briefly) when a wheel is blocked, and what the fuse and the software must cut. Budget every figure, not only the average.

4. Regulators: buck against linear

The motors run straight from the pack through the driver, but the board and the sensors need a steady 5 V (or 3.3 V). Basic Electronics 9 section 9 compared the two ways of making it. A linear regulator drops the surplus voltage as heat: it passes the load current unchanged, so the pack supplies the same current as the load and the wasted power is (Vin − Vout) I. A buck (switching) converter converts power, not current: it draws Pin = Pout / η with a typical efficiency η of 85 to 95 %, so from a higher voltage it draws proportionally less current. The price of the buck is switching noise and a slightly bigger part.

Linear: I(in) = I(out); P(lost) = ( V(in) - V(out) ) x I(out); efficiency = V(out) / V(in). Buck: P(in) = P(out) / eta (typical 0.85 to 0.95); I(in) = P(in) / V(in). The build: the 5 V rail at 170 mA (average) from the 7.4 V pack. Linear: P(pack) = 7.4 x 0.170 = 1.258 W; heat in the regulator = ( 7.4 - 5.0 ) x 0.170 = 0.408 W (0.516 W at the 215 mA peak); efficiency = 5.0 / 7.4 = 68 % Buck 90 %: P(pack) = 5.0 x 0.170 / 0.90 = 0.944 W; I(pack) = 0.944 / 7.4 = 0.128 A. Saving: 1.258 - 0.944 = 0.314 W, which is 12 % of the robot's 2.58 W average. Runtime with the linear regulator: the pack current average is 0.170 + 0.211 + 0.011 = 0.391 A, so P = 2.90 W and t = 5.92 / 2.90 = 2.04 h = 122.7 min, against 137.6 min with the buck: about 15 minutes (11 %) less, plus a warm regulator. It matters more with bigger rail currents and bigger packs: a 1.0 A rail from an 11.1 V (3S) pack through a linear regulator wastes ( 11.1 - 5.0 ) x 1.0 = 6.1 W as heat: too hot to touch without a heat sink. A buck wastes about 0.56 W (5.0 / 0.90 - 5.0).

The rule of thumb that follows: use a buck converter for any rail that carries more than about 100 to 200 mA from a pack well above the rail voltage; use a linear (LDO) regulator where the current is tiny, where the input is only a little above the output, or where a very quiet supply matters (a sensitive analogue sensor). A common good design is a buck to a rail a little above the target, then a small LDO for the quiet part. Keep the buck's switching noise away from the line and distance sensors (shorter wires, a ground plane or a clean star, and a filter capacitor), and choose a converter rated for the peak rail current with margin: 215 mA is 11 % of a 2 A module.

5. Low-voltage cutoff, charging and storing a LiPo pack

The low-voltage cutoff

A lithium cell that is run flat is damaged (Basic Electronics 9 section 8: never below 3.0 V per cell, and 3.3 V per cell under load is a sensible cutoff). The robot must watch its own battery and stop before that. The usual circuit is the voltage divider of Basic Electronics 10 section 4 feeding an analogue input, and the usual logic is a state of the behaviour machine (Robotics Fundamentals 8 section 2): a warning threshold, a cutoff threshold, and a debounce so that the voltage dip of one start does not trigger it. Read the pack at rest or smooth the reading (Robotics Fundamentals 5 section 9), because the reading under load sags by I R.

Divider for the 2S pack: R1 = 56 kohm (top), R2 = 33 kohm (bottom) into a 3.3 V, 12-bit ADC. V(pin) = V(pack) x 33 / 89 = 0.3708 x V(pack); ADC count = V(pin) / 3.3 x 4095 The divider current at 8.4 V is 8.4 / 89000 = 94 uA, negligible next to the pack; the pin never sees more than 3.115 V. Pack voltage Per cell At the pin ADC count Action 8.40 V 4.20 V 3.115 V 3865 full, at rest 7.40 V 3.70 V 2.744 V 3405 nominal 7.00 V 3.50 V 2.596 V 3221 WARN: flash the LED; finish the task and go home 6.60 V 3.30 V 2.447 V 3037 CUTOFF: motors off, latched, after 2 s in a row below this 6.00 V 3.00 V 2.225 V 2761 the absolute floor: damage starts; the cutoff must act long before The reading is a filtered average (say the mean of 16 samples), the cutoff needs 2 s of readings below the threshold (the debounce of Robotics Fundamentals 8), and once it fires the robot stays off until it is power-cycled and charged: a robot that restarts as the load drops and the voltage recovers will run the pack flat in a series of short bursts. A divider tolerance of 1 % shifts the thresholds by about 0.07 V: check the reading with a multimeter and adjust the numbers in the code.

Charging and storing a LiPo pack safely

Charging is the most dangerous thing most hobbyists do with a battery. A lithium cell charged beyond 4.20 V, charged after a deep discharge, charged while damaged, or charged without balancing can overheat, swell and burn, and a LiPo fire is hot and hard to put out. These rules are not optional.

  • Never leave a charging pack unattended. Stay in the room, within sight, and stop at the first sign of swelling, a hot smell, hissing or heat. Not overnight, not while you are out, not “just for a minute” in another room.
  • Use a proper lithium charger with the right cell count (a balance charger for a LiPo pack with a balance connector), set to the right chemistry and cell count, at a current of no more than 1C (1.0 A for the 1000 mAh pack; gentler is safer). Do not charge with a bench supply set to “about right” and do not use a charger meant for another chemistry.
  • Charge on a non-flammable surface (a ceramic tile, a metal tray or a fire-resistant LiPo bag), away from paper, curtains, sofas and beds, with a clear space around it, and keep a suitable extinguisher or a bucket of dry sand within reach and a clear way out (ask your local fire service which extinguisher suits lithium battery fires).
  • Never charge a damaged, swollen, punctured, crushed or very old pack, or one that was deeply discharged (below about 3.0 V per cell) and has sat that way. Retire it: discharge it slowly with a bulb, and take it to a battery recycling point, not the household bin.
  • Let a warm pack cool before charging, and let a freshly charged pack cool before use; never charge a pack that is hot to the touch.
  • Store at about 3.8 V per cell (7.6 V for a 2S pack) if it will not be used for more than a week, in a fire-resistant bag or box, in a cool place, not in the robot. Many balance chargers have a “storage” mode that does this. A pack stored full or empty ages quickly.
  • Transport and handling. Protect the leads from shorting (cap the connector or tape it), do not carry loose packs with keys or coins, and do not leave one in a hot car or in direct sun.

If a LiPo pack starts to swell, hiss or smoke: stop charging if you can do so safely, move away, and do not try to carry it through the house; follow the guidance of the battery's maker and the fire service. The robot of section 9 runs from a pack that is small (7.4 Wh), which limits the energy but not the need to treat it with respect; the NiMH alternative in the parts list is the gentler choice for a first build.

6. Wiring and fusing

Wire gauge: heating and voltage drop

Wire is chosen for two things: the heat it can carry (its current rating, set by the insulation and the length of the run) and the voltage lost over its length (Basic Electronics 9 section 12). The round-trip length counts, because the current flows out and back. Voltage drop is V = I Rwire and the power lost as heat is P = I2 Rwire.

Wire resistance (typical, copper, from Basic Electronics 9 section 12): 22 AWG 53.0 mohm/m; 20 AWG 33.3 mohm/m; 18 AWG 20.9 mohm/m; 26 AWG (jumper) about 133 mohm/m plus 50 to 100 mohm per contact. Worked example: the motor supply of the build, 0.3 m from the star point to the driver and 0.3 m back (0.6 m round trip), carrying the 4.865 A STALL current: Wire (AWG) R for 0.6 m (out and back) V drop at 4.865 A P lost in the wire Chassis rating 22 0.0318 ohm 0.155 V 0.75 W 7 A 20 0.0200 ohm 0.097 V 0.47 W 11 A 18 0.0125 ohm 0.061 V 0.30 W 16 A 26 jumpers + 2 contacts of 75 mohm 0.230 ohm 1.12 V 5.44 W under 1 A: NOT usable At the 0.565 A working peak the drop in 22 AWG is only 0.565 x 0.0318 = 0.018 V: the stall case is the demanding one, and the fuse (below) limits its duration. Choice for the build: 20 AWG silicone-insulated wire for the pack, the switch, the e-stop and the motor driver (0.097 V lost at stall, rating 11 A against a 1 A fuse); 22 or 24 AWG for the signals. The jumper row is the lesson: motor current through a breadboard or a thin jumper loses over a volt at stall, dumps 5 W in a few centimetres of thin wire and its contacts, and is a fire risk. Motor current is soldered or screwed, never pushed through a breadboard.

Connectors, the switch and the ground

  • Connectors. Choose a connector rated above the current it carries, and keyed so it cannot go in backwards. Typical maker's ratings (approximate, from memory; always read the data sheet): Dupont and breadboard contacts about 1 A (signals only); JST-XH about 3 A (balance leads, small loads); XT30 about 30 A; XT60 about 60 A. The build uses an XT30 for the pack and screw terminals or solder for the motor supply. Crimp and solder properly: a poor crimp has a high resistance, heats up, and is a classic cause of “it only fails when the motors work hard”.
  • The main switch. Put a switch in the positive lead, after the fuse, rated for the stall current at the pack voltage in DC (a DC rating is lower than the AC rating printed on many rocker switches: a switch marked 6 A at 250 V AC may be rated only a fraction of that at DC). A 5 A DC-rated switch is the minimum for the 5.03 A stall of the build.
  • A common ground. Every part that exchanges a signal must share a ground, or the signal has no reference. But the way the grounds are joined matters (below). The motor current's return path must not share a thin wire with a sensor's reference.

Fuses

A fuse protects the wire and the battery from a short or an overload; it does not protect the load. Two limits fix its size: it must be above the normal current (so that it never blows during ordinary work) and below the rating of the thinnest wire it protects (so that it blows before the wire overheats). The usual rule is to choose the nearest standard value at 125 to 150 % of the normal (largest sustained) current, then check it against the wire rating and against the start-up and stall transients. Place it in the positive lead as close to the battery as possible, so that only a few centimetres of wire are unprotected; use a fuse with a voltage rating at or above the pack voltage; and, for a lithium pack, a fast-acting or a slow-blow type chosen to tolerate the short start-up peaks (Basic Electronics 9 section 12 advised a fast-blow type close to the positive terminal, and warned that a resettable polyfuse is not enough on its own against a strong lithium pack).

Fuse sizing for the build: normal (largest sustained, peak working) current from table C of section 3: 0.565 A 125 % to 150 %: 1.25 x 0.5654 = 0.707 A to 1.50 x 0.5654 = 0.848 A Standard values near that: 0.75 A (sold, but less common) or 1 A. Choose 1 A: the first common value (177 % of 0.5654 A: standard values are coarse, so the rule is a guide, not a law). Check against the wire: 20 AWG is rated 11 A, 22 AWG 7 A: 1 A is far below both. OK. Check against transients: at stall the pack supplies 5.03 A, five times the fuse rating: a typical 1 A fuse opens in a second or so (read the time-current curve on its data sheet), so a SUSTAINED stall blows the fuse by design (it protects the driver, whose rating is about 1.2 A continuous, 3.2 A peak, for the common TB6612FNG module, from memory). The software must therefore catch a stall in well under a second (section 7), and a fuse that blows during ordinary driving means the robot, not the fuse, needs attention. Start-up: the buck converter's input capacitor charges with a brief surge, which a slow-blow type tolerates. A second example (a different robot): motors and logic draw 2.4 A at their largest sustained load. 125 % to 150 %: 3.0 A to 3.6 A, so a 3 A fuse (125 %), or 3.5 A if sold. The wire must be rated above 3 A: 24 AWG is rated 3.5 A, which is too close; use 22 AWG (7 A) or 20 AWG (11 A).

Star distribution, strain relief and separate supplies

The motors switch large, noisy currents, and a board shares the same pack. If the motor current and the board's current flow through the same stretch of wire, the motor's voltage drops and spikes show up on the board's supply and on its ground, and the board resets or reads nonsense (the brown-out and grounding of Basic Electronics 9 sections 10 and 11). The cure is a star: every branch has its own wires from one central point, so the branches do not share resistance.

Star power distribution (positive side above, ground side below; each branch has its own pair of wires from the star point): battery + --[ fuse 1 A ]--[ main switch ]--- STAR (+) ----+-----------------[ E-STOP, normally closed ]--[ 100 to 470 uF ]---> motor driver VM | +--------------------------------------------------[ 5 V buck ]--> Pico VSYS, HC-SR04 | +--[ 56 kohm ]--+--[ 33 kohm ]--+ (battery divider; the middle goes to the ADC pin) | | battery - ------------------------------------------ STAR (-) -----------+---------------+------> driver GND, buck GND, Pico GND (one wire each, all meeting at the star) Rules: the motor driver's ground wire is the thickest, and goes straight to the star, never through the board's ground pin. The bulk capacitor sits at the driver's VM pin and ground pin (Basic Electronics 9 section 11): it supplies the start-up surge so that the pack's sag does not reach the logic. The buck's input and output each get a capacitor close to the module, and its output wire to the board is short. The e-stop opens only the motor branch: the board stays alive to log and to show a status; the motors cannot be powered by anything else.

Strain relief means that a pull on a wire is taken by something other than the joint. A solder joint or a screw terminal fails when it is flexed or pulled, and the failure is intermittent and hard to find. Clamp each wire bundle to the frame with a tie or a clip a few centimetres from each connector so that the wire, not the joint, takes the strain; leave a small loop of slack; use stranded wire (not solid) anywhere that moves; and keep wires away from wheels, gears and moving joints. A tidy loom is also a safety feature: loose wires catch on wheels and short against each other.

For the logic supply, separate the motor and logic supplies whenever the motors are large enough to disturb the pack: a dedicated buck to the logic, the motors fed straight from the star, bulk capacitors at the driver (Basic Electronics 9 section 5 on servos made the same point with a separate servo supply, and Basic Electronics 10 section 8 on driving a motor from a board safely). In a small robot like the build, one pack feeds both through a star, which works; on a larger robot, or one with servos or a gripper (Robotics Fundamentals 9), give the motors their own pack or converter and join only the grounds.

7. E-stops, safe testing and fail-safe design

A robot can fail in ways the author did not imagine: a program freezes, a sensor reads nonsense, a wire comes loose, the floor is slippery, a person steps into the path. Safety is the set of habits and hardware that make the failure harmless. The central question is not “will it fail?” but “when it does, what does it do?”

Hardware kill switch against software stop

StopWhat it doesWorks when the program has crashed?Use it for
Hardware e-stop (a normally-closed button in the motor supply)Opens the motor power circuit directly; no software in the pathYes: a frozen, crashed or misbehaving program cannot override itThe emergency stop that anyone can hit; the last line of defence
Watchdog timerA hardware countdown that resets the board (and so drops the motor outputs) if the program stops kicking itYes, within its timeout (Robotics Fundamentals 8 section 7: 5 times the loop period, 100 ms for a 20 ms loop)Catching a frozen program without a person
Software stop (the STOP and LOW_BATT states)The behaviour machine commands zero speedNo: needs a running program and working sensorsNormal, controlled stops: a blocked path, a lost line, a low battery
Driver or fuse limitThe driver's own thermal and current limits; the fuse opens on overcurrentYesProtecting parts and wire from a stall or a short

The lesson of the table is that the emergency stop must not depend on the thing that might be broken. A software button that tells the program to stop is not an emergency stop; a mushroom button that opens the motor supply is. Use all four layers: the software handles ordinary stops, the watchdog catches a frozen program, the driver and fuse limit a stall, and the hardware e-stop handles everything else.

Fail-safe design principles

  • Fail to the safe state. Decide what “safe” means for each failure (Robotics Fundamentals 8 section 7): for a small wheeled robot it is motors off. For an arm holding a load, or a robot on a slope, it may be “held”, not “released” (Robotics Fundamentals 9 section 10: a brake or a non-back-drivable gearbox).
  • The safe state is what the hardware does when power or signal is lost, not only what software chooses. A normally-closed e-stop opens when pressed or when its wire breaks. Pull-down resistors (10 kΩ) on the driver's standby and PWM pins keep the motors off while the board is starting up or has reset, when its pins float.
  • Stop on silence. Treat the absence of a good signal as a fault: a distance sensor that reports nothing, an encoder that stops counting while the motors are driven (a stall or a broken wire), a command link that goes quiet. A stall check, “duty above 30 % and the wheel speed under 10 % of the wanted speed for 0.3 s: cut the motors”, catches a jammed wheel long before the fuse does.
  • Limit everything. Cap the duty, the speed, the acceleration and the current so that no single bug can command the maximum. A lower limit costs a little performance and removes a whole class of accidents.
  • Make the safe action the easy one. The e-stop is big, red, reachable without leaning over the robot, and needs a deliberate action (the start button) to run again: releasing the stop must not restart the motors by itself.
  • Test the stops. A stop that has never been tested may not work. Press the e-stop, freeze the program, pull a sensor lead and flatten the battery on the bench, on purpose, before you trust them (the tests of section 9).

Safe testing, in order

  1. Power off: look first. Check the polarity, the connectors, the fuse and for any loose strand or bare metal (continuity and short checks, section 9).
  2. Wheels off the ground. Put the robot on a block so that the wheels spin freely. Run every motor, the encoders, the sensors and the stops with nothing to run into. A bench supply with a current limit of about 0.5 A in place of the pack makes the first power-on gentle: a short or a stall folds the supply back instead of the pack burning.
  3. Speed-limit the first floor runs. Cap the duty at about 25 %: from the motor model, 25 % of 7.4 V is 1.85 V, and (1.85 − 0.17 × 2.0) / 0.006 = 252 rad/s at the motor, which is about 0.16 m/s at the wheels. Raise the cap in steps only after each step behaves.
  4. Clear the area. A flat, clear floor, no people or pets in the way, a hand within reach of the e-stop, and a stopping distance (below) known and respected.
  5. Add one thing at a time. Straight line, then turns, then the line, then the obstacle stop; each test passes before the next begins (Robotics Fundamentals 8 section 7: test each behaviour alone).
  6. Log and review. Record the state changes and the battery voltage; a log of what the robot did is the only witness to a failure.

Stopping distance, with the numbers of the build

The stopping arithmetic of Robotics Fundamentals 1 section 2 (reaction distance plus braking distance) and Robotics Fundamentals 8 section 7 fixes how early the robot must act. For the build:

Latency of the build: ultrasonic update 60 ms + control loop 20 ms + compute 5 ms + motors and driver 30 ms = 115 ms. Braking deceleration 2.0 m/s^2 (assumed: measure it on your floor). v = 0.3 m/s: reaction 0.3 x 0.115 = 0.0345 m; braking 0.3^2 / ( 2 x 2.0 ) = 0.0225 m; stop = 0.0570 m. The obstacle threshold is 0.25 m, a margin of 0.25 / 0.057 = 4.4. v = 0.4 m/s: reaction 0.0460 m; braking 0.0400 m; stop = 0.0860 m. Margin 0.25 / 0.086 = 2.9. Software freeze at 0.3 m/s with the 100 ms watchdog (5 x the 20 ms loop): 0.3 x 0.100 = 0.030 m before the power is cut, plus 0.0225 m of braking = 0.0525 m. A person hits the e-stop at 0.4 m/s, with a typical human reaction of about 0.25 s (approximate): 0.4 x 0.25 = 0.100 m, plus 0.040 m braking = 0.140 m. The stop is only as quick as the person, so on first runs keep the speed down and the clearance up: at the 25 % duty cap (about 0.16 m/s): 0.16 x 0.25 = 0.040 m, plus 0.16^2 / 4 = 0.0064 m = 0.046 m.

Arms and other pinch points

Anything with joints can trap a finger. If you extend the build with an arm (section 9, extensions), apply Robotics Fundamentals 9 section 10: size each joint for the payload at its worst pose, find the pinch points (the inside of an elbow, a gripper's jaws), cap speed and force, decide how each joint holds its load when power is cut, and test slowly with everyone outside the reach. A wheel is a pinch point too: keep fingers and cables away from the gap between a wheel and the chassis when the robot is powered.

8. Ethics and responsibility

A robot is a machine that acts in the world, and what it does is the builder's responsibility. Four points, briefly.

  • Privacy. A camera, a microphone or a robot that moves about a home records people, often without their thinking about it. Decide what is recorded, where it is stored, who can see it, and tell the people it concerns; do not point a robot at places where people expect privacy, and treat recorded images and sound as sensitive data (in the UK, data protection law can apply to cameras that capture people outside a purely private setting; take proper advice for anything beyond your own home).
  • Safety of people and pets. A small robot can trip, pinch or frighten. Keep it slow, lightweight and soft-edged where it shares a room; keep fingers, hair, pet tails and small children away from wheels and arms; fit the stops of section 7; and do not run an untested robot unattended, least of all with a lithium battery on board.
  • Dual use. Most robotics ideas can be used to help or to harm: the same navigation and vision serves a delivery robot and a weapon. Think about how what you build could be misused, share it responsibly, and be wary of work whose evident purpose is to hurt people or to watch them without consent.
  • Honest claims. Say what the robot actually does, and what it was tested for. “Runs about 1.5 hours” is true if you measured it; “avoids all obstacles” is false if a black chair leg beats the sensor. Overclaiming about autonomy, safety or accuracy misleads the people who rely on it, and a robot sold or used at work has legal obligations (safety marking, product liability) that a hobby project does not.

9. The build: a small line-following, obstacle-avoiding robot

The design below is a plan for the simplest robot that uses every subsystem of the course: two driven wheels and a caster (differential drive, Robotics Fundamentals 4), geared motors with encoders (Robotics Fundamentals 3 and Robotics Fundamentals 6), a line sensor array and an ultrasonic sensor (Robotics Fundamentals 5), a feedback loop for the wheels and the line (Robotics Fundamentals 7), a behaviour state machine (Robotics Fundamentals 8), and the power and safety of this chapter. It is hardware-neutral: any board with the right pins will do (Basic Electronics 11 section 1 compares them), and the code is described in pseudocode only. Real board code, in MicroPython or C, is the work of the planned course Programming for Robotics.

9.1 Requirements and specification

#RequirementHow it is measured (pass if)
R1Follows a black 19 mm line (electrical tape) on a light floor at an average of about 0.2 m/s, with bends of radius at least 0.3 m3 laps of the test oval (lap about 3.1 m) without losing the line for more than 3 s and without entering STOP
R2Stops for an obstacle on the lineStops at least 0.10 m from a card placed in its path; waits up to 10 s for it to clear, then stops for good
R3Drives straight when told toLateral drift of at most 30 mm over 2 m (after calibration)
R4Turns accurately on the spotA commanded 360 degree turn ends within 5 degrees of the start heading
R5Runs for at least 90 minutes on one chargeComputed 137.6 min (section 3); the measured runtime is at least 90 min
R6Fails safeE-stop, watchdog and low-battery cutoff each stop the motors in the tests of section 9.8
R7CostParts under about 180 pounds, tools and a multimeter excluded (approximate)

The maximum speed is 0.4 m/s and the line-following base speed is 0.30 m/s, slowed on bends by the rule v = vmax / (1 + c|x|) (Robotics Fundamentals 8 section 3). The build is intentionally modest: a robot that meets this table is a real, working machine, and every number in it can be checked.

9.2 Parts list (approximate prices in GBP)

PartNotesApproximate price (£)
Chassis kit: plate, ball caster, 2 wheels of 65 mmA cheap two-wheel acrylic or metal kit; the wheels fix the 65 mm of the calculations; confirm the track width8 to 15
2 geared 6 V motors with quadrature encoders (about 50:1)The motors of the calculations; encoders giving about 12 counts per motor revolution, 600 per wheel revolution20 to 35
Raspberry Pi Pico (or an Arduino Uno or Nano)3.3 V logic (Pico) or 5 V (Arduino): Basic Electronics 10 and Basic Electronics 11 compare the boards4 to 6
Dual motor driver module (TB6612FNG in the example)Rated for the motors: the TB6612FNG is about 1.2 A continuous and 3.2 A peak per channel (from memory), below the 3 A stall of these motors, so it relies on the fuse and the stall rule; a 3 A class driver is the safer buy4 to 7
5-channel IR reflectance (line) module, digital outputs12 mm pitch, powered from 3.3 V so its outputs are safe for the Pico3 to 6
HC-SR04 ultrasonic sensor5 V part; its echo needs a divider for a 3.3 V board2 to 4
5 V buck converter module, 2 ALogic rail (section 4)2 to 5
2S LiPo pack, 1000 mAh, 20C, with an XT30 connectorAlternative: a holder of 6 AA NiMH cells (7.2 V nominal), gentler for a first build8 to 14
2S balance chargerMandatory with a LiPo pack; skip if you use NiMH with its own charger15 to 30
Fire-resistant LiPo bagFor charging and storage (section 5)4 to 8
Fuse holder with 1 A fuses (slow-blow and fast-blow spares)In the positive lead near the pack2 to 4
Main rocker switch, at least 5 A DCCheck the DC rating1 to 3
E-stop push button, normally closed, at least 5 A DCIn series with the motor supply; red, large, within reach3 to 7
Wire (20 and 22 AWG silicone), connectors, heat-shrinkSection 66 to 12
Perfboard or breadboard, headers and Dupont leadsA breadboard for signals only, never for motor current4 to 8
Resistors and capacitors56 k and 33 k (battery divider), 1 k and 2 k (echo divider), 10 k pull-downs, a 100 to 470 uF bulk capacitor, 100 nF decoupling2 to 4
Standoffs, screws, cable ties, 19 mm black tapeFor mounting, strain relief and the test track4 to 8
TotalMultimeter, soldering iron and small tools not included92 to 176

Prices vary by supplier, and these are rough ranges from memory. A cheaper kit (yellow TT-type motors without encoders) will not match the calculations below: those motors are bigger and slower and have no feedback, which changes the sizing, the odometry and the test results. The calculations are for the parts listed.

9.3 Design calculations (reusing the course)

MOTORS (Robotics Fundamentals 3 section 6): m = 0.8 kg, wheel diameter 65 mm (r = 0.0325 m), 50:1 gearbox (eta = 0.9^3 = 0.729), the typical 6 V motor (2.0 ohm, k = 0.006, I0 = 0.15 A, stall torque 0.018 N m, no-load speed 9549 rpm) Top speed 0.4 m/s: wheel 0.4 / 0.0325 = 12.31 rad/s = 117.5 rpm; gear ratio window N = (0.6 to 0.7) x 9549 / 117.5 = 49 to 57: 50:1 sits in it; motor at 0.4 m/s: 5876 rpm = 61.5 % of the no-load speed. Worst working load (10 deg slope, a = 0.8 m/s^2, margin 1.5): F = 2.235 N, tau(motor) = 0.00149 N m = 8.3 % of stall (inside the 25 to 30 % guide, with a large margin), I = 0.399 A, duty 48 % at 0.3 m/s. Traction limit: 0.78 x 0.8 x 0.8 x 9.81 x cos 10 = 4.82 N, more than the 2.23 N needed: the wheels do not slip. The stall push of both motors would be 40 N: far more than needed, which is why the stall rule matters. KINEMATICS AND ODOMETRY (Robotics Fundamentals 4 sections 3 and 5): track width L = 0.15 m; 600 ticks per wheel revolution (12 x 50); wheel circumference pi x 0.065 = 0.2042 m. Distance per tick = 0.2042 / 600 = 0.340 mm; ticks per metre = 2938; 2 m = 5876 ticks. Heading resolution: one tick of difference turns the robot by 0.000340 / 0.15 = 0.00227 rad = 0.13 deg. Turning: v(left) = v - w L / 2, v(right) = v + w L / 2. A turn on the spot at w = 2.0 rad/s needs the wheels at +/- 2.0 x 0.075 = 0.15 m/s. Speed from ticks at the 50 Hz loop: one tick per 20 ms is 0.340 mm / 0.020 s = 0.017 m/s, 5.7 % of 0.3 m/s: too coarse for a speed loop on one sample, so average over about 100 ms (5 loops), as in Robotics Fundamentals 6 section 2. DRIFT (Robotics Fundamentals 4 section 6): a tyre 1 % bigger than the other gives a heading error of 0.01 / 0.15 = 0.0667 rad per metre. Over D = 2 m: heading 0.0667 x 2 = 0.133 rad = 7.6 deg, lateral 0.0667 x 2^2 / 2 = 0.133 m = 133 mm. The spec (30 mm over 2 m) needs eps = 2 x 0.030 / 2^2 = 0.015 rad/m, so the diameter mismatch must be under 0.015 x 0.15 = 0.00225 = 0.22 %: calibrate (section 9.8). The spin test (5 deg of 360) needs the track width right within 5 / 360 = 1.4 % (2.1 mm of 150 mm). SENSORS (Robotics Fundamentals 5): line array of 5 sensors at a 12 mm pitch, positions x(i) = -24, -12, 0, +12, +24 mm, mounted about 40 mm ahead of the axle (assumed) and 3 to 8 mm above the floor (typical for IR reflectance parts). The 19 mm tape covers one or two sensors, so the weighted position takes values in 6 mm steps (-24 to +24): x(line) = sum( w x ) / sum( w ), line lost when sum( w ) = 0. Resolution 6 mm; the 0.04 m of look-ahead delays the response a little (Robotics Fundamentals 7 section 8). Ultrasonic: echo time for 0.25 m = 2 x 0.25 / 343 = 1.458 ms (c = 343 m/s at 20 C); ping every 60 ms; the usable range is about 0.02 to 4 m, in a cone of about 15 degrees (typical). Filter with a median of 3 (Robotics Fundamentals 5 section 9). CONTROL (Robotics Fundamentals 7): outer loop, the line follower of section 12 of that chapter: e = -x(line) mm, w = Kp e + Kd de/dt, starting values Kp = 0.05 rad/s per mm, Kd = 0.002 rad/s per (mm/s) (tune by section 9 of that chapter). Speed: v = 0.30 / ( 1 + 0.05 |x| ). At the extreme x = 24 mm: v = 0.30 / 2.2 = 0.136 m/s; w = 0.05 x ( -24 ) = -1.2 rad/s; v(left) = 0.136 + 1.2 x 0.075 = 0.226 m/s, v(right) = 0.136 - 0.090 = 0.046 m/s: both positive, so no wheel reverses. Inner loop: a PI on each wheel's speed (cascade, Robotics Fundamentals 7 section 10) from the encoder speed to the duty, duty capped at 81 %. Both loops run at 50 Hz in the plan; a faster inner loop is an upgrade. BEHAVIOUR (Robotics Fundamentals 8): states WAIT, FOLLOW, SEARCH, BLOCKED, STOP, LOW_BATT (the table below); obstacle threshold 0.25 m to stop, 0.35 m to resume (hysteresis of 0.10 m). POWER AND SAFETY: budget, runtime, fuse, wire, cutoff: sections 2 to 7 (137.6 min, 1 A fuse, 20 AWG, 6.6 V cutoff).
Behaviour state machine (events on the arrows, timeouts in brackets): WAIT --start button--> FOLLOW FOLLOW --no line for 0.3 s--> SEARCH (spin toward the side where the line was last seen, 1.0 rad/s) FOLLOW --front distance < 0.25 m--> BLOCKED (stop, wheels braked) SEARCH --line found--> FOLLOW SEARCH --3 s with no line--> STOP (report "line lost" with the LED) BLOCKED --front distance > 0.35 m for 0.5 s--> FOLLOW BLOCKED --10 s with the way still blocked--> STOP any --pack below 6.6 V for 2 s--> LOW_BATT (motors off, latched, LED flashing) STOP / LOW_BATT --only a power cycle (and a charge, for LOW_BATT)--> WAIT A second mode (a jumper to ground selects it) for a robot with no line on the floor: DRIVE --front < 0.30 m--> TURN --front > 0.45 m--> DRIVE, with the escape rule of Robotics Fundamentals 8 section 3 (3 avoid events in 10 s: reverse 0.30 m and turn 90 to 180 deg).

9.4 Block diagram

POWER SENSE - THINK - ACT battery 2S LiPo 7.4 V +-----------------------+ | | Raspberry Pi Pico | <-- line module (5 wires) [ fuse 1 A ] | 50 Hz loop: | <-- HC-SR04 trig, echo | | odometry, line, | <-- encoders (4 wires) [ main switch ] | state machine, | <-- start button | | wheel PI loops, | <-- battery divider (ADC) +----------------+--------------------+ | watchdog 100 ms | | | | +-----------+-----------+ [ E-STOP, NC ] [ 5 V buck ] [ divider ] | | | 4 direction pins, 2 PWM pins, standby [ motor driver ] +--> Pico VSYS, HC-SR04 | | | +--> (through the Pico's 3.3 V) line module, [ motor driver ] --> left motor, right motor [ left ] [ right ] encoders, driver logic | [ motor ] [ motor ] +--> status LED + encoder + encoder All the grounds meet at ONE star point on the battery minus (section 6). The e-stop opens only the motor branch.

9.5 Wiring table, pin by pin

The table gives each connection first in hardware-neutral terms (what it needs) and then as an example for one named board, the Raspberry Pi Pico. The GP numbers are the Pico's GPIO numbers, not physical pin numbers, and are an example from memory: check every pin against your own board's pinout diagram (some pins have fixed roles, and on the Pico W the on-board LED is wired differently).

FunctionHardware-neutral requirementPico example (check it)Notes
Left encoder A, BTwo digital inputs, edge-capable (interrupt or a fast poll); encoder powered at the board's logic levelGP2, GP3Quadrature (Robotics Fundamentals 6 section 2); swap A and B if the count runs backwards
Right encoder A, BAs aboveGP4, GP5Swap A and B on the right so that forward counts up on both
Driver standbyA digital output that enables the driver; pulled low so the motors are off at resetGP9 (STBY) with a 10 kΩ pull-down to groundFail-safe: a floating pin leaves the driver off
Left motor directionTwo digital outputs (forward, reverse)GP10 (AIN1), GP11 (AIN2)Both low or both high brakes or coasts, see the driver data sheet (Basic Electronics 9 section 3)
Left motor speedOne PWM output, 20 kHz or so (Basic Electronics 9 section 2)GP12 (PWMA)10 kΩ pull-down; the same PWM slice as GP13 (one frequency for both)
Right motor speedOne PWM outputGP13 (PWMB)10 kΩ pull-down
Right motor directionTwo digital outputsGP14 (BIN1), GP15 (BIN2)As the left
Line sensors 1 to 5Five digital inputs (on or off); sensor module powered from the board's logic voltage so its outputs are at that levelGP16, GP17, GP18, GP19, GP20; module VCC to 3V3Left to right; position = weighted average (Robotics Fundamentals 5 section 4). The board's 3.3 V regulator supplies about 100 mA here, which is within its rating (check the data sheet)
Ultrasonic triggerA digital output (a 10 microsecond pulse)GP6 to TRIGHC-SR04 powered from the 5 V rail
Ultrasonic echoA digital input reading the echo pulse width; the 5 V echo must be divided for a 3.3 V inputGP7 from ECHO through a 1 kΩ (series) and 2 kΩ (to ground) divider5 V x 2 / 3 = 3.33 V at the pin (the level shifting of Basic Electronics 10 section 7 and circuit 4 of its section 10)
Battery monitorAn analogue input, with a divider that keeps it below the ADC referenceGP26 (ADC0) from 56 kΩ (top) and 33 kΩ (bottom)3.115 V at 8.4 V; table in section 5
Start buttonA digital input with a pull-up; closes to groundGP21, internal pull-up, button to groundThe run command; releasing the e-stop does not restart the robot
Status LEDA digital output through a resistorGP25 (on-board LED on the plain Pico)Steady while running, flashing when the battery is low
Driver motor supply (VM)The pack voltage, through the fuse, the main switch and the e-stop; a bulk capacitor at the pinsFrom the star (+) via the e-stop, 100 to 470 uF to ground at the driver20 AWG wire; the thickest ground from the driver straight to the star (-)
Driver logic supply (VCC)The board's logic voltage3V3 (OUT)Check the module: some tie logic and motor supplies together
Board and sensor supplyA regulated rail from the buck, not from the motor branch5 V buck output to VSYS through a Schottky diode (so USB and the battery cannot back-feed each other); HC-SR04 straight from the 5 V railCheck the Pico data sheet for the allowed supply pins and the diode arrangement before connecting USB and the battery together

With an Arduino Uno (5 V logic) the same plan works, with changes: the Uno has only two external-interrupt pins (D2 and D3), so each encoder's channel A goes to one of them and channel B to an ordinary pin (or use pin-change interrupts); PWM comes from pins 3, 5, 6, 9, 10 or 11; the echo divider is not needed; the battery divider can use A0 (a 5 V reference gives 3.1 V at 8.4 V, still safe); and the line module can run from 5 V. Check the pin capabilities against Basic Electronics 10 section 1.

9.6 Assembly order

  1. Build the frame. Fit the motors, wheels and caster to the chassis; check that the robot sits level and that the centre of mass is over the wheels and not far behind them (Robotics Fundamentals 2 section 3); measure the real track width and wheel diameter and write them down.
  2. Mount the battery and the star board. Fix the pack low and central with a strap, put the fuse holder, the main switch and the e-stop where they can be reached, and lay out the star board. Do not connect the battery yet.
  3. Wire the power side with the battery disconnected: the fuse, the switch, the e-stop, the buck module and the divider; strain-relief each bundle. Keep the fuse out until the continuity checks of section 9.8 pass.
  4. Mount the board and the driver; wire the driver's motor outputs, its logic pins and its pull-downs; solder the motor wires (never through a breadboard).
  5. Add the encoders, then the line module and the ultrasonic sensor with its echo divider. Mount the line module 3 to 8 mm above the floor and about 40 mm ahead of the axle; mount the ultrasonic sensor at the front, pointing forward and level.
  6. Run the power-off tests (continuity, shorts, resistance of the motors), then the voltage tests with the fuse in and the wheels on a block (section 9.8, tests 1 and 2).
  7. Test the pieces in order: encoders, then the driver, the stops, the line module and the ultrasonic sensor, each alone, with the wheels in the air, before any floor test.
  8. Then the floor: speed-limited and with a clear floor, then straight line and spin calibration, then the line, then the obstacle test, raising the speed cap in steps.

9.7 The top-level control loop (hardware-neutral pseudocode)

Only the top-level loop is shown, in short Python-style pseudocode. The function names stand for what your board's library calls them; the odometry update, the line position, the PID and the state machine are the code of Robotics Fundamentals 4, Robotics Fundamentals 5, Robotics Fundamentals 7 and Robotics Fundamentals 8. The pseudocode was run with simple stand-in functions to check that the structure holds together.

LOOP_DT = 0.02 # 50 Hz; the hardware watchdog bites at 100 ms (5 x the loop period) TRACK, V_MAX, C_SLOW = 0.15, 0.30, 0.05 # m, m/s, per mm of line error KP, KD = 0.05, 0.002 # line follower gains (starting values: tune them) D_STOP, D_GO, V_CUT = 0.25, 0.35, 6.6 # obstacle thresholds (m) and the battery cutoff (V) DUTY_MAX = 0.25 # first-run cap; raise it in steps after every test passes def behaviour(state, x_line, last_side): # returns (forward speed, turn rate) if state == "FOLLOW": e = -x_line # mm: positive when the line is to the left w = KP * e + KD * line_error_rate() # counter-clockwise positive return V_MAX / (1 + C_SLOW * abs(x_line)), w if state == "SEARCH": return 0.0, 1.0 * last_side # spin toward the side where the line was last seen return 0.0, 0.0 # WAIT, BLOCKED, STOP, LOW_BATT: stand still state = "WAIT" while True: t0 = now() kick_watchdog() # the hardware resets the board if this stops d_l, d_r = read_wheel_distances() # metres since the last call, from the encoders x_line, seen, last_side = read_line() # weighted position in mm; seen = False if no sensor sees the line front = read_front_distance() # metres, median-filtered volts = read_battery_volts() # the average of 16 samples state = next_state(state, seen, front, volts, start_pressed()) # the transition table of section 9.3 v, w = behaviour(state, x_line, last_side) v_l, v_r = v - w * TRACK / 2, v + w * TRACK / 2 # inverse kinematics of Robotics Fundamentals 4 drive_wheel(LEFT, v_l, d_l / LOOP_DT, DUTY_MAX) # the wheel-speed PI loop; stall check inside (cut if stalled for 0.3 s) drive_wheel(RIGHT, v_r, d_r / LOOP_DT, DUTY_MAX) wait_until(t0 + LOOP_DT) # keep the loop period fixed

9.8 Test plan with expected readings

Each test has an expected reading (a number you can compare with your meter or your log) and a pass condition. Run them in order, and do not move to the next until the last passes. The expected values come from the calculations above and are approximate; real parts differ, and a reading that is merely different from the figure is not necessarily a fault, while a reading that is wildly different (or a short) always is.

#TestHowExpected (approximate)Pass if
1Continuity and shorts (power off, battery unplugged)Multimeter on resistance: pack + to pack - with the switch on, fuse in and e-stop released; fuse, switch and e-stop each alone; the star grounds; each motor's windingPack + to - high, no short (the 89 kΩ divider is in parallel, so tens of kΩ); fuse under 1 Ω; switch and e-stop under 0.5 Ω closed and open (OL) when pressed; ground points under 0.5 Ω to the star; each motor about 2 Ω (the data sheet's value)No short (never below about 10 kΩ across the pack); stops open the circuit; windings are close to the data sheet
2Voltages (fuse in, wheels on a block)Multimeter on DC volts at the pack, the driver's VM, the buck output and the board's 3.3 VPack 8.2 to 8.4 V when full; VM within 0.05 V of the pack; buck output 5.0 V (within 0.25 V); 3.3 V within 0.1 V; the divider pin 3.115 V at 8.4 V, an ADC count near 3865All within the ranges; the ADC reading agrees with the meter within about 2 %
3Currents (wheels in the air, meter in series with the pack)First with the motors off, then each motor at the 25 % duty capLogic only about 0.13 A (0.08 to 0.18 A); with both motors at 25 % duty in the air about 0.20 A (0.15 to 0.30 A)Under about 0.4 A: more than 0.5 A in the air means a binding gearbox, a short or a driver fault
4Encoder count per revolutionMark a wheel; turn it by hand exactly one turn, then ten turns, and read the count; check both signs600 per wheel revolution (12 counts x 50:1): 6000 for ten turns; both counts rise when the wheel turns forward600 within +/- 3 per turn and 6000 within +/- 10 for ten; signs right on both wheels
5Straight-line drift (R3)At the 25 % cap, drive 2 m (5876 ticks) along a tape measure; measure the sideways offset at the endUnder 30 mm after calibration; before calibration 1 % of tyre mismatch gives 133 mmLateral drift at most 30 mm; if more, calibrate (below) and retest
6Spin test (R4)Command a 360 degree turn on the spot; mark the start and finish headingsEnd within 5 degrees of the start; a track width 3 % out would leave the robot 11.6 degrees shortHeading error within 5 degrees (a track width within 1.4 %)
7Line follow (R1)A test oval of 19 mm tape (two straights of 0.6 m and two semicircular ends of radius 0.3 m, lap 3.08 m); 3 lapsAbout 15 s per lap at an average of 0.2 m/s, so about 46 s for three laps; sideways wobble within about 12 mm on the straights3 laps; no state of STOP; no SEARCH longer than 3 s
8Obstacle (R2)Place a card across the line 1 m ahead; start at 0.3 m/s; log the distance when it stopsThe robot stops about 0.19 m from the card (the 0.25 m threshold minus the 0.057 m stopping distance); the echo time at 0.25 m is 1.46 msStops, never touches the card, at least 0.10 m away; resumes within 1 s when the card is removed, or stops for good after 10 s
9Stops and the cutoff (R6)(a) Wheels in the air, press the e-stop. (b) Insert a deliberate infinite loop in the program. (c) Replace the pack by a bench supply and lower it slowly to 6.5 V. (d) Do not test the fuse by shorting the pack; check it by continuity only(a) The wheels stop within about 0.5 s and do not restart on release. (b) The watchdog resets the board and the motors stop within about 0.1 s. (c) LOW_BATT after about 2 s below 6.6 V, latchedAll three stops work and the motors do not restart without a deliberate action
Calibrating the drift (test 5), a worked example: the robot drives 2.0 m "straight" and ends 40 mm to the left. Lateral offset y = eps x D^2 / 2, so eps = 2 y / D^2 = 2 x 0.040 / 2.0^2 = 0.020 rad/m (heading error per metre). The diameter mismatch is eps x L = 0.020 x 0.15 = 0.003 = 0.3 %. That is above the 0.22 % limit, so the test FAILS (40 mm against the 30 mm limit). Fix: scale the distance per tick of one wheel by 1.003 (the wheel that travelled farther gets the larger scale), rerun, and measure again; repeat until the offset is under 30 mm. The check on the arithmetic: a 0.3 % mismatch over 2 m gives 0.003 / 0.15 x 2.0^2 / 2 = 0.040 m: the same 40 mm. Calibrating the spin (test 6): if the robot ends 11.6 degrees short of 360, the track width the code uses is too small by the ratio 348.4 / 360 = 0.968: multiply TRACK by 1.033 (0.150 becomes 0.155), then retest.

9.9 Troubleshooting

SymptomLikely causeCheck and fix
The board resets when the motors startBrown-out from the pack's sag or a shared wire (Basic Electronics 9 section 10)Bulk capacitor at the driver; separate star branches for motor and logic; check the pack's charge and its sag (section 2); thicker motor wire
A motor does not runStandby low, e-stop open, fuse blown, a loose connectorCheck STBY, the e-stop, the fuse by continuity, then the motor wires at the driver with a meter on VM
The fuse blows during drivingA stall (a jammed wheel, a snagged wire) or a shortLook at the log for the stall rule; free the wheel; check for a short with the meter; never fit a bigger fuse to stop it blowing
It drives in an arc on a straight commandWheel diameter mismatch, motor difference, encoder sign or scaleRun test 4, then calibrate by test 5; check the wheels turn the same number of ticks per revolution
It overshoots turns or is 12 degrees shortWrong track width in the codeMeasure the track width between the tyre contact patches; calibrate by test 6
An encoder counts backwards or erraticallyA and B swapped, a loose wire, noise from the motorSwap A and B; twist the encoder pair; keep it away from the motor leads; add 100 nF at the pin
The line follower snakes from side to sideKp too high for the speed, the sensor too far ahead, or too much delay (Robotics Fundamentals 7 section 7)Halve Kp, add Kd, lower the speed, move the array closer to the axle, then retune in the order of Robotics Fundamentals 7 section 9
It loses the line on bendsToo fast, the array too high, tape too narrow or glossyLower the base speed or raise C_SLOW; set the array 3 to 8 mm above the floor; check the sensor thresholds on the real floor; test the SEARCH rule
It stops for nothing, or does not stop for a chair legFalse echoes, a soft or angled surface, a narrow object outside the coneMedian filter; lower the speed; add a second sensor or a bump switch (Robotics Fundamentals 5 section 5); test with a flat card first
The battery reads wrongWrong divider values, a loose ground, noise, or reading under loadCheck the pin voltage with a meter (3.115 V at 8.4 V); average 16 samples; compare at rest and under load
A pack is warm, puffy or smells hotOver-discharge, a short, abuse or ageStop at once; do not charge or use it; follow section 5

9.10 Extension ideas

  • Add a gyro (Robotics Fundamentals 6 section 4) and fuse it with the wheel heading by a complementary filter, for a drift-free straight line and an accurate spin.
  • Replace the ultrasonic sensor by a time-of-flight sensor (Robotics Fundamentals 5 section 3) for a narrower, faster reading, or add side sensors for wall following (Robotics Fundamentals 8 section 3).
  • Sense the motor current (Robotics Fundamentals 5 section 7) to detect a stall directly and to measure the real power budget.
  • Log and map: record the pose and the sensor readings, then build an occupancy grid and plan a path with A* (Robotics Fundamentals 8 section 4) as a second program.
  • Redesign the frame as a 3D-printed or laser-cut part (Robotics Fundamentals 2 section 4), with a proper battery tray, a protected e-stop and a bumper.
  • Add a small servo arm (Robotics Fundamentals 9) with a separate servo supply and the arm safety rules of that chapter, and re-budget the power and the centre of mass.
  • Telemetry: a Pico W or ESP32 can stream the log over Wi-Fi so that you can watch the battery, the state and the PID terms live.

10. Course complete: a recap of Chapters 1 to 10

ChapterTitleThe one thing to keepWhere it appears in the build
1What Is a Robot?A robot senses, decides and acts in a loop closed through the world; latency and stopping distance set how early it must react.The 50 Hz loop, the stopping distance (section 7), runtime (section 2)
2Mechanics and StructureFrames, levers, centre of gravity and the support polygon decide whether a robot is stiff, light and stays on its wheels.The chassis, the battery position, assembly step 1
3Motion: Motors, Gears and WheelsTorque, speed and power; size a motor from the load, the gear ratio and the stall torque, and check the current.Motor sizing and the power budget (section 3, section 9.3)
4Drive Systems and KinematicsDifferential drive turns wheel speeds into motion, odometry integrates it, and small errors in wheel size and track width drift fast.Kinematics, odometry, drift and spin calibration
5Sensors: Seeing the WorldA sensor has range, noise, resolution and a sample rate; filter, calibrate and choose by the job.The line array, the ultrasonic sensor, the median filter
6Position, Orientation and FeedbackEncoders measure the wheels, an IMU measures the turn, and fusion and feedback keep the estimate honest.Encoder counts, the speed loop, the gyro extension
7Control: Making It Do What You WantClosed-loop PID with tuning, windup and the causes of oscillation; cascades and feedforward.The line-follower PID and the wheel-speed loops
8Behaviour and Decision-MakingReactive behaviours, state machines, timeouts and watchdogs; fail safe, then plan and localise.The state machine, the stops and the watchdog
9Arms and ManipulatorsForward and inverse kinematics, the Jacobian, payload torque, grippers and arm safety.The safety rules and the arm extension
10Power, Safety and Building Your First RobotSize the battery, budget the power, wire and fuse it, stop it safely and test in order; then put it all together.This chapter, and the whole build

You can now reason about a small robot from the battery to the behaviour: why a motor was chosen, what the wheels do, what a sensor can and cannot tell you, why a loop oscillates, and what makes a machine safe to run. The calculations are all things you can repeat with a pencil, and the build above is a way to find out how much of it is true on your own bench.

The path on: Programming for Robotics, and possible later courses

Programming for Robotics (planned; not yet written) is the next course on this site, and it is the other half of this one. Robotics Fundamentals has kept the code hardware-neutral and short on purpose. Programming for Robotics will turn the same ideas into real code on real boards: reading sensors and driving motors, timing and interrupts for encoders, the PID loop and the state machine as programs, odometry and logging, and the top-level loop of section 9.7 written in MicroPython or C. If you build the robot of this chapter, that course is where its control loop becomes running code.

Possible later robotics courses, mentioned only as ideas and not planned: project-style courses whose topic is building a robot, perhaps around a commercial kit, in the manner of this chapter's build plan but carried through to a finished and tested machine. If those appear, they will build on the habits of this chapter: size it, budget it, fuse it, test it in order, and never trust a stop that you have not tested.

11. Challenges

Challenge 1: Power budget and fuse choice
A small delivery cart runs from a 3S LiPo pack (11.1 V nominal, 2200 mAh, 20C, internal resistance about 90 mΩ). Its two motors each draw 0.9 A on average, 1.6 A at their worst working load and 7.5 A at stall (all measured at the pack). The 5 V logic rail, from a 90 % efficient buck converter, carries a controller (0.25 A average, 0.35 A peak), sensors (0.12 A, 0.12 A) and a gripper servo (0.10 A average, 0.70 A peak). (a) Find the rail current average and peak, and the current they draw from the pack. (b) Find the total pack current for the average, the worst working peak and the stall, and the average power. (c) Find the usable energy and the runtime, using the 0.8 factor. (d) Choose a fuse by the 125 to 150 % rule, say which wire gauges are acceptable (20 AWG rated 11 A, 22 AWG 7 A, 24 AWG 3.5 A), and find the voltage drop of the chosen run if it is 0.4 m each way (20 AWG 33.3 mΩ/m, 22 AWG 53.0 mΩ/m). (e) Find the C-rate at stall and the voltage sag. (f) Compare a linear regulator with the buck for the rail: pack power and heat, average and peak.
View solution
Challenge 2: Safety review of a given design
A hobbyist describes a robot. It runs from a 3S LiPo pack (3000 mAh, 20C) wired directly to two motor drivers with 26 AWG jumper leads on a breadboard, 0.25 m each way, with no fuse. The power switch cuts only the 5 V supply of the controller. The “stop” is a button read by the program. The controller gets its 5 V from a linear regulator that also feeds a servo. The motor driver's enable pin is not pulled down. The robot drives at 0.8 m/s, stops when an ultrasonic sensor reads under 0.15 m, has a total latency of 0.15 s and brakes at 2.0 m/s^2. There is no watchdog and no battery monitor. The pack is charged overnight on a sofa by a bench supply set to 12.6 V, and then left in the robot, fully charged, for months. (a) List at least ten faults. (b) Rank the five most dangerous. (c) Find the stopping distance, whether the 0.15 m threshold is enough, and the fastest speed that stops within 0.15 m, with and without a margin of 2. (d) Find the heat in the 26 AWG leads at a stall current of 10 A, and the pack's maximum short-circuit current. (e) Give a corrected design, one fix per fault.
View solution
Challenge 3: Adapt the build to a heavier payload
The build of section 9 is to carry a 1.4 kg payload, so the total mass becomes 2.2 kg. The speed stays at 0.3 m/s, the acceleration at 0.8 m/s^2, the slope at 10 degrees and the same 6 V motors, 50:1 gearbox and 65 mm wheels are kept (2.0 ohm, k = 0.006, I0 = 0.15 A, stall torque 0.018 N m, efficiency 0.729, Crr = 0.03, mu = 0.8, traction safety factor 0.78). The 7.4 V pack and the 5 V logic budget are unchanged (170 mA average, 215 mA peak on the rail, 90 % buck), and a 5 % loss allowance is kept on the motor current. (a) Find the force, the wheel torque, the motor torque with a margin of 1.5, the current, the percentage of stall torque, the voltage needed and the duty at the worst working load; check traction. (b) Find the cruise current and duty on the flat, the pack current for the average (1.5 times cruise), and the total average pack current and power. (c) The robot must run for 3 hours. Find the capacity needed with the 0.8 factor, and the capacity needed if the cold and aged factors (0.8 and 0.9) also apply; choose a standard pack. (d) Find the peak working pack current and the fuse by the 125 to 150 % rule. (e) State, in one sentence each, which parts of the original plan stay and which must change.
View solution

Quick reference

  • Battery: E = V C; E(usable) = 0.8 E; t = 0.8 V C / P; C-rate = I(peak) / C; V(terminal) = V(open) − I R; simple derating t = 0.8 k(cold) k(age) V C / P. NiMH forgiving; Li-ion and LiPo energetic and dangerous; LiFePO4 safer and heavier; lead-acid cheap and very heavy.
  • Power budget: list every load at average and peak; the average sets the runtime, the peak sets the regulator, wire, fuse and C-rate; budget the stall case too. The build: 0.349 A, 2.58 W average; 0.565 A peak working; 5.03 A at stall; 137.6 min on 1000 mAh.
  • Regulators: linear loses (Vin − Vout) I as heat; buck draws Pout / η (typically 85 to 95 %); use a buck above about 100 to 200 mA from a high input, a linear where the current is tiny or quiet matters.
  • Low-voltage cutoff: divider into the ADC; warn at 3.5 V per cell, cut off at 3.3 V per cell under load for 2 s in a row, latched; never below 3.0 V per cell.
  • LiPo: never charge unattended; proper balance charger at 1C or less; non-flammable surface; storage at about 3.8 V per cell; never charge damaged or swollen packs.
  • Wire and fuse: V = I Rwire over the round trip; fuse at 125 to 150 % of the normal current, below the wire rating, close to the battery; check the stall transient; DC rating on switches and e-stops; motor current never through a breadboard.
  • Layout: star distribution from one point, separate motor and logic branches, the thickest ground to the star, bulk capacitor at the driver, strain relief on every bundle.
  • Safety: a hardware e-stop that does not depend on the program, plus a watchdog (5 times the loop period), driver and fuse limits and software stops; fail to the safe state; pull-downs on driver pins; stop on silence; limit duty, speed and current; test wheels-off-ground first, one thing at a time. Stopping distance = v × latency + v2/2a.
  • The build: two motors with encoders (600 ticks per wheel revolution, 0.340 mm per tick), a 5-sensor line module, an ultrasonic sensor, a Pico or an Arduino, a motor driver, a buck and a fused pack; states WAIT, FOLLOW, SEARCH, BLOCKED, STOP and LOW_BATT; calibrate the drift (eps = 2y/D2, mismatch = eps L) and the spin; test in order.
  • Ethics: privacy, the safety of people and pets, dual use, and honest claims.

That completes Robotics Fundamentals. The next step on this site is Programming for Robotics (planned), where the loops, the filters, the PID and the state machine of these chapters become code that runs on a board.