Sensors: Seeing the World

Robotics Fundamentals

Course 1 · Chapter 5 · Sensors: Seeing the World

Robotics Fundamentals 1 described the loop at the heart of every robot: sense, think, act. Robotics Fundamentals 3 and 4 were the “act” half, motors, wheels and the geometry that turns wheel speeds into motion, and they ended with a robot that keeps a running guess of where it is (odometry) but has no idea what is around it. This chapter is the “sense” half. A sensor is the robot's only window on the world, and it is a narrow and smeared one: every sensor measures one thing, over a limited range, with some noise, some delay and some bias. A robot designer's skill is knowing what each sensor really tells you, what it cannot tell you, and how to clean up what it says. We follow a measurement from the physics to the number in the program, look at the numbers that describe a sensor (its specifications), meet the common robot sensors (distance, line, bump, light, current, camera), and then cover the three things that make sensor data usable: filtering noise, calibration, and working out how large the remaining error is.

Ranges, beam angles, resolutions, response times and prices in this chapter are typical or approximate values from memory, for the kind of low-cost parts used on small robots; they vary a lot between models, so always read the datasheet of the part you actually buy. The formulas (time of flight, similar triangles, the statistics of averaging, error propagation) are standard and exact for the idealised models described.

1. From physical quantity to number

A computer can only work with numbers, and the world is made of light, sound, force and heat. A sensor is a chain of conversions, and knowing the chain tells you where each error can creep in. The first link is the transducer, a part whose electrical behaviour changes with the physical quantity: a light-dependent resistor's resistance falls as light rises, a microphone-like ultrasonic element produces a voltage when sound arrives, a photodiode passes a current in proportion to light, a switch opens or closes. The rest of the chain turns that change into a clean voltage and then into a number.

+------------+ +--------------+ +---------------+ +-----------+ +--------------+ | physical | | transducer | | conditioning | | ADC | | software | | quantity: |-->| changes its |-->| divider, amp, |-->| voltage |-->| counts to | | light, | | resistance, | | filter: make | | to counts | | units, then | | sound, | | voltage or | | a clean | | 0 to 1023 | | filter and | | force... | | current | | voltage | | (10 bit) | | calibrate | +------------+ +--------------+ +---------------+ +-----------+ +--------------+ Where each link is covered: divider: Basic Electronics 3 conditioning: Basic Electronics 7 ADC: Basic Electronics 10 software: sections 9 to 11 of this chapter

The electronics of the middle links is the subject of Basic Electronics 3 (voltage dividers, which turn a resistance change into a voltage), Basic Electronics 7 (signal conditioning: amplifying a small signal and removing high-frequency noise) and Basic Electronics 10 (analogue-to-digital conversion). Here we only need the arithmetic of the last step. An n-bit analogue-to-digital converter (ADC) with reference voltage Vref turns the input into a whole number, and its smallest step is the least significant bit (LSB).

LSB = Vref / 2^n counts = floor( V / Vref x 2^n ), limited to 2^n - 1 V (estimate) = (counts + 0.5) LSB Worked example: a 10-bit ADC with Vref = 5.0 V. LSB = 5.0 / 1024 = 4.883 mV. A sensor that gives 20 mV per centimetre therefore resolves 4.883 / 20 = 0.244 cm per count: the ADC alone limits the resolution to about a quarter of a centimetre. Worked example: a light-dependent resistor (LDR) on the top of a divider, with 10 kohm to ground below it (Basic Electronics 3): Vout = 5.0 x 10k / (10k + R(LDR)) Bright light, R(LDR) = 2 kohm: Vout = 5.0 x 10 / 12 = 4.167 V counts = floor(4.167 / 5.0 x 1024) = 853 Dim room, R(LDR) = 20 kohm: Vout = 5.0 x 10 / 30 = 1.667 V counts = 341 Nearly dark, R(LDR) = 1000 kohm: Vout = 5.0 x 10 / 1010 = 0.0495 V counts = 10 (typical LDR resistances, illustrative) Notice that the answer is not proportional to the light, and the resolution is uneven. The divider (and the LDR itself) is nonlinear, so the last few counts at the dark end cover a huge change of resistance. That is typical: the raw number is a measure of the sensor's state, and turning it into engineering units (lux, centimetres) is the job of software.
Three kinds of output
Analogue sensors give a voltage that you read with an ADC (the LDR above). Digital sensors report an on or off level (a switch, a threshold comparator), or a number already converted inside the sensor and sent over a bus (many distance, inertial and camera modules). Timing sensors give a pulse whose width or position carries the measurement (the ultrasonic sensor below). The processing differs, but the questions are the same: what range, what resolution, how noisy, how fast?

2. Sensor specifications

A datasheet describes a sensor with a handful of terms. Learning to read them is the quickest way to avoid buying the wrong part.

