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.

NoteCuriosity Corner

Q1. A drive motor cannot simply be wired to a pin of a microcontroller. Why not, and what is placed between them? Q2. There is an ordinary DC motor inside a servo motor. Why, then, can a servo hold a commanded angle when a plain DC motor cannot? Q3. An infrared sensor pointed at the floor reports a staircase as “no floor”. Why does bright sunlight make the same sensor unreliable? Q4. If a robot already has an ultrasonic sensor that measures distance, why would a designer still fit a contact bumper? Q5. A gyroscope tells a machine how fast it is turning. Why does it still need an accelerometer to work out which way is up?

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.

NoteDefinition

An actuator is a component of a robot that converts supplied energy, usually electrical energy, into a controlled mechanical movement of a part of the robot.

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.

Q. If a motor is rated 6 V and my battery pack gives 6 V, is that enough to know the motor will work in my robot?

A. No. The voltage tells you the motor will not be damaged, but not that it will turn your robot. You also need to know the torque it can produce at that voltage and the current it will draw, because a pack that sags under a heavy current will fail even at the right voltage.

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.

NoteDefinition

A sensor is a device that detects a physical quantity in the robot’s environment or in its own motion and converts it into an electrical signal that the robot’s controller can read and interpret.

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.

Table 13.1 – the six sensor types studied in this chapter, the physical quantity each responds to, and whether it reports on the environment or on the robot’s own motion | Sensor | Physical quantity it responds to | Reports on | |—|—|—| | IR | Intensity of reflected or emitted infrared light | Environment | | Ultrasonic | Time taken by a sound pulse to return | Environment | | LIDAR | Time taken by a laser light pulse to return | Environment | | Touch | Physical contact, and sometimes contact force | Environment | | Gyroscopes | Angular velocity, the rate of turning about an axis | Own motion | | Accelerometer | Linear acceleration, including the acceleration due to gravity | Own motion |

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.

treating a sensor reading as the true value What students do: write a program that says “if the reading is less than 20, an obstacle is 20 cm away”, without ever checking the sensor against a measured distance. What happens: the robot behaves correctly against a white cardboard box and then drives straight into a dark cloth bag or a glass panel, because those surfaces return a different signal at the same distance. The fix: measure the sensor’s reading at several known distances against the surfaces you will actually meet, and set the threshold from those measurements. A reading is evidence about the world, not the world.

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.

the sense–plan–act loop Statement: A robot operates by repeatedly executing a cycle of three stages — sensing the current state of the environment and of itself, deciding on an action from those readings, and commanding its actuators to carry that action out. In words: Look, think, move, and then look again to see what your move did. Why it holds: A robot has no continuous knowledge of the world, only the readings it has just taken. Since its own actions change the world, any decision made from an old reading is a decision about a situation that no longer exists. Used for: Structuring the program of almost any robot, from a line follower to a planetary rover; separating a sensing fault from a decision fault from an actuation fault when something goes wrong. Watch out: The loop is only as good as its slowest stage. If any one stage is slow, the robot acts on stale information, and no improvement to the other two stages will fix it.

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.

NoteDefinition

A direct current (DC) motor is an electric motor that runs on direct current and converts electrical energy into continuous rotational mechanical energy at its shaft.

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.

the force on a current-carrying conductor in a magnetic field Statement: A conductor of length \(l\) carrying a current \(I\) placed in a magnetic field of flux density \(B\) experiences a force \(F = BIl\) when the conductor lies at right angles to the field. The direction of the force is perpendicular to both the current and the field. In words: Current across a magnetic field gets pushed sideways. Why it holds: The moving charges that make up the current are themselves deflected by the magnetic field, and because they are confined to the wire, the push on them is transmitted to the wire as a whole. Used for: Producing the turning force in every motor in this chapter, and, run in reverse, producing a voltage in a generator or in a wheel encoder. Watch out: The force is zero when the current runs along the direction of the field, and largest when it runs across it. This is why the shape of the pole pieces, which sets the field direction where the conductors pass, is part of the motor’s design and not decoration.

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.

Q. If torque is proportional to current, and current is highest when the motor is stalled, does that mean a stalled motor is producing its maximum useful work?

A. It is producing its maximum torque but no useful work at all, because work needs movement and the shaft is not moving. All the electrical energy going in is turning into heat in the armature winding, which is exactly why a motor left stalled will overheat and can be damaged.

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.

the road speed of a robot from its motor’s rated speed

Given: A gearmotor with an output speed of \(N = 200\) rpm (typical for a BO gearmotor at 6 V, running with no load); a wheel of diameter 65 mm mounted directly on the output shaft.

Find: The forward speed of the robot in metres per second (m/s).

Method: The wheel rolls without slipping, so one revolution of the wheel moves the robot forward by one circumference. Multiplying the circumference by the number of revolutions per second gives the speed. Radius \(r\) is half the diameter, so \(r = 32.5\) mm \(= 0.0325\) m.

\[\text{circumference} = 2\pi r = 2\pi \times 0.0325\ \text{m} = 0.2042\ \text{m}\]

\[\text{revolutions per second} = \frac{200}{60} = 3.333\ \text{s}^{-1}\]

\[v = 0.2042\ \text{m} \times 3.333\ \text{s}^{-1} = 0.681\ \text{m/s}\]

About 0.68 m/s.

Check: A person walks at roughly 1.4 m/s, so this is about half walking pace. That is fast but believable for a small robot on a smooth floor — and it is the no-load figure, so the loaded robot will be slower. A result of 68 m/s or 0.0068 m/s would have signalled an arithmetic slip immediately.

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.

connecting a motor straight to a controller pin What students do: wire one motor terminal to a digital pin and the other to GND, then call digitalWrite(pin, HIGH) and expect the wheel to turn. What happens: at best the motor twitches or hums because the pin cannot supply enough current; at worst the output driver inside the microcontroller is permanently damaged, and that pin — sometimes the whole board — stops working. The fix: the pin sends a low-current signal to a motor driver, and the driver switches the motor’s current from the battery. The controller commands; it never supplies.

Q1. A drive motor cannot simply be wired to a pin of a microcontroller. Why not, and what is placed between them?

A. Because a controller pin is built to deliver a signal of about 20 mA, while a motor needs hundreds of milliamperes to run and more than an ampere at stall — the pin would be destroyed long before the motor turned properly. A motor driver is placed between them. The pin sends a small control signal to the driver, and the driver, connected to the battery, switches the motor’s much larger current on and off and in either direction.

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

producing a PWM signal on an Arduino board

analogWrite(pin_number, duty_value);

Parts: pin_number is a pin capable of PWM output — on the Arduino UNO these are pins 3, 5, 6, 9, 10 and 11. duty_value is an integer from 0 to 255, where 0 is permanently off and 255 is permanently on. Returns / Effect: Returns nothing. The pin begins producing a square wave of fixed frequency whose duty cycle is duty_value / 255, and it continues to do so until changed. Example:

analogWrite(9, 128);    // roughly 50 per cent duty cycle on pin 9
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.

ramping the speed of a DC motor and reversing it Input: None from a sensor. The two direction lines and the enable line of one H-bridge on the L298N. Output: Rotation of the motor shaft, at a speed set by the duty value, in a direction set by the two direction lines. Method:

1. Configure the two direction pins and the enable pin as outputs.
2. Set the direction pins to the forward combination: one HIGH, the other LOW.
3. Set the duty value to 0.
4. Repeat while the duty value is not more than 255:
       a. Write the duty value to the enable pin as a PWM signal.
       b. Report the duty value.
       c. Wait one second so the change can be observed.
       d. Increase the duty value by 51.
5. Write 0 to the enable pin and set both direction pins LOW to stop.
6. Set the direction pins to the reverse combination: the first LOW, the second HIGH.
7. Write a mid-range duty value to the enable pin and wait two seconds.
8. Stop as in step 5, and return to step 2.

Why it works: The two direction pins decide which pair of switches in the H-bridge conducts, and therefore which way current passes through the motor. The enable pin’s PWM duty cycle sets the average voltage across the motor, and by the speed relation the average voltage sets the speed. Watch out: At very low duty values the average voltage is not enough to overcome friction, so the shaft does not move at all even though current is flowing and the motor is warming. Never reverse the direction pins while the enable pin is at a high duty value; bring the duty to 0 first, or the sudden reversal draws a very large current.

ramping a DC motor up in steps and then reversing it Problem: Drive one BO gearmotor forward, raising its speed in five equal steps from rest to full speed, stop it, then run it in reverse at about 60 per cent speed, reporting each stage on the serial monitor. Board and components: Arduino UNO; one L298N motor driver module; one BO gearmotor with a 65 mm wheel; one 6 V battery pack with holder; connecting wires. Wiring: - Motor terminals to OUT1 and OUT2 of the L298N. - Battery positive to the +12V terminal of the L298N; battery negative to the GND terminal of the L298N. - GND terminal of the L298N also to a GND pin of the Arduino UNO, so that the board and the driver share one common ground. Without this connection the driver has no reference against which to read the control signals, and the motor behaves erratically or not at all. - IN1 of the L298N to Arduino pin 7; IN2 to pin 8; ENA to pin 9, which is a PWM pin. - The ENA jumper on the module is removed so that pin 9 controls the enable input. - The 5V pin of the L298N is left unconnected; the Arduino UNO is powered from the USB cable during this exercise.

// Speed and direction control of one DC motor through an L298N driver.

const int IN1 = 7;      // direction input 1 of the driver
const int IN2 = 8;      // direction input 2 of the driver
const int ENA = 9;      // PWM enable input of the driver

void setup() {
    pinMode(IN1, OUTPUT);
    pinMode(IN2, OUTPUT);
    pinMode(ENA, OUTPUT);
    Serial.begin(9600);
}

// Runs the motor in the forward direction at the given duty value.
void driveForward(int duty) {
    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, LOW);
    analogWrite(ENA, duty);
}

// Runs the motor in the reverse direction at the given duty value.
void driveReverse(int duty) {
    digitalWrite(IN1, LOW);
    digitalWrite(IN2, HIGH);
    analogWrite(ENA, duty);
}

// Removes drive from the motor and lets it coast to rest.
void stopMotor() {
    analogWrite(ENA, 0);
    digitalWrite(IN1, LOW);
    digitalWrite(IN2, LOW);
}

