Chapter 13: Motors and Sensors
In 2002 a company called iRobot put a disc-shaped cleaning robot on sale, and it had to survive something no laboratory machine had faced before: an ordinary home, with chair legs, loose slippers, and a staircase.
The engineers had a choice. They could give the machine an expensive scanner, let it build a map of the room, and plan a route through that map. Or they could give it almost no information and very good reflexes.
They chose reflexes. The front of the robot is a spring-loaded bumper that presses a switch when it strikes something, so the robot learns about the chair leg by touching it. Underneath, small infrared sensors face straight down at the floor. Each one shines invisible light at the carpet and watches for the reflection. Over a floor, the light comes back. Over the top step of a staircase, it does not, and the robot reverses before a wheel ever leaves the ground.
Two motorised wheels do the rest, turning at different speeds to steer.
That is the whole trick. A machine that cannot see, cannot plan and does not know what a room is will still clean one, because two cheap sensors and two motors were matched carefully to the job they had to do.
Photograph
Fig. 13.0-1 – the underside of a disc-shaped domestic cleaning robot, turned over on a table, with the two motorised drive wheels, the front castor wheel and the small downward-facing infrared cliff sensors clearly visible near the front edge; the front bumper strip should be visible along the rim. Sourcing note: a plain, well-lit product or teardown photograph of the underside; an image showing only the top casing, or one in which the wheels and the downward-facing sensors cannot be told apart, is unusable. Brand markings should be minimal or cropped out.
This chapter is about the two families of parts that made that machine possible — the motors that let a robot act, and the sensors that let it perceive. By the end of it you will be able to choose both for a task of your own.
Keep these five questions in mind as you read. Each one is answered somewhere in this chapter.
13.1 How a Robot Acts and How It Perceives
A kitchen mixer acts on the world but knows nothing about it. A clinical thermometer knows something about the world but does nothing with it. A robot is the machine that does both, and the two halves have names: the parts that act are actuators, and the parts that perceive are sensors.
Everything in this chapter belongs to one half or the other. Motors are actuators. Infrared, ultrasonic, LIDAR, touch, gyroscope and accelerometer devices are sensors. Before studying any of them individually, it is worth being clear about what each half is for, because that is what tells you when a particular device is the right choice.
13.1.1 Actuators: Turning Electrical Energy into Motion
Think about what a robot physically does. It rolls a wheel, swings a joint, closes a gripper, lifts a lid, spins a propeller. Every one of those is a mechanical movement, and every one of them has to be paid for with energy.
An actuator is the component that makes that payment. It takes energy in one form — usually electrical energy in a school or hobby robot — and delivers mechanical movement at its output.
Actuators come in two broad output shapes. A rotary actuator turns a shaft, and a linear actuator pushes or pulls along a straight line. The motors in this chapter are rotary actuators; a wheel is bolted straight onto the shaft, and a joint is driven through gears or a linkage.
Torque and speed
A rotating output is described by two quantities, and a robot builder needs both.
The first is how fast the shaft turns. This is stated in revolutions per minute (rpm) in most component data, and in radians per second (rad/s) in calculations, where 1 rpm equals \(2\pi/60\) rad/s, which is about 0.105 rad/s.
The second is how hard the shaft can turn. If you push on a spanner near the nut, the nut does not move; push at the far end of the same spanner with the same force and it does. The turning effect depends on the force and on how far from the axis it acts. That turning effect is torque.
\[\tau = F \times d\]
Here \(\tau\) is the torque in newton metres (N·m), \(F\) is the force applied in newtons (N), and \(d\) is the perpendicular distance from the axis of rotation to the line of the force, in metres (m). Fig. 13.1-1 shows the two quantities on a driven wheel.
Diagram
Fig. 13.1-1 – a motor shaft with a wheel mounted on it, seen from the side; the axis of rotation marked at the centre; a force arrow F drawn at the rim tangential to the wheel; the perpendicular distance from the axis to the line of the force labelled d; a curved arrow around the axis labelled torque, with the units N·m shown beside it; a separate curved arrow labelled speed with rpm shown beside it
Speed and torque are not independent, and they are not both free. A motor that spins very fast usually pushes weakly, and a motor that pushes hard usually turns slowly. Much of the work of choosing an actuator is deciding where on that trade you want to sit, and you will meet it properly in section 13.2.3.
What the actuator costs you
No actuator turns all the electrical energy it is given into useful movement. Some of it becomes heat in the windings, some is lost in friction in the bearings and gears, and some is lost in the electronics that drive it. Electrical power drawn is \(P = VI\), measured in watts (W), where \(V\) is the supply voltage in volts (V) and \(I\) the current in amperes (A) — and only a fraction of that appears at the shaft.
This matters for two practical reasons. A motor that runs warm is normal; a motor that runs hot enough to be uncomfortable to touch is being asked for more than it can give. And the current drawn by an actuator is almost always larger than anything else in a small robot, which is why actuators need their own power arrangements rather than being fed from a controller pin.
13.1.2 Sensors: Turning Physical Quantities into Signals
A controller cannot feel a wall. It can only read numbers. Something has to stand between the physical world and the controller and turn one into the other, and that something is a sensor.
A sensor is a device that responds to a physical quantity — a distance, a light level, a contact force, a rate of turning — and produces an electrical signal that a controller can read.
The part of a sensor that actually performs the conversion from one form of energy to another is called a transducer. In an ultrasonic sensor the transducer is the small disc that turns an electrical signal into sound and sound back into electricity. In a touch sensor it is the switch contact. Most sensors you will use are a transducer plus a small amount of circuitry that cleans up, amplifies or digitises what the transducer produced.
Looking outward and looking inward
The six sensors named in this chapter divide neatly into two groups by what they are pointed at.
Four of them look outward, at the world around the robot: infrared, ultrasonic and LIDAR sensors report on objects at a distance, and touch sensors report on objects the robot has actually reached. Two of them look inward, at the robot’s own motion: a gyroscope reports how fast the robot is rotating and an accelerometer reports how it is accelerating and how it is tilted.
A robot needs both. Outward sensors alone will tell it there is a wall ahead but not that it is itself sliding sideways down a ramp. Inward sensors alone will tell it that it is turning but not that it is about to hit something.
Read the middle column of Table 13.1 carefully, because it contains an uncomfortable truth. Not one of these devices measures the thing you actually want.
You want the distance to a wall. The ultrasonic sensor measures a time. You want to know whether the robot is over a black line. The infrared sensor measures a brightness. You want to know which way is up. The accelerometer measures an acceleration. In every case the quantity you want has to be worked out from the quantity the sensor gives you, and that step is where most sensor problems are born.
That working-out step also has to be tuned to the particular device and the particular setting, by comparing its readings against known values and adjusting the calculation to match. This is calibration, and a sensor that has not been calibrated for the surface, the lighting or the material it is being used on will give confident, repeatable, wrong answers.
13.1.3 The Sense–Plan–Act Loop
Now put the two halves together. A robot reads its sensors, decides what to do about what it read, and commands its actuators. Then it does the whole thing again, and again, for as long as it is switched on. This repeating cycle is called the sense–plan–act loop, and it is the basic organising idea of every robot in this book.
Fig. 13.1-2 shows the cycle, and the important feature of the figure is the arrow that returns from the actuators to the sensors. It closes the loop, and it closes it through the physical world: the wheels turn, the robot moves, and because the robot has moved, the next sensor reading is different.
Diagram
Fig. 13.1-2 – flow: sensors read the environment → controller converts the readings into values → controller decides on an action → command sent to the motor driver → actuator moves the robot → the robot’s position in the environment changes → arrow returning to the first block to close the loop; the three stages labelled sense, plan and act along the outside of the cycle; power supply shown as a separate block with arrows to the controller and to the actuator
Consider a line-following robot on a workshop floor. It reads two downward-facing sensors, notices that the left one is over the dark line and the right one is not, decides that it has drifted right, and slows its left wheel to swing back. A few milliseconds later it reads again, and by then its own action has changed what there is to read.
Why the speed of the loop matters
Nothing in the loop is instantaneous. The sensor takes time to respond, the controller takes time to compute, and the motor takes time to change speed. The total delay between something happening in the world and the robot’s response appearing at its wheels is called latency, and it is measured in milliseconds (ms).
Latency is what decides whether a robot travelling towards a wall stops in front of it or in it. A robot moving at 0.5 m/s covers 5 cm in 100 ms. If its loop takes that long, it has already travelled 5 cm past the point where it should have decided to stop, before it even begins to slow down.
This is why the response time of a sensor, which sounds like a dry specification, will keep returning as a design constraint through the rest of this chapter. A slower sensor is not merely less convenient — it changes what the robot is physically able to avoid.
13.2 The DC Motor
Of all the actuators you can put on a robot, the DC motor is the one you will meet first and use most. It is cheap, it is small, it runs directly from a battery, and it does exactly one thing: as long as current flows, the shaft keeps turning.
That single sentence contains both its strength and its weakness. Continuous rotation is precisely what a wheel wants. It is precisely what a robot joint does not.
13.2.1 Construction of a DC Motor
Open a small motor and you will find two things that matter: a part that stays still and a part that turns.
The stator is the stationary part, and its job is to produce a steady magnetic field across the space where the moving part sits. In a small hobby motor this field comes from two curved permanent magnets stuck to the inside of the steel casing. In larger motors it comes from a field winding wrapped around pole pieces and supplied with current. The steel casing itself, called the yoke or frame, is not just a shell — it carries the magnetic field around from one pole to the other.
The rotor is the part that turns. It carries the armature, which is a set of coils of insulated copper wire wound on a laminated iron core and fixed to the shaft. Current is sent through these coils, and it is the armature that experiences the turning force.
Getting current into a coil that is spinning is the awkward part, and it is solved by the last two components. The commutator is a ring of copper segments on the shaft, insulated from one another, with each segment connected to the ends of one armature coil. The brushes are two fixed blocks of carbon, held against the commutator by springs, through which current enters and leaves. As the shaft turns, the commutator segments slide past the brushes.
Fig. 13.2-1 shows the arrangement in cross-section.
Diagram
Fig. 13.2-1 – cross-section of a DC motor drawn as a circle within the yoke; the yoke or frame labelled on the outside; two field poles marked N and S facing inward with the field winding shown on them; the armature conductors shown as a ring of small circles on the rotor core; the shaft at the centre; the commutator segments drawn on the shaft with two carbon brushes pressed against them from opposite sides, each brush labelled and connected to a supply terminal marked + and −; an arrow showing the direction of rotation
The BO motor used in most school robots hides all of this inside a yellow plastic case, together with a gearbox, and brings out just two wires. The two wires are the whole electrical interface: connect them to a supply and the shaft turns; swap them over and it turns the other way.
13.2.2 Working Principle
Place a wire carrying a current in a magnetic field and the wire experiences a sideways force. This is the effect at the heart of every electric motor, and its direction is at right angles to both the current and the field.
Now apply this to the armature. One side of a coil sits under the north pole and the other side under the south pole, so the field crosses the two sides in opposite directions. The force on one side is therefore upward and on the other side downward. A pair of equal and opposite forces acting at a distance from the shaft is exactly the situation described by \(\tau = F \times d\) in section 13.1.1, and the rotor turns.
Why the motor does not simply stop after half a turn
Follow the coil round. After it has turned through half a revolution, the side that was under the north pole is now under the south pole. If the current in it were still flowing the same way, the force on it would now push it backwards, and the rotor would settle into a fixed position and vibrate there.
This is what the commutator prevents. Just as each coil passes the point where the force would reverse, its commutator segment slides off one brush and onto the other, which reverses the current in that coil. The force on it therefore keeps pushing in the same rotational direction. Fig. 13.2-2 shows the same coil before and after the changeover.
Diagram
Fig. 13.2-2 – two side-by-side sketches of a single armature coil between an N pole on the left and an S pole on the right; in sketch (a) the coil is horizontal, current direction marked into the page on one side and out of the page on the other, force arrows drawn up on one side and down on the other, curved rotation arrow shown; in sketch (b) the coil has turned through half a revolution, the commutator segments have swapped brushes, the current directions in the coil sides are reversed, and the force arrows are shown still driving rotation the same way
So the commutator and brushes together act as a mechanical switch that reverses the armature current at exactly the right instant, many times per revolution. The result is a torque that always acts in one direction, and continuous rotation.
That mechanical switch is also the DC motor’s weakest part. The brushes rub, so they wear away and eventually need replacing. The sliding contact makes and breaks current, so it sparks slightly, and that sparking radiates electrical noise which can disturb sensitive circuits nearby.
13.2.3 The Governing Relations: Voltage, Torque and Speed
Three relations describe how a DC motor behaves electrically. They are worth understanding rather than memorising, because between them they explain every one of the motor’s practical characteristics.
The voltage equation
As soon as the armature starts turning, its coils are moving through the magnetic field. A conductor moving through a magnetic field has a voltage induced in it, and that induced voltage opposes the supply that caused the motion. It is called the back electromotive force (back emf).
\[V = E_b + I_a R_a\]
Here \(V\) is the applied supply voltage in volts (V), \(E_b\) is the back emf in volts (V), \(I_a\) is the armature current in amperes (A), and \(R_a\) is the resistance of the armature winding in ohms (Ω).
The back emf grows as the motor speeds up. Rearranged, \(I_a = (V - E_b)/R_a\), and this single line explains a great deal. When the motor is spinning freely and fast, \(E_b\) is nearly as large as \(V\), so the current is small. When the motor is held still, \(E_b\) is zero, so the current is limited only by \(R_a\) — and \(R_a\) in a small motor is often just a few ohms. A 6 V motor with an armature resistance of 3 Ω will draw 2 A the instant it is stalled, which may be ten times its normal running current.
The torque equation
The torque a motor develops depends on how much current is flowing through the armature and on how strong the field is.
\[\tau = k \Phi I_a\]
Here \(\tau\) is the developed torque in newton metres (N·m), \(\Phi\) is the magnetic flux per pole in webers (Wb), \(I_a\) is the armature current in amperes (A), and \(k\) is a constant fixed by the construction of the motor — the number of conductors, the number of poles and the winding arrangement.
In a permanent-magnet motor \(\Phi\) is fixed, so this reduces to a simple statement: torque is proportional to current. A motor asked to push harder does not decide to draw more current out of politeness; the physics runs the other way round. Loading the shaft slows it, slowing it reduces the back emf, reducing the back emf raises the current, and the raised current produces the extra torque.
The speed equation
Substituting the back emf, which is itself proportional to the speed and the flux, into the voltage equation gives the speed relation.
\[N \propto \frac{V - I_a R_a}{\Phi}\]
Here \(N\) is the rotational speed of the shaft in revolutions per minute (rpm).
For a permanent-magnet motor with \(\Phi\) fixed, speed rises almost in proportion to the applied voltage. That is the property the whole of section 13.2.5 rests on: to control the speed of a DC motor, you control the voltage across it.
13.2.4 Characteristics of a DC Motor
Put the three relations together and the motor’s behaviour under load falls out. As the load torque increases, the motor slows; as it slows, the current rises; and the relationship between speed and torque is very nearly a straight line, as Fig. 13.2-3 shows.
Diagram
Fig. 13.2-3 – speed–torque characteristic of a DC motor at constant supply voltage; horizontal axis labelled torque with unit N·m, vertical axis labelled speed with unit rpm; a straight line falling from the vertical axis to the horizontal axis; the intercept on the vertical axis labelled no-load speed, the intercept on the horizontal axis labelled stall torque; a second dashed line on a right-hand axis labelled armature current in A, rising from left to right, with its highest point at stall labelled stall current; a point marked in the middle of the straight line labelled operating point
Two points on that line have names, and component data sheets quote both.
The no-load speed is the speed the shaft reaches with nothing attached to it, at the left-hand end of the line. It is the fastest the motor will ever turn at that supply voltage.
The stall torque is the torque at which the shaft stops turning altogether, at the right-hand end of the line. It is the hardest the motor will ever push, and it is reached at the moment of maximum current, called the stall current.
A motor is never designed to work at either end. At no load it does nothing useful, and at stall it produces no motion and gets hot. Useful operation sits somewhere in the middle, and a well-chosen motor spends its working life in that region with the stall torque held in reserve for starting and for climbing.
The gearbox changes everything
A bare DC motor turns fast and pushes weakly — a few thousand rpm and a torque measured in a few millinewton metres is typical for a small one. A robot wheel wants the opposite.
A gearmotor is a DC motor with a gear train built onto its output shaft. The gear train divides the speed by the gear ratio and multiplies the torque by very nearly the same ratio, less what is lost to friction in the gear teeth. A motor turning at 6000 rpm behind a 30:1 gearbox delivers about 200 rpm at roughly thirty times the torque. This is what the yellow BO gearmotor in your laboratory kit is, and it is why it can move a robot when a bare motor of the same size cannot.
Notice what the worked example quietly assumed: that the motor runs at its rated speed. It will not, once it is carrying the robot. This is the everyday consequence of the falling speed–torque line, and it is why a robot that runs beautifully on a bench with its wheels in the air crawls when it is put on the floor.
13.2.5 Driving a DC Motor from a Controller
Here is where students most often damage hardware, so the reasoning matters more than the wiring.
A digital output pin of an Arduino UNO is designed to signal, not to supply power. Each pin can safely source or sink of the order of 20 mA, and that is a firm design limit. A BO gearmotor draws a few hundred milliamperes while running normally and over an ampere at stall. Connecting the motor to the pin therefore asks the pin for fifty times what it can give, and what fails is the controller, not the motor.
The H-bridge
A driver has to do two things: pass a large current, and let the controller reverse the motor without anyone rewiring it. Both are done by an arrangement of four switching elements called an H-bridge, named for the shape of the circuit when the motor is drawn as the crossbar between two vertical pairs of switches.
Close the top-left and bottom-right switches and current flows through the motor one way. Close the top-right and bottom-left switches instead and it flows the other way, so the motor reverses. Close none and the motor coasts. Closing both switches on the same side at once would short the battery through the driver, and it is one of the reasons a ready-made driver module is preferred to a home-made one.
The L298N module in your laboratory kit contains two such H-bridges, so it can drive two motors independently. Each bridge takes two direction inputs and one enable input.
Pulse width modulation
The speed equation told us that speed follows the voltage across the motor. But a microcontroller pin has only two states, on and off, and cannot output half a volt-something. The way out is to switch fully on and fully off, very rapidly, and vary the proportion of time spent on.
This is pulse width modulation (PWM). The fraction of each cycle for which the signal is high is called the duty cycle, usually stated as a percentage. Because the motor’s rotor has inertia and its windings have inductance, it cannot respond to each individual pulse; it responds to the average, and the average voltage is the supply voltage multiplied by the duty cycle. Fig. 13.2-4 shows three duty cycles of the same PWM signal.
Diagram
Fig. 13.2-4 – three PWM waveforms drawn one below the other on a common time axis, each a square wave of the same period; the first with a narrow high portion labelled 25% duty cycle, the second half high labelled 50%, the third mostly high labelled 75%; the period marked with a double-headed arrow on the top waveform and labelled T; a dashed horizontal line across each waveform marking the average voltage, with the label rising from the first waveform to the third
Putting it together
Before writing any code, state the method. The task is to bring a wheel smoothly up to speed, stop it, and run it the other way.
Fig. 13.2-5 shows the complete circuit. Trace the ground line in it with your finger: it is one continuous rail joining the battery negative, the driver’s GND terminal and the board’s GND pin, and every one of the three must be on it.
Diagram
Fig. 13.2-5 – circuit: Arduino UNO connected to an L298N motor driver module driving one BO gearmotor; Arduino pin 7 to IN1, pin 8 to IN2, pin 9 to ENA, each wire labelled with both pin names; motor terminals to OUT1 and OUT2; a 6 V battery pack with its positive lead to the +12V terminal and its negative lead to the GND terminal; a wire from the L298N GND terminal to an Arduino GND pin; the ground connections drawn as a single continuous rail and labelled common ground; the ENA jumper shown removed and annotated; the L298N 5V pin shown unconnected and annotated; the Arduino USB cable shown as its power source
13.2.6 Applications, Advantages and Limitations
Read the first limitation again, because it is the reason the next section exists. A DC motor is an excellent answer to “turn this wheel” and a poor answer to “hold this joint at 45°”.
13.2.7 Selecting a DC Motor for a Task
Choosing a motor is a sequence of questions, asked in this order.
What torque does the load need, and at what speed? This is the first question because it is the one that decides whether the motor can do the job at all. Work out the torque the wheel or joint must produce in the worst case you expect — usually starting from rest, or climbing a slope — and the speed you want at that torque. Compare both against the motor’s speed–torque line, and keep a clear margin below the stall torque so that the motor is not living at the hot end of the graph.
What supply voltage is available? The motor’s rated voltage should match the battery pack. A 6 V motor run from a 12 V pack will be fast and short-lived; a 12 V motor run from a 6 V pack will turn slowly and may not start under load at all.
How much current will it draw, and can the driver supply it? Check the stall current, not the running current, because the stall current is what flows every time the motor starts and every time the robot is blocked. The driver and the battery must both be able to supply it, at least briefly.
Does the task need position control? If it does, either budget for an encoder and the control code to go with it, or reconsider and use the actuator in section 13.3.
That final remark is the habit worth carrying away. A calculation that says “it just fits” in an idealised case is a calculation that says “it will not fit” in a real workshop.
13.3 The Servo Motor
Section 13.2 ended on a limitation. A DC motor will turn a wheel all day, but ask it to move a robot’s elbow to 45° and hold it there against the weight of the forearm, and it has no idea what 45° means. It knows only how much voltage it is being given.
The servo motor is the answer to that problem, and the interesting thing about it is that there is still an ordinary DC motor inside. What has been added is not a better motor. It is knowledge of where the shaft actually is.
Photograph
Fig. 13.3-1 – a standard hobby servo motor photographed on a plain background, with its three-wire lead clearly visible and separated so the individual wires can be distinguished, and a plastic output horn fitted to the splined output shaft; a second horn lying beside it. Sourcing note: the three wires must be distinguishable and the splined shaft visible; an image in which the lead is coiled out of sight, or the servo is already buried in an assembly, is unusable.
13.3.1 What Makes a Servo Different
A servo motor is commanded by angle, not by speed. You do not tell it “turn”; you tell it “go to 60°”, and it goes there and stays there. If something pushes the output shaft away from 60°, the servo pushes back until it returns.
Three phrases in that definition are doing real work.
Commanded angular position means the input is a position, not a voltage or a speed. Limited range means the shaft does not spin freely; a standard hobby servo moves through about 180° and is stopped mechanically at each end. Holds that position against a load means it does not merely arrive — it stays, and it keeps working to stay.
That last property is what makes a servo suitable for a joint. A robot arm holding a marker against a whiteboard is not a machine that has finished moving. It is a machine that is continuously resisting being moved.
13.3.2 Inside a Servo Motor
Open the case and there are four parts, shown as a system in Fig. 13.3-2.
Diagram
Fig. 13.3-2 – block diagram of the inside of a servo motor drawn inside a dashed boundary labelled servo case; blocks in order: control circuit, integrated H-bridge, DC motor, gear train, output shaft; arrows left to right between them; the output shaft block also connected downward to a block labelled potentiometer; an arrow labelled feedback voltage running from the potentiometer back to the control circuit; an arrow entering the boundary from the left labelled command pulse from controller, and two more entering labelled supply and ground; the difference taken inside the control circuit annotated as error = commanded position − actual position
A small DC motor provides the movement, exactly as described in section 13.2. A gear train reduces its speed and multiplies its torque, which is why a servo the size of a matchbox can hold up a light arm. An integrated H-bridge on the control board switches the motor’s current in either direction.
The fourth part is the one that changes everything. A potentiometer is a resistor with a sliding contact, whose resistance between the contact and one end depends on how far the contact has moved. Inside a servo it is mechanically coupled to the output shaft, so when the shaft rotates the sliding contact rotates with it. The resistance therefore varies with the shaft angle, and it produces a voltage that represents where the shaft actually is at this instant.
The loop inside the loop
Follow the arrows in Fig. 13.3-2 round. The control circuit receives the commanded position from the controller and the actual position from the potentiometer, and it subtracts one from the other.
That difference is called the error. If the error is positive the shaft is behind where it should be and the circuit drives the motor forward; if it is negative the circuit drives the motor backwards; and as the shaft approaches the commanded position the error shrinks, so the drive is reduced and the shaft settles rather than overshooting. When the error is zero the motor is left with just enough current to hold station.
Information about the output being sent back to influence the input is called feedback, and a system that uses it is said to work in closed-loop control.
13.3.3 The Control Signal and the Commanded Angle
How does a controller send an angle down a single wire? Not as a number and not as a voltage, but as the width of a pulse.
A servo expects a train of pulses repeated about every 20 ms, which is a repetition rate of about 50 Hz. The gap between pulses carries no information at all. The angle is encoded entirely in how long each pulse stays high. Fig. 13.3-3 shows three commands as they appear on the signal wire.
Diagram
Fig. 13.3-3 – three pulse trains drawn one below the other on a common time axis; each shows two consecutive narrow high pulses with the interval between the leading edges marked 20 ms; the first has a pulse width labelled 1.0 ms and is annotated shaft commanded to 0°, the second 1.5 ms annotated 90°, the third 2.0 ms annotated 180°; a note on the figure that the horizontal scale of the pulse is exaggerated for clarity
For a typical hobby servo, a pulse of about 1.0 ms commands one extreme of travel, about 1.5 ms commands the centre, and about 2.0 ms commands the other extreme, with positions in between mapping linearly onto pulse widths in between. These figures are typical rather than universal; individual servos vary by a fraction of a millisecond at each end, which is one reason a servo’s zero position may not be exactly where you expected it.
The servo’s control circuit reads the width of every pulse it receives and treats it as the freshly commanded position. Since a pulse arrives fifty times a second, the comparison in the previous subsection is repeated fifty times a second, which is what makes the holding action feel continuous.
13.3.4 Characteristics of a Servo Motor
Range of motion. A standard servo travels about 180° and no further, because internal stops prevent it. A variant called a continuous-rotation servo removes the stops and reinterprets the pulse width as a speed command instead of a position command, but it is then no longer able to hold an angle.
Transit speed. Servos are specified by the time taken to travel 60°, and a typical figure is 0.1 s to 0.2 s at no load. A servo is not instant, and a program that commands a large movement and then immediately reads a sensor will read it before the arm has arrived.
Holding torque. This is the torque the servo can resist at a held position, usually quoted in kg·cm; recall that 1 kg·cm is 0.0981 N·m. It is the specification that decides whether an arm will sag.
Positional accuracy and deadband. Feedback typically keeps the shaft within a degree or two of the commanded angle. It is not better than that, because every servo has a small deadband — a range of error so small that the control circuit does not act on it. Without a deadband the motor would be driven back and forth endlessly around the target and would buzz constantly.
Current draw. A servo holding a light load draws very little current. The same servo holding a heavy load, or pushing against an obstruction, draws a great deal, because a large error means a large drive to the internal motor. Current therefore rises with load rather than being fixed, which is exactly the behaviour that catches out a robot whose supply was sized for the unloaded case.
13.3.5 Driving a Servo Motor from a Controller
Generating a 1.5 ms pulse fifty times a second, accurately, while also running the rest of a program, is a job for a timer rather than for hand-written delays. The Arduino Servo library does this using the board’s timer hardware, so a program only ever states the angle it wants.
Powering the servo
The signal wire may come from the controller. The power wires must not.
Fig. 13.3-4 shows the connections. Compare its ground rail with the one in Fig. 13.2-5: the principle is identical even though the components are different.
Diagram
Fig. 13.3-4 – circuit: Arduino UNO with one hobby servo; the servo’s three wires drawn separately and labelled signal, supply and ground; signal wire to Arduino pin 9; supply wire to the positive terminal of a 6 V battery pack; ground wire to the negative terminal of the pack; an additional wire from the pack’s negative terminal to an Arduino GND pin; the ground connections drawn as one continuous rail and labelled common ground; the Arduino 5V pin shown clearly unconnected with an annotation; the USB cable shown supplying the board
13.3.6 Applications, Advantages and Limitations
That final limitation deserves a moment. A servo is closed-loop internally and open-loop as far as your program is concerned. Your program knows what it asked for. If the arm is jammed, or the servo has been unplugged, the program will carry on in complete confidence — which is why a robot that must be certain a movement happened needs a separate sensor, such as one of those in the second half of this chapter, to confirm it.
13.4 Choosing Between a DC Motor and a Servo Motor
You now know two actuators well enough to be asked the only question that matters at a workbench: which one goes on this robot?
The answer is almost never decided by which motor is better. Neither is. It is decided by what the moving part has to do, and the fastest way to settle it is to ask four questions in order.
Does the part rotate continuously, or move to a position?
This single question settles most cases on its own. A wheel, a fan, a pump or a conveyor roller has to keep turning, and nobody cares which way up it ends. That is a DC motor.
A shoulder, an elbow, a gripper jaw, a steering linkage or a camera mount has to reach a stated angle and stay there. That is a servo motor.
A robot is quite likely to need both. A small pick-and-place machine built in a school workshop typically has two BO gearmotors driving its wheels and two or three servos in its arm, and there is nothing inconsistent about that. The wheels are being asked to travel; the arm is being asked to point.
Can the actuator produce the torque needed at the speed needed?
Having chosen the family, check that the particular unit can do the work, using the method of section 13.2.7. For a DC motor, compare the required torque against the stall torque with a clear margin. For a servo, compare the load it must hold against its quoted holding torque, and check its transit time against how quickly the movement has to happen.
What supply is available, and what will the current do under load?
DC motors in school robots are commonly rated 6 V or 12 V; hobby servos usually want 4.8 V to 6 V. In both cases the running current is not the number that matters. The stall current of a DC motor and the loaded current of a servo are what the battery and the driver must survive, and both are several times the comfortable figure printed on the packet.
How much control complexity are you willing to build?
A servo hides its feedback loop inside its own case, so a program needs one line to command an angle. A DC motor hides nothing, so a program that must know where the shaft is has to be given a sensor and the code to use it.
That sensor is an encoder — a device fitted to a rotating shaft that produces a series of electrical pulses as the shaft turns, so that counting the pulses gives the angle turned and timing them gives the speed. A DC motor with an encoder and a well-written control loop can do everything a servo does, with more range and more speed, but it is a substantially larger piece of engineering. In a school laboratory that is a project in itself, not a component choice.
Read Table 13.4 across the middle row once more, because it captures the whole distinction in one line. Put a load on a DC motor and hold its shaft, and it fights until it burns. Put a load on a servo and hold its shaft, and it fights until you let go. The difference is not the motor. It is that one of them knows where it is.
13.5 Reading a Sensor
The six sensors in the rest of this chapter work on completely different physics. One listens for an echo, one times a laser pulse, one feels a contact, one senses the deflection of a vibrating mass. Yet all six end up doing the same thing: handing a number to a controller.
How they hand it over is worth studying once, here, rather than six times over. It is also where a surprising number of robot faults live, because a sensor can be perfectly healthy and still be read wrongly.
13.5.1 Digital and Analogue Outputs
A sensor’s output takes one of a small number of forms, and the form decides how you wire it and which instruction reads it.
A two-state digital output
A digital output has only two states: high, meaning close to the supply voltage, and low, meaning close to 0 V. It answers a yes-or-no question. Is the bumper pressed? Is there something within range? Is the surface underneath dark?
Many sensor modules produce this from an underlying continuous measurement by comparing it against a threshold — a set level, above which the output goes one way and below which it goes the other. On a typical IR sensor module the threshold is set by the small trimmer potentiometer on the board, and turning that screw changes how near an object must be before the output switches.
A controller reads such a pin with digitalRead(), which returns HIGH or LOW. On a 5 V board the pin reads HIGH above roughly 3 V and LOW below roughly 1.5 V; a voltage between those two is in no-man’s-land and the result cannot be relied upon.
An analogue output
An analogue output is a voltage that varies continuously with the measured quantity. A reflective IR sensor’s raw output might sit at 0.4 V over a black line and 3.6 V over white paper, taking every value in between as the robot drifts across the edge.
This carries far more information than a threshold does, which is why an analogue reading can tell you how dark the surface is, and not merely that it is dark.
A timed pulse
Some modules answer with the duration of a pulse rather than its level. The HC-SR04 ultrasonic module in section 13.7 does exactly this: it raises its echo pin and holds it high for a time equal to the flight time of the sound. Nothing about the voltage carries information; the whole measurement is in the length of the pulse, and the controller reads it by timing the pin.
Digital data over a communication protocol
The more capable devices — LIDAR units, gyroscopes and accelerometers — measure far too much to fit on one wire as a level. They contain their own processing, package their readings as numbers, and send those numbers to the controller over a communication protocol such as I2C, SPI or UART. The wiring is a shared bus rather than one pin per reading, and the protocols themselves are studied later in this course.
Table 13.5 explains something that puzzles students when they first open a robotics kit. The simplest sensors need the most work from your program, because they hand over a raw electrical quantity and leave the interpretation to you. The most sophisticated ones need the least, because they have already done the interpretation inside themselves.
13.5.2 Analogue-to-Digital Conversion
A microcontroller cannot store a voltage. It stores numbers. The component that bridges the gap is the analogue-to-digital converter (ADC), a circuit built into the microcontroller that measures the voltage on an analogue pin and reports it as a whole number.
The conversion compares the input against a reference voltage and divides the range into a fixed number of steps. The Arduino UNO’s ADC is a 10-bit converter, which means \(2^{10} = 1024\) possible codes, numbered 0 to 1023, spread across 0 V to the reference voltage of 5 V. Fig. 13.5-1 shows what this does to a smoothly changing signal.
Diagram
Fig. 13.5-1 – a graph with time on the horizontal axis and voltage on the vertical axis from 0 V to 5 V; a smooth curving analogue signal drawn as a solid line; a set of closely spaced horizontal dashed gridlines representing the ADC’s discrete levels; a staircase drawn on top of the smooth curve showing the value actually recorded at each sample, with three sample points marked and labelled with their integer codes; a note on the vertical axis that one step corresponds to about 4.9 mV
The staircase is the point of the figure. Whatever the true voltage, the number returned is the nearest step, so the smallest change the board can possibly detect is one step:
\[\text{step size} = \frac{5\ \text{V}}{1024} = 0.00488\ \text{V} = 4.88\ \text{mV}\]
To turn a reading back into a voltage, the conventional calculation scales the code so that the highest code, 1023, corresponds to the full 5 V.
13.5.3 Range, Resolution, Response Time and Noise
Every sensor data sheet quotes the same handful of properties, and the six sections that follow will quote them again for each device. They are worth understanding once, in the abstract, so that they read as engineering constraints rather than as numbers to memorise.
Range is the span between the smallest and largest values the sensor can report meaningfully. Below the minimum it is blind — an ultrasonic module cannot measure an object touching its face — and above the maximum it either saturates at its top value or reports nothing at all. A robot must be programmed to recognise both ends, because a sensor at the edge of its range does not announce that it has run out; it simply returns a number that looks like any other.
Resolution, accuracy and repeatability carry exactly the meanings you met as specifications of a robot, and they apply just as firmly to a sensor. Resolution is the smallest change the sensor can distinguish, such as the 4.88 mV step of the ADC above. Accuracy is how close its readings are to the true value. Repeatability is how closely it agrees with itself when the same measurement is taken again under identical conditions. A sensor can be highly repeatable and badly inaccurate — that is precisely the situation an uncalibrated device is in, and it is the most misleading of all, because consistent wrong answers look trustworthy.
Response time is how long the sensor takes to produce a valid reading after the quantity changes, or after it is asked. Section 13.1.3 showed why this belongs to the design of the robot and not merely to the sensor: a slow sensor lengthens the sense–plan–act loop, and a longer loop means the robot travels further before it can react.
Noise is the random fluctuation present in every reading, from electrical interference, from the sensor’s own electronics, and from the environment. Drift is different and more dangerous: it is a slow, systematic wandering of the reading over time or with temperature, even when the measured quantity has not changed at all. Noise makes a reading jitter around the truth and can be reduced by averaging several readings. Drift moves the truth itself, and averaging does nothing about it — you will meet it again, at its worst, in the gyroscope of section 13.10.
13.6 Infrared (IR) Sensors
Point a television remote at a wall, press a button, and nothing appears to happen. Hold a phone camera in front of the remote and press again, and a small lamp on the front of the remote flashes. The lamp was always flashing. Your eye simply cannot see the light it emits.
That light is infrared, and the whole of this section rests on one convenient fact about it: it behaves exactly like visible light — it travels in straight lines, it reflects off surfaces, it is absorbed by dark ones — but it is invisible, so a robot can flood a room with it without anyone noticing.
13.6.1 Working Principle
Infrared light has a wavelength just beyond the red end of the visible spectrum. The devices used in robotics work in the near infrared, typically around 850 nm to 950 nm, where cheap emitters and detectors are readily available.
An infrared (IR) sensor of the kind used on a small robot has two parts facing the same way. An IR LED emits a beam of infrared light. Beside it, a photodiode or a phototransistor — a component whose electrical behaviour changes with the light falling on it — measures how much infrared comes back.
If nothing is in front of the sensor, the light travels away and very little returns. If an object is close, a good deal of the light bounces off it and reaches the detector. Fig. 13.6-1 shows the arrangement.
Diagram
Fig. 13.6-1 – active IR proximity sensing; on the left a rectangular block labelled IR sensor module containing two smaller blocks, one labelled IR LED (emitter) and one labelled photodiode (receiver); an arrow labelled emitted IR light leaving the LED and striking an object drawn on the right; a second arrow labelled reflected IR light returning from the object to the photodiode; the object shown twice, once near and once far, with the returning arrow drawn thick for the near object and thin for the far one
The amount of returned light therefore carries information about what is in front of the sensor. A complete module adds the electronics that make that information usable: an amplifier to raise the small photodiode current to a workable voltage, and usually a comparator that turns the result into a two-state digital output, with a trimmer potentiometer to set the switching threshold.
What the sensor is really measuring
Look carefully at what has happened. You wanted to know how far away the object is. The sensor has told you how much light came back — and how much light comes back depends on the distance and on the colour of the surface and on its finish and on its angle.
A white card at 15 cm and a black cloth at 4 cm can return exactly the same amount of light, and the sensor has no way at all to tell them apart. This is the single most important fact about IR sensing, and every advantage and limitation later in this section follows from it.
Rejecting the sunlight
Sunlight and filament lamps pour out infrared, and to a photodiode this is a bright background against which a small reflected beam must be seen. Cheap sensors solve this by modulation: the emitter does not shine steadily but flashes at a fixed frequency, often around 38 kHz, and the receiving circuit responds only to light flickering at that frequency. Steady infrared from the sun is then ignored.
Modulation helps considerably, and it is why an IR remote works across a sunlit room. It does not solve everything, because very strong sunlight can still saturate the detector so that no flicker is distinguishable on top of it.
13.6.2 Active and Passive Infrared Sensing
The sensor described so far provides its own light and looks at the reflection. It is therefore called an active IR sensor, and it works in complete darkness because it brings its own illumination.
There is a second, quite different device. Every warm object emits infrared of its own; a human body radiates strongly at wavelengths around 10 µm. A passive infrared (PIR) sensor emits nothing at all and simply watches for that radiation.
Inside it is a pyroelectric element, a material that produces a small electrical signal when the infrared falling on it changes. A plastic lens over the element divides the view into a pattern of zones, so that a warm body walking across the field of view passes from zone to zone and the received radiation rises and falls. That change is what the sensor reports. Fig. 13.6-2 shows the idea.
Diagram
Fig. 13.6-2 – a PIR sensor drawn in section; a small block labelled pyroelectric element behind a domed lens labelled segmented lens; fan-shaped detection zones spreading outward from the lens, drawn as alternating shaded and unshaded wedges; a walking figure shown at two successive positions crossing from one zone into the next, with arrows labelled infrared radiated by warm body reaching the element; an annotation stating that the output responds to the change in received radiation, not to its steady level
This has a striking consequence. A PIR sensor detects a person walking past and then, if that person stands perfectly still, gradually stops reporting them. It is a motion detector, not a presence detector, and it cannot measure distance at all.
13.6.3 Characteristics
Range. A simple reflectance sensor of the sort used for line following works from a few millimetres up to about 1–2 cm above the surface, and is usually mounted within that band. Proximity modules that measure by triangulation typically cover about 10–80 cm. Time-of-flight IR modules can reach around 2 m indoors. All these figures are typical and vary between devices.
Resolution and accuracy. An intensity-based IR sensor gives either a two-state answer or an analogue value with limited precision. It is entirely adequate for telling a line from a floor or a near wall from open space, and it is a poor instrument for measuring an actual distance.
Field of view. The field of view is the cone within which the sensor responds to an object. IR sensors have a fairly narrow one, commonly around 20° to 40° depending on the emitter and any lens fitted, so they mostly detect what is directly in front of them. Narrow is not automatically better: it means an obstacle just off to one side is invisible.
Response time. IR sensors are fast, updating within microseconds to milliseconds. This is why they suit line following, where a robot moving at speed must react to an edge it has only just crossed.
Sensitivity to materials. Performance varies with the colour and finish of the target, as section 13.6.1 explained. Dark and matt black surfaces reflect little and appear farther away or vanish altogether. Shiny surfaces at an angle reflect the beam away like a mirror rather than back to the detector. Transparent materials such as glass may not be detected at all, since the light passes through.
Ambient light. Strong ambient infrared raises the background against which the sensor works and can saturate it. Modulation reduces the problem but does not remove it, and IR sensors are generally more reliable indoors than in direct sunlight.
13.6.4 Applications, Advantages and Limitations
The commonest use of IR sensing on a school robot is line following, so it is worth building once, properly.
Two sensors are mounted under the front of the chassis, spaced so that they straddle a dark line on a light floor. While the robot is centred, both look at the floor. If it drifts to the right, the left-hand sensor moves over the line; if it drifts left, the right-hand sensor does. Fig. 13.6-3 shows the three cases.
Diagram
Fig. 13.6-3 – three plan views of a robot chassis seen from above on a light floor with a dark line running vertically; two small squares near the front of the chassis labelled left sensor and right sensor, spaced wider apart than the line; in view (a) the chassis is centred and both sensors are clear of the line, annotated go straight; in view (b) the chassis has drifted right so the left sensor lies over the line, annotated slow the left wheel to turn left; in view (c) the chassis has drifted left so the right sensor lies over the line, annotated slow the right wheel to turn right
13.7 Ultrasonic Sensors
A bat flying through a dark room does not see the walls. It shouts, listens for the return, and works out where everything is from how long the sound took to come back. It is a method that cares nothing for the colour of the wall, and works as well at midnight as at noon.
That is exactly what the ultrasonic sensor does, and it is the natural partner to the IR sensor of the previous section, because its strengths sit precisely where the IR sensor’s weaknesses are.
13.7.1 Working Principle
Human hearing stops at about 20 kHz. Sound above that frequency is called ultrasound, and the sensors used in robotics work around 40 kHz — inaudible, so a corridor full of robots is a silent corridor.
A module such as the HC-SR04 carries two small cylinders side by side. Each contains a piezoelectric element, a material that changes shape slightly when a voltage is applied across it and, conversely, produces a small voltage when it is deformed. One element is driven electrically and vibrates, radiating sound. The other is deformed by returning sound and produces the electrical signal that the module detects.
The measurement runs as follows. The module emits a short burst of about eight cycles at 40 kHz, then falls silent and listens. The burst travels outward, strikes a surface, and part of it returns. The module measures the interval between sending and receiving, which is called the time-of-flight, and reports it. Fig. 13.7-1 shows the path.
Diagram
Fig. 13.7-1 – ultrasonic ranging; on the left a module labelled ultrasonic sensor with two cylindrical transducers labelled transmitter and receiver; an arrow of short wave symbols labelled emitted burst travelling right to an object; a second arrow of wave symbols labelled returning echo travelling back to the receiver; the horizontal separation between module and object labelled d with a double-headed arrow; an annotation stating that the sound covers the distance d twice
The single most important feature of Fig. 13.7-1 is that the sound makes the journey twice. It goes out and it comes back, so the distance the sound has travelled is twice the distance to the object.
Why there is a minimum distance
The transmitting element does not stop vibrating the instant it is switched off; like a struck bell, it rings on for a short time. During that period the module cannot distinguish a genuine echo from its own residual noise, so it simply ignores everything.
The consequence is a blind zone close to the sensor — typically the first 2 cm or so — within which an object cannot be measured at all. An obstacle in the blind zone does not report as “very close”. It reports as nothing, which is the same thing the module reports for an empty room, and a robot that does not allow for this will happily drive into a wall it is already touching.
13.7.2 Computing Distance from the Echo Time
The sensor gives a time. You want a distance. Converting one to the other needs the speed of sound and one halving.
For air at about 20 °C the speed of sound is 343 m/s. Converting to units that suit a microsecond timer:
\[343\ \text{m/s} = 34300\ \text{cm/s} = 0.0343\ \text{cm/µs}\]
The temperature problem
The speed of sound in air is not a constant; it rises with temperature, by roughly 0.6 m/s for every degree Celsius. A sensor calibrated for a 20 °C laboratory and then used in a 40 °C warehouse is working with a speed about 12 m/s too low, so every distance it reports is about 3.5 per cent short. At 2 m that is an error of 7 cm.
This is not a fault in the sensor. It is the price of measuring a distance by timing something whose speed depends on the weather, and it is why serious installations add a temperature sensor and correct for it.
Reading the sensor with a controller
The HC-SR04 is commanded by one pin and answers on another. A pulse of at least 10 µs on the trigger pin starts a measurement. The module then raises its echo pin and holds it high for exactly the time of flight, as Fig. 13.7-2 shows. Timing that pulse is the whole of the measurement.
Diagram
Fig. 13.7-2 – timing diagram with three horizontal traces on a common time axis; the first labelled TRIG showing a single short pulse annotated 10 µs minimum; the second labelled transducer showing a short group of eight wave cycles annotated 40 kHz burst, starting just after the trigger pulse; the third labelled ECHO showing a pulse that begins when the burst is sent and ends when the echo returns, its width marked with a double-headed arrow and labelled time of flight; a note that a wider ECHO pulse means a more distant object
13.7.3 Characteristics
Range. A common module such as the HC-SR04 covers roughly 2 cm to 4 m, with the lower figure set by the blind zone. Larger industrial units reach 10 m or more, though accuracy falls off with distance as the returning echo weakens.
Resolution. Because the timing is done on a microsecond scale, the resolution is fine — of the order of 1 cm or better. Note that the resolution is far better than the accuracy in practice, since the speed of sound used in the calculation is itself only approximate.
Beam width. Ultrasound spreads out into a cone rather than a narrow line. A typical 40 kHz transducer has a beam half-angle of about 15°, giving a detection cone roughly 30° wide. Fig. 13.7-3 shows what this means in practice.
Diagram
Fig. 13.7-3 – plan view of an ultrasonic sensor at the left with a shaded cone spreading to the right, the full angle of the cone labelled about 30°; a small object drawn off to one side but still inside the cone, with a dashed line from the sensor to it labelled the sensor reports its distance but not its direction; a second object drawn just outside the cone edge, labelled not detected; a small shaded semicircle immediately in front of the sensor labelled blind zone, about 2 cm
The cone cuts both ways. It means the sensor notices an obstacle that is not directly ahead, which is useful; and it means that when the sensor reports 40 cm, the robot knows something is 40 cm away somewhere in that cone and has no idea where. A doorway and a chair leg can produce identical readings.
Response time. Sound is slow, and the sensor must wait for the echo. To measure out to 4 m the sound must travel 8 m, which at 343 m/s takes about 23 ms, so the module cannot be read much faster than about forty times a second, and rather less if repeated readings are to be free of leftover echoes. Compared with the microseconds of an IR sensor, this is sluggish, and it directly limits how fast a robot relying on it can safely travel.
Target properties. Hard, smooth, flat surfaces facing the sensor reflect well. A surface at a steep angle behaves like a mirror held obliquely and deflects the sound away instead of back. Soft, porous materials such as curtains, cushions and thick clothing absorb the sound and return little.
13.7.4 Applications, Advantages and Limitations
Set the last two sections side by side for a moment. An IR sensor is fast, short-range, cheap and easily fooled by the surface. An ultrasonic sensor is slower, longer-range and indifferent to the surface, but vague about direction. Neither is a substitute for the other, and a robot that carries both is not being wasteful — it is covering each sensor’s blind spot with the other’s strength.
13.8 LIDAR Sensors
The ultrasonic sensor of the previous section works by timing a pulse. Its weaknesses — the slowness, the wide vague cone — come from the medium it uses. Sound is slow and it spreads.
Replace the sound with a laser beam and both problems disappear at once. Light is fast and a laser beam stays narrow over long distances, so instead of “something is 40 cm away somewhere in front”, you can have “there is a surface 4.12 m away at a bearing of 37°”. That is what light detection and ranging (LIDAR) provides, and it is the sensor that makes genuine mapping possible.
13.8.1 Working Principle
A LIDAR sends out a short pulse of laser light, usually infrared, and measures how long it takes to return after striking a surface. The distance follows from the same time-of-flight relation given in section 13.7.2, with the speed of light in place of the speed of sound.
\[d = \frac{c \times \Delta t}{2}\]
Here \(c\) is the speed of light in air, about \(3.00 \times 10^8\) m/s, and \(\Delta t\) is the round-trip time in seconds. Fig. 13.8-1 shows the arrangement.
Diagram
Fig. 13.8-1 – LIDAR ranging; on the left a block labelled laser emitter with a narrow straight beam labelled emitted pulse travelling right to a target block; a returning beam labelled reflected pulse arriving at a second block labelled detector below the emitter; the distance between the unit and the target labelled d; the round-trip time labelled Δt beside the beams; the relation d = c Δt / 2 written as an annotation, with c labelled the speed of light
The physics is identical to the ultrasonic case. The engineering is not, and the reason is worth working out for yourself.
Timing at that scale is difficult and expensive, so many practical units avoid measuring the pulse directly. Instead they send out light whose brightness is varied smoothly at a known high frequency, and compare the phase of the returning light with the phase being transmitted. The shift between them corresponds to the flight time and gives the distance without the need to catch a single nanosecond-wide event.
From one distance to a map
A single LIDAR reading is just a number, like an ultrasonic reading. What makes the device powerful is that the beam is swept, usually by a rotating mirror or by spinning the whole optical assembly, and a reading is taken at every small step of the rotation.
Each reading is therefore a distance paired with an angle. Plot all of them and you get a set of points marking the surfaces around the robot, called a point cloud. Fig. 13.8-2 shows what one scan of a room produces.
Diagram
Fig. 13.8-2 – plan view of a room with a table and two chairs; a small circle at the centre labelled 2D scanning LIDAR with a dashed circle around it showing the path of the rotating beam; several radial lines drawn outward at intervals labelled measurement beams, each ending in a dot on the first surface it meets; the dots together tracing the outline of the walls and the visible edges of the furniture, labelled point cloud; the region directly behind the table shown blank and labelled hidden from the sensor
Look at the blank region in the figure. A LIDAR reports the first surface each beam meets and nothing beyond it, so anything in the shadow of an obstacle is simply absent from the scan. A robot that treats absence as open space will drive confidently into whatever was hidden.
13.8.2 Types of LIDAR
2D scanning LIDAR. A single rangefinder is spun, or its beam is swept by a rotating mirror, to cover a full circle in one horizontal plane. The result is a two-dimensional slice of the surroundings taken at the height of the sensor. This is the type most often fitted to indoor mobile robots, and it is what produced the scan in Fig. 13.8-2. Note the limitation built into the word slice: a step or a low kerb below the scanning plane is invisible.
3D LIDAR. Several laser beams are stacked at different elevations, or a 2D unit is tilted up and down rapidly, so that the point cloud fills a volume instead of a plane. This is the arrangement used on self-driving vehicles, where knowing the height of an object matters as much as its bearing.
Single-point LIDAR modules. A small unit that measures in one fixed direction only, with no scanning at all. It plays the same role as an ultrasonic sensor — one distance, straight ahead — but with a much narrower beam and better precision. These are used as height sensors on drones and for measuring to a specific chosen target.
Photograph
Fig. 13.8-3 – a 2D scanning LIDAR unit mounted on the top deck of a small indoor mobile robot, photographed from the side at close range so that the rotating upper section and the fixed base are distinguishable, with the emitting window visible. Sourcing note: the unit must be identifiable as a rotating scanner rather than a plain box, and the robot beneath it should be visible for scale; a close-up of a bare unit with no context, or an artist’s rendering, is unusable. Brand markings should be minimal or cropped out.
13.8.3 Characteristics
Range. A 2D unit intended for indoor robots typically covers about 6 m to 30 m, depending on the model. Units built for vehicles reach 100 m to 200 m with more powerful lasers. The range achieved in practice depends on the laser power, the sensitivity of the detector and how well the target reflects.
Accuracy and resolution. LIDAR is precise. Accuracy at the centimetre level is routine and millimetre level is available, a small unit being quoted at something like ±30 mm over 20 m. This is an order of magnitude better than an ultrasonic module can manage.
Angular resolution. The angular resolution is the angle between one measurement and the next as the beam sweeps round, commonly between 0.25° and 1°. It decides how much detail the point cloud holds, and its consequences are easy to underestimate.
Field of view. A scanning unit typically covers a full 360° in its plane. Some cover about 270°, leaving a blind sector where the cable and mounting sit.
Update rate. A 2D unit usually rotates at 5 Hz to 15 Hz and takes several hundred readings per revolution — 360 or 720 are common figures. At ten revolutions a second with 360 readings each, that is 3600 distance measurements every second, and the robot receives a complete fresh outline of its surroundings ten times a second. That is enough to navigate on while moving, and it is the basis of simultaneous localisation and mapping (SLAM), in which a robot builds a map of an unknown space and works out its own position within that map at the same time.
Environmental conditions. Fog, smoke and heavy dust scatter the laser light, so pulses return from the air itself rather than from surfaces and the range drops. Very dark or mirror-like surfaces reflect poorly or deflect the beam away, exactly as they do for an IR sensor, because a LIDAR is an optical device after all.
13.8.4 Applications, Advantages and Limitations
13.9 Touch Sensors
The three sensors so far all measure at a distance, and all three can be wrong. An IR sensor misjudges a dark cloth, an ultrasonic beam slides off an angled wall, a LIDAR beam passes either side of a chair leg. In each case the robot believes the way ahead is clear, and drives on.
A touch sensor cannot be fooled in that way, because it does not measure anything at a distance. It reports that contact has happened. Its reading arrives too late to prevent the collision — and that is exactly why every serious mobile robot has one.
13.9.1 Working Principle
The simplest touch sensor is a switch. Two conductors are held apart by a spring; when something presses on the actuator, they meet and complete a circuit. The output is a clean two-state signal: contact or no contact.
Nothing about that is difficult. What is difficult, and what causes most of the trouble students meet with switches, is reading one correctly.
Why a switch needs a resistor
A switch has two states, but a pin wired to a switch alone has three. When the switch is closed the pin is firmly connected to whatever the other side of the switch goes to. When the switch is open the pin is connected to nothing at all — the floating input of section 13.5.2, drifting under electrical noise and reading HIGH and LOW at random.
The cure is to give the pin something to hold on to when the switch is open. A pull-up resistor connects the pin to the supply through a high resistance, typically a few tens of kilohms. With the switch open, that resistor gently holds the pin at the supply voltage, so it reads HIGH. With the switch closed, the pin is connected directly to ground, which wins easily against a resistor of tens of kilohms, so it reads LOW. Fig. 13.9-1 shows the arrangement.
Diagram
Fig. 13.9-1 – circuit: a push switch wired to an Arduino UNO; one terminal of the switch to digital pin 4, the other terminal to a GND pin; a resistor of about 20 kΩ drawn inside a dashed box labelled internal pull-up resistor, connecting pin 4 up to the 5V rail; the 5V rail and the GND rail drawn as horizontal lines and labelled; two annotations, one reading switch open: pin held at 5 V, reads HIGH, and one reading switch closed: pin pulled to 0 V, reads LOW
Notice that the logic is inverted: pressing the switch makes the pin read LOW, not HIGH. This surprises everyone the first time and is worth stating in a comment in your own programs.
Microcontrollers include pull-up resistors on their pins, which can be switched on in software, so the resistor in Fig. 13.9-1 usually does not have to be fitted physically.
Contact bounce
Watch a switch closing with fast enough instruments and it does not close once. The metal contacts strike, separate slightly, strike again, and settle after a few milliseconds of chatter. This is contact bounce, and Fig. 13.9-2 shows what a pin sees during it.
Diagram
Fig. 13.9-2 – a voltage-against-time trace for a pin with an internal pull-up as a switch closes; the trace starts at 5 V labelled switch open, then drops and rises several times in rapid succession over a span marked with a double-headed arrow labelled bounce, typically a few milliseconds, before settling steadily at 0 V labelled switch closed; a dashed vertical line marking the end of a debounce interval, annotated read the state only after this point
To a human that chatter is invisible. To a controller executing thousands of instructions per millisecond, it is a series of separate presses and releases, and a program that counts bumps will count five where there was one.
The remedy is debouncing: ignoring changes until the reading has stayed the same for a settling period, typically 10 ms to 50 ms, and only then accepting it as genuine.
13.9.2 Types of Touch Sensors
Mechanical switches. A micro-switch or a limit switch — a switch with a lever or roller actuator, placed to be struck at a particular point of travel — gives a plain two-state output. These are the commonest tactile sensors in robotics, used for collision detection, for marking the end of a joint’s travel and for enforcing mechanical limits.
Resistive tactile sensors. A force-sensitive resistor (FSR) is a thin flexible polymer whose resistance falls as pressure on it increases. Read with a simple resistor network into an analogue pin, it gives an approximate measure of how hard the contact is, not merely that it happened.
Capacitive touch sensors. These detect the change in electrical capacitance caused by a conductive object, such as a human hand, coming close. They respond to a very light touch or even to proximity, since no actual force is needed, and they are the technology behind touch panels. On a robot they are used where a person’s touch should stop or wake the machine.
Piezoelectric sensors. The same piezoelectric effect that drives an ultrasonic transducer works here in reverse: a disc produces a voltage spike when it is struck or deformed. This makes it an excellent detector of knocks and vibration and a poor detector of a steady weight, because it responds to changes in force rather than to force itself.
Strain-gauge and optical arrays. Fine strain gauges or small optical elements measure the deformation of a surface at many points, giving a picture of how pressure is distributed across it rather than a single number. These appear in the fingertips of advanced robotic hands.
Whiskers. A flexible wire or rod is mounted so that touching an obstacle bends it, and the bending is measured, often by a potentiometer or strain sensor. A whisker reaches ahead of the robot’s body, so contact is made before the chassis itself arrives.
Photograph
Fig. 13.9-3 – a lever-actuated microswitch photographed at close range on a plain background, with the hinged metal lever, the plunger it presses and the three solder terminals all clearly visible and distinguishable. Sourcing note: the lever must be visibly separate from the body so the actuating action is understandable; a switch photographed already soldered into a crowded board is unusable.
13.9.3 Characteristics
Two-state or analogue. A mechanical switch gives a plain digital event; a force-sensitive resistor or a piezoelectric element gives an analogue value that varies with the force. The choice decides whether the robot learns that it touched something or how hard.
Force range and sensitivity. A micro-switch needs a definite actuation force to click over, often of the order of 50 g. Force-sensitive resistors respond across a range from a few hundred grams to several kilograms, but their response is not a straight line and is not precise. Piezoelectric elements are extremely sensitive to small rapid changes and useless for a steady load.
Resolution. Analogue tactile sensors distinguish a light touch from a firm press quite comfortably. They are not measuring instruments, and a robot that needs an accurate force reading requires a calibrated load cell or a strain gauge rather than an FSR.
Durability. Mechanical switches are robust but have a finite number of operations before the contacts fail, and a bumper struck thousands of times will eventually need replacing. FSRs wear out if repeatedly flexed. Capacitive sensors have no moving parts and last well, but they are sensitive to electrical noise and may need recalibrating as humidity changes.
Latency. Response is essentially instantaneous — the contact either exists or it does not. The only delay is the settling period deliberately added for debouncing, and for a mechanical switch that is the whole of its response time.
13.9.4 Applications, Advantages and Limitations
13.10 Gyroscope Sensors
Every sensor so far has looked outward. The last two look inward, and they answer a question no outward-looking sensor can: what is the robot itself doing?
Consider a two-wheeled robot commanded to turn ninety degrees. It slows one wheel for the calculated time and stops. Did it turn ninety degrees? On a smooth floor, roughly. On a carpet where one wheel slipped, not at all — and nothing in the robot’s wheels or motors has any idea, because the motors did exactly what they were told.
A gyroscope answers that question by measuring the rotation itself rather than the commands that were meant to cause it.
13.10.1 Working Principle
A gyroscope sensor measures angular velocity: how fast the device is rotating, in degrees per second (°/s) or radians per second (rad/s), about one or more axes. On a robot those axes are usually named as in Fig. 13.10-1.
Diagram
Fig. 13.10-1 – a small wheeled robot drawn in perspective with three mutually perpendicular axes through its centre; the axis pointing forward labelled x with a curved arrow around it labelled roll; the axis pointing to the side labelled y with a curved arrow labelled pitch; the vertical axis labelled z with a curved arrow labelled yaw; a note that a wheeled robot turning left or right on a flat floor is rotating about the z axis
Read the units again, because they contain the sensor’s single most important property. A gyroscope reports a rate, not a position. Held perfectly still at any angle — upright, tilted, upside down — it reports zero, because it is not rotating. It tells you that you are turning; it never tells you which way you are facing.
The Coriolis effect
Modern robotic gyroscopes are microelectromechanical systems (MEMS) devices: tiny mechanical structures etched into silicon alongside the circuitry that reads them, all in a chip a few millimetres across.
Inside is a small mass suspended on microscopic springs, which the chip keeps vibrating steadily back and forth along one direction. When the chip is rotated about an axis perpendicular to that vibration, the vibrating mass is deflected sideways, at right angles both to its vibration and to the rotation.
The sideways deflection is minute, but it is proportional to the rate of rotation. Capacitive sensing fingers on the chip detect it, and an on-chip circuit amplifies the signal, corrects it for temperature and delivers a calibrated number. Fig. 13.10-2 shows the structure in principle.
Diagram
Fig. 13.10-2 – a square outline labelled MEMS gyroscope chip; a small block at the centre labelled vibrating mass, suspended by four zig-zag lines labelled micro-springs; a double-headed straight arrow through the mass labelled driven vibration; a curved arrow around the chip labelled rotation Ω; a short arrow from the mass perpendicular to the driven vibration labelled Coriolis deflection, proportional to Ω; two sets of interleaved comb-like lines beside the mass labelled capacitive sensing fingers, with an arrow leading from them to a small block labelled on-chip processing and digital output
The reading leaves the chip as a number over a communication protocol such as I2C or SPI, one value per axis, so a controller reads it as data rather than as a voltage.
Turning a rate into an angle
If a gyroscope reports how fast the robot is turning, and you keep track of that over time, you can work out how far it has turned. Rate multiplied by time gives angle, and for a rate that changes, the total angle is the accumulated sum of the small angles turned in each short interval.
\[\theta = \sum \omega \, \Delta t\]
Here \(\theta\) is the angle turned in degrees (°), \(\omega\) is the angular velocity read at each sample in degrees per second (°/s), and \(\Delta t\) is the interval between samples in seconds (s). This accumulation is called integration, and it is what lets a gyroscope be used for heading.
It also carries a hidden cost, which the worked example below makes plain.
13.10.2 Characteristics
Output. The sensor reports the rate of turn about each of its axes, signed so that the sign gives the direction of rotation. A robot turning at 90 °/s to the right shows about +90 °/s on the vertical axis, depending on how the chip is mounted. Stationary, it shows approximately zero.
Range. Devices offer selectable full-scale ranges such as ±250 °/s, ±500 °/s and ±2000 °/s. A narrower range gives finer resolution but saturates if the robot spins faster than the limit, at which point the reading sticks at the maximum and all information about the real rate is lost. Choose the range from the fastest rotation the robot will genuinely perform.
Resolution. A 16-bit output spread across a ±250 °/s range divides 500 °/s into \(2^{16} = 65536\) codes, giving about \[\frac{500\ \text{°/s}}{65536} = 0.0076\ \text{°/s}\] per code. Rotations far too slow to see are therefore well within the device’s power to detect.
Noise and zero-bias drift. A gyroscope’s reading when it is perfectly still is not exactly zero, and worse, that false offset itself wanders slowly with temperature and time. This is zero-bias drift, and it is the defining weakness of the device. It matters so much precisely because of the integration in section 13.10.1: noise averages out over many samples, but a bias does not — it accumulates without limit. A good MEMS device may drift by only a few degrees per hour; a poor or uncalibrated one can drift by several degrees per second, which makes its integrated heading worthless within a minute.
Fig. 13.10-3 shows what this looks like on a robot that is not moving at all.
Diagram
Fig. 13.10-3 – a graph with time in seconds on the horizontal axis and computed heading in degrees on the vertical axis; a horizontal solid line at 0° labelled true heading, robot stationary; a second line starting at 0° and rising steadily away from it, labelled heading computed by integrating the gyroscope; the widening vertical gap between the two lines labelled accumulated drift error, with an arrow showing it growing with time
Bandwidth. Gyroscopes respond quickly and can be sampled at high rates, which is what makes them suitable for balancing and flight stabilisation where a correction is needed within milliseconds.
Sensitivity to vibration. The sensing element is a vibrating mass, so external vibration reaching the chip can be read as rotation. On a robot with an unbalanced wheel or a hard-mounted motor this produces a restless, noisy signal, and the usual remedy is mechanical — mounting the board on a soft pad rather than bolting it rigidly to the chassis.
13.10.3 Applications, Advantages and Limitations
The limitation that matters most is the second one. A gyroscope is a superb short-term instrument and a hopeless long-term one, and everything about how it is used follows from that. The next section supplies exactly what it lacks.
13.11 Accelerometers
Sit in a bus with your eyes closed. You cannot tell how fast it is going, but you know exactly when it pulls away and when it brakes, and you know which way up you are. Steady motion is invisible to you; changes in motion, and gravity, are not.
An accelerometer senses in precisely that way, and the two things it can report — changes in motion and the direction of gravity — turn out to be the two things a gyroscope cannot supply.
13.11.1 Working Principle
An accelerometer measures acceleration, the rate at which velocity is changing, along one or more axes. Devices used in robotics are three-axis, reporting along the x, y and z directions of the chip.
Readings are given either in metres per second squared (m/s²) or in units of g, where 1 g is the acceleration due to gravity, 9.81 m/s². The g unit is convenient because the sensor’s most common reading is exactly that.
Inside, a MEMS accelerometer is a tiny mass suspended on silicon springs. When the chip accelerates, the mass lags behind, because inertia resists any change in its motion, and this lag deflects the springs. Interleaved fingers on the mass and on the fixed frame form small capacitors whose value changes as the mass moves, and the chip’s electronics convert that change into a number.
Diagram
Fig. 13.11-1 – a square outline labelled MEMS accelerometer chip; a block at the centre labelled proof mass suspended by four zig-zag lines labelled springs; a bold arrow outside the chip labelled acceleration of the chip pointing right; the proof mass drawn slightly displaced to the left of centre, annotated the mass lags behind, deflecting the springs; interleaved comb-like fingers between the mass and the frame labelled capacitive sensing fingers, with the gap on one side shown narrower than on the other; an arrow from the fingers to a small block labelled on-chip processing and digital output
Why a stationary sensor does not read zero
Here is the property that makes an accelerometer useful for orientation, and it takes a moment to accept.
Place the chip flat on a table, motionless. Its vertical axis reads about +1 g, not 0. The chip is not accelerating anywhere, but the table is pushing up on it to hold it against gravity, and it is that support the suspended mass responds to. Tip the chip on its side and the +1 g moves to a different axis.
So the readings of a stationary accelerometer form a vector of fixed length 1 g that always points along the vertical, however the chip is turned. Measuring which way that vector lies within the chip’s own axes tells you how the chip is tilted — an absolute reference no gyroscope can provide.
13.11.2 Characteristics
Range. Devices offer full-scale ranges such as ±2 g, ±4 g, ±8 g and ±16 g. For tilt sensing and gentle movement, ±2 g is enough and gives the finest resolution. A drone or a jumping robot may need ±8 g or more so that the reading does not saturate during a fast manoeuvre or an impact.
Resolution. A 16-bit device set to ±2 g spreads 4 g across \(2^{16} = 65536\) codes: \[\frac{4\ \text{g}}{65536} = 0.000061\ \text{g} = 0.061\ \text{mg}\] This is far finer than any robot needs for tilt, and it is why an accelerometer distinguishes 1 g upward from 1 g downward, and every angle between, without difficulty.
Static and dynamic acceleration together. This is the accelerometer’s central difficulty. Its readings contain the effect of gravity and the effect of the robot’s own motion added together, and the device cannot separate them. A robot sitting on a 20° slope and a robot accelerating hard on level ground can produce very similar readings. On a curved path the mixture is worse still. The tilt calculation of section 13.11.1 is therefore trustworthy only when the robot is still or moving steadily — which is exactly when a robot is least interesting.
Noise and vibration. Accelerometers pick up vibration readily, and on a robot with running motors the reading jitters constantly. Averaging several samples smooths this at the cost of a slower response. Like all MEMS devices they also carry a small bias that varies with temperature.
13.11.3 Applications, Advantages and Limitations
Read the last limitation together with the last limitation of section 13.10.3, and the reason for the next subsection becomes obvious. Neither device can do the job alone.
13.11.4 Combining a Gyroscope and an Accelerometer
Set the two sensors side by side and their weaknesses are complementary, which is an unusually convenient thing for two sensors to be.
Look along the two rows about short and long intervals. The gyroscope is excellent over a second and untrustworthy over a minute. The accelerometer is unreliable second by second but correct on average over a minute. Combining them so that each covers the other’s failing is called sensor fusion, and the usual arrangement takes the fast-changing part of the estimate from the gyroscope and slowly corrects it towards the tilt that the accelerometer reports, so the drift is continually pulled back to the vertical without the accelerometer’s jitter reaching the output.
A package containing both, and sometimes a magnetometer as well, is called an inertial measurement unit (IMU). Fig. 13.11-2 shows how the two paths are brought together.
Diagram
Fig. 13.11-2 – block diagram of an inertial measurement unit; a block labelled gyroscope with an arrow to a block labelled integrate rate to give angle, annotated fast and smooth, drifts over time; a block labelled accelerometer with an arrow to a block labelled compute tilt from the direction of gravity, annotated no drift, but noisy and disturbed by movement; both arrows converging on a block labelled sensor fusion; a single arrow leaving it labelled estimated orientation; a dashed boundary drawn around all the blocks labelled inertial measurement unit
A balancing robot shows the whole arrangement working. It must know its lean angle within a few milliseconds or it falls over, which rules out the accelerometer alone, since its readings are thrown about by the very corrections the robot is making. It must also still know its lean angle after ten minutes of balancing, which rules out the gyroscope alone. Fused together, they hold it upright.
13.12 Matching the Sensor to the Task
Six sensors have been described, and not one of them has been declared the best. That was deliberate. A sensor is not good or bad in itself; it is suited or unsuited to a particular job in particular conditions, and the engineering skill this chapter has been building towards is deciding which.
The decision is made by asking five questions, in this order.
What physical quantity do you actually need?
Beginners ask “which sensor should I use?” before deciding what they need to know, and end up fitting whatever the kit contains. Ask instead: does the robot need a distance, a presence, a direction, a contact, a tilt or a rate of turning?
The answer eliminates most of the list immediately. A robot that must stay level needs an accelerometer and no amount of ultrasonic ranging will help. A robot that must confirm it has actually gripped something needs a touch sensor, not a rangefinder.
Over what range, and with what precision?
A line follower reads a surface a centimetre below itself; an IR sensor is the obvious answer and a LIDAR would be absurd. A warehouse robot planning a route across a hall needs metres of range with real bearing information, and only a LIDAR provides it. Between them sits the ultrasonic sensor’s few metres of coarse, cheap distance.
Precision matters separately from range. “Is there something in front of me?” needs far less precision than “how far is that pallet, to the centimetre?”, and paying for precision you do not need is one of the commonest design mistakes.
How fast must the reading arrive?
Section 13.1.3 established why: the robot travels while the loop runs. An IR sensor answers in microseconds, an ultrasonic module takes tens of milliseconds because it must wait for sound to come back, and a scanning LIDAR delivers a complete picture five to fifteen times a second. A robot moving quickly cannot be steered by a slow sensor, whatever else that sensor’s merits.
What are the conditions?
This is where most sensor choices are actually decided, and Table 13.11 sets out what each of the outward-looking devices is defeated by.
Read down the “blind to” row rather than across the table. It is the row that decides real installations, because a sensor that is excellent in the laboratory and blind to the one obstacle your building contains is not excellent at all.
For the inward-looking pair the same question is asked differently. A gyroscope is chosen when a fast, smooth rate of turning is needed and the interval is short; an accelerometer when an absolute reference to the vertical is needed and the robot is reasonably steady; and in almost every real robot, both are chosen together for the reasons set out in section 13.11.4.
What can you afford — in money, power, and computing?
Cost is the obvious constraint and rarely the binding one on a school robot. Power and computing are subtler. A LIDAR spins a motor, drives a laser and produces thousands of readings a second, all of which the robot must carry the battery and the processor for. Fitting a sensor whose output the controller has no time to read is worse than fitting nothing, because it consumes the loop that the rest of the robot depends on.
Using more than one
Notice how often the answers above conflict: cheap and blind to glass, or accurate and expensive; fast and short-range, or long-range and slow. The usual resolution is not to find a perfect sensor but to use two imperfect ones whose failures do not coincide.
A delivery robot in a hospital corridor might carry a LIDAR for planning its route, downward IR sensors to catch the edge of a stairwell, ultrasonic sensors to notice a glass door the LIDAR beam passes straight through, and a bumper for everything else. Each covers a specific blindness of another, and the bumper covers all of them at once, at the cost of a collision that has already happened.
That is the layered arrangement worth remembering: distant sensing for planning, close sensing for reacting, and contact sensing as the fail-safe that assumes both of the others have failed.
Closing the loop
Every choice in this section eventually returns to the cycle in Fig. 13.1-2. Sensors decide what a robot can know, motors decide what it can do, and the program in between decides how well the one is turned into the other.
The two halves are not independent. A fast motor demands a fast sensor, because the robot covers more ground during each pass of the loop. A sensor that is vague about direction demands a cautious speed, because the robot cannot steer around what it cannot locate. And a robot whose actuator has no feedback of its own — the DC motor of section 13.2 — depends entirely on external sensors to discover whether what it commanded actually happened.
Choosing the motors and choosing the sensors are therefore one decision, not two.
13.13 Summary
Actuators and sensors
- A robot both acts on the world and perceives it. The parts that act are actuators; the parts that perceive are sensors.
- An actuator converts supplied energy, usually electrical, into a controlled mechanical movement. A rotary actuator’s output is described by its speed, in rpm or rad/s, and its torque, \(\tau = F \times d\), in N·m.
- No actuator converts all its electrical energy into useful movement; the remainder becomes heat. Actuators draw far more current than logic circuits and therefore need their own power arrangements.
- A sensor detects a physical quantity and converts it into an electrical signal the controller can read. The part that performs the conversion is the transducer.
- No sensor measures the quantity you actually want. It measures a proxy — a returned intensity, an echo time, a deflection — from which the wanted quantity must be worked out. Calibration is what makes that step correct for the particular device, surface and setting.
- Of the six sensors studied, IR, ultrasonic, LIDAR and touch report on the environment; gyroscopes and accelerometers report on the robot’s own motion.
- A robot repeatedly senses, decides and acts, and its own action changes what there is to sense next. Latency, the total delay round this sense–plan–act loop, decides what the robot is physically able to avoid.
The DC motor
- A DC motor runs on direct current and produces continuous rotation. It consists of a stator providing the magnetic field, a rotor carrying the armature windings, a commutator and brushes.
- Its working principle is the force on a current-carrying conductor in a magnetic field. Opposing forces on the two sides of an armature coil produce a torque about the shaft.
- The commutator and brushes reverse the current in each coil twice per revolution, so the torque always acts in one direction and rotation continues. This sliding contact is also what wears out and what generates electrical noise.
- The voltage equation is \(V = E_b + I_a R_a\). Back emf grows with speed, so a fast-spinning motor draws little current and a stalled motor draws its maximum.
- The torque equation is \(\tau = k\Phi I_a\): torque is proportional to armature current. A loaded motor slows, its back emf falls, its current rises, and the extra torque follows.
- The speed relation is \(N \propto (V - I_a R_a)/\Phi\). For a permanent-magnet motor, speed follows the applied voltage — which is what makes speed control possible.
- Speed falls almost linearly as load torque rises. The no-load speed and the stall torque are the two ends of that line; the stall current flows at the stall end and overheats the motor.
- A gearmotor divides speed by the gear ratio and multiplies torque by nearly the same ratio, which is what allows a small motor to move a robot.
- A motor is never wired to a controller pin, which can supply only about 20 mA. A motor driver containing an H-bridge switches the motor’s current from the battery and allows reversal without rewiring.
- Speed is set by pulse width modulation: the pin switches fully on and off rapidly, and the duty cycle fixes the average voltage the motor responds to.
- A DC motor runs open loop. It has no means of reporting where its shaft is, so it suits continuous rotation and not position holding.
The servo motor
- A servo motor contains a motor, a gear train, a position sensor and a control circuit, and rotates its output shaft to a commanded angle within a limited range — about 180° for a standard hobby servo — holding it against a load.
- A potentiometer coupled to the output shaft reports the actual position. The control circuit subtracts it from the commanded position and drives the internal motor in whichever direction reduces the error.
- This is closed-loop control: the measured output is compared with the desired value and the difference drives the correction. Its quality depends entirely on the quality of the measurement.
- The command arrives as a pulse repeated about every 20 ms, that is at about 50 Hz. The angle is encoded in the pulse width — typically about 1.0 ms for one extreme, 1.5 ms for the centre and 2.0 ms for the other extreme.
- A servo is specified by its range of travel, its transit time for 60°, its holding torque and its deadband, the small error it does not act on. Its current rises with load and becomes large if the shaft is obstructed.
- A servo is closed loop inside its own case and open loop as far as the program is concerned: the controller commands an angle and is never told whether it was reached.
Choosing between the two motors
- Continuous rotation with no particular final position — wheels, conveyors, pumps, propellers — is a DC motor. Movement to a stated angle and holding it — joints, grippers, steering, camera mounts — is a servo motor.
- The remaining questions are whether the torque is available at the speed required, whether the supply matches and can deliver the stall or loaded current, and how much control complexity is being taken on.
- A DC motor with an encoder can do a servo’s job with more range and speed, at the cost of substantially more engineering.
Reading a sensor
- Sensor outputs take four forms: a two-state digital level, an analogue voltage, a timed pulse, or digital data over a communication protocol such as
UART,I2C,SPIorCAN. - An analogue-to-digital converter turns a voltage into a number. The Arduino UNO’s is 10-bit, giving 1024 codes across 5 V, so one step is about 4.88 mV.
- An unconnected input pin floats and returns meaningless, wandering readings; it does not return zero.
- Every sensor is described by its range, its resolution, accuracy and repeatability, its response time, and its noise and drift. Noise makes readings jitter around the truth and can be averaged out; drift moves the truth itself and cannot.
The six sensors
- An IR sensor emits infrared from an LED and measures how much returns to a photodiode or phototransistor. It reports returned intensity, which depends on distance, colour, finish and angle together — so a dark surface close by reads like a pale one far away. Emitters are usually modulated so that steady ambient infrared can be rejected. A passive infrared sensor emits nothing and responds instead to changes in the heat radiated by warm bodies, detecting movement rather than presence.
- An ultrasonic sensor emits a burst of about 40 kHz sound and times its echo, giving \(d = v\Delta t/2\); the halving accounts for the sound covering the distance twice. It is indifferent to colour and lighting and detects glass and dark matt surfaces, but it has a blind zone of a few centimetres, a wide cone that gives poor directionality, and a slow response because sound is slow. Its accuracy depends on the speed of sound, which changes with air temperature.
- A LIDAR times a laser pulse by the same relation with the speed of light, so it needs nanosecond-scale electronics of its own. Sweeping the beam pairs each distance with an angle, building a point cloud, which is what makes mapping and SLAM possible. It is precise and directional and expensive, sees only the first surface along each beam, and degrades in fog, smoke and dust.
- A touch sensor reports contact rather than measuring at a distance. A switch needs a pull-up resistor so the pin has a defined voltage in both states, and needs debouncing because contacts chatter for a few milliseconds when they close. Types include mechanical switches, resistive force-sensitive resistors, capacitive sensors, piezoelectric elements, strain-gauge and optical arrays, and whiskers. It cannot be fooled by a surface, and it learns nothing until the collision has already happened.
- A gyroscope measures angular velocity using the Coriolis deflection of a vibrating mass in a MEMS chip. It reports a rate, never an absolute orientation. An angle obtained by accumulating \(\theta = \sum \omega \Delta t\) is smooth and accurate over short intervals, but zero-bias drift accumulates in the sum and makes it worthless over long ones.
- An accelerometer measures linear acceleration from the deflection of a proof mass on silicon springs. A stationary device senses 1 g along the vertical, which gives an absolute tilt reference that does not drift; but it cannot separate gravity from the robot’s own motion, so its tilt reading is trustworthy only when the robot is still or moving steadily.
- The gyroscope and the accelerometer fail in opposite ways, so they are combined by sensor fusion in an inertial measurement unit — the gyroscope supplying fast smooth changes, the accelerometer continually correcting the estimate back towards the true vertical.
Matching sensor to task
- Choose a sensor by asking what quantity is needed, over what range and precision, how quickly the reading must arrive, what conditions it must survive, and what can be afforded in money, power and computing.
- What defeats each sensor matters more than what each sensor does well, because a device that is blind to the one obstacle in your building is not suitable however good its specifications are.
- Real robots layer sensors so that their blindnesses do not coincide: distant sensing for planning, close sensing for reacting, and contact sensing as the fail-safe that assumes both of the others have failed.
- Choosing motors and choosing sensors is one decision. A fast actuator demands a fast sensor, a vague sensor demands a cautious speed, and an open-loop actuator depends entirely on external sensing to confirm that what was commanded actually happened.
13.14 Key Terms
- Accelerometer — a sensor that measures linear acceleration along one or more axes, including the effect of gravity, from the deflection of a small suspended mass.
- Actuator — a component that converts supplied energy, usually electrical, into a controlled mechanical movement of a part of the robot.
- ADC (analogue-to-digital converter) — a circuit inside the microcontroller that measures the voltage on an analogue pin and reports it as a whole number.
- Analogue output — a sensor output that is a voltage varying continuously with the quantity being measured.
- Angular resolution — the angle between one measurement and the next as a scanning sensor sweeps its beam round.
- Angular velocity — the rate at which something is rotating about an axis, measured in °/s or rad/s.
- Armature — the set of current-carrying coils on the rotor of a DC motor, on which the turning force acts.
- Back emf (back electromotive force) — the voltage induced in a motor’s armature by its own rotation, which opposes the applied supply and grows with speed.
- Blind zone — the region immediately in front of an ultrasonic sensor, within which an object is too close to be measured at all.
- Brushes — the fixed carbon blocks pressed against the commutator, through which current enters and leaves the rotating armature.
- Calibration — adjusting how a sensor’s raw reading is interpreted, by comparing it against known values under the conditions in which it will be used.
- Closed-loop control — control in which the actual output is measured, compared with the desired value, and the difference used to drive the system towards it.
- Commutator — the ring of insulated copper segments on a motor shaft that reverses the current in each armature coil at the right instant to sustain rotation.
- Contact bounce — the rapid chatter of a mechanical switch’s contacts as they open or close, lasting a few milliseconds.
- Coriolis effect — the apparent sideways deflection of an object moving within a rotating frame of reference, used by a gyroscope to sense rotation.
- DC motor (direct current motor) — an electric motor that runs on direct current and produces continuous rotation of its shaft.
- Deadband — the small range of error inside which a servo’s control circuit takes no corrective action.
- Debouncing — ignoring changes in a switch reading until it has stayed the same for a settling period, so that one press is counted once.
- Digital output — a sensor output having only two states, high or low, usually produced by comparing a measurement against a threshold.
- Drift — a slow systematic wandering of a sensor’s reading over time or with temperature, even when the measured quantity has not changed.
- Duty cycle — the fraction of each cycle of a switching signal for which it is high, usually stated as a percentage.
- Encoder — a device fitted to a rotating shaft that produces pulses as it turns, so that counting them gives the angle turned and timing them gives the speed.
- Error — in a control system, the difference between the commanded value and the actual measured value.
- Feedback — information about a system’s output returned to influence its input.
- Field of view — the cone within which a sensor responds to an object.
- Floating input — an input pin connected to nothing, whose voltage drifts under electrical noise so that its readings are meaningless.
- FSR (force-sensitive resistor) — a thin flexible component whose resistance falls as the pressure applied to it increases.
- Gearmotor — a DC motor with a gear train on its output shaft, which divides the speed and multiplies the torque.
- Gyroscope — a sensor that measures the rate at which the device is rotating about one or more axes.
- H-bridge — an arrangement of four switching elements in a motor driver that allows current to be passed through a motor in either direction.
- IMU (inertial measurement unit) — a package containing a gyroscope and an accelerometer, and sometimes a magnetometer, whose readings are combined to estimate orientation.
- IR sensor (infrared sensor) — a sensor that emits infrared light and measures how much of it returns, or that responds to infrared radiated by warm bodies.
- Latency — the total delay between an event occurring in the world and the robot’s response to it appearing at its actuators.
- LIDAR (light detection and ranging) — a sensor that measures distance by timing a laser pulse, usually sweeping the beam so that each distance is paired with the angle at which it was taken.
- Limit switch — a switch with a lever or roller actuator, placed to be struck at a particular point of a mechanism’s travel.
- MEMS (microelectromechanical systems) — tiny mechanical structures etched into silicon alongside the circuitry that reads them.
- Modulation — flashing a sensor’s emitter at a fixed frequency so that the receiver can respond only to that flicker and ignore steady ambient light.
- Motor driver — a circuit that receives a low-current control signal from a controller and switches the motor’s much larger current from the battery.
- No-load speed — the speed a motor’s shaft reaches at a given supply voltage with nothing attached to it.
- Noise — the random fluctuation present in every sensor reading, which can be reduced by averaging.
- Open-loop control — control in which the output is commanded but never measured, so the system cannot detect whether the command was achieved.
- PIR sensor (passive infrared sensor) — a sensor that emits nothing and detects changes in the infrared radiated by warm bodies, so reporting movement rather than presence.
- Point cloud — the set of points produced by a scanning sensor, each marking a surface at a measured distance and angle.
- Potentiometer — a resistor with a sliding contact whose resistance varies with the contact’s position, used inside a servo to report shaft angle.
- Pull-up resistor — a high-value resistor connecting an input pin to the supply, so that the pin has a defined voltage when the switch is open.
- PWM (pulse width modulation) — switching a signal fully on and off rapidly and varying the proportion of time spent on, so as to set an average voltage.
- Response time — how long a sensor takes to produce a valid reading after the measured quantity changes or after it is asked.
- Rotor — the rotating part of a motor, carrying the armature and fixed to the shaft.
- Sense–plan–act loop — the repeating cycle in which a robot senses its situation, decides on an action, commands its actuators, and senses again.
- Sensor — a device that detects a physical quantity and converts it into an electrical signal the controller can read.
- Sensor fusion — combining the readings of two or more sensors so that each covers the other’s weakness.
- Servo motor — a packaged actuator that rotates its output shaft to a commanded angle within a limited range and holds it there against a load.
- SLAM (simultaneous localisation and mapping) — building a map of an unknown space while at the same time working out one’s own position within it.
- Stall current — the current a motor draws when its shaft is held still, the largest current it will take.
- Stall torque — the torque at which a motor’s shaft stops turning altogether, the hardest it will push.
- Stator — the stationary part of a motor, which provides the magnetic field.
- Threshold — a set level against which a measurement is compared to produce a two-state output.
- Time-of-flight — the interval between sending a pulse and receiving its reflection, from which distance is calculated.
- Torque — the turning effect of a force about an axis, equal to the force multiplied by its perpendicular distance from the axis, measured in N·m.
- Touch sensor — a sensor that reports physical contact, and in some types how firm that contact is.
- Transducer — the part of a sensor that actually converts one form of energy into another.
- Ultrasonic sensor — a sensor that measures distance by emitting a burst of sound above the range of human hearing and timing its echo.
- Zero-bias drift — the slow wandering of a gyroscope’s reading away from zero when it is not rotating, which accumulates without limit when the reading is integrated.
13.15 Objective Questions
- A DC motor draws its largest current when
- it is spinning freely with no load
- its shaft is held so that it cannot turn
- its supply voltage is reduced to half
- its back emf is nearly equal to the supply voltage
- For a typical hobby servo receiving pulses every 20 ms, the pulse width that commands the centre of its travel is about
- 0.5 ms
- 1.0 ms
- 1.5 ms
- 2.0 ms
- Two statements are given below, one labelled Assertion (A) and the other labelled Reason (R). Select the correct option. Assertion (A): A gyroscope on its own cannot tell a stationary robot whether it is level or tilted. Reason (R): A gyroscope measures angular velocity, and reports approximately zero whenever the device is not rotating, whatever its orientation.
- Both A and R are true, and R is the correct explanation of A.
- Both A and R are true, but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
- Match each sensor in Column I with the physical quantity it responds to in Column II.
| Column I | Column II |
|---|---|
| a. Ultrasonic sensor | i. Rate of turning about an axis |
| b. Accelerometer | ii. Time taken by a sound pulse to return |
| c. Gyroscope | iii. Intensity of returned infrared light |
| d. IR sensor | iv. Linear acceleration, including that due to gravity |
- Fill in the blanks.
- The component that reverses the current in each armature coil of a DC motor to sustain rotation is the ____________.
- The fraction of each cycle for which a switching signal stays high is called the ____________.
- The region immediately in front of an ultrasonic sensor in which an object cannot be measured is called the ____________.
- Inside a servo motor, the actual position of the output shaft is reported by a ____________.
- State whether each of the following is true or false.
- An input pin left unconnected reads 0 when tested with
analogRead(). - An ultrasonic sensor gives the same reading for a white card and a black cloth placed at the same distance.
- A standard hobby servo can be used to drive a robot’s wheel continuously.
- Averaging many readings reduces noise but does not remove drift.
- Write the full form of each of the following abbreviations: PWM, ADC, LIDAR, IMU, MEMS, SLAM.
13.16 Check Your Concepts
Define torque and give its SI unit. State how the torque developed by a DC motor changes as its armature current increases, and name the quantity that falls as the motor is loaded and so allows that current to rise.
Differentiate between the accuracy and the repeatability of a sensor. Give one example of a situation in which a sensor is highly repeatable but poorly accurate, and explain why this combination is more dangerous than obvious random error.
Explain the working principle of a servo motor with the help of a labelled block diagram of its internal parts. Using your diagram, explain why a servo motor holds a commanded angle while a plain DC motor cannot.
Give reasons for the following.
- An ultrasonic sensor cannot measure an object placed 1 cm from its face.
- An IR proximity sensor that works well indoors becomes unreliable near a sunlit window.
- A common ground wire must be run between an Arduino UNO and an
L298Nmotor driver even though each has its own supply connection.
A gearmotor with an output speed of 150 rpm drives a wheel of diameter 70 mm mounted directly on its shaft. Assuming the wheel rolls without slipping, calculate the forward speed of the robot in m/s, and the time it would take to cross a 3.0 m corridor at that speed. State one reason why the measured time in the workshop is likely to be longer than your calculated value.
A robot is to move forward continuously and stop whenever an obstacle comes within 20 cm of its ultrasonic sensor. Write the algorithm for this behaviour, stating its input, its output and the boundary case it must handle, and then write the corresponding program for an Arduino UNO. State the board, the components and the complete wiring, including where the grounds are joined.
The elbow joint of a small robotic arm must move to any angle between 0° and 150° and hold that angle while the arm carries a light load. Compare a plain DC motor, a servo motor, and a DC motor fitted with an encoder against the criteria of position control, range of movement and engineering complexity. Recommend one of the three for this joint, and justify your recommendation with reasons drawn from all three criteria.
13.17 Diagram, Circuit & Output Reading
- A student wires a single BO gearmotor as follows.
- Motor terminals to
OUT1andOUT2of anL298Nmodule. - A 6 V battery pack: positive lead to the
+12Vterminal of theL298N, negative lead to theGNDterminal of theL298N. IN1of theL298Nto Arduino pin 7,IN2to pin 8,ENAto pin 9.- The Arduino UNO is powered from a USB cable, and nothing else is connected.
There is exactly one fault in this wiring. Identify it, state what the student is likely to observe when the program is run, and state the single connection that must be added.
- Study the following fragment, which forms part of a program running on an Arduino UNO with pin 9 wired to the enable input of a motor driver.
int total = 0;
for (int duty = 40; duty <= 200; duty += 40) {
analogWrite(9, duty);
total = total + duty;
Serial.println(total);
delay(500);
}- How many lines does the fragment print, and what exactly is printed on each?
- What value of
dutycauses the loop to end? - After the loop has finished, what PWM value remains on pin 9, and what is the motor doing?
- An
HC-SR04module on a robot returns the following echo pulse durations in five successive measurements, taken at 20 °C where the speed of sound is 0.0343 cm/µs. A returned value of 0 means the timing gave up before any echo arrived.
| Measurement | Echo pulse duration (µs) |
|---|---|
| 1 | 870 |
| 2 | 1750 |
| 3 | 0 |
| 4 | 1780 |
| 5 | 4900 |
- Calculate the distance reported by measurements 1, 2 and 5.
- State what measurement 3 tells the robot, and explain why treating it as a distance of 0 cm would be dangerous.
- Measurements 2 and 4 were taken with nothing in the scene moving. Name the sensor property that accounts for the difference between them.
- The table gives typical figures for two gearmotors offered to a school robotics team. The robot has a total mass of 1.8 kg, two driven wheels of diameter 65 mm, and a 6 V battery pack, and it must climb a ramp inclined at 12°. The motor driver available can supply 1.2 A per channel continuously.
| Specification | Motor P | Motor Q |
|---|---|---|
| Rated voltage | 6 V | 12 V |
| No-load speed at rated voltage | 200 rpm | 300 rpm |
| Stall torque at rated voltage | 0.078 N·m | 0.21 N·m |
| Stall current at rated voltage | 0.9 A | 1.6 A |
- Calculate the torque each drive motor must produce to hold the robot moving steadily up the ramp. Take \(g = 9.81\) m/s².
- State, with reasons drawn from the table, whether Motor P is a suitable choice.
- Motor Q has the larger stall torque. Give two separate reasons why it may still be the wrong choice for this robot.
13.18 Case-Based Questions
- A school robotics club builds a line-following robot to carry papers along a corridor between two rooms. The robot uses two BO gearmotors with an output speed of 200 rpm driving 65 mm wheels, an
L298Ndriver, a 6 V battery pack, and two IR modules with digital outputs mounted 8 mm above the floor at the front of the chassis, straddling a black tape line on a pale floor. The program reads both sensors, steers by slowing one wheel, and repeats every 20 ms.
Part of the corridor runs beside a large window and is in direct sunlight for much of the afternoon. A stairwell opens off the far end of the corridor.
- Calculate the robot’s forward speed in m/s and the distance it travels during one 20 ms pass of its sense–plan–act loop. Comment on whether that distance is small enough for the robot to correct its heading before leaving a 20 mm wide line.
- Explain what is likely to happen to the robot in the sunlit stretch of corridor, naming the sensor property responsible, and suggest one practical change to the robot that would reduce the problem.
- The club decides the robot must never reach the stairwell, even if the line is lost. Recommend one additional sensor for this purpose, state where it should be mounted and what it should report, and justify why the two IR line sensors already fitted are not sufficient.
- A warehouse plans a small delivery robot to run along an aisle 2.4 m wide. One side of the aisle is fitted with glass-fronted storage cabinets. Metal support poles about 5 cm across stand at intervals down the middle of the aisle. The team is considering a 2D scanning LIDAR with an angular resolution of 1.0° and a range of 12 m, and a set of ultrasonic modules with a range of 4 m.
- Calculate the spacing between adjacent LIDAR measurement points at a distance of 6.0 m, and state whether a 5 cm pole at that distance is certain to be detected. Show your working.
- Explain why the glass-fronted cabinets are a difficulty for the LIDAR, and state which of the two sensors under consideration handles them better and why.
- Recommend a set of sensors for this robot, giving for each one the job it does and the specific failure of another sensor that it covers. Include in your answer the reason a contact sensor is fitted even though both ranging sensors are present.