SpecificationMeaningExample (typical, approximate)
RangeSmallest and largest value it can measure. Many sensors also have a minimum range, below which they failUltrasonic 2 cm to 4 m
ResolutionThe smallest change in the quantity that changes the output. Set by the ADC or by the sensor's own steps. Not the same as accuracy0.3 cm for an ultrasonic module; 4.88 mV for a 10-bit ADC at 5 V
AccuracyHow close a reading is to the true value, including any consistent offset (bias) and the random noise±3 mm plus 1 % of the reading
Precision (repeatability)How tightly repeated readings of the same true value cluster: the random spread. A precise sensor can still be consistently wrongStandard deviation 0.15 cm
NoiseRandom variation in the output that does not come from the quantity. Quoted as a standard deviation (σ) or a peak-to-peak valueσ = 0.5 cm at 1 m
Response timeHow long the output takes to follow a change: the time to reach 63 % (one time constant) or 90 % of a stepAn LDR may take tens of milliseconds to respond (typical); a photodiode microseconds
Sample (update) rateHow many new readings per second the sensor can supplyAbout 15 to 25 Hz for an ultrasonic sensor; 10 Hz for a typical 2D lidar rotation
Field of view (beam angle)The cone or width the sensor sees. A wide beam gives coverage but poor direction; a narrow beam the reverseUltrasonic about 15 degrees each side of the axis; infrared a few degrees
Linearity and sensitivityWhether the output is proportional to the input, and how much output you get per unit of inputInfrared triangulation is strongly nonlinear (section 3)

Accuracy versus precision

The two words are often swapped, but they describe two different faults. Bias (a systematic error) makes a sensor inaccurate; noise (a random error) makes it imprecise. They need different cures: calibration removes bias, averaging reduces noise (sections 9 and 10). Here are ten readings from each of two imaginary sensors measuring a true value of 100.0.

94 97 100 103 106 | | | | | true value ^ A: accurate, not precise ** * * ** * * ** B: precise, not accurate 262 (one column is 0.25 units; * is one reading, a digit is that many readings in the same column) Sensor A: mean 99.95, sigma 1.60 bias 0 (almost), noise large Single readings are off by 1 or 2 units, but the average of many is right. Sensor B: mean 103.00, sigma 0.15 bias +3.0, noise tiny Every reading is almost the same and every reading is 3.0 too high. Averaging 100 readings: A's mean has sigma 1.60 / 10 = 0.16 (good). B's mean is still 3.0 too high (averaging cannot find a bias). Subtract the known bias and B is the better sensor.
Resolution is not accuracy
A sensor that displays 0.1 mm steps but is only accurate to ±5 mm is no better than a ruler with 5 mm marks. Decimals in a number show the sensor's resolution (and the code's formatting), not its truth. The accuracy line of the datasheet, with its conditions (temperature, target colour, distance), is the one to trust.

Sample rate and the robot's speed

A robot moves between readings. The distance it travels between two readings is v / f (speed over update rate). At 0.5 m/s with a 15 Hz sensor, that is 0.5 / 15 = 3.3 cm. Add the delay of any filter (section 9) and the time the program takes, and the robot may be 10 cm closer to a wall than its last number says. When you choose a sensor, ask whether it updates fast enough for the speed you want, and whether the robot can stop within the distance at which it first sees an obstacle (stopping distances come from the motor and wheel figures of Robotics Fundamentals 3, and Robotics Fundamentals 7 deals with the control loop's own delay).

3. Distance sensors

Ultrasonic: time of flight of sound

An ultrasonic sensor sends a short burst of sound at about 40 kHz (too high to hear), waits for the echo, and measures the time. Sound travels out to the object and back, so the distance is half of the speed times the time. The speed of sound in air depends on temperature T (in degrees Celsius), by a good approximation:

sensor object [ S ] ))) ----------------- d -----------------> | [ S ] <--------------------- d ------------------ | echo round trip time t = 2 d / v so d = v t / 2 (v = speed of sound) v(T) = 331.3 + 0.606 T m/s (dry air; T in degrees Celsius; humidity adds a small amount, ignored here) T (deg C): -10 0 20 30 40 v (m/s): 325.24 331.30 343.42 349.48 355.54 (the speed rises by 0.606 m/s, or 0.18 %, for every degree) Worked example (T = 20 deg C): the echo takes t = 5.83 ms. v = 331.3 + 0.606 x 20 = 343.42 m/s d = 343.42 x 0.00583 / 2 = 1.001 m Time per centimetre of range: 2 x 0.01 / 343.42 = 58.2 microseconds (so a timer resolving 1 microsecond gives a resolution of 0.17 mm in theory) Longest wait for a 4 m range: 2 x 4 / 343.42 = 23.3 ms Allowing the echoes to die away, the practical ping interval is 40 to 60 ms (typical), about 15 to 25 readings a second. The beam spreads: about 15 degrees each side of the axis (approximate), so at 2 m the sound covers a patch 2 x 2 x tan(15 deg) = 1.07 m wide.

The wide beam is both the strength and the weakness of the ultrasonic sensor. It is a good “is something in front?” detector, since a thin pole will still reflect some sound, but it cannot tell you where across the beam the object is. Know the usual troubles before you trust one:

  • Soft and angled surfaces. Fabric and foam absorb the sound; a smooth flat wall at a steep angle (more than about 20 or 30 degrees from square-on, approximate) reflects the sound away like a mirror, and the sensor sees nothing, or a longer echo that went off a second wall.
  • Crosstalk. If several sensors fire at once, each hears the others' echoes. Fire them in turn.
  • Minimum range. The same element transmits and listens, so for a short time after the burst it cannot hear: a blind zone of a few centimetres.
  • Temperature. Section 11 shows how much error a wrong assumed temperature makes, and how to remove it.

Infrared triangulation

An infrared (IR) distance sensor of the triangulation type has an infrared emitter and a position-sensitive detector side by side, behind a lens, a fixed distance b (the baseline) apart. The emitter's narrow beam hits the object; the reflected light comes back to the lens at an angle that depends on the distance, and lands on a spot on the detector that moves as the object moves. Similar triangles turn the spot's position x into the distance.