void loop() {
    for (int duty = 0; duty <= 255; duty += 51) {
        driveForward(duty);
        Serial.print("Forward, duty = ");
        Serial.println(duty);
        delay(1000);
    }

    stopMotor();
    Serial.println("Stopped");
    delay(1000);

    driveReverse(153);
    Serial.println("Reverse, duty = 153");
    delay(2000);

    stopMotor();
    Serial.println("Stopped");
    delay(1000);
}

Sample output / observed behaviour: The serial monitor, set to 9600 baud, shows the following for one pass of loop(), after which the same lines repeat.

Forward, duty = 0
Forward, duty = 51
Forward, duty = 102
Forward, duty = 153
Forward, duty = 204
Forward, duty = 255
Stopped
Reverse, duty = 153
Stopped

The wheel stays still for the first line or two, then begins to turn slowly and gets visibly faster at each step until it is running at full speed. It coasts to rest, turns the other way at a moderate speed for two seconds, and stops again.

Identifier description:

[Table:] Table 13.2 – the identifiers used in the DC motor drive program, with their types and purposes | Identifier | Type | Purpose | |—|—|—| | IN1 | const int | Arduino pin number wired to the first direction input of the driver | | IN2 | const int | Arduino pin number wired to the second direction input of the driver | | ENA | const int | Arduino PWM pin number wired to the enable input of the driver | | duty | int | Duty value from 0 to 255 passed to analogWrite() to set the speed | | driveForward() | function | Sets the direction pins for forward rotation and applies the duty value | | driveReverse() | function | Sets the direction pins for reverse rotation and applies the duty value | | stopMotor() | function | Sets the duty value to 0 and clears both direction pins | [/Table]

Notes: The three pin numbers are declared as named constants rather than typed as bare numbers in each call, so that rewiring the robot means editing one line instead of hunting through the program. Direction and speed are deliberately kept in separate functions from the sequence in loop(), because that separation is what lets the same three functions be reused later when the duty value comes from a sensor rather than from a counting loop.

the for loop of the drive program, from the moment the board is reset

Pass duty at entry Condition duty <= 255 Pin 7 / Pin 8 PWM on pin 9 Line printed
1 0 true HIGH / LOW 0 (off) Forward, duty = 0
2 51 true HIGH / LOW 51 (about 20%) Forward, duty = 51
3 102 true HIGH / LOW 102 (40%) Forward, duty = 102
4 153 true HIGH / LOW 153 (60%) Forward, duty = 153
5 204 true HIGH / LOW 204 (80%) Forward, duty = 204
6 255 true HIGH / LOW 255 (fully on) Forward, duty = 255
— 306 false unchanged unchanged loop ends

Result: Six lines are printed and the loop exits when duty reaches 306, not 255, because the increment happens before the test. The trace also shows why the first pass produces no visible motion: a duty value of 0 leaves the enable input permanently low, so no current reaches the motor at all.

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

A robot placed on a bench with its wheels touching the surface will drive itself off the edge the moment the motor starts. Raise the chassis on a block so the wheels spin free, or run it on the floor. Keep fingers, hair and loose sleeves clear of the wheel and the gearbox, and always disconnect the battery before changing any wiring — a stray lead touching a terminal on a live driver can short the pack.

Change the increment in the for loop from 51 to 10 and run the program again with the wheels raised clear of the bench. Note the smallest duty value at which the wheel actually begins to turn, and repeat with a weight resting on the chassis. Explain why the two figures differ.

13.2.6 Applications, Advantages and Limitations

DC motor Working principle: Direct current is fed through the armature coils of a rotor placed in the magnetic field of the stator. Each current-carrying conductor experiences a force at right angles to the field, and the pair of opposing forces on the two sides of a coil produces a torque about the shaft. The commutator and brushes reverse the current in each coil twice per revolution, so the torque always acts the same way and rotation is continuous. Components: Stator with permanent magnets or a field winding, yoke or frame, rotor carrying the armature windings on a laminated core, commutator, carbon brushes, shaft and bearings; in a gearmotor, a gear train on the output shaft. Advantages: Simple to use, since a two-wire connection and a voltage are all it needs. Inexpensive, and available in a wide range of sizes. High power for its size and weight, giving compact drive assemblies. Responds quickly to a change of applied voltage, so it starts, stops and reverses rapidly. Reversal needs nothing more than swapping the polarity of the supply, which an H-bridge does electronically. Limitations: It runs in open-loop control — the motor has no built-in means of reporting where its shaft is or how fast it is turning, so it cannot by itself be commanded to a particular position. Achieving that needs an added encoder and extra control code. The brushes wear and eventually fail, and the sparking at the commutator generates electrical noise that can disturb nearby sensor circuits. Held at stall it draws a very large current and overheats quickly. Where it is used: Drive wheels of mobile robots, robot cars and rovers; conveyor belts and transport mechanisms in industrial systems; pumps, cooling fans and other continuously spinning subsystems; and, in its brushless form, the propeller motors of drones and quadcopters.

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.

the torque a drive motor must produce to climb a ramp

Given: A school robot of total mass \(m = 1.5\) kg; two driven wheels, each of diameter 65 mm, sharing the load equally; a ramp inclined at \(\theta = 10°\) to the horizontal; the robot is required to climb it at a steady speed. Take \(g = 9.81\) m/s².

Find: The torque each drive motor must produce, in N·m.

Method: At a steady speed there is no acceleration, so the driving force at the wheel rims must exactly balance the component of the robot’s weight acting down the slope. That component is \(mg\sin\theta\). Dividing by the number of driven wheels gives the force at one rim, and multiplying by the wheel radius gives the torque at one shaft, since the rim force acts at a distance \(r\) from the axis.

\[W = mg = 1.5\ \text{kg} \times 9.81\ \text{m/s}^2 = 14.72\ \text{N}\]

\[F_{\text{slope}} = W \sin\theta = 14.72\ \text{N} \times \sin 10° = 14.72 \times 0.1736 = 2.556\ \text{N}\]

\[F_{\text{per wheel}} = \frac{2.556\ \text{N}}{2} = 1.278\ \text{N}\]

\[r = \frac{65\ \text{mm}}{2} = 32.5\ \text{mm} = 0.0325\ \text{m}\]

\[\tau = F_{\text{per wheel}} \times r = 1.278\ \text{N} \times 0.0325\ \text{m} = 0.0415\ \text{N·m}\]

About 0.042 N·m, that is roughly 42 mN·m, at each of the two drive motors.

Check: A BO gearmotor is typically quoted at around 0.8 kg·cm of stall torque, and since 1 kg·cm is 0.0981 N·m, that is about 0.078 N·m. The requirement is a little more than half of the stall torque, so a pair of these motors will climb the ramp but with less margin than is comfortable — and this calculation has ignored rolling resistance and the extra torque needed to start from rest on the slope, both of which push the real requirement higher. A gentler ramp, lighter chassis or higher-ratio gearbox would be the sensible response.

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.

NoteDefinition

A servo motor is a packaged actuator containing a motor, a gear train, a position sensor and a control circuit, which rotates its output shaft to a commanded angular position within a limited range and holds that position against a load.

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.

closed-loop control Statement: In closed-loop control, the actual output of a system is measured and compared with the desired value, and the difference between them — the error — is used to drive the system in the direction that reduces the error. In words: Measure what you actually got, compare it with what you asked for, and correct the difference. Why it holds: The correcting action is driven by the error itself, so any disturbance that increases the error automatically increases the correction that opposes it. The system does not need to know why it was disturbed. Used for: Holding a robot joint at an angle, keeping a drive wheel at a set speed with an encoder, maintaining temperature, and almost every situation where an actual value must match a demanded one. Watch out: Closed-loop control is only as good as its measurement. If the potentiometer inside a servo wears out and reports the wrong angle, the servo will confidently and precisely hold the wrong position, and nothing in the loop can detect this.

Q2. There is an ordinary DC motor inside a servo motor. Why, then, can a servo hold a commanded angle when a plain DC motor cannot?

A. Because the servo also contains a potentiometer coupled to its output shaft, which reports where the shaft actually is. Its control circuit continuously compares that reported position with the commanded position and drives the internal DC motor in whichever direction reduces the difference. A plain DC motor has no such sensor and no such comparison — it runs open loop, so it can be told how much voltage to take but never told, and never able to check, where its shaft has ended up.

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.

finding the pulse width for a commanded angle

Given: A servo in which a pulse width of 1.0 ms corresponds to 0° and 2.0 ms corresponds to 180°, with a linear relation between them (typical values). The pulses repeat every 20.0 ms.

Find: The pulse width required to command 120°, and the duty cycle of the resulting signal.

Method: The pulse width varies linearly with angle, so the extra width above the 1.0 ms minimum is the full 1.0 ms span multiplied by the fraction of the full 180° travel that is being commanded. The duty cycle is the pulse width divided by the repetition period.

\[\text{fraction of travel} = \frac{120°}{180°} = 0.6667\]

\[t_{\text{pulse}} = 1.0\ \text{ms} + (0.6667 \times 1.0\ \text{ms}) = 1.667\ \text{ms}\]

\[\text{duty cycle} = \frac{1.667\ \text{ms}}{20.0\ \text{ms}} \times 100 = 8.33\ \%\]

A pulse width of about 1.67 ms, giving a duty cycle of about 8.3 per cent.

Check: Substituting 90° into the same working gives exactly 1.5 ms, which matches the quoted centre position, so the relation is being applied correctly. Note also how small the duty cycle is. This is a signal that carries information, not power — unlike the PWM signal driving the enable pin of the motor driver in section 13.2.5, where the duty cycle was the power.

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.

Q. What happens if I command a servo to an angle its mechanical stop prevents it from reaching?

A. The shaft reaches the stop and can go no further, so the potentiometer keeps reporting a position short of the target and the error never falls to zero. The control circuit keeps driving the internal motor at full effort against a shaft that cannot move — a stall. The servo draws heavy current, gets hot, and can be damaged within a minute or two, all while looking as though nothing is happening.

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.

commanding a servo with the Arduino Servo library

#include <Servo.h>

Servo servo_object;

servo_object.attach(pin_number);
servo_object.write(angle_in_degrees);