O object |\ | \ | \ reflected ray d | \ | \ E--b--L emitter E, lens L, baseline b |\ f = lens to detector ------+-*------ detector |x| spot position x from the axis (schematic, not to scale) Similar triangles: x / f = b / d so d = b f / x and x = b f / d (the spot moves as 1/d) Worked example (illustrative, b = 20 mm, f = 10 mm, so b f = 200 mm squared): d (mm): 100 150 200 300 500 spot position x (mm): 2.00 1.33 1.00 0.67 0.40 error in d for a spot error of 0.01 mm, d error = d^2 x 0.01 / 200: 0.5 mm 1.1 mm 2.0 mm 4.5 mm 12.5 mm Close up, a tiny spot error means a tiny distance error; far away the same spot error means a large one. The error grows with the SQUARE of the distance (the 1 over d law).

The output voltage therefore follows roughly V ≈ k / d (typical sensors: a curve like 12 / d with d in centimetres and V in volts, rising to a peak at a minimum distance and then falling again closer in, so readings below the minimum range are wrong, not just inaccurate). With a 10-bit ADC at 5 V this nonlinearity decides the resolution:

Model V = 12 / d (d in cm, typical shape, approximate). Counts = floor(V / 5.0 x 1024). Distance from counts: d = 12 / (counts x 0.004883) = 2457.6 / counts d (cm) V (V) counts size of one count (cm) 10 1.200 245 0.04 20 0.600 122 0.16 40 0.300 61 0.65 80 0.150 30 2.6 One ADC count is worth 2.6 cm at 80 cm but only 0.04 cm at 10 cm: the same sensor and ADC are 65 times coarser at the far end. The software linearises the reading, either by the formula d = k / V (fit k and an offset by calibration, section 10), or with a lookup table and interpolation.

Triangulation sensors have a narrow beam (they can find a thin pole or a table edge) and a faster update than ultrasound (tens of milliseconds, typical), and they fail in direct sunlight and on very dark, shiny or transparent surfaces. A simpler relative, the IR reflective sensor (an emitter and a phototransistor pointing the same way), measures how much light bounces back, which depends on the surface as much as on the distance; use it to detect the presence of something (a line, a table edge) rather than to measure a distance.

Laser time of flight

Light travels about 3 × 108 m/s, a million times faster than sound, so timing a pulse of light to centimetre accuracy needs a stopwatch of picosecond resolution: a distance of 1 cm is a round trip of 2 × 0.01 / (3 × 108) = 66.7 ps. Small laser sensors do this with specialised detectors that build up a histogram of arrival times from many pulses, or with the phase-shift method: modulate the light at frequency f and measure the phase delay φ of the returning light.

Time of flight: d = c t / 2 c = 3 x 10^8 m/s (approx) 5 mm needs a timing resolution of 2 x 0.005 / 3e8 = 33 ps Phase shift: d = c phi / (4 pi f) unambiguous range = c / (2 f) (phi in radians, between 0 and 2 pi) Worked example: f = 20 MHz. Unambiguous range = 3e8 / (2 x 20e6) = 7.5 m. A measured phase of 90 degrees (pi / 2): d = 3e8 x (pi / 2) / (4 pi x 20e6) = 1.875 m One degree of phase is worth 1.875 / 90 = 20.8 mm, so a phase measurement good to a degree gives a resolution of about 2 cm.

Typical small laser time-of-flight modules reach about 2 m indoors (approximate, less in sunlight and on dark targets) with millimetre-level resolution, a narrow beam (a few degrees to a few tens of degrees depending on the model) and a digital interface. Glass and mirrors confuse them, as they do the infrared sensors.

Lidar

Lidar (light detection and ranging) is a laser distance sensor on a rotating or scanning mount, so it measures distance in many directions. A common low-cost 2D unit spins a single ranging element and reports a ring of readings, each an angle θ and a range r, about 5 to 10 times a second. The points convert to a map in the robot's frame by the usual polar-to-Cartesian formulas, and the spacing between neighbouring points grows with range.

Point in the robot frame: x = r cos(theta) y = r sin(theta) Spacing of neighbouring points at range r with angular step dtheta: s = r dtheta Worked example: a reading r = 2.0 m at theta = 30 degrees: x = 2.0 x 0.8660 = 1.732 m, y = 2.0 x 0.5000 = 1.000 m. With a 1 degree step (0.01745 rad): 360 points per turn, and at 10 turns a second 3600 points per second (illustrative). Spacing at 4 m: 4 x 0.01745 = 0.070 m = 7.0 cm Spacing at 10 m: 10 x 0.01745 = 0.175 m = 17.5 cm A thin pole 5 cm wide can fall between two points at 4 m and be missed; a wall cannot.

A 2D lidar sees a single horizontal slice, so it misses a table top above it and a step below it; 3D lidar and depth cameras add the missing dimension at higher cost and data rate. Lidar is the sensor of choice for mapping a room (Robotics Fundamentals 8 returns to mapping and localisation).

Distance sensorRange (typical)BeamResolutionStrengthsWeaknesses
Ultrasonic2 cm to 4 mWide, about 15 degrees each sideAbout 0.3 cmCheap; works on most surfaces including glass; unaffected by lightWide beam; soft and angled surfaces missed; slow; depends on temperature
IR triangulationAbout 10 cm to 80 cm (varies by model)NarrowFine close, coarse far (1 over d)Cheap; narrow beam; fastNonlinear; sunlight and surface colour matter; short range
IR reflectiveUnder 5 cmNarrowNot for distanceVery cheap; ideal for lines and edgesDepends on surface reflectance
Laser time of flight (single point)About 3 cm to 2 m (small modules)NarrowAbout 1 mmAccurate; compact; digital outputSunlight and dark or transparent targets; costs more
2D lidarAbout 0.15 m to 12 m (low-cost)360 degree scan, narrow per pointMillimetres to centimetres, points spaced by r dthetaMaps a whole plane; long rangeCostly; single slice; moving parts; data rate

4. Line sensors

A line-following robot needs to know where a dark line (typically black tape on a pale floor, about 19 mm wide, approximate) lies under it. The standard device is a reflectance array: a row of IR reflective sensors (an emitter and a phototransistor each), a few millimetres above the floor, spaced across the robot's width. A pale floor reflects a lot of light (a low or a high reading depending on the circuit), and a black line absorbs it. Each sensor yields an analogue value; the program turns the whole row into a single number: the position of the line.

Threshold and normalisation

Raw values differ between sensors (their gains and mounting heights differ) and between floors, so first calibrate each sensor: sweep the array over both the line and the floor and record each sensor's lowest value loi (white) and highest hii (black). Then rescale every reading to a common 0 to 1 scale, wi = (rawi − loi) / (hii − loi) (limited to 0 and 1). A simple “line or not” decision compares wi with a threshold, usually 0.5, halfway between the floor and the line.

The weighted average line position

Let sensor i sit at position xi across the bar (zero at the centre, positive to the right). If you only use the on or off decisions, the position can only take values at the sensors, a resolution equal to the spacing. Using the full analogue weights gives a much finer, continuous answer, the weighted average (a centre of mass of the dark pixels):

Line position: x(line) = sum( w_i x_i ) / sum( w_i ) Line lost if sum( w_i ) is smaller than about 0.2 (no sensor sees the line) Sensor positions for n sensors with pitch p: x_i = ( i - (n - 1) / 2 ) p (i = 0 to n - 1; the pattern is symmetric about the middle) Worked example: 8 sensors, pitch 8 mm (typical), so the positions are -28, -20, -12, -4, +4, +12, +20, +28 mm. sensor i: 0 1 2 3 4 5 6 7 x_i (mm): -28 -20 -12 -4 +4 +12 +20 +28 w_i: 0.00 0.00 0.00 0.30 1.00 0.45 0.00 0.00 w_i x_i: 0.00 0.00 0.00 -1.20 +4.00 +5.40 0.00 0.00 sum(w) = 1.75 sum(w x) = -1.20 + 4.00 + 5.40 = 8.20 mm x(line) = 8.20 / 1.75 = 4.69 mm to the right of the centre of the bar. With only on or off (threshold 0.5): only sensor 4 is on, so x = +4 mm, a resolution of 8 mm, and a step to +12 mm if sensor 5 climbs above 0.5. A noisy white-floor reading of 0.05 on the far sensor 7 (x = +28 mm) shifts the answer to (8.20 + 0.05 x 28) / (1.75 + 0.05) = 5.33 mm: it changes the result by 0.64 mm. Ignore weights below a small noise floor (about 0.05 to 0.1) so that far-away noise cannot pull the answer sideways.

The robot steers to drive that position to zero. With the sign convention of Robotics Fundamentals 4, where counter-clockwise turning is positive, a line to the right (positive x) needs a clockwise turn. How hard to steer for a given error is the job of the control loop in Robotics Fundamentals 7, and Robotics Fundamentals 8 builds the full line-following behaviour. The array is best mounted ahead of the wheels: the further ahead it sits, the earlier it sees the line curve away, although a long lever arm also makes a hunting (oscillating) robot swing more.

Here is the calculation as short, hardware-neutral Python-style pseudocode. The sensor reading and the steering are left to Programming for Robotics.

def line_position(raw, lo, hi, pitch, floor=0.05, lost=0.2): n = len(raw) total = 0.0 moment = 0.0 for i in range(n): w = (raw[i] - lo[i]) / (hi[i] - lo[i]) # 0 on the floor, 1 on the line w = min(1.0, max(0.0, w)) if w < floor: # ignore small noise readings w = 0.0 x = (i - (n - 1) / 2) * pitch # position across the bar, mm total += w moment += w * x if total < lost: return None # line lost: the caller decides what to do return moment / total # millimetres, positive to the right

5. Bump and limit switches

The simplest sensor is a switch. A bump switch (a micro-switch with a lever, or a whisker) tells a robot that it has touched something; a limit switch tells a mechanism that it has reached the end of its travel (an arm joint, a gantry axis, a gripper closed). Both are digital and cheap, and both are the last line of defence, which is why they are worth fitting even on a robot full of cleverer sensors.

  • Wiring. A switch needs a pull-up (or pull-down) resistor so the input has a defined level when the switch is open (a pull-up is a resistor from the input to the supply). The common arrangement is a pull-up with the switch to ground: open reads high, pressed reads low.
  • Fail-safe wiring. A switch that is normally closed (pressed means open) makes a broken wire look the same as a pressed switch, so a fault stops the robot rather than leaving it blind. For safety-related limits, this is the better choice.
  • Bounce. The metal contacts rattle for a few milliseconds when they close (typically 1 to 10 ms, approximate), making a burst of on and off readings. Debounce in hardware (a small capacitor) or in software: accept a change only if the new level has been stable for about 10 to 20 ms.
  • Placement. A bump switch only reports after contact, so it tells you about an obstacle after the robot has hit it; at speed it is a collision detector, not an avoidance sensor. A limit switch should be set so that the mechanism stops before it hits its hard stop, with some travel to spare for the time it takes to brake.