Parts: servo_object is a name you choose for one physical servo. pin_number is the digital pin wired to the servo’s signal wire; on the Arduino UNO, using the library disables PWM output on pins 9 and 10, so those pins are the natural ones to give to servos. angle_in_degrees is an integer from 0 to 180. Returns / Effect: attach() returns nothing and starts the pulse train on that pin. write() returns nothing and changes the pulse width so that the servo moves towards the stated angle; the pulses continue automatically afterwards, which is what holds the position. Example:

armServo.attach(9);
armServo.write(90);     // move to the centre of travel and hold there
Powering the servo

The signal wire may come from the controller. The power wires must not.

powering a servo from the controller board’s 5 V pin What students do: connect the servo’s red wire to the 5V pin of the Arduino UNO and its brown or black wire to GND, with the board itself powered from USB. What happens: the servo works while unloaded, then jerks or buzzes as soon as it lifts anything, and the board resets on its own — the serial monitor restarts from the beginning of the program. The servo’s current surge has pulled the 5 V rail down below the level the microcontroller needs. The fix: power the servo from its own pack of 4.8 V to 6 V, join that pack’s negative to the Arduino GND so the two share a common ground, and send only the signal wire to the pin. The board then supplies information, and the pack supplies energy.

stepping a servo through its travel and returning it to centre Input: None from a sensor. One servo attached to a PWM-capable pin. Output: Angular position of the servo’s output shaft, and a report of each commanded angle on the serial monitor. Method:

1. Attach the servo object to its signal pin and start the serial connection.
2. Set the commanded angle to 0.
3. Repeat while the commanded angle is not more than 180:
       a. Write the commanded angle to the servo.
       b. Report the commanded angle.
       c. Wait one second, which is long enough for the shaft to arrive.
       d. Increase the commanded angle by 45.
4. Write 90 to the servo and report that it is holding.
5. Wait two seconds, then return to step 2.

Why it works: Each call to write() changes the width of the pulses the library is generating, and the servo’s internal loop drives the shaft until its potentiometer agrees with the new pulse width. Because the pulses keep being sent, the position is held during each one-second wait rather than drifting. Watch out: The one-second wait is not a decoration. If the next angle is written immediately, the shaft is still in transit and the earlier command is simply abandoned, so the arm appears to skip positions. Choose the wait from the servo’s transit-speed specification and the size of the step.

stepping a servo through its range and holding it at the centre Problem: Move a servo from 0° to 180° in steps of 45°, pausing at each position long enough for it to arrive, then return it to the centre and hold it there, reporting every commanded angle. Board and components: Arduino UNO; one standard hobby servo motor; one 6 V battery pack with holder; connecting wires. Wiring: - Servo signal wire (usually orange or yellow) to Arduino pin 9. - Servo supply wire (usually red) to the positive terminal of the 6 V pack. - Servo ground wire (usually brown or black) to the negative terminal of the pack. - Negative terminal of the pack also to a GND pin of the Arduino UNO, forming the common ground. The signal is a voltage measured against ground, so without this wire the servo has no reference for the pulses and will not respond correctly. - The Arduino UNO is powered from the USB cable. Nothing is connected to its 5V pin.

// Steps one hobby servo through its travel and returns it to the centre.

#include <Servo.h>

const int SERVO_PIN = 9;    // signal pin wired to the servo

Servo armServo;

void setup() {
    armServo.attach(SERVO_PIN);
    Serial.begin(9600);
}

void loop() {
    for (int angle = 0; angle <= 180; angle += 45) {
        armServo.write(angle);
        Serial.print("Commanded angle = ");
        Serial.println(angle);
        delay(1000);
    }

    armServo.write(90);
    Serial.println("Holding at centre");
    delay(2000);
}

Sample output / observed behaviour: The serial monitor, set to 9600 baud, shows the following for one pass of loop(), after which the same lines repeat.

Commanded angle = 0
Commanded angle = 45
Commanded angle = 90
Commanded angle = 135
Commanded angle = 180
Holding at centre

The output horn snaps to one end of its travel, then steps round in four visible jumps, pausing at each. It then swings back to the middle and stays there for two seconds. If you press gently against the horn while it is holding, you can feel it resisting, and it returns to the centre when you let go.

Identifier description:

[Table:] Table 13.3 – the identifiers used in the servo control program, with their types and purposes | Identifier | Type | Purpose | |—|—|—| | SERVO_PIN | const int | Arduino pin number wired to the servo’s signal wire | | armServo | Servo | Object representing the physical servo, through which it is commanded | | angle | int | Commanded angular position in degrees, from 0 to 180 | [/Table]

Notes: attach() is called once in setup() rather than in loop(), because the pulse train has to be started once and then left running; re-attaching on every pass would interrupt it. The choice of 45° steps and one-second waits is deliberate — a smaller step with the same wait would look slow and jerky, and the same step with a shorter wait would let the next command overwrite a movement still in progress.

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

A servo has real force at its output horn and no sense of what is in the way. Keep fingers clear of the horn and of any linkage it drives while power is on, and mount the servo so that a fast swing cannot strike anything. If a servo starts buzzing continuously and feels warm, it is stalled against an obstruction — disconnect its supply at once rather than waiting to see whether it settles.

13.3.6 Applications, Advantages and Limitations

servo motor Working principle: A commanded position arrives as a pulse of a particular width, repeated about fifty times a second. A potentiometer coupled to the output shaft reports the shaft’s actual position as a voltage. The internal control circuit compares the two, and drives a small DC motor through an integrated H-bridge in whichever direction reduces the difference. Gear reduction between the motor and the output shaft lowers the speed and raises the torque. When the error falls inside the deadband, drive is reduced to whatever is needed to hold station. Components: DC motor, gear train, potentiometer acting as the position sensor, electronic control circuit with an integrated H-bridge, output shaft with a splined horn, three-wire lead for signal, supply and ground. Advantages: Gives precise control of angular position without the user having to build any feedback loop. High torque for its weight, because of the gearing, so a small unit can move a substantial load. Responds and corrects quickly over small movements, which is what a robot joint needs. Simple to interface — one signal wire, plus power — since all the control complexity is inside the case. Limitations: Travel is limited to about 180°, so it cannot drive a wheel; a continuous-rotation variant can, but then loses the ability to hold an angle. Slower than a bare DC motor of the same size, because the gearing trades speed for torque. Current rises with load and becomes large if the shaft is obstructed, at which point the servo overheats. Costs more per unit than a plain DC motor of comparable output. And the feedback is internal and invisible: the controller commands an angle but is never told whether the servo actually reached it. Where it is used: Joints of small robotic arms and humanoid robots, where each servo holds one limb angle; steering mechanisms and pan-and-tilt camera mounts on mobile robots; control surfaces and camera gimbals on radio-controlled aircraft and drones; and positioning of tools and parts in machines where closed-loop correction is required.

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.

Table 13.4 – DC motor and servo motor compared as actuators for a robot | Feature | DC motor | Servo motor | |—|—|—| | Nature of motion | Continuous rotation in either direction | Movement to a commanded angle, held there | | Range of travel | Unlimited | Limited, about 180° for a standard hobby servo | | What the controller sends | A PWM signal that sets the average voltage, and two direction lines | A pulse whose width represents the desired angle | | Feedback on shaft position | None; runs open loop unless an encoder is added | Built in, from an internal potentiometer, working closed loop | | Behaviour when held against a load | Stalls, draws its maximum current and overheats | Holds the position, drawing current in proportion to the load | | Speed and torque | Fast and weak when bare; a gearbox trades speed for torque | Geared down already, so slower but with high holding torque | | Extra hardware needed | A motor driver such as the L298N to carry the current | None beyond a suitable supply; the driver is inside the case | | Control code needed | Simple for speed; substantial for position | One instruction per commanded angle | | Relative cost for a given output | Lower | Higher | | Typical robot use | Drive wheels, conveyors, pumps, propellers | Arm joints, grippers, steering, pan-and-tilt mounts |

Q. A continuous-rotation servo turns endlessly like a DC motor and needs no separate driver. Why not use one for the drive wheels and avoid the L298N altogether?

A. You can, and small robots often do. What you give up is the feedback: once the mechanical stops and the position loop are removed, the pulse width sets a speed rather than an angle, and nothing measures whether that speed was achieved. You also inherit the servo’s gearing, so the wheel turns slowly, and you pay servo prices for an actuator that is now doing a DC motor’s job.

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 – the output form typically produced by each of the six sensor types studied in this chapter | Sensor | Usual output form | Read by the controller as | |—|—|—| | IR | Two-state digital, or analogue voltage | A HIGH/LOW state, or a number from the ADC | | Ultrasonic | Timed pulse on an echo pin | A duration in microseconds | | LIDAR | Digital data over a communication protocol | A stream of angle-and-distance values | | Touch | Two-state digital, or analogue voltage for force sensors | A HIGH/LOW state, or a number from the ADC | | Gyroscopes | Digital data over a communication protocol | Signed numbers, one per axis | | Accelerometer | Digital data over a communication protocol | Signed numbers, one per axis |

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.

reading a sensor pin on an Arduino board

pinMode(pin_number, INPUT);

digitalRead(pin_number);
analogRead(analog_pin_name);

Parts: pin_number is any digital pin. analog_pin_name is one of the analogue input pins, written A0 to A5 on the Arduino UNO. INPUT sets the pin to receive rather than drive. Returns / Effect: digitalRead() returns HIGH or LOW. analogRead() returns an integer from 0 to 1023 representing the voltage on that pin. Neither changes anything in the hardware being read. Example:

int bumperState = digitalRead(4);
int lightLevel = analogRead(A0);

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.

converting an ADC reading into a voltage and a light level

Given: A reflective IR sensor’s analogue output is connected to pin A0 of an Arduino UNO running from a 5.00 V reference. A call to analogRead(A0) returns 412. Earlier calibration on the same surface gave 880 over white card and 95 over black tape.

Find: The voltage at the pin, and whether the sensor is over the white card or the black tape.

Method: The reading is a code between 0 and 1023 representing a voltage between 0 V and 5.00 V, so the voltage is the code multiplied by the volts per code, taking 1023 as full scale. The surface is then judged against the two calibration readings.