6. Light sensors

Light sensors turn brightness into a voltage. A light-dependent resistor (LDR) is cheap and slow, with a response of tens of milliseconds and a strongly nonlinear resistance; a photodiode or phototransistor is fast and more linear, giving a current in proportion to the light. Section 1 worked an LDR in a divider: the output is higher in bright light (when the LDR is on the top of the divider), and the divider turns resistance into a voltage that the ADC reads.

  • Uses. Detecting day or night, seeking a light source (two sensors pointing slightly apart; steer toward the brighter), reading a surface's brightness (the line and edge sensors above), and as the receiver in infrared beam-break and remote-control links.
  • Ambient light. Room lights, sunlight and shadows change the reading. Sensors that detect the robot's own infrared modulated at a known frequency (and ignore everything else) are much more robust; a simple software version takes one reading with the emitter on and one with it off, and uses the difference.
  • Colour. A colour sensor is a small group of photodiodes behind red, green and blue filters, read as three numbers; the same lighting caveats apply, so calibrate against white and black.

7. Current sensing, briefly

A robot can feel its own motors by measuring the current they draw. A motor under load draws more current (Robotics Fundamentals 3), and a stalled motor draws the maximum, so the current tells you about load, stall, a jammed gripper and the state of the battery. The usual sensor is a shunt resistor: a small resistor, a fraction of an ohm, in series with the motor. The current I causes a voltage V = I R across it, which is tiny, so an amplifier (Basic Electronics 7) raises it to a range the ADC can read.

Shunt voltage: V = I R Heat in the shunt: P = I^2 R Amplifier of gain G, then a 10-bit ADC at 5 V Worked example: R = 0.1 ohm, G = 10 (illustrative). Running, I = 0.4 A: V = 0.04 V, amplified 0.40 V, counts = floor(0.40 / 5 x 1024) = 81 Heat 0.4^2 x 0.1 = 0.016 W Stalled, I = 2.5 A: V = 0.25 V, amplified 2.50 V, counts = 512 Heat 2.5^2 x 0.1 = 0.625 W (the resistor must be rated well above that) A program that sees counts rise towards 512 can cut the power before the motor and wiring overheat (Robotics Fundamentals 10 covers fusing and safe testing). The compromise: a bigger R gives a bigger signal but wastes more voltage and power; a smaller R wastes less but gives a smaller signal and a noisier reading.

8. Cameras, briefly

A camera is a sensor with hundreds of thousands of “pixels” instead of one, so it can see what the other sensors cannot: colour, shape, texture, text, the difference between a ball and a wall, and many objects at once. Cameras are now cheap, and are why vision-based robots can do things that were impossible with distance sensors alone. But they are hard to use, for four reasons.

  • Data volume. A 640 by 480 colour image at 30 frames a second is 640 × 480 × 3 bytes × 30 = 27,648,000 bytes a second (about 27.6 MB/s) before any processing. A small controller cannot cope; it needs a more powerful processor, or a camera module that does some of the work itself.
  • Depth is lost. A single camera records a flat projection; a distant large object and a near small one can look the same. If the size of an object is known, distance follows from similar triangles, d = f W / w (focal length f in pixels, real width W, width in the image w in pixels). For f = 600 pixels and a 0.10 m wide object seen 60 pixels wide, d = 600 × 0.10 / 60 = 1.00 m; but a one-pixel error in w (59 or 61 pixels) gives 1.017 m or 0.984 m, so the error is about 1.7 % per pixel and grows as the object shrinks. Two cameras (stereo) or a depth sensor measure depth directly.
  • Lighting. The same object looks different in sunlight, shade and lamp light; algorithms that work in the lab can fail outdoors.
  • Interpretation. A distance sensor gives you a distance. A camera gives you an array of numbers, and turning it into “there is a red ball two metres to the left” takes software (computer vision), which is outside the scope of this course.

9. Noise and filtering

Real readings jump about. Part of it is noise: small random variation, often well described by a bell-shaped (Gaussian) spread with a standard deviation σ. Part is outliers: occasional wild values (an ultrasonic echo off the wrong wall, a missed pulse reading zero, a spike from a motor). Filters reduce both, and different filters suit each kind. Every filter makes the same trade: less noise, but more delay.

Averaging many independent readings

If you take N readings with independent random errors each of standard deviation σ, their mean has a smaller spread, the standard error:

Mean: x(mean) = (x1 + x2 + ... + xN) / N Spread of the mean: sigma(mean) = sigma / sqrt(N) Worked example: sigma = 0.5 cm for a single reading. N: 1 4 16 25 100 sigma(mean): 0.50 0.25 0.125 0.100 0.050 cm Four times the readings only halves the noise, and 100 times the readings cut it by 10: the gain is slow. Reaching 0.05 cm takes 100 readings, which at 20 readings a second is 5 seconds. It holds only for independent random noise. A bias (section 2), or a slow drift that changes between readings, is NOT averaged away.

Filters for a stream of readings