\[V = \text{reading} \times \frac{5.00\ \text{V}}{1023} = 412 \times 0.004888\ \text{V} = 2.01\ \text{V}\]

The midpoint between the two calibration values is

\[\frac{880 + 95}{2} = 487.5\]

and 412 lies below it, closer to the black-tape reading.

About 2.01 V at the pin, and the sensor is over the dark surface, though not far from the boundary between the two.

Check: 412 is roughly two-fifths of full scale, and two-fifths of 5 V is 2 V, so the voltage is right. The second part is a reminder that the number 412 means nothing on its own — it became useful only when compared with readings taken from the actual surfaces, which is calibration doing its work.

Q. What does analogRead() return if I forget to connect anything to the pin?

A. Not zero. An unconnected input pin is a floating input: it is joined to nothing, so its voltage drifts under the influence of electrical noise from nearby wires and even from your hand. The readings wander, often changing every time you call it. This is why an apparently working sensor program that produces plausible-looking rubbish is so often a loose wire rather than a coding fault.

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.

Connect a reflective IR sensor’s analogue output to A0 and print analogRead(A0) once every 200 ms. Record the readings over white paper, over black tape and over a shiny surface, at two heights. Then repeat the whole set with the room lights switched off, and compare.

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.

Q. If the reading depends on the surface as well as the distance, how can a line-following robot work at all?

A. Because a line follower does not need the distance. It keeps the sensor at a fixed height above the floor, so distance is held constant and the only thing that changes is the surface. The reading then depends on reflectance alone, and the black line and the white floor separate cleanly. This is a common engineering move: if a measurement depends on two things, fix one of them.

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.

Table 13.6 – active IR sensing and passive infrared (PIR) sensing compared | Feature | Active IR sensor | Passive infrared (PIR) sensor | |—|—|—| | Source of the light detected | An IR LED on the sensor itself | The warm body being detected | | Wavelength region used | Near infrared, about 850–950 nm | Far infrared, around 10 µm | | What it reports | Presence of a reflecting surface, and roughly its nearness | A change in received heat radiation, that is, movement of a warm body | | Detects a stationary object | Yes, as long as it reflects | No; a motionless person eventually stops being reported | | Detects a cold object | Yes | No | | Typical robotic use | Line following, edge detection, short-range obstacle sensing | Detecting the presence of people near or around the robot | | Power drawn | Higher, since the emitter must be driven | Very low, since nothing is emitted |

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.

Q3. An infrared sensor pointed at the floor reports a staircase as “no floor”. Why does bright sunlight make the same sensor unreliable?

A. The sensor shines infrared downward and measures what comes back. Over the floor, the surface is close and returns a strong reflection. Over the top step of a staircase there is nothing within range to reflect from, so almost no light returns and the sensor reports the same thing it would report for empty space — which is exactly what a drop is. Sunlight breaks this because it contains a great deal of infrared of its own. It floods the detector with background light that the sensor did not emit, so a strong reading no longer means “something reflected my beam”, and a real drop can be read as solid floor.

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

two-sensor line following Input: Two IR sensors mounted at the front of the chassis, straddling the line, each giving a two-state output that reads HIGH over the dark line and LOW over the light floor. Output: Duty values applied to the enable inputs of the left and right drive motors, both driven forward. Method:

1. Read the left sensor and the right sensor.
2. If neither sensor is over the line:
       run both wheels at the cruise duty.
3. Otherwise, if only the left sensor is over the line:
       run the left wheel at the slow duty and the right wheel at the cruise duty.
4. Otherwise, if only the right sensor is over the line:
       run the left wheel at the cruise duty and the right wheel at the slow duty.
5. Otherwise, both sensors are over dark:
       stop both wheels.
6. Wait a short interval and return to step 1.

Why it works: Slowing the wheel on the side that has strayed onto the line makes the robot pivot gently towards that side, which carries the straying sensor back off the line. The correction is therefore always in the direction that removes the condition that caused it — the same closed-loop reasoning as in section 13.3.2, but built in software from two crude sensors. Watch out: If both sensors read dark, the robot is not on a line at all but on a broad dark patch or a junction, and steering has no meaning; stopping is safer than guessing. The correction is also fixed in size, so on a sharp bend the robot may cross the line entirely before the correction takes effect.

a two-sensor line-following robot Problem: Drive a two-wheeled robot forward along a dark line on a light floor, correcting its heading whenever either front sensor crosses the line, and stopping if both do. Board and components: Arduino UNO; one L298N motor driver module; two BO gearmotors with 65 mm wheels; two IR line sensor modules with digital outputs; one 6 V battery pack with holder; connecting wires. Wiring: - Left motor to OUT1 and OUT2 of the L298N; right motor to OUT3 and OUT4. - Battery positive to the +12V terminal of the L298N; battery negative to its GND terminal, and from there to an Arduino GND pin as the common ground. - IN1 to Arduino pin 7, IN2 to pin 8, ENA to pin 9; IN3 to pin 4, IN4 to pin 2, ENB to pin 10. Pins 9 and 10 are PWM pins, and both enable jumpers on the module are removed. - Left IR module output to pin 12; right IR module output to pin 11. - Both IR modules take VCC from the Arduino 5V pin and GND from an Arduino GND pin. The two modules together draw a few tens of milliamperes, which the board can supply; the motors never do. - The threshold trimmer on each IR module is adjusted so that its indicator LED changes state as the sensor is moved from the floor onto the line.

// Two-sensor line follower using IR modules and an L298N driver.

const int LEFT_IN1 = 7;         // left motor direction inputs
const int LEFT_IN2 = 8;
const int LEFT_EN = 9;          // left motor PWM enable
const int RIGHT_IN1 = 4;        // right motor direction inputs
const int RIGHT_IN2 = 2;
const int RIGHT_EN = 10;        // right motor PWM enable

const int LEFT_SENSOR = 12;     // digital output of the left IR module
const int RIGHT_SENSOR = 11;    // digital output of the right IR module

const int CRUISE = 160;         // duty value for the wheel running normally
const int SLOW = 70;            // duty value for the wheel being held back

void setup() {
    pinMode(LEFT_IN1, OUTPUT);
    pinMode(LEFT_IN2, OUTPUT);
    pinMode(LEFT_EN, OUTPUT);
    pinMode(RIGHT_IN1, OUTPUT);
    pinMode(RIGHT_IN2, OUTPUT);
    pinMode(RIGHT_EN, OUTPUT);

    pinMode(LEFT_SENSOR, INPUT);
    pinMode(RIGHT_SENSOR, INPUT);
}

// Drives both wheels forward at the two duty values given.
void setWheelSpeeds(int leftDuty, int rightDuty) {
    digitalWrite(LEFT_IN1, HIGH);
    digitalWrite(LEFT_IN2, LOW);
    digitalWrite(RIGHT_IN1, HIGH);
    digitalWrite(RIGHT_IN2, LOW);
    analogWrite(LEFT_EN, leftDuty);
    analogWrite(RIGHT_EN, rightDuty);
}

void loop() {
    int leftOnLine = digitalRead(LEFT_SENSOR);
    int rightOnLine = digitalRead(RIGHT_SENSOR);

    if (leftOnLine == LOW && rightOnLine == LOW) {
        setWheelSpeeds(CRUISE, CRUISE);
    } else if (leftOnLine == HIGH && rightOnLine == LOW) {
        setWheelSpeeds(SLOW, CRUISE);
    } else if (leftOnLine == LOW && rightOnLine == HIGH) {
        setWheelSpeeds(CRUISE, SLOW);
    } else {
        setWheelSpeeds(0, 0);
    }

    delay(20);
}

Sample output / observed behaviour: The program prints nothing. Placed astride the line, the robot runs forward at a steady speed. Each time it wanders far enough for one front sensor to cross the line, that side visibly slows for a moment and the robot swings back towards the centre, so it travels in a gentle weaving path rather than a perfectly straight one. Lifted onto a plain dark surface, where both sensors read dark, it stops.

If your IR modules read the opposite way round — LOW over the line and HIGH over the floor — the robot will steer the wrong way and leave the track immediately. Swap HIGH and LOW in the two middle tests rather than rewiring anything.

Identifier description:

[Table:] Table 13.7 – the identifiers used in the line-following program, with their types and purposes | Identifier | Type | Purpose | |—|—|—| | LEFT_IN1, LEFT_IN2 | const int | Arduino pins wired to the direction inputs of the left motor’s bridge | | LEFT_EN | const int | PWM pin wired to the enable input of the left motor’s bridge | | RIGHT_IN1, RIGHT_IN2 | const int | Arduino pins wired to the direction inputs of the right motor’s bridge | | RIGHT_EN | const int | PWM pin wired to the enable input of the right motor’s bridge | | LEFT_SENSOR, RIGHT_SENSOR | const int | Arduino pins wired to the digital outputs of the two IR modules | | CRUISE | const int | Duty value used by a wheel that is running normally | | SLOW | const int | Duty value used by a wheel that is being held back to steer | | leftOnLine, rightOnLine | int | State just read from each IR module, HIGH over the line or LOW over the floor | | setWheelSpeeds() | function | Sets both wheels forward and applies the two duty values | [/Table]

Notes: CRUISE and SLOW are named constants because tuning a line follower means adjusting exactly these two numbers, and they should be adjustable in one place. The 20 ms wait at the end of loop() keeps the robot from re-reading the same sensor state hundreds of times a second without any of it having changed; it is short enough that the sense–plan–act loop still runs fifty times a second.

the decision logic of the line follower, as the robot drifts to the right and is corrected

Step leftOnLine rightOnLine Branch taken leftDuty rightDuty What the robot does
1 LOW LOW first 160 160 runs straight ahead
2 LOW LOW first 160 160 still straight, but drifting right
3 HIGH LOW second 70 160 left wheel slows, robot swings left
4 HIGH LOW second 70 160 still swinging back towards the line
5 LOW LOW first 160 160 centred again, runs straight
6 HIGH HIGH fourth 0 0 both sensors dark, robot stops

Result: The correction lasts only as long as the condition that caused it, because the moment the left sensor comes off the line the first branch is taken again. The trace also shows why the fourth branch is needed at all — without it, a junction or the end of the track would fall through to one of the steering cases and the robot would turn for no reason.

infrared (IR) sensor Working principle: An IR LED emits a beam of infrared light. A photodiode or phototransistor beside it measures the infrared returning from whatever is in front. A near or pale surface returns more light than a distant or dark one, and the returned intensity is amplified and either compared against a threshold to give a two-state output or read directly as an analogue value. The emitter is usually modulated at a fixed frequency so that steady ambient infrared can be rejected. In the passive form, no light is emitted and a pyroelectric element responds instead to changes in the infrared radiated by warm bodies. Components: IR LED emitter, photodiode or phototransistor receiver, amplifier, comparator with a threshold-setting trimmer potentiometer, and in some modules a lens or shroud; a PIR module has a pyroelectric element and a segmented lens in place of the emitter and receiver pair. Advantages: Inexpensive, small and light, so several can be fitted to one robot. Draws little power and is simple to interface, needing only a supply and one pin. Responds within microseconds to milliseconds, fast enough for line following at speed. Works in complete darkness, because it brings its own light. Detects thin objects and edges that a wider-beam sensor would miss. Limitations: Reports reflected intensity, not distance, so its readings depend on the colour, finish and angle of the target as much as on how far away it is. Dark surfaces read as far away and shiny angled ones may reflect the beam away entirely; transparent objects may not register. Strong ambient infrared, especially direct sunlight, degrades or defeats it. Its useful range is short, so it is unsuitable for long-range measurement, and its narrow field of view leaves objects to the side unseen. Where it is used: Line-following robots that read a track on the floor; edge and drop detection on cleaning and delivery robots; short-range obstacle sensing as an electronic bumper; receiving commands from IR remote controls and short-range signalling between robots; and beacon-based localisation, where fixed emitters mark known positions for a robot to home in on.

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.

distance by time-of-flight Statement: If a pulse travels from the sensor to a surface and back in a total time \(\Delta t\), moving at speed \(v\) in the medium, the distance to the surface is \[d = \frac{v \times \Delta t}{2}\] In words: Speed multiplied by time gives the whole journey; halving it gives the one-way distance. Why it holds: The outward and return paths are the same length, so the total path is \(2d\). Since \(2d = v \Delta t\), dividing by two gives \(d\). Used for: Every ranging device that sends a pulse and waits for it to return — ultrasonic sensors here, and the LIDAR of section 13.8, where the pulse is light instead of sound. Watch out: The halving is not optional and is the most common mistake in this calculation. The value used for \(v\) must also be right for the medium and its temperature, or every reading is wrong by the same proportion.

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.

converting an echo time into a distance

Given: An HC-SR04 module returns an echo pulse of duration \(\Delta t = 1160\) µs. The air temperature is about 20 °C, so the speed of sound is \(v = 0.0343\) cm/µs.

Find: The distance from the sensor to the reflecting surface, in centimetres.

Method: The echo pulse duration is the total out-and-back time of flight. Multiplying it by the speed of sound gives the whole path travelled, and halving that gives the distance to the surface.

\[\text{total path} = v \times \Delta t = 0.0343\ \text{cm/µs} \times 1160\ \text{µs} = 39.79\ \text{cm}\]

\[d = \frac{39.79\ \text{cm}}{2} = 19.9\ \text{cm}\]

About 19.9 cm.

Check: A little under 20 cm is comfortably inside the module’s working range and well outside its blind zone, so the figure is believable. As a rough guide worth remembering, sound covers about 1 cm out and back in 58 µs, and \(1160 / 58 = 20\), which agrees.

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

measuring distance with an ultrasonic module Input: The trigger and echo pins of an ultrasonic module, and the speed of sound in the current air. Output: The distance to the nearest surface in front of the sensor, in centimetres, or an indication that nothing was found. Method:

1. Hold the trigger pin low briefly so the module starts from a clean state.
2. Raise the trigger pin for at least 10 microseconds, then lower it.
3. Measure how long the echo pin stays high, giving up after a set time limit.
4. If the measured time is zero, no echo returned; report that nothing was found.
5. Otherwise multiply the measured time by the speed of sound and divide by two.
6. Report the resulting distance.
7. Wait long enough for the last echoes to die away, then return to step 1.

Why it works: The module encodes the time of flight as the width of the echo pulse, so timing that pulse measures the flight directly, and the halving in step 5 accounts for the sound making the journey twice. Watch out: Step 3 must have a time limit. Without one, the program waits indefinitely for an echo that will never arrive when the sensor faces an open room or a sound-absorbing surface. Step 7 matters too: measure again too soon and the tail of the previous echo can be mistaken for the start of the new one.

reporting the distance to the nearest obstacle Problem: Measure the distance to whatever is in front of an ultrasonic sensor about five times a second and report it on the serial monitor, stating clearly when nothing is within range. Board and components: Arduino UNO; one HC-SR04 ultrasonic module; connecting wires. Wiring: - VCC of the module to the Arduino 5V pin. - GND of the module to an Arduino GND pin. - TRIG of the module to Arduino pin 9. - ECHO of the module to Arduino pin 10. - The board is powered from the USB cable; the module draws only a few milliamperes and can be supplied from the board.

// Measures distance with an HC-SR04 ultrasonic module and reports it.

const int TRIG_PIN = 9;
const int ECHO_PIN = 10;

const float CM_PER_MICROSECOND = 0.0343;    // speed of sound at about 20 °C
const unsigned long ECHO_TIMEOUT = 30000;   // give up after 30 ms of silence

void setup() {
    pinMode(TRIG_PIN, OUTPUT);
    pinMode(ECHO_PIN, INPUT);
    Serial.begin(9600);
}

// Sends one burst and returns the distance in cm, or -1.0 if no echo returns.
float measureDistance() {
    digitalWrite(TRIG_PIN, LOW);
    delayMicroseconds(2);
    digitalWrite(TRIG_PIN, HIGH);
    delayMicroseconds(10);
    digitalWrite(TRIG_PIN, LOW);

    unsigned long echoTime = pulseIn(ECHO_PIN, HIGH, ECHO_TIMEOUT);

    if (echoTime == 0) {
        return -1.0;
    }
    return (echoTime * CM_PER_MICROSECOND) / 2.0;
}

void loop() {
    float distance = measureDistance();

    if (distance < 0) {
        Serial.println("No echo: nothing within range");
    } else {
        Serial.print("Distance = ");
        Serial.print(distance, 1);
        Serial.println(" cm");
    }

    delay(200);
}

Sample output / observed behaviour: With the sensor resting about 20 cm from a wall and then turned to face an open room, the serial monitor at 9600 baud shows lines in this form, one every 200 ms.

Distance = 19.9 cm
Distance = 20.1 cm
Distance = 19.8 cm
No echo: nothing within range
No echo: nothing within range

The exact figures vary by a millimetre or two from reading to reading even with nothing moving, which is the noise described in section 13.5.3 and is entirely normal.

Identifier description:

[Table:] Table 13.8 – the identifiers used in the ultrasonic ranging program, with their types and purposes | Identifier | Type | Purpose | |—|—|—| | TRIG_PIN | const int | Arduino pin wired to the module’s trigger input | | ECHO_PIN | const int | Arduino pin wired to the module’s echo output | | CM_PER_MICROSECOND | const float | Speed of sound expressed in cm per microsecond | | ECHO_TIMEOUT | const unsigned long | Longest time, in microseconds, to wait for an echo | | echoTime | unsigned long | Measured width of the echo pulse, in microseconds | | distance | float | Computed distance in cm, or −1.0 when no echo returned | | measureDistance() | function | Sends one burst, times the echo and converts it to a distance | [/Table]

Notes: The function returns −1.0 rather than 0 for a failed measurement, because 0 is a perfectly plausible distance and would be indistinguishable from a genuine reading close to the sensor. Separating the measurement from the reporting also means the same measureDistance() can later feed a steering decision instead of a serial line, without a word of it changing.

timing the echo without a timeout What students do: call pulseIn(ECHO_PIN, HIGH) with no third argument, because the program works fine while the sensor is pointed at a wall. What happens: as soon as the sensor faces an open room, a soft curtain or a sharply angled surface, no echo returns. The default timeout is one full second, so the program freezes at that line for a whole second on every failed reading. A robot doing this stops responding to everything else, including its bumper. The fix: give pulseIn() an explicit timeout suited to the range you need — 30000 µs corresponds to about 5 m of travel, so about 2.5 m of distance — and treat a returned 0 as “no echo” rather than as a distance.

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

ultrasonic sensor Working principle: A piezoelectric transmitter emits a short burst of sound at about 40 kHz. The burst travels through the air, reflects from a surface, and part of it returns to a piezoelectric receiver. The module measures the interval between transmission and reception, and the distance follows as \(d = v \Delta t / 2\), the halving accounting for the sound covering the distance twice. The module reports the interval as the width of a pulse on its echo pin. Components: Piezoelectric transmitting transducer, piezoelectric receiving transducer, drive electronics generating the 40 kHz burst, amplifier and detection circuit for the weak returning echo, and timing circuitry with trigger and echo pins. Advantages: Independent of the colour, brightness and lighting of the target, since it works with sound rather than light, so it performs identically in darkness and in sunlight. Detects transparent objects such as glass and dark matt surfaces that defeat an IR sensor. Covers a useful range of several metres, well beyond simple IR devices. Inexpensive and simple to interface, needing only two pins. Limitations: Has a blind zone of a few centimetres in which nothing can be measured. Its wide cone gives poor directionality — it reports that something is at a certain distance, not where in the cone it is. Soft or sound-absorbing surfaces and steeply angled ones may return no usable echo at all. Readings fluctuate because of noise and multiple reflections, and other ultrasonic sources nearby can confuse it. It is slow compared with optical methods, and its accuracy depends on the speed of sound, which changes with air temperature. Where it is used: Obstacle detection and avoidance on mobile robots, often with the sensor mounted on a servo so it can sweep and find a clear path; wall-following and rough mapping by taking readings at several headings; measuring the fill level of a tank or bin by pointing downward at the contents; and low-altitude height holding on drones, where it reports height above the ground directly and works in the dark.

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.

the time a LIDAR must be able to measure

Given: A LIDAR unit reports a wall at \(d = 10.0\) m. The speed of light in air is \(c = 3.00 \times 10^8\) m/s.

Find: The round-trip time of flight, and how it compares with the time an ultrasonic sensor would take over the same distance at 343 m/s.