FilterFormulaGood forCost
Moving average of NMean of the last N readingsSmoothing random noise; simpleDelay of (N − 1) / 2 samples; smears an outlier over N readings; stores N values
Median of N (N odd)The middle value of the last N sortedRemoving outliers and spikes, while keeping sharp edgesLess smoothing of ordinary noise; a little more computation
Exponential filteryk = yk−1 + α (xk − yk−1), 0 < α ≤ 1Smoothing with almost no memory or computation: one stored numberDelay grows as α falls; an outlier decays away gradually, never vanishes at once

The exponential filter (also called an exponential moving average or EMA) is the digital version of the simple RC low-pass filter of Basic Electronics 4. The factor α says how much of each new reading to trust: α = 1 passes the readings unchanged, and a small α smooths a lot and reacts slowly. After a step change in the input, the output covers a fraction 1 − (1 − α)n of the step in n samples; it reaches 63 % after about 1 / (−ln(1 − α)) samples, roughly (1 − α) / α as a rule of thumb, which with a sample interval dt gives a time constant of about dt (1 − α) / α.

Worked example: one outlier

An ultrasonic sensor measures a wall 100 cm away. Twelve consecutive readings contain one wild echo (130.0). The table compares a mean of the last three readings (MA3), a median of the last three (Med3) and an exponential filter with α = 0.25 (started from the first reading).

k raw MA3 Med3 EMA(0.25) 1 100.4 - - 100.40 2 99.7 - - 100.23 3 100.2 100.10 100.2 100.22 4 99.5 99.80 99.7 100.04 5 130.0 109.90 100.2 107.53 <-- the outlier arrives 6 100.1 109.87 100.1 105.67 7 99.8 109.97 100.1 104.20 8 100.6 100.17 100.1 103.30 9 99.9 100.10 99.9 102.45 10 100.3 100.27 100.3 101.91 11 99.6 99.93 99.9 101.34 12 100.0 99.97 100.0 101.00 Mean of all 12 readings: 102.51 (the outlier drags it 2.5 cm off) Median of all 12: 100.05 Mean without the outlier: 100.01 MA3: jumps by 9.9 and stays wrong for three readings (the outlier is in the window of 3). EMA: jumps by 7.5 and decays, each step keeping 75 % of the error: 7.5, 5.7, 4.2, 3.3, 2.5, 1.9, 1.3, 1.0. Med3: never worse than 0.3 off: a single wild value never becomes the middle one. Use a median when readings have occasional wild values; use an average or EMA for ordinary noise; use both in sequence for both. Step response of the EMA (alpha = 0.25) to a jump from 100 to 120: after 1, 2, 3, 4, 5 samples: 105.0, 108.8, 111.6, 113.7, 115.3; after 10 samples 118.9. (63 % after 1 / (-ln 0.75) = 3.5 samples.) The delay is the price: a moving average of N readings lags the truth by (N - 1) / 2 samples. At 20 readings a second (dt = 0.05 s) with N = 5, the lag is 2 samples = 0.10 s, and a robot moving at 0.5 m/s travels 5.0 cm in that time.

The three filters as short, hardware-neutral Python-style pseudocode:

def moving_average(window, x, n): window.append(x) # window is a list of the latest readings if len(window) > n: window.pop(0) # drop the oldest reading return sum(window) / len(window) def median_filter(window, x, n): # n should be odd window.append(x) if len(window) > n: window.pop(0) return sorted(window)[len(window) // 2] # the middle value def exponential_filter(y_prev, x, alpha): # keep y_prev between calls; start it at the first reading return y_prev + alpha * (x - y_prev) # alpha = 1 passes x unchanged, small alpha smooths more
Filter the right thing, at the right rate
Hardware does part of this for free: a capacitor across a sensor output is an RC filter before the ADC (Basic Electronics 4). Filter before you take a decision from the number, but keep the delay small in a control loop (Robotics Fundamentals 7): a robot steering by a heavily smoothed reading reacts late and can oscillate. For a quick “obstacle ahead?” decision, a median of 3 or 5 removes false alarms with little delay.

10. Calibration

Calibration removes the systematic part of a sensor's error by measuring it against known true values. If a sensor reads in a straight-line way, reading = gain × true + offset, only two numbers need finding, and the inverse turns a reading back into the true value.

Two-point calibration: take two known true values t1 and t2 (at the two ends of the working range), and the readings r1 and r2 they give. g = (t2 - t1) / (r2 - r1) true = g (r - r1) + t1 (this reproduces both points exactly, and interpolates between them) Worked example: a distance sensor reads 12.4 cm at a true 10.0 cm and 102.9 cm at a true 100.0 cm. g = (100.0 - 10.0) / (102.9 - 12.4) = 90.0 / 90.5 = 0.99448 true = 0.99448 (r - 12.4) + 10.0 = 0.99448 r - 2.331 Reading 77.3 cm: true = 0.99448 x 77.3 - 2.331 = 74.54 cm (without calibration the error would be +2.8 cm) Check points (true, reading): (30, 32.1) (50, 52.6) (75, 77.3) errors of the two-point calibration: -0.41 -0.02 -0.46 cm (the sensor is slightly nonlinear, or noisy) Least-squares straight line through ALL five points (10, 12.4), (30, 32.1), (50, 52.6), (75, 77.3), (100, 102.9): reading = 1.00543 true + 2.172 so true = (r - 2.172) / 1.00543 errors at the five points: +0.17 -0.23 +0.16 -0.28 +0.18 cm (the largest is 0.28 cm, smaller than the two-point 0.46 cm)
  • Average the calibration readings. A two-point calibration puts the noise of two readings straight into the gain and the offset, so average 50 or 100 readings at each point (section 9: the noise falls as 1 over the square root of N) and place the points near the two ends of the range you use.
  • More points, and a check point. A line through several points, fitted by least squares (the line that minimises the sum of squared errors), averages their noise; and a point not used in the fit shows whether the straight-line model is any good. If it is not, use a curve or a lookup table.
  • Calibrate in a linear variable. The infrared sensor of section 3 is nonlinear in distance but close to linear in 1 / V (since V ≈ k / d), so fit d against 1 / V as a straight line.
  • Line and light sensors are calibrated in the same way, with the floor and the line as the two known “true” points: section 4's loi and hii are a two-point calibration of each sensor.
  • Calibrations expire. Temperature, supply voltage, lighting and wear change a sensor, so recalibrate when conditions change, or compensate (section 11).