Method: Rearranging the time-of-flight relation gives \(\Delta t = 2d / v\) for either sensor, with \(v\) being the speed of the pulse in the medium.

\[\Delta t_{\text{light}} = \frac{2 \times 10.0\ \text{m}}{3.00 \times 10^8\ \text{m/s}} = 6.67 \times 10^{-8}\ \text{s} = 66.7\ \text{ns}\]

\[\Delta t_{\text{sound}} = \frac{2 \times 10.0\ \text{m}}{343\ \text{m/s}} = 5.83 \times 10^{-2}\ \text{s} = 58.3\ \text{ms}\]

About 66.7 ns for the laser pulse, against about 58.3 ms for sound — a difference of roughly 900 000 times.

Check: A 1 cm error in the reported distance corresponds to a timing error of only about 67 picoseconds, which confirms that this measurement is beyond the reach of an ordinary microcontroller timer. That is exactly why a LIDAR contains its own dedicated high-speed electronics and hands the controller a finished distance rather than a raw pulse to time.

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.

A LIDAR contains a working laser. Units sold for robotics are normally rated as eye-safe in ordinary use, but that rating assumes the housing is intact and the optics are undisturbed. Never open a LIDAR unit, never remove or defeat its cover, and do not hold the aperture up to your eye to look for the beam. Treat the emitting window in the same way you would treat any laser: keep it pointed away from faces, including your own.

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.

the gap between adjacent LIDAR measurements

Given: A 2D scanning LIDAR with an angular resolution of 1.0° is used in a hall. A chair leg 4.0 cm wide stands 5.0 m from the sensor.

Find: The spacing between adjacent measurement points at that distance, and whether the chair leg is certain to be detected.

Method: Successive beams diverge by the angular resolution, so at a distance \(r\) the gap between the points where they land is the arc length \(s = r\theta\), with \(\theta\) expressed in radians.

\[\theta = 1.0° = 1.0 \times \frac{\pi}{180} = 0.01745\ \text{rad}\]

\[s = r\theta = 5.0\ \text{m} \times 0.01745 = 0.0873\ \text{m} = 8.7\ \text{cm}\]

About 8.7 cm between adjacent measurement points, which is more than twice the width of the chair leg. The leg may therefore fall entirely between two beams and go undetected.

Check: At 1 m the same calculation gives 1.7 cm, so the leg would certainly be hit by at least two beams close up. This matches what the geometry demands — the beams fan out, so detail is lost with distance — and it explains why an obstacle a robot ignored from across the hall suddenly appears when it gets nearer.

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

LIDAR Working principle: A laser diode emits pulses of infrared light. Each pulse travels out, reflects from the first surface it meets and returns to a photodiode detector. The unit measures the round-trip time — directly, or indirectly by comparing the phase of the returned light with that of the transmitted light — and computes the distance as \(d = c\Delta t / 2\). A rotating mirror or a spinning assembly sweeps the beam, so each distance is recorded against the angle at which it was taken, building a point cloud of the surroundings. Components: Laser diode emitter, photodiode detector, high-speed timing and processing electronics, rotating mirror or motor-driven scanning assembly, and a communication interface that delivers a stream of angle-and-distance values. Advantages: Gives high accuracy and high angular detail, so the robot learns not just that something is there but exactly where. Covers long ranges and wide areas quickly, thousands of readings per second. Works equally in daylight and darkness, since it supplies its own light. Its narrow beam gives real directional information, which no ultrasonic sensor can. Limitations: Considerably more expensive and more complex than the other sensors in this chapter, and often more capability than a small robot needs. Draws more power, because it has a spinning assembly, a laser and continuous processing. Produces a large volume of data, so the robot needs the computing capacity to handle it. Performance falls in fog, smoke and dust, and against very dark or mirror-like surfaces. It sees only the first surface along each beam, so anything in shadow is missing from the scan, and a 2D unit sees only its own plane. Where it is used: Mapping and SLAM on indoor mobile robots, including the higher-specification cleaning robots that plan a systematic route rather than wandering; obstacle, lane and environment sensing on autonomous vehicles, where a 3D point cloud of the surroundings is required; and survey work from drones, scanning terrain, forests and structures from above.

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.

enabling a pin’s internal pull-up resistor

pinMode(pin_number, INPUT_PULLUP);

Parts: pin_number is the digital pin the switch is connected to. INPUT_PULLUP sets the pin as an input and connects the internal pull-up resistor between that pin and the supply. Returns / Effect: Returns nothing. The pin now reads HIGH when the switch is open and LOW when the switch is closed to ground. Example:

pinMode(4, INPUT_PULLUP);       // switch wired between pin 4 and GND

wiring a switch with no pull-up What students do: connect one side of the switch to a digital pin and the other to 5V, declare the pin as INPUT, and test for HIGH. What happens: pressing the switch works. Releasing it does not — the pin is now connected to nothing, so it floats and keeps reporting the button as pressed, or flickers between states as a hand moves nearby. The fix: wire the switch between the pin and GND and declare the pin INPUT_PULLUP, then test for LOW. Every input pin needs a defined voltage in both switch states, not just one.

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.

debouncing a mechanical switch Input: The state of a switch pin, read repeatedly; a settling period long enough to outlast the bounce. Output: The stable state of the switch, reported once per genuine change. Method:

1. Read the current state of the pin.
2. If it differs from the reading taken last time, note the present moment as the
   time of the last change, and remember this reading.
3. If the reading has now stayed the same for at least the settling period,
   and it differs from the stable state currently on record:
       a. Accept it as the new stable state.
       b. If the new stable state means the switch is pressed, report a press.
4. Return to step 1.

Why it works: The bouncing contacts change state repeatedly within a few milliseconds, and every one of those changes restarts the settling clock in step 2. The condition in step 3 can therefore only be satisfied once the chatter has stopped, so exactly one press is reported. Watch out: The settling period must be longer than the bounce but shorter than the fastest press a person or a robot can genuinely produce. Too short and the chatter gets through; too long and real contacts are missed.

counting bumps from a debounced bumper switch Problem: Detect each time the bumper of a mobile robot strikes something, report the running count on the serial monitor, and count each strike exactly once despite contact bounce. Board and components: Arduino UNO; one lever microswitch mounted as a front bumper; connecting wires. Wiring: - One terminal of the microswitch to Arduino pin 4. - The other terminal of the microswitch to an Arduino GND pin. - No external resistor; the internal pull-up on pin 4 is used. - The board is powered from the USB cable.

// Counts bumper strikes, ignoring the contact bounce of the switch.

const int BUMPER_PIN = 4;
const unsigned long SETTLING_TIME = 20;   // milliseconds

int lastReading = HIGH;        // state seen on the previous pass
int stableState = HIGH;        // state accepted as genuine
unsigned long lastChangeTime = 0;
int bumpCount = 0;

void setup() {
    pinMode(BUMPER_PIN, INPUT_PULLUP);
    Serial.begin(9600);
}

void loop() {
    int reading = digitalRead(BUMPER_PIN);

    if (reading != lastReading) {
        lastChangeTime = millis();
        lastReading = reading;
    }

    if (millis() - lastChangeTime >= SETTLING_TIME && reading != stableState) {
        stableState = reading;

        // A pulled-up pin reads LOW when the switch is closed.
        if (stableState == LOW) {
            bumpCount = bumpCount + 1;
            Serial.print("Bump number ");
            Serial.println(bumpCount);
        }
    }
}

Sample output / observed behaviour: The serial monitor at 9600 baud stays blank until the bumper is struck. Three separate strikes produce exactly three lines.

Bump number 1
Bump number 2
Bump number 3

Remove the debouncing — accept every change the moment it appears — and a single firm strike typically produces several lines at once, which is the clearest demonstration of bounce you will get without an oscilloscope.

Identifier description:

[Table:] Table 13.9 – the identifiers used in the bumper counting program, with their types and purposes | Identifier | Type | Purpose | |—|—|—| | BUMPER_PIN | const int | Arduino pin wired to the bumper microswitch | | SETTLING_TIME | const unsigned long | Time in milliseconds the reading must hold steady before it is accepted | | lastReading | int | State of the pin on the previous pass through loop() | | stableState | int | State currently accepted as the genuine state of the switch | | lastChangeTime | unsigned long | Value of millis() when the reading last changed | | bumpCount | int | Running count of genuine strikes | | reading | int | State of the pin on this pass through loop() | [/Table]

Notes: millis() returns the number of milliseconds since the board was last reset, so subtracting a stored value from it measures elapsed time without stopping the program. That distinction matters here: a delay() of 20 ms would also let the bounce settle, but during it the robot could not read its other sensors or steer, and a robot that goes deaf for 20 ms every time it touches something is not safer for having a bumper.

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

touch sensor Working principle: A physical contact between the robot and an object produces a change in an electrical property, which the controller reads. In a mechanical switch the contact closes a circuit and the output changes state. In a resistive sensor the pressure lowers the material’s resistance, giving an analogue voltage that varies with force. In a capacitive sensor a conductive object nearby changes the measured capacitance. In a piezoelectric element the deformation itself generates a voltage. Components: The sensing element — switch contacts, force-sensitive polymer, capacitive plate or piezoelectric disc — a mechanical actuator such as a lever, bumper strip or whisker that carries the contact to it, and the interface circuitry, which for a simple switch is nothing more than a pull-up resistor. Advantages: Direct and unambiguous, since it confirms an actual physical event rather than inferring one from a reflection or an echo. Unaffected by lighting, colour, surface finish, sound or dust, so it works where every other sensor in this chapter can fail. Very low in cost, particularly the switch types, and simple to wire and read. Capacitive versions detect a human touch, which is useful for safety and for interaction. Limitations: Reports only on contact, so the robot must already have struck the object before it learns anything, and a collision at speed can damage what was struck or the robot itself. Its area of influence is confined to wherever the sensor happens to be, so an obstacle met by an unprotected part of the chassis goes unreported. The data is sparse — a few discrete contact points — and carries nothing like the picture of the surroundings that a LIDAR scan gives. Mechanical types bounce and wear out. Where it is used: Collision detection on mobile robots, where a bumper strip around the front confirms a strike and triggers a reverse-and-turn; grip force sensing in robotic grippers, where fingertip sensors prevent a delicate object being crushed and confirm that it has not slipped; slip detection through vibration in the fingertips of advanced hands; identifying a surface by how much it yields when pressed; and homing and travel limits on robotic arms and machine tools, where limit switches define the zero position and prevent movement beyond a safe range.