11. Error propagation

A measured distance is computed from other measured quantities, each with its own error. Error propagation estimates the error in the result. For a product or quotient, the relative errors of independent inputs add in quadrature (square, add, square root); for a sum or difference, the absolute errors do.

For q = a b / c (independent errors): dq / q = sqrt( (da/a)^2 + (db/b)^2 + (dc/c)^2 ) For q = a + b: dq = sqrt( da^2 + db^2 ) The ultrasonic distance d = v t / 2, with v = 331.3 + 0.606 T: dd / d = sqrt( (dv/v)^2 + (dt/t)^2 ), dv = 0.606 dT Worked example 1: a 3 deg C error in the assumed temperature (T = 20 deg C), at d = 1 m. dv / v = 0.606 x 3 / 343.42 = 0.529 % -> an error of 5.3 mm at 1 m (and 21.2 mm at 4 m: it grows in proportion to the distance) Worked example 2: a timing jitter of 20 microseconds in the echo measurement. dt / t = 20e-6 / 5.824e-3 = 0.343 % at 1 m -> 3.4 mm. The distance error from timing is v dt / 2 = 343.42 x 20e-6 / 2 = 3.4 mm at EVERY range (a constant, not proportional). Combined at 1 m: sqrt( 5.3^2 + 3.4^2 ) = 6.3 mm (0.63 %). Combined at 4 m: sqrt( 21.2^2 + 3.4^2 ) = 21.4 mm (temperature dominates). The same error as a bias. If the program assumes 20 deg C when the air is really 5 deg C, and an object is truly 1.000 m away: the true speed is 331.3 + 0.606 x 5 = 334.33 m/s; the echo takes 2 / 334.33 = 5.982 ms; the program calculates 343.42 x 5.982e-3 / 2 = 1.027 m (27 mm, or 2.7 %, too far). The fix: measure the temperature (a cheap sensor next to the transducer) and use v(T) = 331.3 + 0.606 T in the program, so the error falls to the uncertainty in T alone.
Find the dominant error first
In the example the temperature term was worth more than the timing term from about 1 m onwards. Improving the timer further would have gained nothing. Error propagation is how you find out which input to improve, and which to leave alone.

12. Choosing a sensor

Start from the job, not the sensor. Ask what the robot needs to know, how accurately, how fast, over what range, and in what environment (light, dust, floor, other robots), and what the data will cost in wiring, processing and money.

JobGood choicesTrade-offs
Is something in front of me? (obstacle detection)Ultrasonic; laser time-of-flight; IR triangulationUltrasonic is wide and cheap but misses angled and soft surfaces; laser and IR are narrow and may miss a thin object between beams; none sees a glass door reliably
Follow a lineIR reflectance array (5 to 8 sensors); a camera for complex tracksThe array is cheap and fast but sensitive to ambient light and floor; a camera is flexible but needs processing
Detect a table edge or step (cliff)Downward IR reflective sensorVery cheap; short range; fooled by dark or shiny floors, so test on the real floor
Measure distance to a wall to a few millimetresLaser time-of-flight; IR triangulation at close rangeHigher cost; sunlight and surface colour affect them; ultrasonic is cheaper but only good to a few millimetres at best (typical)
Map a room2D lidar (a camera plus software is an alternative)Costly, with a high data rate; sees one plane only
Know that I have hit somethingBump switch or whiskerVery cheap and certain, but reports only after contact
Know a mechanism has reached its endLimit switch (normally closed wiring); hall or optical end-stopSwitches wear; optical sensors need clean surroundings
Know it is day or night, or find a lightLDR; photodiode; phototransistorAn LDR is cheap but slow and nonlinear; a photodiode is faster and more linear but needs a better circuit
Detect a stalled motor or a jammed gripperCurrent sensing (shunt and amplifier)Costs a resistor, an amplifier and an ADC channel; the shunt wastes some power and the signal is noisy
Recognise objects, colours or markersCamera (with software)Richest data but heavy processing, lighting dependence and cost

Two more rules of thumb. First, combine sensors so that each covers the other's weakness: an ultrasonic sensor for wide coverage with an infrared for a narrow check, a bump switch under everything as a last resort. Second, measure on your own robot, floor and lighting before designing the behaviour around a number. Robotics Fundamentals 6 adds the sensors that measure the robot itself (encoders, gyroscopes, accelerometers) and how to combine their data with those from this chapter.

13. Challenges