Q4. If a robot already has an ultrasonic sensor that measures distance, why would a designer still fit a contact bumper?

A. Because the ultrasonic sensor can miss things, and the bumper cannot. Sound slides off surfaces at a steep angle, is absorbed by soft materials such as curtains and cushions, and returns nothing at all from within the sensor’s blind zone of the first couple of centimetres. In each of those cases the robot is told the way ahead is clear when it is not. The bumper is the last line of defence: it reports a certainty rather than an inference, and it costs a few rupees and one pin. A robot that trusts a single ranging sensor with no fail-safe will eventually meet the one obstacle that sensor cannot see.

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 Coriolis effect Statement: An object moving within a rotating frame of reference appears to be deflected from a straight path, sideways to its direction of travel. The size of the apparent deflection is proportional to the speed of the object and to the rate of rotation of the frame. In words: If you move in a straight line across something that is turning, your path across it comes out curved. Why it holds: The object travels in a straight line as judged from outside, but the frame beneath it has rotated during the journey, so measured against that frame the path is curved. The faster the frame turns, the greater the discrepancy. Used for: Measuring angular velocity in a MEMS gyroscope, where the vibrating mass is the moving object and the chip is the rotating frame; it also explains the large-scale circulation of winds and ocean currents. Watch out: The deflection is apparent, not a real extra force acting on the object. It exists only because the measurement is being made from within something that is turning — which is exactly the situation of a sensor bolted to a robot.

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.

heading from a gyroscope, and what drift does to it

Given: A gyroscope on a wheeled robot is read every \(\Delta t = 20\) ms, that is every 0.020 s. During a turn it reports a steady \(\omega = 60\) °/s for 1.50 s. The same device has an uncorrected zero reading of \(+0.40\) °/s — it reports that value even when perfectly still.

Find: (a) The angle turned during the 1.50 s. (b) The heading error that accumulates if the robot then stands motionless for 2.0 minutes while the program keeps integrating.

Method: Each sample contributes \(\omega \Delta t\) to the total angle, so the accumulated angle is the rate multiplied by the total time. The same accumulation applies to the false rate reported when the robot is still, since the program cannot tell a real rotation from a false one.

  1. Angle contributed by one sample:

\[60\ \text{°/s} \times 0.020\ \text{s} = 1.2°\]

Number of samples in 1.50 s:

\[\frac{1.50\ \text{s}}{0.020\ \text{s}} = 75\]

\[\theta = 75 \times 1.2° = 90°\]

  1. Standing still for \(2.0 \times 60 = 120\) s at a false rate of 0.40 °/s:

\[\theta_{\text{error}} = 0.40\ \text{°/s} \times 120\ \text{s} = 48°\]

  1. The robot turned 90°. (b) After two minutes of standing still, the computed heading is wrong by 48°.

Check: Part (a) can be verified without the samples at all — 60 °/s for 1.5 s is 90° — so the sampling arithmetic is consistent. Part (b) is the uncomfortable one: an error of 48° is more than half a right angle, produced by a machine that never moved. The magnitude is entirely believable, because integration adds the error at every single sample and never removes any of it.

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

gyroscope sensor Working principle: A small mass inside a MEMS chip is kept vibrating along a fixed direction. When the chip rotates, the Coriolis effect deflects the vibrating mass sideways, at right angles to both the vibration and the axis of rotation, by an amount proportional to the rate of rotation. Capacitive sensing structures on the chip measure this tiny deflection and on-chip electronics convert it into a calibrated angular velocity, delivered as a digital value for each axis. Components: Vibrating proof mass suspended on micro-springs, drive circuitry to sustain the vibration, capacitive sensing fingers, on-chip amplifier with temperature compensation, and a digital interface such as I2C or SPI. Advantages: Measures rotation directly, smoothly and with very little delay, which is what fast stabilisation requires. Unaffected by magnetic fields, unlike a compass, and unaffected by the pull of gravity, unlike an accelerometer. Small, low in cost and low in power as a MEMS device, and easily sampled at high rates. Limitations: Suffers from zero-bias drift, so an angle obtained by integrating its output grows steadily more wrong and cannot be trusted over long periods. Gives no absolute orientation whatever — it cannot say which way the robot is facing, only that it is turning. Reports rotation, not position, so it says nothing about how far the robot has travelled. Sensitive to vibration, which it may report as rotation. Saturates and loses all information if the rotation exceeds the selected range. Where it is used: As part of an inertial measurement unit on mobile robots, providing orientation and motion data; in balancing robots, where the rate at which the body is tipping must be sensed instantly so that the wheels can be driven to correct it; in drone autopilots, where roll and pitch rates are counteracted many times a second to hold the aircraft steady; in camera gimbals, which counter-rotate to keep a camera level as the base moves; and for measuring the rotational speed of a joint or platform without any physical contact with it.

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.

finding the tilt of a robot from its accelerometer

Given: A robot is standing motionless on a ramp. Its accelerometer, mounted with the x axis pointing forward along the chassis and the z axis perpendicular to the deck, reads \(a_x = 3.36\) m/s² and \(a_z = 9.22\) m/s². The y reading is zero.

Find: The angle of the ramp to the horizontal, and a check that the readings are self-consistent.

Method: With the robot at rest the only acceleration present is that due to gravity, which is 9.81 m/s² acting vertically. On a ramp inclined at \(\theta\), gravity resolves into a component along the deck of \(g\sin\theta\) and one perpendicular to it of \(g\cos\theta\). Their ratio gives the tangent of the tilt, and the ratio is used rather than either reading alone because it does not depend on knowing \(g\) precisely.

\[\tan\theta = \frac{a_x}{a_z} = \frac{3.36}{9.22} = 0.3644\]

\[\theta = \tan^{-1}(0.3644) = 20.0°\]

Check on consistency:

\[\sqrt{a_x^2 + a_z^2} = \sqrt{(3.36)^2 + (9.22)^2} = \sqrt{11.29 + 85.01} = \sqrt{96.30} = 9.81\ \text{m/s}^2\]

The ramp is inclined at about 20° to the horizontal.

Check: The two readings combine to a total of 9.81 m/s², exactly the acceleration due to gravity, which is what a stationary sensor must show. Had the total come to, say, 12 m/s², the robot would not have been stationary at all and the tilt calculation would not apply — which is the whole difficulty described in the next subsection.

Q. If an accelerometer can measure acceleration, can I integrate it twice to find how far the robot has travelled, the way a gyroscope’s rate is integrated to give an angle?

A. In principle yes, and in practice no. Integrating once gives velocity and integrating again gives position, but every small error in the reading is accumulated twice over. A gyroscope’s bias grows an angle error steadily; a double integration grows a distance error far faster, and the computed position is useless within seconds. Accelerometers are never used on their own to measure distance travelled.

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

accelerometer Working principle: A small proof mass inside a MEMS chip is suspended on silicon springs. When the chip accelerates, inertia makes the mass lag behind and deflect the springs by an amount proportional to the acceleration. Interleaved capacitive fingers detect the deflection and on-chip electronics convert it into a calibrated value for each axis. Because the support force that holds the chip against gravity is itself sensed, a stationary chip reports a total of 1 g directed along the vertical, from which its tilt can be found. Components: Proof mass on micro-springs, fixed and moving capacitive sensing fingers, on-chip amplifier with temperature compensation, and a digital interface such as I2C or SPI; three sensing structures, one per axis. Advantages: Gives an absolute reference to the vertical, which a gyroscope cannot, so it can report a steady tilt indefinitely without drifting away. Detects sudden linear motion, impacts and vibration that other sensors miss. Small, inexpensive and low in power as a MEMS device, and commonly packaged with a gyroscope in one chip. Limitations: Cannot separate the acceleration due to gravity from the acceleration due to the robot’s own movement, so tilt readings are only reliable when the robot is still or moving steadily. Cannot be integrated twice to give position, because the error grows far too quickly. Picks up vibration, which appears as noise on every axis. Reports nothing at all about rotation about the vertical axis, since turning on a flat floor does not change the direction of gravity within the chip. Where it is used: Tilt sensing on robots and on drones at start-up, to establish which way is level; detecting that a robot has started or stopped moving, and detecting collisions as a sudden spike; monitoring vibration to warn that a motor or wheel is out of balance, and detecting impacts beyond a safe threshold; recognising gestures such as a device being shaken; and fall detection on wearable and human-assist robots, so that protection can be triggered.

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.

Table 13.10 – gyroscope and accelerometer compared as sensors of a robot’s own motion | Feature | Gyroscope | Accelerometer | |—|—|—| | Quantity measured | Angular velocity, in °/s or rad/s | Linear acceleration, in m/s² or g | | Reading when perfectly still | Approximately zero | A total of 1 g along the vertical | | Gives absolute orientation | No; only the rate of change | Yes for tilt, by sensing the direction of gravity | | Behaviour over a short interval | Accurate, smooth and fast | Noisy, and corrupted by the robot’s own motion | | Behaviour over a long interval | Drifts away steadily as the bias accumulates | Stays correct on average; does not drift | | Senses rotation about the vertical axis | Yes | No | | Main weakness | Zero-bias drift when integrated to an angle | Cannot separate gravity from movement |

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

Q5. A gyroscope tells a machine how fast it is turning. Why does it still need an accelerometer to work out which way is up?

A. Because a gyroscope measures only the rate of turning, never an absolute position. Held perfectly still at any angle it reads zero, so on its own it cannot say whether the machine is level or on its side. An angle can be obtained by adding up the rate over time, but every small error in the reading is added in too and never removed, so that angle drifts steadily away from the truth. An accelerometer supplies what is missing: a stationary one always senses gravity as a 1 g pull along the vertical, giving a fixed reference that does not drift. Combining the two — the gyroscope for fast, smooth changes and the accelerometer to keep pulling the estimate back towards true vertical — gives an orientation that is both responsive and correct over time, which is why the two are almost always found in the same package.

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.

Table 13.11 – the four outward-looking sensors of this chapter compared as sources of information about the environment | Feature | IR | Ultrasonic | LIDAR | Touch | |—|—|—|—|—| | What it reports | Intensity of returned infrared, read as nearness or as surface brightness | Distance, from the echo time | Distance paired with the angle it was taken at | That contact has occurred, and in some types how firm it is | | Typical range | A few millimetres to about 80 cm, depending on type | About 2 cm to 4 m | About 6 m to 30 m indoors | Contact only | | Blind to | Transparent objects, and dark or steeply angled surfaces | Objects within the blind zone, soft absorbing materials, steeply angled surfaces | Anything in the shadow of a nearer object; for a 2D unit, anything outside its scanning plane | Everything it has not physically touched | | Effect of ambient light | Degraded, and possibly defeated, by strong sunlight | None | None | None | | Effect of target colour and finish | Large; a black cloth close by reads like a white card far away | Negligible | Small, except for very dark or mirror-like surfaces | None | | Directional information | Detects roughly ahead within a narrow cone; no bearing | Poor; the object is somewhere within a wide cone | Excellent; each distance carries its own angle | Only the fixed position of the sensor itself | | Response | Microseconds to milliseconds | About 23 ms for a reading out to 4 m | Thousands of readings per second, a full scan 5–15 times a second | Immediate, apart from the debounce interval | | Relative cost and data handling | Lowest cost, negligible processing | Low cost, negligible processing | Highest cost, substantial processing and power | Lowest cost, negligible processing |

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.

Set up an IR proximity module and an ultrasonic module side by side, both reporting to the serial monitor. Present each of these to them at the same fixed distance: white paper, black cloth, a sheet of glass, a cushion, and a smooth board turned to about 45°. Record which surfaces each sensor reads correctly, and use the two sets of results to explain why a robot in a hospital corridor would carry both.

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
  1. A robot both acts on the world and perceives it. The parts that act are actuators; the parts that perceive are sensors.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. Of the six sensors studied, IR, ultrasonic, LIDAR and touch report on the environment; gyroscopes and accelerometers report on the robot’s own motion.
  7. 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
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. 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.
  11. 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
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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
  1. 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.
  2. 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.
  3. 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
  1. 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, SPI or CAN.
  2. 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.
  3. An unconnected input pin floats and returns meaningless, wandering readings; it does not return zero.
  4. 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
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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
  1. 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.
  2. 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.
  3. 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.
  4. 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

  1. 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.
  2. Actuator — a component that converts supplied energy, usually electrical, into a controlled mechanical movement of a part of the robot.
  3. 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.
  4. Analogue output — a sensor output that is a voltage varying continuously with the quantity being measured.
  5. Angular resolution — the angle between one measurement and the next as a scanning sensor sweeps its beam round.
  6. Angular velocity — the rate at which something is rotating about an axis, measured in °/s or rad/s.
  7. Armature — the set of current-carrying coils on the rotor of a DC motor, on which the turning force acts.
  8. 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.
  9. Blind zone — the region immediately in front of an ultrasonic sensor, within which an object is too close to be measured at all.
  10. Brushes — the fixed carbon blocks pressed against the commutator, through which current enters and leaves the rotating armature.
  11. 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.
  12. 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.
  13. 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.
  14. Contact bounce — the rapid chatter of a mechanical switch’s contacts as they open or close, lasting a few milliseconds.
  15. Coriolis effect — the apparent sideways deflection of an object moving within a rotating frame of reference, used by a gyroscope to sense rotation.
  16. DC motor (direct current motor) — an electric motor that runs on direct current and produces continuous rotation of its shaft.
  17. Deadband — the small range of error inside which a servo’s control circuit takes no corrective action.
  18. Debouncing — ignoring changes in a switch reading until it has stayed the same for a settling period, so that one press is counted once.
  19. Digital output — a sensor output having only two states, high or low, usually produced by comparing a measurement against a threshold.
  20. Drift — a slow systematic wandering of a sensor’s reading over time or with temperature, even when the measured quantity has not changed.
  21. Duty cycle — the fraction of each cycle of a switching signal for which it is high, usually stated as a percentage.
  22. 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.
  23. Error — in a control system, the difference between the commanded value and the actual measured value.
  24. Feedback — information about a system’s output returned to influence its input.
  25. Field of view — the cone within which a sensor responds to an object.
  26. Floating input — an input pin connected to nothing, whose voltage drifts under electrical noise so that its readings are meaningless.
  27. FSR (force-sensitive resistor) — a thin flexible component whose resistance falls as the pressure applied to it increases.
  28. Gearmotor — a DC motor with a gear train on its output shaft, which divides the speed and multiplies the torque.
  29. Gyroscope — a sensor that measures the rate at which the device is rotating about one or more axes.
  30. H-bridge — an arrangement of four switching elements in a motor driver that allows current to be passed through a motor in either direction.
  31. IMU (inertial measurement unit) — a package containing a gyroscope and an accelerometer, and sometimes a magnetometer, whose readings are combined to estimate orientation.
  32. 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.
  33. Latency — the total delay between an event occurring in the world and the robot’s response to it appearing at its actuators.
  34. 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.
  35. Limit switch — a switch with a lever or roller actuator, placed to be struck at a particular point of a mechanism’s travel.
  36. MEMS (microelectromechanical systems) — tiny mechanical structures etched into silicon alongside the circuitry that reads them.
  37. 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.
  38. 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.
  39. No-load speed — the speed a motor’s shaft reaches at a given supply voltage with nothing attached to it.
  40. Noise — the random fluctuation present in every sensor reading, which can be reduced by averaging.
  41. Open-loop control — control in which the output is commanded but never measured, so the system cannot detect whether the command was achieved.
  42. 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.
  43. Point cloud — the set of points produced by a scanning sensor, each marking a surface at a measured distance and angle.
  44. Potentiometer — a resistor with a sliding contact whose resistance varies with the contact’s position, used inside a servo to report shaft angle.
  45. 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.
  46. 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.
  47. Response time — how long a sensor takes to produce a valid reading after the measured quantity changes or after it is asked.
  48. Rotor — the rotating part of a motor, carrying the armature and fixed to the shaft.
  49. Sense–plan–act loop — the repeating cycle in which a robot senses its situation, decides on an action, commands its actuators, and senses again.
  50. Sensor — a device that detects a physical quantity and converts it into an electrical signal the controller can read.
  51. Sensor fusion — combining the readings of two or more sensors so that each covers the other’s weakness.
  52. 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.
  53. 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.
  54. Stall current — the current a motor draws when its shaft is held still, the largest current it will take.
  55. Stall torque — the torque at which a motor’s shaft stops turning altogether, the hardest it will push.
  56. Stator — the stationary part of a motor, which provides the magnetic field.
  57. Threshold — a set level against which a measurement is compared to produce a two-state output.
  58. Time-of-flight — the interval between sending a pulse and receiving its reflection, from which distance is calculated.
  59. 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.
  60. Touch sensor — a sensor that reports physical contact, and in some types how firm that contact is.
  61. Transducer — the part of a sensor that actually converts one form of energy into another.
  62. Ultrasonic sensor — a sensor that measures distance by emitting a burst of sound above the range of human hearing and timing its echo.
  63. 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

  1. A DC motor draws its largest current when
  1. it is spinning freely with no load
  2. its shaft is held so that it cannot turn
  3. its supply voltage is reduced to half
  4. its back emf is nearly equal to the supply voltage
  1. For a typical hobby servo receiving pulses every 20 ms, the pulse width that commands the centre of its travel is about
  1. 0.5 ms
  2. 1.0 ms
  3. 1.5 ms
  4. 2.0 ms
  1. 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.
  1. Both A and R are true, and R is the correct explanation of A.
  2. Both A and R are true, but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.
  1. 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
  1. Fill in the blanks.
  1. The component that reverses the current in each armature coil of a DC motor to sustain rotation is the ____________.
  2. The fraction of each cycle for which a switching signal stays high is called the ____________.
  3. The region immediately in front of an ultrasonic sensor in which an object cannot be measured is called the ____________.
  4. Inside a servo motor, the actual position of the output shaft is reported by a ____________.
  1. State whether each of the following is true or false.
  1. An input pin left unconnected reads 0 when tested with analogRead().
  2. An ultrasonic sensor gives the same reading for a white card and a black cloth placed at the same distance.
  3. A standard hobby servo can be used to drive a robot’s wheel continuously.
  4. Averaging many readings reduces noise but does not remove drift.
  1. Write the full form of each of the following abbreviations: PWM, ADC, LIDAR, IMU, MEMS, SLAM.

13.16 Check Your Concepts

  1. 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.

  2. 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.

  3. 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.

  4. Give reasons for the following.

  1. An ultrasonic sensor cannot measure an object placed 1 cm from its face.
  2. An IR proximity sensor that works well indoors becomes unreliable near a sunlit window.
  3. A common ground wire must be run between an Arduino UNO and an L298N motor driver even though each has its own supply connection.
  1. 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.

  2. 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.

  3. 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

  1. A student wires a single BO gearmotor as follows.
  • Motor terminals to OUT1 and OUT2 of an L298N module.
  • A 6 V battery pack: positive lead to the +12V terminal of the L298N, negative lead to the GND terminal of the L298N.
  • IN1 of the L298N to Arduino pin 7, IN2 to pin 8, ENA to 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.

  1. 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);
}
  1. How many lines does the fragment print, and what exactly is printed on each?
  2. What value of duty causes the loop to end?
  3. After the loop has finished, what PWM value remains on pin 9, and what is the motor doing?
  1. An HC-SR04 module 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
  1. Calculate the distance reported by measurements 1, 2 and 5.
  2. State what measurement 3 tells the robot, and explain why treating it as a distance of 0 cm would be dangerous.
  3. Measurements 2 and 4 were taken with nothing in the scene moving. Name the sensor property that accounts for the difference between them.
  1. 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
  1. Calculate the torque each drive motor must produce to hold the robot moving steadily up the ramp. Take \(g = 9.81\) m/s².
  2. State, with reasons drawn from the table, whether Motor P is a suitable choice.
  3. 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

  1. 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 L298N driver, 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.

  1. 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.
  2. 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.
  3. 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.
  1. 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.
  1. 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.
  2. 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.
  3. 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.