Challenge 1: Time of flight and its errors
(a) An ultrasonic sensor in air at 25 degrees C measures an echo time of 8.40 ms. Find the speed of sound and the distance. (b) The program wrongly assumes 20 degrees C. What distance does it report for the same echo, and what is the error in millimetres and in per cent? (c) The air is really 35 degrees C and an object is truly 2.00 m away, but the program assumes 20 degrees C. Find the echo time and the distance reported, and the error. (d) At 1.5 m and 20 degrees C, the timing jitter is 30 microseconds and the temperature is known to within 2 degrees C. Find the error from each source and the combined error in millimetres. (e) A laser time-of-flight sensor must resolve 5 mm: what timing resolution does it need? A phase-shift sensor modulated at 10 MHz measures a phase of 60 degrees: find the distance, the unambiguous range, and the distance that one degree of phase is worth. (f) How wide is the ultrasonic beam at 3 m, taking 15 degrees each side of the axis, and why can it not tell you which side a thin pole is on?
View solution
Challenge 2: Filtering and averaging
A distance sensor watches a target 150 cm away and produces ten readings (cm): 150.2, 149.6, 150.5, 149.9, 168.0, 150.1, 149.7, 150.4, 150.0, 149.8. (a) Find the mean, the median, and the mean without the outlier. (b) Find the moving average of 3 and the median of 3 for readings 3 to 10, and say how long each is wrong because of the outlier and by how much at worst. (c) Find the exponential filter output with alpha = 0.4, starting from the first reading, for all ten readings, and the error at each step from the outlier onwards (take the true value as 150.0). (d) A single reading has sigma = 0.4 cm. How many independent readings give a mean with sigma at most 0.1 cm, and how long does that take at 25 readings a second? How far does a robot at 0.3 m/s move in that time? How many for 0.05 cm? (e) With alpha = 0.4 and dt = 0.04 s, find the approximate time constant, and the fraction of a step the filter has covered after 1 to 5 samples. (f) What delay in seconds does the moving average of 3 add?
View solution
Challenge 3: Line position, calibration, current and choice
(a) A six-sensor line array has pitch 10 mm. Each sensor's calibration gave lo = 60, 70, 80, 75, 65, 90 and hi = 860, 880, 900, 870, 850, 900 (ADC counts). The raw readings are 62, 150, 700, 820, 280, 95. Find the sensor positions, the six normalised weights, and the line position by the weighted average. What would an on or off decision with a threshold of 0.5 report? Which way should the robot turn (use the convention of Robotics Fundamentals 4)? (b) A distance sensor reads 8.2 cm at a true 10.0 cm and 196.5 cm at a true 200.0 cm. Find the two-point calibration (gain and offset), and the true value for a reading of 120.0 cm. A check point reads 101.4 cm when the true distance is 100.0 cm: what does the calibration give there, and what does that tell you? (c) A motor current sensor uses a shunt of 0.05 ohm and an amplifier of gain 20, into a 10-bit ADC at 5 V. Find the counts at a running current of 0.5 A and a stall current of 3.2 A, the heat in the shunt at stall, and the count at which a 2.0 A trip should operate. (d) Suggest a sensor, with one reason and one drawback, for: stopping a small robot at a table edge; keeping a robot 20 cm from a wall to within 5 mm; stopping a robot arm joint at the end of its travel safely.
View solution

Quick reference

  • Chain: physical quantity, transducer, conditioning, ADC, software. LSB = Vref / 2n; counts = floor(V / Vref × 2n).
  • Specifications: range, resolution (not accuracy), accuracy (bias plus noise), precision (spread), noise, response time, field of view, sample rate. Bias is cured by calibration, noise by averaging.
  • Ultrasonic: d = v t / 2; v = 331.3 + 0.606 T m/s; 58.2 µs per cm at 20 °C; wide beam; soft and angled surfaces fail.
  • IR triangulation: d = b f / x; output about k / d; error grows as d2; resolution is coarse far away.
  • Laser time of flight and lidar: d = c t / 2 (1 cm is 66.7 ps); phase shift d = c φ / (4 π f), range c / (2f); lidar x = r cos θ, y = r sin θ, point spacing r dθ.
  • Line sensors: normalise (raw − lo) / (hi − lo); position = Σ w x / Σ w; lost if Σ w is small.
  • Switches: pull-up resistor, debounce 10 to 20 ms, normally closed wiring for fail-safe limits. Current sensing: V = I R, P = I2R, amplify then read.
  • Camera: rich but heavy data (27.6 MB/s for 640 × 480 colour at 30 frames a second); depth needs two views or a known size, d = f W / w.
  • Filters: mean, moving average (delay (N − 1) / 2 samples), median (kills outliers), exponential y += α (x − y); σ(mean) = σ / √N.
  • Calibration: g = (t2 − t1) / (r2 − r1), true = g (r − r1) + t1; average the readings, use more points and a check point; fit a linear variable.
  • Error propagation: relative errors of a product add in quadrature; temperature error is proportional to range, timing error is constant; fix the dominant error first.

Next, Robotics Fundamentals 6 turns the sensors on the robot itself: position, orientation and feedback. Wheel encoders, which count the turns the odometry of Robotics Fundamentals 4 depends on; inertial units with gyroscopes, accelerometers and compasses that measure how the robot is turning and tilting; why those readings drift, and how to combine several imperfect sensors (sensor fusion) in plain words; dead reckoning; and why GPS is not the answer indoors. The filters, calibration and error estimates from this chapter will be used all the way through.