Chapter 11: Single-Board Computers, Microcontroller Architecture and Decision Making

On 20 July 1969, minutes from the surface of the Moon, the computer aboard the lunar module Eagle interrupted the landing with an alarm code: 1202. A little later it raised another, 1201. Neither meant that the machine had failed. Both meant that it had been given more work than it could finish in the time available, and that it was throwing some of that work away.

The Apollo Guidance Computer was tiny by any measure you would recognise. Its program was fixed in about thirty-six thousand words of memory that could not be overwritten in flight, and it had roughly two thousand words of erasable memory for the numbers it was working on. The alarms arose because the rendezvous radar was left in a setting that kept demanding attention, eating into the spare time the computer needed for the descent.

What saved the landing was how the machine had been built to decide. Its tasks were ranked. When the work would not fit, it restarted, ran the highest-priority jobs — steering the engine, updating the guidance — and dropped the rest. The crew landed with the alarms still appearing.

Every robot you will build faces the same three questions in miniature. Where does the program live, and where do the working numbers live? What happens when two things demand attention at once? And how does a machine turn a measurement into a decision?

Photograph

Fig. 11.0-1 – the Apollo Guidance Computer display and keyboard unit (the DSKY) together with the computer chassis, photographed straight on so that the numeric display panel, the keypad and the caution and status lights are all legible. Sourcing note: a NASA or museum photograph of the real hardware or a flight-configuration unit; artist’s impressions, film stills, screen captures of simulator software and cropped close-ups showing only the keypad are unusable.

NoteCuriosity Corner

Q1. That computer kept its instructions in one memory and its working numbers in another. Why do control computers still split memory that way, and what does the split buy them? Q2. The Apollo machine set some jobs aside to finish more urgent ones on time. How does a modern robot controller recognise an event that cannot wait its turn? Q3. A robot builder can choose a chip the size of a postage stamp or a board that runs a full operating system. What actually decides which one a robot needs? Q4. A sensor hands the controller a voltage, not a yes or a no. How does that voltage become a decision the robot can act on? Q5. Why can a robot be made to move forward only when two conditions are true at the same time, and how is that condition written so a controller can test it?

This chapter will answer all five of these questions.

11.1 The Computing System of a Robot

A robot is easy to describe as a body. There is a chassis, there are wheels or joints, there are motors to drive them, and there are sensors bolted where they can see something useful. Yet none of that moves on its own. A motor turns because a voltage is applied to it, and something must decide when to apply that voltage, in which direction, and for how long.

That deciding part is the controller — the computing element of the robot, which reads what the sensors report, works out what should happen next, and issues the electrical signals that make it happen. Everything in this chapter is about the controller: what it is made of, how it is organised inside, and how it turns a measurement into a decision.

The controller is also the part a student most often gets wrong when planning a robot, because it is chosen last and by habit. A board is picked because it was in the kit, and only afterwards does the builder discover that it cannot supply the pins, the speed or the memory the task needs. Choosing well means understanding what is inside the board.

11.1.1 Sensing, Deciding and Acting

Watch an automatic door in a shop. A sensor above the frame notices something approaching, a small circuit decides that the door should open, and a motor slides it back. The three actions happen in that fixed order, and then the whole thing repeats — the sensor looks again, the circuit decides again, the motor is told again.

A robot works in exactly the same cycle, endlessly. A sensor converts something physical — a distance, a temperature, a reflected beam of light — into an electrical signal. The controller reads that signal and compares it against what the program expects. It then sends a command to an actuator, the component that converts electrical energy into motion or some other physical effect, and the robot changes what it is doing. Then the cycle begins again.

This repeating cycle is called the sense–plan–act loop, and it is the backbone of every robotic system. Fig. 11.1-1 shows one turn of the loop drawn out, with the last arrow returning to the first block, because the loop never runs once — it runs continuously for as long as the robot is powered.

Diagram

Fig. 11.1-1 – flow: physical quantity (distance to a wall) → sensor produces an electrical signal → controller reads the signal → controller compares it with the programmed threshold and decides → command sent to the motor driver → motor turns and the robot moves → the distance to the wall changes, with the last arrow returning to the first block to close the loop; each arrow labelled with what travels along it (physical quantity, signal, decision, command, motion)

Why the speed of the loop matters

The loop takes time. Reading a sensor takes time, the decision takes time, and the command takes time to reach the motor. While all of that is happening, the robot has not stopped — it is still moving at whatever speed it was already travelling.

So a slow loop means a robot that acts on stale information. The controller decides on the basis of where the wall was, not where it is. This is why an engineer treats the time taken by one turn of the loop as a design quantity to be measured, not an accident to be tolerated.

how far a robot travels during one turn of its control loop

Given: forward speed of the robot, \(v = 0.30\) m/s; time taken by one complete turn of the sense–plan–act loop, \(t = 20\) ms.

Find: the distance the robot covers between one sensor reading and the next.

Method: during one loop the speed is effectively constant, so the distance travelled is \(d = v \times t\). The loop time must first be converted from milliseconds to seconds, since the speed is in metres per second: \(20\) ms \(= 0.020\) s.

\[d = v \times t = 0.30 \text{ m/s} \times 0.020 \text{ s} = 0.0060 \text{ m}\]

\[d = 0.0060 \text{ m} \times 1000 = 6.0 \text{ mm}\]

the robot travels 6.0 mm between one reading and the next.

Check: 6 mm is a small fraction of a typical 150 mm chassis, so the robot’s picture of the world is only slightly out of date, and the magnitude is sensible. Had the loop taken 200 ms instead, the same arithmetic would give 60 mm — nearly half a chassis length of blind travel, which is why a delay() of a fifth of a second inside a control loop is a real design fault and not a stylistic one.

Q. A laptop is far more powerful than any robot controller. Why is it not used as one?

A. Computing power is not the difficulty. A laptop has no pins that a sensor can be wired to, it takes tens of seconds to start, and its operating system shares the processor among many programs, so the time between an event and the response to it varies from one moment to the next. A robot needs pins, an instant start and predictable timing far more than it needs speed.

11.1.2 Where the Decision Is Actually Made

The computer inside a robot belongs to a family of machines that most people never think of as computers at all. There is one in a washing machine, one in a microwave oven, one in a digital weighing scale and several in a car. Each is built into a larger product, runs one fixed program, and has no keyboard or screen of its own.

A computing system of this kind is called an embedded system, because the computer is embedded inside the equipment it controls rather than being a general-purpose machine the user programs afresh each day. The robot’s controller is an embedded system, and that shapes every demand made on it.

NoteDefinition

An embedded system is a computing system built into a larger device, dedicated to controlling that device, running a fixed program stored in the device itself rather than serving as a general-purpose computer.

Four demands follow from that role, and they explain almost every design choice in the rest of this chapter.

First, the controller must connect directly to electrical signals. A sensor does not send a file; it holds a pin at a voltage, or pulses it, and the controller must be able to read that pin and drive other pins in return.

Second, it must respond within a known time. The gap between an event happening and the controller responding to it is called the latency of the system, and in robotics what matters is not only that the latency is small but that it is predictable. A response that usually takes 2 ms but occasionally takes 200 ms is worse than one that always takes 10 ms, because a robot cannot be designed around behaviour that varies unpredictably.

Third, it must be modest in its power consumption, because a robot carries its supply on board and every milliampere spent on computing is a milliampere not available for driving motors.

Fourth, it must start instantly. A robot arm that had to boot for half a minute after every power cut would be unusable on a production line.

11.1.3 Two Kinds of Computing Board

Two quite different kinds of board are used to meet those demands, and a robotics student meets both. They are not rivals so much as specialists.

The first is the microcontroller: a single chip that holds a processor, its memory and its input-output hardware together, and runs one program directly on that hardware with no operating system underneath. It is small, cheap, frugal with power, and starts working within milliseconds of being switched on. Its strength is timing — it does a modest job at a precise and repeatable moment.

The second is the single-board computer (SBC): a complete computer built on one printed circuit board, running a full operating system such as Linux, with memory measured in gigabytes and storage on a card or a drive. Its strength is capability — it can process a camera image, hold a map of a building, run several programs at once and talk to a network.

A useful way to hold the difference is that a microcontroller is good at doing a small thing exactly on time, while a single-board computer is good at doing a large thing whenever it can. Fig. 11.1-2 shows where each sits in a robot’s electronics.

Diagram

Fig. 11.1-2 – block diagram of a robot’s computing system: a sensors block on the left with arrows carrying signals into a central controller block; the controller block drawn as two stacked parts labelled single-board computer (high-level tasks) and microcontroller (low-level timing) with a two-way arrow between them labelled data link; an arrow from the microcontroller to a motor driver block labelled command; an arrow from the motor driver to a motors block labelled power; a battery block at the bottom with dashed arrows to every other block labelled power supply

Many robots carry only one of the two. A line-following robot built in a school workshop needs nothing beyond a microcontroller, because reading two sensors and setting two motor speeds is a small job that must happen on time. A robot that recognises ripe fruit from a camera image needs a single-board computer, because that job is far beyond a single chip. Larger machines carry both, and the sections that follow will show why that pairing works so well.

The rest of this chapter takes the two boards in turn — first the microcontroller and what is inside it, then the single-board computer — before returning to the question of how the controller, whichever kind it is, converts sensor readings into decisions.

11.2 The Microcontroller

11.2.1 What a Microcontroller Is

Open a desktop computer and you find the work shared out among many chips on a large board: a processor in one socket, memory in another, storage on a separate drive, and further chips handling the ports along the back edge. The parts are separate because each can then be chosen, upgraded and replaced on its own.

A microcontroller takes the opposite approach. The processor, the memory that holds the program, the memory that holds the working values, the clock circuitry that paces everything, and the hardware that connects to the outside world are all fabricated on a single piece of silicon and sealed in one package. Fig. 11.2-1 shows such a chip: what looks like one component is an entire computer.

Photograph

Fig. 11.2-1 – a 28-pin dual in-line package microcontroller chip, such as the ATmega328P, photographed against a plain background beside a common object for scale (a one-rupee coin or a matchstick); the printed part marking on the top face and both rows of pins must be legible. Sourcing note: a plain product or laboratory photograph of the real chip; renderings, illustrations and photographs in which the part marking cannot be read are unusable.

NoteDefinition

A microcontroller is a complete computing unit fabricated on a single chip, integrating a processor, program memory, data memory, clock circuitry and input-output hardware, and designed to run one stored program that senses and controls a physical device.

The pieces of hardware built onto the chip alongside the processor — the timers, the converter that reads analogue voltages, the ports, the communication units — are called peripherals. In a desktop computer a peripheral is something you plug in, such as a printer. Inside a microcontroller a peripheral is a block of circuitry on the same die as the processor, waiting to be switched on by the program.

That integration is the whole point. Because a peripheral sits beside the processor rather than at the far end of a cable, the program can start a measurement or change a pin in a handful of clock cycles, and it can do so at a moment it chooses. In writing and in conversation the short form MCU is often used in place of the full word.

A microprocessor and a microcontroller are not the same thing. A microprocessor is the processing core alone, and needs external memory and support chips before it can do anything. A microcontroller is that core with its memory and peripherals already beside it, which is why one chip and a power supply are enough to build a working robot controller.

11.2.2 Why a Robot Uses a Microcontroller

The four demands set out in section 11.1.2 — direct electrical connection, predictable timing, low power and instant starting — describe a microcontroller almost exactly, which is no accident, since these chips were designed for precisely this kind of work.

What the chip does well

Its pins are the connection. A sensor is wired to a pin, and a single instruction reads whether that pin is high or low, or what voltage is present on it. Nothing sits between the program and the hardware.

Its timing is predictable, because there is no operating system deciding what should run next. The program written by the engineer is the only program on the chip, so an instruction executes when the flow of the program reaches it and not at some later moment chosen by a scheduler. This property is called deterministic timing, and it is the single strongest reason a microcontroller is trusted with a motor.

Its appetite for power is small — typically tens of milliamperes while running, and far less in a sleep state — which matters greatly on a robot carrying its own battery.

And it starts at once. Power is applied and the program begins within milliseconds, because there is no operating system to load.

What the chip does badly

Every one of those strengths is bought with a limitation, and an engineer must know them before choosing.

Memory is the tightest constraint. A common robotics microcontroller offers a few tens of kilobytes for the program and a few kilobytes for working values. That is ample for reading sensors and driving motors, and hopeless for storing an image.

There is no file system and no screen. Results are not saved to a document; they are sent out over a wire to something else that can store or display them.

Only one program runs. The chip cannot do a heavy computation and stay responsive at the same time, because a long calculation blocks everything behind it.

And processing an image, holding a map of a building, or running a machine learning model is simply out of reach. Those tasks belong to the other kind of board.

how many sensor readings will fit in the data memory of a microcontroller

Given: data memory available on the chip, 2 KB of SRAM, where 1 KB \(= 1024\) bytes; each stored distance reading is held in an int variable occupying 2 bytes; the rest of the program’s variables and its stack are estimated to need 400 bytes.

Find: the largest number of readings that can be held in an array in data memory.

Method: the memory left for the array is the total data memory minus the memory reserved for everything else. Dividing that remainder by the size of one reading gives the number of readings that fit. Whole readings only, so the result is rounded down.

\[\text{total data memory} = 2 \times 1024 \text{ bytes} = 2048 \text{ bytes}\]

\[\text{memory left for the array} = 2048 \text{ bytes} - 400 \text{ bytes} = 1648 \text{ bytes}\]

\[\text{number of readings} = \frac{1648 \text{ bytes}}{2 \text{ bytes per reading}} = 824\]

824 readings can be stored.

Check: the figure is physically sensible — at one reading every 20 ms, 824 readings cover about 16 s of travel, which is a short run across a laboratory floor and nothing like a day’s logging. This is exactly why a robot that must keep a long record sends its readings out to another device instead of holding them on the chip.

11.2.3 Microcontrollers Commonly Used in Robotics

Hundreds of microcontrollers are manufactured, and a robot builder meets only a handful of families. Four are described here because they are widely used in teaching laboratories and in working machines, and because the differences between them show what an engineer is really choosing when a chip is selected. None is better than the others in general; each is better for a particular job.

The ATmega328P is an 8-bit chip and the one at the heart of the Arduino Uno. It offers a generous number of pins for its size, a converter for reading analogue sensors, and hardware for generating the pulses that control motor speed. Its appeal for a first robot is that its behaviour is simple enough to reason about completely.

The ATmega2560 is from the same family and is used on the Arduino Mega 2560. It is chosen when a design runs out of pins or memory — a robot arm with six servos, several limit switches and a display will exhaust a smaller chip’s pins long before it exhausts its speed.

The STM32 family uses a 32-bit core and is chosen when the control loop itself is demanding: faster arithmetic, a richer set of timers, and more communication ports than an 8-bit chip can offer. Balancing robots and motor controllers that must run their loops hundreds of times a second are typical homes for it.

The ESP32 is a 32-bit chip with Wi-Fi and Bluetooth built onto the same die. It is chosen when the robot must talk to a phone, a laptop or a network without a separate radio module — for a telemetry link from a field robot, or a machine controlled from across a workshop.

Table 11.1 sets the four side by side. Read it for the pattern rather than for the numbers: moving down the table, memory and speed grow, and so does the complexity of the tools needed to program the chip.

Table 11.1 – typical figures for four microcontrollers used in robotics; program memory, data memory and clock frequency are typical values for the common board version of each chip and vary with the exact part number | Microcontroller | Core and typical clock | Program memory (Flash) | Data memory (SRAM) | ADC resolution | Commonly chosen for | |—|—|—|—|—|—| | ATmega328P | 8-bit, 16 MHz on the Arduino Uno | 32 KB | 2 KB | 10-bit | first robots, simple sensing and motor control | | ATmega2560 | 8-bit, 16 MHz on the Arduino Mega 2560 | 256 KB | 8 KB | 10-bit | designs needing many pins and larger programs | | STM32 family (F1, F4) | 32-bit, tens to well over a hundred megahertz | varies widely with the part | varies widely with the part | 12-bit | fast control loops and precise timing | | ESP32 | 32-bit dual core, up to about 240 MHz | on the module, commonly 4 MB | about 520 KB on chip | 12-bit | robots needing Wi-Fi or Bluetooth on the controller |

Notice the ADC resolution column, because it is the one figure in the table that changes what a robot can actually sense. A 10-bit converter divides its measuring range into 1024 steps, while a 12-bit converter divides the same range into 4096 steps, so the finer converter can distinguish smaller changes in a sensor’s output. Section 11.3.6 returns to what that means in volts.

Q. A faster clock sounds better. Does raising it always make a robot perform better?

A. No. A faster clock helps only if the processor is the slow part of the loop, and often it is not. An ultrasonic sensor takes a few tens of milliseconds to return a reading, and no clock speed shortens that wait. A faster chip also draws more current, which shortens the run time of a battery-powered robot. Speed is worth paying for when the arithmetic is heavy, not when the robot is simply waiting for the physical world.

Open the Arduino IDE with an Arduino Uno connected, compile any working sketch, and read the two lines the IDE prints at the end of the compilation. They report how much of the 32 KB of program memory and how much of the 2 KB of dynamic memory your sketch uses. Add one array of 200 int values to the sketch, compile again, and note by how many bytes the dynamic memory figure rises.

11.3 Inside a Microcontroller

A microcontroller is sold as a single component, but it is not a single thing. Inside the package are eight or nine distinct blocks of circuitry, each doing one job, joined by a set of internal wires along which values travel. This section takes those blocks one at a time and then puts them back together as a diagram you can read.

Do not treat what follows as a parts list to be memorised. Each block exists because a control task demanded it, and knowing which block does what is how an engineer works out why a robot behaves as it does — why a reading is coarse, why a motor stutters, why an event was missed.

11.3.1 What Architecture Means in an Embedded System

In everyday speech, architecture is about buildings. In computing it means something close to the same idea: the architecture of a chip is the way its parts are arranged, how instructions and data are stored, and along which paths information moves between the parts.

Architecture is not decoration, because it decides behaviour that a robot builder can measure. How quickly one turn of a control loop finishes, how soon an urgent event is attended to, and how much of the chip’s memory a program may use are all consequences of the arrangement inside.

Two levels of the word are used, and they are easy to confuse. The narrower sense concerns only how program instructions and data are held in memory and moved to the processor, and section 11.4 deals with that. The wider sense — the one used in this section — is the whole practical design of the chip: the core, the memories, the clock, and every peripheral block around them.

11.3.2 The Processing Core

At the centre of the chip is the processing core, the part that actually executes the program. It is built from three kinds of hardware, shown in Fig. 11.3-1.

The control unit is the coordinator. It brings in each instruction in turn, works out what that instruction means, and switches on whichever parts of the chip are needed to carry it out.

The arithmetic logic unit (ALU) does the work that involves values: addition and subtraction, comparison of one number with another, and the logical operations on which section 11.7 is built.

The registers are a very small number of storage locations inside the core itself, each holding a single value that the core is working on at this instant. They are far faster to reach than memory, which is why a value being added or compared is brought into a register first.

Diagram

Fig. 11.3-1 – block diagram of a microcontroller processing core: three labelled blocks inside a boundary marked processing core — control unit, arithmetic logic unit and registers; a two-way arrow between registers and arithmetic logic unit labelled operands and results; arrows from the control unit to both other blocks labelled control signals; two arrows crossing the boundary to blocks outside marked program memory and data memory, labelled instructions in and data in or out

The core does not run a program in one continuous action. It repeats a short cycle, over and over, for every single instruction in the program.

the fetch–decode–execute cycle Statement: the processing core executes a program by repeating three steps for each instruction in turn — fetch the instruction from program memory, decode it to determine the operation and its operands, and execute it, after which the cycle begins again with the next instruction. In words: the core does one small thing at a time, and the program is simply a very long list of those small things carried out in order. Why it holds: the core has no way of knowing what a program means as a whole. It holds the address of the next instruction, brings that instruction in, obeys it, and advances the address. Used for: it explains why the number of instructions executed per second sets the speed of a control loop, and why a long calculation delays everything written after it. Watch out: the cycle is strictly sequential in the basic model, so nothing in the program happens “in the background” unless a peripheral or an interrupt makes it happen. A program waiting inside a delay() is not idle by choice — the core is still stepping through instructions that do nothing useful.

11.3.3 The Memory Subsystem

A robot controller needs to remember three quite different kinds of thing, and a microcontroller provides three kinds of memory to hold them. Fig. 11.3-2 shows them side by side.

The program itself is held in flash memory. This is non-volatile memory, meaning its contents survive when power is removed, which is why a robot switched on next morning still knows what to do. The fixed program stored there, which defines the behaviour of the device, is called its firmware.

The values a running program works with — sensor readings, counters, the results of calculations — are held in static random-access memory (SRAM). SRAM is volatile: everything in it is lost the moment power is removed or the chip is reset. That is not a flaw. It guarantees that the robot starts each time from a clean, known state rather than from whatever it happened to be doing when it was switched off.

A third, smaller memory sits between the two. Electrically erasable programmable read-only memory (EEPROM) is non-volatile like Flash, but it is meant to be written by the running program rather than by the programmer. It is where a robot keeps the few values that must survive a power cut but are not part of the program — a sensor calibration figure measured in the laboratory, a chosen speed setting, the number of hours the machine has run.

Diagram

Fig. 11.3-2 – block diagram of the memory subsystem of a microcontroller: three labelled memory blocks — program memory (Flash), data memory (SRAM) and EEPROM — each connected by a two-way arrow to a central processing core block; each memory block annotated with what it holds (firmware; variables, arrays and stack; calibration values and settings) and with the word non-volatile or volatile

Table 11.2 – Flash, SRAM and EEPROM compared; sizes and endurance figures are typical values for the ATmega328P and vary with the chip | Feature | Flash (program memory) | SRAM (data memory) | EEPROM | |—|—|—|—| | What it holds | the firmware, and fixed constants | variables, arrays and the stack while the program runs | small values that must survive power-off | | Contents survive power-off | yes | no | yes | | Written by | the programmer, when the chip is loaded | the running program, constantly | the running program, occasionally | | Typical size | 32 KB | 2 KB | 1 KB | | Typical write endurance | about 10,000 write cycles | unlimited | about 100,000 write cycles | | Speed of access | fast to read | fastest | slow to write |

The write endurance row is the one students overlook. EEPROM does not last forever: it tolerates on the order of a hundred thousand writes to a location, which is enormous if a calibration value is saved once a week and exhausted within hours if a program writes a sensor reading to the same location inside its main loop.

expecting a variable to survive a power cut What students do: they store a calibration value the robot measured — a wheel diameter, a light threshold — in an ordinary variable, and expect it to still be there after the robot is switched off and on. What happens: the variable was in SRAM, which is volatile, so the value is gone and the robot behaves as though it had never been calibrated. The fix: write values that must survive to EEPROM, and read them back into a variable when the program starts. Ordinary variables are for the present run only.

11.3.4 Clock and Reset Circuitry

Nothing inside a microcontroller happens when it feels like it. Every action is paced by a steady stream of electrical pulses produced by an oscillator, usually a quartz crystal or a resonator. That stream is the clock, and one pulse of it is a clock cycle.

The clock is what makes timing possible at all. Because the core knows how many cycles an operation takes, it can count cycles to measure time, generate a pulse of a chosen length, or send a bit at a chosen rate. If the clock is inaccurate, every one of those goes wrong together: motor pulses drift, serial communication garbles, and timed measurements read incorrectly.

how long one clock cycle lasts, and how many fit into a millisecond

Given: clock frequency of the microcontroller, \(f = 16\) MHz \(= 16 \times 10^{6}\) Hz.

Find: the duration of one clock cycle, and the number of clock cycles that occur in 1 ms.

Method: the period of a repeating signal is the reciprocal of its frequency, \(T = 1/f\). The number of cycles in a given time is that time divided by the period, or equivalently the frequency multiplied by the time.

\[T = \frac{1}{f} = \frac{1}{16 \times 10^{6} \text{ Hz}} = 6.25 \times 10^{-8} \text{ s} = 62.5 \text{ ns}\]

\[n = f \times t = 16 \times 10^{6} \text{ Hz} \times 1 \times 10^{-3} \text{ s} = 16\,000 \text{ cycles}\]

one clock cycle lasts 62.5 ns, and 16 000 cycles occur in 1 ms.

Check: the magnitude is sensible. Sixteen thousand cycles per millisecond means that even a program needing several hundred instructions per pass can complete a turn of its loop in well under a millisecond, which is exactly why a chip of this modest speed is adequate for driving a small robot.

Beside the clock sits the reset circuitry, which puts the chip into a known starting state — every register cleared, the program counter pointing at the first instruction. Reset happens when power is first applied, when the reset pin is pulled low, and, on most chips, when the supply voltage sags below a safe level. That last case is called brown-out detection, and it matters on a robot: when a motor starts, it draws a surge of current that can drag the supply down, and a controller without brown-out protection may carry on executing instructions on a voltage too low to execute them correctly.

11.3.5 General-Purpose Input and Output Ports

The pins along the edges of the chip are its contact with the physical world. Most of them are general-purpose input/output (GPIO) pins, and the word general-purpose is meant literally: the program decides, at run time, whether a pin is an input to be read or an output to be driven.

As an input, a pin reports one of two states. On a chip running at 5 V, a voltage above roughly 3 V is read as HIGH and a voltage below roughly 1.5 V is read as LOW. Between those thresholds the reading is not defined, which is why a slowly changing signal can produce a flickering result.

As an output, a pin is connected internally either to the supply rail or to ground, so the program can put a chosen voltage on a wire. This is how an indicator LED is lit, how a relay is switched, and how a control signal is sent to a motor driver.

A pin that is set as an input and connected to nothing is not at 0 V. It is left electrically floating, picking up whatever stray voltage the surroundings induce in it, and reading it produces meaningless, changing values. To prevent this, most microcontrollers can switch a resistor inside the chip between the pin and the supply, called a pull-up resistor, which holds the pin at a definite HIGH until something external pulls it down. Fig. 11.3-3 shows the standard arrangement for a push button.

Diagram

Fig. 11.3-3 – circuit: Arduino UNO with a tactile push button; one side of the button wired to digital pin 2, the other side wired to GND; the internal pull-up resistor of the microcontroller drawn as a dashed resistor inside the board outline, connected between pin 2 and the 5V rail, labelled internal pull-up enabled in software; annotation showing pin 2 reads HIGH when the button is released and LOW when it is pressed; no external resistor in the circuit

Q. With an internal pull-up enabled, a pressed button reads LOW and a released button reads HIGH. Why is the logic the wrong way round?

A. Because the pull-up holds the pin high, and the button’s only job is to connect the pin to ground. Pressing therefore pulls the pin down. The arrangement is used because it needs no external components and because the pin is never left floating in either state. The inversion is dealt with in software, and section 11.7.5 shows the operator that does it.

There is a hard limit on what a pin can drive. A GPIO pin is a signal source, not a power source: it can supply on the order of 20 mA safely, with an absolute maximum in the region of 40 mA, and the whole chip is limited too. An LED with its series resistor is well within that. A motor is not, by a factor of a hundred or more.

driving a motor straight from a GPIO pin What students do: they wire a small DC motor between a digital pin and ground, expecting digitalWrite(pin, HIGH) to run it. What happens: the motor stalls or barely twitches, the supply voltage dips, the chip may reset, and the output driver on that pin can be permanently damaged. The failure is often intermittent, which makes it hard to diagnose. The fix: put a motor driver such as the L298N between the controller and the motor. The pin then carries only a control signal of a few milliamperes, while the motor’s current is drawn from the battery through the driver.

11.3.6 The Analogue Interface

Most of the physical world does not arrive as HIGH or LOW. A temperature sensor, a soil moisture probe, a potentiometer and a light-dependent resistor all deliver a voltage that varies continuously. A digital core cannot work with a continuous voltage, so a converter stands between the two.

The analogue-to-digital converter (ADC) measures the voltage on a pin and returns a whole number representing it. The number of distinct values it can return is fixed by its resolution, stated in bits: a 10-bit converter produces one of \(2^{10} = 1024\) levels, and a 12-bit converter one of \(2^{12} = 4096\) levels, across its measuring range.

Diagram

Fig. 11.3-4 – a smoothly rising and falling analogue voltage curve drawn against time, with a horizontal grid of equally spaced quantisation levels across the vertical axis; the digitised output drawn over it as a staircase that jumps from one level to the next; vertical dashed lines marking the instants at which the converter samples; labels for one quantisation step on the vertical axis and one sampling interval on the horizontal axis

the smallest voltage change a 10-bit converter can distinguish

Given: converter resolution, 10 bits; measuring range from 0 V to a reference voltage of 5.00 V.

Find: the voltage represented by one step of the converter’s output.

Method: a converter of \(n\) bits divides its range into \(2^{n}\) equal levels, so one step corresponds to the range divided by the number of levels.

\[\text{number of levels} = 2^{10} = 1024\]

\[\text{one step} = \frac{5.00 \text{ V}}{1024} = 4.88 \times 10^{-3} \text{ V} = 4.88 \text{ mV}\]

one step corresponds to about 4.88 mV.

Check: the figure is sensible and useful. It says that a sensor whose output changes by 2 mV over the range you care about will produce no change at all in the reading, while a sensor swinging over a full volt gives about 200 distinguishable steps — plenty. Resolution is only ever adequate or inadequate relative to the sensor it is measuring.

The reverse conversion, from a number to a genuine analogue voltage, needs a digital-to-analogue converter, and this is where a common misunderstanding arises. Many robotics microcontrollers, including the ATmega328P on the Arduino Uno, have no digital-to-analogue converter at all. What they offer instead is described next, and it is not the same thing.

11.3.7 Timers and Pulse Width Modulation

A timer is a counter built into the chip that increments with the clock, independently of the program. Because it runs on its own, it keeps counting while the core is busy with other instructions, and the program can look at its value whenever it wishes.

That independence is what makes non-blocking timing possible. A program that must flash a light every second can either sit inside a delay() doing nothing for a second, or read the timer, note that a second has passed, and get on with reading its sensors in between. On a robot, the second approach is almost always the correct one.

Timers do more than count. They can capture the exact moment an input pin changes, which is how the echo time of an ultrasonic sensor is measured, and they can change an output pin automatically when the count reaches a set value, which is how precisely timed pulses are generated.

The most important use of that last ability is pulse width modulation (PWM): switching an output rapidly between fully on and fully off, and controlling the proportion of time it spends on. That proportion is called the duty cycle, expressed as a percentage.

pulse width modulation Statement: a load is driven by a rapidly repeating rectangular waveform of fixed frequency, and the average power delivered is controlled by varying the duty cycle — the fraction of each period for which the output is on. In words: instead of supplying half the voltage, the chip supplies the full voltage half the time, fast enough that the motor or lamp responds only to the average. Why it holds: a motor’s speed and a filament’s brightness respond to average power over many cycles, not to the instantaneous voltage, because the mechanical inertia of the rotor and the thermal inertia of the filament smooth out the switching. Used for: setting motor speed through a driver, dimming lights, and generating the control pulses that position a servo motor. Watch out: the output pin is still switching between full supply and zero, so PWM is not a substitute for a true analogue voltage. A sensor or an amplifier expecting a steady voltage will see the switching, not the average, unless a filter is added.

Diagram

Fig. 11.3-5 – three PWM waveforms drawn one below the other on a common time axis, each a rectangular wave of the same period; the first labelled 25 per cent duty cycle, the second 50 per cent and the third 75 per cent; on each waveform the on time and the full period are marked with dimension arrows; a dashed horizontal line across each showing the average value, rising from the first waveform to the third

11.3.8 The Interrupt System

Suppose a robot must stop the instant its bumper switch is struck. One way is for the program to check the switch every time round its main loop. This is called polling, and it works — provided the loop is short. If the loop happens to be waiting for an ultrasonic sensor when the bumper closes, the strike is noticed late, or, if the switch has already sprung back, not at all.

The alternative is to let the event announce itself. An interrupt is a signal from a peripheral or a pin that causes the core to suspend the program it is running, execute a short piece of code written for that event, and then resume the main program exactly where it left off. The short piece of code is the interrupt service routine (ISR).

NoteDefinition

An interrupt is a hardware signal that suspends the normal execution of the program, transfers control to a designated interrupt service routine, and returns to the interrupted point once that routine has finished.

The everyday parallel is a doorbell. You could walk to the door every two minutes to see whether anyone has arrived, which is polling, or you could fit a bell and get on with your work, which is an interrupt. The bell is better not because it is faster but because it never misses a caller and costs nothing while nobody is there.

Diagram

Fig. 11.3-6 – a horizontal timeline showing program execution: a long bar labelled main program, interrupted partway by a vertical arrow from below labelled interrupt signal from bumper switch; a short bar above labelled interrupt service routine (stop motors, set flag); a return arrow leading back down to the main program bar, which continues from the exact point at which it was suspended; the short duration of the routine marked with a dimension arrow

Table 11.3 – polling and interrupts compared | Feature | Polling | Interrupt | |—|—|—| | How the event is noticed | the program checks the input each time round the loop | the hardware signals the core when the event occurs | | Response time | depends on how long the loop takes; varies | short and largely independent of what the loop is doing | | Risk of missing a brief event | high, if the event ends before the next check | very low | | Processor time used when nothing happens | wasted on repeated checks | none | | Complexity of the program | simple, all in one flow | greater; the routine must be short and share data carefully | | Suited to | inputs that change slowly and are not urgent | urgent, brief or unpredictable events |

Interrupts are ranked. When two arrive at once, the chip’s interrupt controller decides which is served first, so a time-critical source such as an overcurrent trip can take precedence over a routine one such as a completed sensor conversion.

That ranking is not a modern convenience. It is exactly what kept the Apollo landing running when the computer ran short of time, and it is why the alarms in the opening story were a sign of a working design rather than a broken one.

Q2. The Apollo machine set some jobs aside to finish more urgent ones on time. How does a modern robot controller recognise an event that cannot wait its turn?

A. it does not recognise the event by looking for it. The event is wired to an interrupt source, so the hardware itself stops the main program and runs a short service routine for that event as soon as it occurs. Where several such events can happen, the interrupt controller ranks them, and the higher-priority routine runs first — the same principle of ranked tasks that let the guidance computer abandon low-priority work and keep steering the descent.

An interrupt service routine must be kept short. While it runs, the main program is suspended, so a routine that itself takes a long time defeats the purpose. The usual practice on a robot is for the routine to do the minimum — stop the motors, record the time, set a flag — and leave the rest of the response to the main loop.

11.3.9 Communication Interfaces

A robot controller rarely works alone. It reads an inertial sensor over a bus, drives a display, exchanges commands with a second board, and reports back to a laptop. Microcontrollers therefore include dedicated hardware for the standard serial links, so that the program need only hand over a byte rather than time every bit itself.

Four are provided across the range of chips used in robotics: UART, I2C, SPI and CAN. At the level of architecture, what distinguishes them is how many wires they use and how many devices can share them.

UART is a two-wire link between exactly two devices, one wire in each direction, and is the link a board uses to talk to a computer over its USB connection.

I2C is a two-wire bus that many devices share, each answering to its own address, which makes it the usual choice for connecting several small sensors without running out of pins.

SPI uses four wires and is faster than either, which suits displays, memory cards and any device that must move a lot of data.

CAN is a robust two-wire bus designed for noisy environments and long runs, and is found in vehicles and in larger industrial machines.

Whichever is used, one rule holds without exception: two boards that exchange signals must have their grounds joined. A signal voltage is meaningless unless both ends measure it from the same reference, and a link between two separately powered boards with no common ground will behave erratically or not at all.

11.3.10 Reading the Complete Block Diagram

Fig. 11.3-7 assembles every block described in this section into the diagram you will meet whenever a microcontroller’s architecture is presented.

Diagram

Fig. 11.3-7 – complete block diagram of a microcontroller: a boundary marking the edge of the chip; inside it a central horizontal line labelled internal bus; blocks connected to the bus by two-way arrows and labelled central processing unit (control unit, ALU, registers), program memory (Flash), data memory (SRAM), EEPROM, clock and reset circuit, timers and PWM unit, interrupt controller, analogue-to-digital converter, general-purpose input/output ports, and serial communication unit (UART, I2C, SPI, CAN); an additional block drawn with a dashed outline labelled digital-to-analogue converter (present on some chips only); arrows crossing the chip boundary from the input/output ports and communication unit to external blocks labelled sensors, motor driver and other boards

The line running through the middle of the diagram is the bus: the set of internal conductors along which addresses, data and control signals travel between the blocks. Everything on the chip is joined to it, and that is what makes the collection a computer rather than a box of parts.

Two things about the diagram are worth stating plainly, because both are commonly misread.

The digital-to-analogue converter is drawn with a dashed outline because it is not present on every chip. Many popular robotics microcontrollers, the ATmega328P among them, have none, and use pulse width modulation where a varying output is needed.

And the diagram is a map of function, not of physical layout. The blocks are not arranged inside the chip in the positions shown; the diagram records which block does what and what talks to what, which is the only thing an engineer needs from it.

Take Fig. 11.3-7 and trace, with a pencil, the path of a single obstacle detection: from the ultrasonic sensor at the pin, through every block involved, to the signal that reaches the motor driver. Write down the blocks in the order the information passes through them, then mark which one measures the echo time and which one would notice a bumper switch without being asked.

11.4 How Instructions and Data Are Organised

11.4.1 Program Memory and Data Memory

Section 11.3.3 established what a microcontroller remembers and where. This section asks a different question, and it is the narrower sense of the word architecture: by what path does the processing core reach those memories, and can it reach two of them at once?

Look at what the core actually asks for while a program runs. It needs a steady supply of instructions, which it only ever reads, and which it usually wants in the order they are stored. It also needs data — the sensor readings, counters and results the instructions work on — which it both reads and writes, and which it wants in no particular order.

Every location in memory has a memory address, a number identifying it, and the complete set of addresses a core can use is its address space. The architectural decision is whether instructions and data live in one address space reached by one set of wires, or in two address spaces reached by two.

That sounds like an internal detail of no consequence to a robot builder. It is not. It decides whether an instruction can be fetched at the same moment a sensor value is being stored, and therefore how steady the timing of a control loop is.

11.4.2 Von Neumann Architecture

The older and simpler answer is to keep everything together. In the Von Neumann architecture, program instructions and data share a single memory space, and the core reaches that memory over a single system bus.

The consequence follows immediately from having one road. An instruction fetch and a data transfer cannot both use the bus at the same instant, so the core does them one after the other: fetch the instruction, then read the operand, then write the result. Memory transactions are serialised.

Diagram

Fig. 11.4-1 – block diagram of the Von Neumann organisation: a block labelled central processing unit on the left; a single thick two-way arrow labelled system bus (instructions and data) running to one memory block on the right labelled unified memory, drawn as a single rectangle divided by a dashed line with the upper part annotated program instructions and the lower part data; the dashed line labelled a boundary in one address space, not two separate memories

Von Neumann architecture Statement: program instructions and data are held in a single memory space and are transferred between memory and the processing core over one shared system bus, so instruction fetches and data accesses take place one after another. In words: one memory, one road to it, and traffic takes turns. Why it holds: with a single bus there is only one path between core and memory, so two transfers cannot be in progress at the same time. Used for: keeping hardware simple, cheap and low in power, and allowing a program to treat code and data uniformly, which is what makes program loading and interpretation straightforward. Watch out: as instruction traffic and data traffic compete for the same bus, throughput is limited by that shared path. This limitation is known as the Von Neumann bottleneck, and it is most noticeable in tight loops that read or write memory on almost every instruction.

The bottleneck is worth naming because it is not a defect that better manufacturing will remove. It follows directly from the choice of one bus, and the only way past it is to change the organisation.

11.4.3 Harvard Architecture

The alternative is to separate the two kinds of traffic entirely. In the Harvard architecture, program memory and data memory are distinct, each with its own bus, so the core has two independent paths to memory rather than one.

The name comes from the Harvard Mark I, an early computer that kept its instructions on punched tape and its working numbers in mechanical counters — separate storage by physical necessity rather than by design choice.

Because the two paths are independent, an instruction can be fetched while a data value is being read or written in the same clock period. Nothing waits for anything else, and the time a given sequence takes stops depending on whether the bus happened to be busy.

Diagram

Fig. 11.4-2 – block diagram of the Harvard organisation: a block labelled central processing unit in the centre; on the left a memory block labelled program memory (Flash) joined by a two-way arrow labelled instruction bus; on the right a memory block labelled data memory (SRAM) joined by a separate two-way arrow labelled data bus; the two arrows drawn clearly apart with a note that both may carry a transfer in the same clock period

Harvard architecture Statement: program instructions and data are held in separate memories, each reached over its own bus, so an instruction fetch and a data access can proceed in parallel. In words: two memories, two roads, and no waiting for the other kind of traffic. Why it holds: independent buses cannot contend with each other, so a fetch and a data transfer occupy different hardware at the same moment. Used for: sustaining a high rate of completed instructions, and — more valuable in robotics — making the time taken by a sequence of instructions steady from one pass to the next. Watch out: two buses and two memory interfaces mean more circuitry, so the chip is more complex and costs more to make. The split is also fixed at manufacture: memory set aside for the program cannot be borrowed for data when a program runs short of working space.

The separation brings a second benefit that is easy to miss. Because the two memories are distinct, the size of the program and the size of the working data can be chosen independently, and code stored in non-volatile program memory cannot be overwritten by a data operation that has gone wrong.

Harvard chips also lend themselves to overlapping the stages of the fetch–decode–execute cycle, so that one instruction is being executed while the next is already being fetched. This overlapping is called pipelining, and it raises the number of instructions completed per second without raising the clock frequency at all.

11.4.4 Comparing the Two Organisations

Table 11.4 – Von Neumann and Harvard organisations compared | Feature | Von Neumann architecture | Harvard architecture | |—|—|—| | Memory organisation | instructions and data share one memory space | program memory and data memory are separate | | Buses | one shared system bus | two independent buses, instruction and data | | Access pattern | fetches and data transfers are serialised | a fetch and a data access can occur in parallel | | Effect on speed | limited by the shared path, the Von Neumann bottleneck | higher sustained rate of completed instructions | | Timing behaviour | varies with how much memory traffic the code generates | steadier and more predictable, cycle to cycle | | Hardware and cost | simpler, smaller, cheaper, lower power | more circuitry, higher cost and complexity | | Use of memory | any part of the space can hold code or data as needed | the division between code and data space is fixed |

mistaking two memories for a Harvard organisation What students do: they see that a chip has Flash for the program and SRAM for variables and conclude that it must be Harvard. What happens: the conclusion may be wrong, because the distinction is not whether two memory devices exist but whether they sit in separate address spaces reached over separate buses. A chip can hold code in Flash and data in SRAM and still place both in one address space served by a single bus, which is a Von Neumann organisation. The fix: look for the buses, not the memory chips. Two independent paths from the core to memory means Harvard; one shared path means Von Neumann.

11.4.5 Why Robotics Controllers Favour the Harvard Organisation

Most microcontrollers used in robotics, including the AVR family to which the ATmega328P belongs and the widely used PIC family, are built on the Harvard organisation. Three properties explain the preference, and only one of them is speed.

The first is steady timing. A robot’s control loop must take very nearly the same time every pass, because the corrections it computes assume a fixed interval between readings. Separate buses remove one of the main sources of variation, since the core never has to wait for a bus another transfer is using.

The second is that the split matches how embedded programs are actually used. The firmware is fixed, written once and read millions of times, so it belongs in non-volatile program memory. Sensor values change thousands of times a second and belong in fast, volatile data memory. Two memories with different characteristics are not an inconvenience here; they are what the job wants.

The third is prompt handling of interrupts. When an interrupt arrives, the core must fetch the first instructions of the service routine while the data of the interrupted program is still being handled, and independent buses make that transition quicker and more consistent.

Q1. That computer kept its instructions in one memory and its working numbers in another. Why do control computers still split memory that way, and what does the split buy them?

A. the split gives the core two independent paths to memory, so it can fetch the next instruction while it reads or writes a value, instead of taking turns on a single shared bus. What that buys a control computer is chiefly predictability — the time a sequence takes stops depending on how much memory traffic it happens to generate — together with the practical benefit that fixed firmware sits in memory that cannot be overwritten by a stray data operation, while fast working memory is reserved for values that change constantly.

Two honest qualifications belong with this. Almost every real microcontroller is a modified Harvard design rather than a pure one: the separate buses are there, but the core is also given a way to read constant values — lookup tables, fixed text — out of program memory, because storing them in scarce data memory would be wasteful.

And the Von Neumann organisation has not been abandoned. Where cost, chip area and power matter more than the last measure of timing predictability, a single-bus design is a sound engineering choice, and some low-cost 32-bit cores use exactly that. Neither organisation is correct in the abstract. Each is correct for a particular set of demands.

Q. Does the Harvard organisation make a chip faster, in the sense of a higher clock frequency?

A. No. The clock frequency is set by the oscillator and by what the silicon can withstand, and the organisation of the buses does not change it. What Harvard changes is how much useful work is completed per clock cycle, because the core stalls less often, and how consistent that work rate is. A Harvard chip and a Von Neumann chip running at the same 16 MHz tick at the same rate; the difference shows in how often one of them is waiting.

11.5 The Single-Board Computer

11.5.1 What a Single-Board Computer Is

A desktop computer is a collection of separate parts: a processor in its socket, memory in its slots, a drive on a cable, and expansion cards along one edge, all bolted to a large board inside a case. A single-board computer takes that entire collection and builds it onto one printed circuit board, typically no larger than a postcard, as Fig. 11.5-1 shows.

Photograph

Fig. 11.5-1 – top view of a Raspberry Pi single-board computer photographed straight down against a plain background, with a common object such as a matchbox beside it for scale; the large processor package, the memory chip, the microSD card slot, the USB and Ethernet connectors, the video output connectors and the long input/output pin header along one edge must all be visible and in focus. Sourcing note: a plain product or laboratory photograph of a real board; renderings, illustrations, and photographs with a case fitted or with cables obscuring the connectors are unusable.

The important difference from a microcontroller is not size but what the board runs. A single-board computer runs a full operating system, usually a version of Linux — the same kind of software that manages a laptop, sharing the processor among several programs, providing a file system, and offering networking, graphics and a command line.

NoteDefinition

A single-board computer is a complete computer built on one printed circuit board, containing the processor, memory, storage interface and input-output interfaces needed to run a full operating system.

That capability is what a robot buys when it carries one. A camera image can be processed, a map of a building can be held in memory, several programs can run at once, and results can be logged to a file or sent across a network — none of which a microcontroller can do.

The price is paid in three currencies. The board draws far more current, it takes tens of seconds to start, and its timing is no longer exactly predictable, because the operating system decides moment by moment which program gets the processor.

11.5.2 Boards Commonly Used in Robotics

Three families appear repeatedly in robotics laboratories and in working machines, and they are chosen for genuinely different reasons.

The Raspberry Pi is the most widely used general-purpose board. It is inexpensive, well documented, easy to set up, and carries a long input-output header that connects directly to sensors, drivers and displays. It is the usual first single-board computer in a school workshop.

The NVIDIA Jetson family — the Jetson Nano, Jetson Xavier NX and Jetson Orin Nano among them — is built for artificial intelligence work at the edge of a system, meaning computation done on the robot itself rather than sent away to a server. These boards carry hardware for accelerating the calculations that vision and neural network models require, and are chosen when a robot must recognise objects, track them or judge depth from a camera in real time.

The BeagleBone Black and BeagleBone AI are known for dependable real-time input and output, because they include programmable units alongside the main processor that handle time-critical signals directly. They suit motor control, encoder capture and industrial interfacing, where precise pulse timing is needed on a board that also runs an operating system.

Table 11.5 – three single-board computer families used in robotics, compared by the reason each is chosen rather than by exact specification, since models within each family differ widely | Board family | Particular strength | Typical robotics role | |—|—|—| | Raspberry Pi | low cost, easy setup, generous input-output header | general-purpose robot computing, logging, control and teaching | | NVIDIA Jetson family | hardware acceleration for vision and neural network work | object detection, tracking and depth estimation on the robot | | BeagleBone Black / BeagleBone AI | dedicated real-time input-output units on the board | precise pulse generation, encoder capture, industrial interfacing |

11.5.3 Processor, Memory and Storage

Fig. 11.5-2 gives the architecture of a single-board computer as a block diagram, in the same way that Fig. 11.3-7 gave the architecture of a microcontroller. Comparing the two diagrams is the quickest way to see what has been added and what has gone.

Diagram

Fig. 11.5-2 – block diagram of a single-board computer: a large block labelled system on a chip containing four inner blocks labelled central processing unit, graphics processing unit, memory controller and high-speed interface blocks; outside it, blocks joined by two-way arrows labelled random-access memory, storage (microSD card or solid-state drive), power management and regulators, network interfaces (Ethernet, Wi-Fi, Bluetooth), USB ports, display output (HDMI), camera interface and general-purpose input/output header; arrows crossing the board boundary from the header and USB blocks to external blocks labelled sensors, motor driver and microcontroller board; a heat sink drawn on top of the system on a chip block

The largest chip on the board is not a processor alone but a system on a chip (SoC): a single die carrying the central processing unit, a graphics processing unit for images and video, the memory controller, and the high-speed interface circuitry, all integrated together. Integration of this kind reduces size and power consumption and improves reliability, since fewer connections run between packages.

Working memory is provided as random-access memory (RAM), and the quantities are of a different order from anything in section 11.3. A microcontroller offers kilobytes; a single-board computer offers gigabytes. It is volatile memory, holding the operating system’s working data, the frames arriving from a camera, and everything the running programs are handling at that moment.

Permanent storage is separate, because the operating system and the robot’s programs must survive being switched off. Most boards boot from a microSD card; some have an eMMC chip soldered on; and where speed or capacity matters, a solid-state drive can be attached over USB or an equivalent high-speed connection. This is where the operating system lives, and where a robot’s logs, photographs and datasets are written.

11.5.4 Power Delivery, Clocking and Thermal Management

Power reaches the board through a USB-C connector, a barrel jack or the pin header, and is then distributed by regulators and, on many boards, a power management integrated circuit, so that each part receives the voltage it needs.

The demand is substantial and, more importantly, it is not steady. A board of this class may draw a few hundred milliamperes while idle and several times that when the processor is working hard and USB devices are attached. A supply chosen for the idle figure will fail exactly when the robot starts doing something interesting.

That variability is why a single-board computer should not share an unbuffered supply with motors. When a motor starts, it pulls a surge of current that drags the rail down, and where a microcontroller would simply reset, an operating system may crash or corrupt the file system it was writing to.

Clocking works as it does on a microcontroller: an oscillator paces the digital circuitry, and the accuracy of that clock keeps communication rates and sampling intervals correct. What differs is timekeeping of the calendar sort. Some boards include a real-time clock with a small backup battery so that the date and time are kept while the board is off; many do not, and instead take the time from the network when they start — which matters if a robot’s data logs are to be stamped correctly while it works in a field with no network.

Finally, these boards get hot. A processor of this power dissipates enough heat that a metal heat sink, and often a small fan, is fitted so that the chip stays within its safe temperature range. Without it the board does not fail outright; it quietly slows itself down to survive, which shows up as a robot that responds well for two minutes and sluggishly thereafter.

The heat sink and the processor beneath it can become hot enough to burn a fingertip after a few minutes of heavy use. Let the board cool before handling it, and always disconnect the supply before adding or moving any wire on the pin header, since a wire touched onto the wrong pin while the board is live can destroy the board or the sensor.

11.5.5 Display, Camera, Networking and USB Interfaces

The interfaces around the edge of the board are what make it a computer rather than a controller, and each has a robotics use.

Display output is provided over HDMI, and on some boards over a ribbon connector intended for small touchscreens. On a robot this is used for a human-machine interface — a screen showing status, a live camera preview, or a dashboard the operator reads while the machine works.

A dedicated camera connector is usually provided, so that an image sensor can be attached directly with low delay and high bandwidth rather than through a general-purpose port. This is the input for line following by vision, object detection and reading printed codes.

Networking is offered through a wired Ethernet port and, on most current boards, through Wi-Fi and Bluetooth built into the design. A robot uses it to receive updated code, to send telemetry to a dashboard and to accept commands from a phone or a laptop.

USB ports accept the peripherals a development bench needs — keyboard, mouse, storage — and, on a working robot, are frequently how a light detection and ranging (LIDAR) unit or a camera is attached, since many such devices present themselves as USB devices.

11.5.6 The General-Purpose Input/Output Header

Along one edge of the board runs a multi-pin header, and this is the part that turns a small computer into a robot controller. It exposes GPIO lines that can be read or driven from a program, together with the standard buses — I2C, SPI and UART — brought out on specific pins. Fig. 11.5-3 shows how the pins are grouped.

Diagram

Fig. 11.5-3 – the 40-pin general-purpose input/output header of a single-board computer drawn as two parallel rows of numbered pins; pins shaded and labelled by group — 3.3 V supply pins, 5 V supply pins, ground pins, general-purpose input/output pins, and the pins carrying I2C, SPI and UART; a caption block at the side stating that the input/output pins operate at 3.3 V logic and that no analogue input is provided

Two facts about this header decide whether a circuit built on it works or destroys the board.

The first is the logic level. The input-output pins of a typical single-board computer operate at 3.3 V, while an Arduino Uno operates at 5 V. A 5 V signal applied to a 3.3 V pin is outside what the pin is designed to withstand.

wiring a 5 V sensor output straight to a 3.3 V input pin What students do: they take a sensor module that has been working on an Arduino Uno at 5 V and connect its output wire directly to a pin on the header of a single-board computer. What happens: the pin is driven above its rated voltage. Sometimes the board appears to work and then fails days later; sometimes the input stops responding at once. The damage is permanent and not repairable in a school workshop. The fix: check the logic level of every device before wiring it. Use a sensor module that can be powered at 3.3 V, or place a level-shifting circuit between the 5 V device and the pin. Power for the module may still come from the 5 V pins; it is the signal pin that must be at 3.3 V.

The second is that many single-board computers, the Raspberry Pi among them, provide no analogue-to-digital converter at all. The header reads digital states only. A sensor that outputs a varying voltage — a light-dependent resistor divider, a soil moisture probe, a potentiometer — cannot be read directly, and needs either an external converter chip on the I2C or SPI bus, or a microcontroller doing the reading and passing the number across.

11.5.7 From Power-On to a Running Robot Program

What happens when the board is switched on follows a fixed order, shown in Fig. 11.5-4, and it explains both the board’s strengths and its slowness.

Diagram

Fig. 11.5-4 – flow: power applied → bootloader in read-only memory executes → operating system loaded from storage into random-access memory → operating system starts its services (file system, network, device drivers) → robot program launched → program reads sensors, computes and issues commands, with the last arrow returning to the program block to show the loop continuing; a time annotation beside the first four blocks reading tens of seconds and beside the last reading milliseconds per pass

A small bootloader held in read-only memory runs first and knows only how to find the operating system in storage and load it. The operating system then starts, sets up the file system, brings up the network and loads the drivers for the attached devices. Only then does the robot’s own program begin.

Once running, the program is one of many the operating system is managing. It reads sensors through the header or over USB, does the heavy work — processing an image, planning a route, updating a map — and issues commands. But it holds the processor only when the scheduler gives it to the program, which is why its timing varies.

Q. The single-board computer is a hundred times faster than a microcontroller. Why is its timing still described as less reliable?

A. Because speed and predictability are different properties. The operating system shares the processor among many programs, and it may pause the robot’s program to service a network packet or write to storage. The pause is short, but it is not the same length every time. A microcontroller running one program alone is slower and yet arrives at the same instruction at the same moment on every pass, which is what a motor pulse needs.

One consequence of running a file system is that the board must be shut down properly. Cutting the power while the operating system is writing to the card can leave the card’s contents damaged and the board unable to start. A robot design that expects the battery to be switched off at any moment needs either a shutdown procedure or an arrangement that stops writing to storage during normal operation.

11.6 Choosing the Right Board

11.6.1 Microcontroller or Single-Board Computer

Everything in the two previous sections comes down to one practical decision that a robot builder must make before anything is wired. Table 11.6 sets the two kinds of board against each other, feature by feature.

Table 11.6 – microcontroller and single-board computer compared | Feature | Microcontroller (MCU) | Single-board computer (SBC) | |—|—|—| | Integration | processor, memory and input-output hardware on one chip | processor, memory, storage and interfaces as separate parts on one board | | Software underneath | none, or a small real-time scheduler | a full operating system such as Linux | | Task handling | one dedicated, repetitive control task | many programs at once, general-purpose computing | | Working memory | kilobytes | gigabytes | | Typical clock | megahertz | gigahertz | | Timing behaviour | deterministic and repeatable | fast on average, but variable pass to pass | | Start-up | within milliseconds of power being applied | tens of seconds while the operating system loads | | Power consumption | very low; suits battery-powered robots | far higher; needs a stable, generous supply | | Analogue input | usually built in | often absent; needs an external converter | | Robotics role | low-level control of sensors, motors and timing | high-level work: vision, mapping, networking, decision-making | | Examples | ATmega328P, STM32, ESP32 | Raspberry Pi, Jetson Nano, BeagleBone |

The table is not a scorecard, and the board with more rows in its favour does not win. The choice is made by asking what the robot’s hardest requirement actually is.

If the hardest requirement is timing — a servo pulse that must be right to a few microseconds, a bumper switch that must stop a motor at once, an encoder pulse that must not be missed — then a microcontroller is the correct answer, and adding a faster board would make the problem worse rather than better.

If the hardest requirement is computation — recognising a ripe tomato in a camera frame, holding a map of a warehouse, planning a route around obstacles that were not there yesterday — then no microcontroller will do, however carefully it is programmed, and a single-board computer is the answer.

Two secondary questions usually settle any remaining doubt. How long must the robot run on its battery, since a single-board computer will empty a pack several times faster? And how quickly must the robot be usable after being switched on, since an operating system takes tens of seconds to become ready?

Q3. A robot builder can choose a chip the size of a postage stamp or a board that runs a full operating system. What actually decides which one a robot needs?

A. the nature of the robot’s hardest task, not its overall ambition. Tasks that must happen at an exact moment — pulses to a servo, a response to a limit switch, a motor speed held steady — belong to a microcontroller, because it runs one program with no operating system deciding when that program gets the processor. Tasks that need heavy computation, large memory, a file system or a network — vision, mapping, logging, remote control — belong to a single-board computer. Battery life and start-up time then settle the remaining cases, and a robot with both kinds of task usually carries both kinds of board.

11.6.2 Where the Arduino Board Fits

Students often ask which of the two categories an Arduino board belongs to, and the confusion is understandable, because an Arduino Uno is a board and a single-board computer is also a board.

Arduino is a microcontroller-based development platform. An Arduino board is built around one microcontroller chip — the ATmega328P in the case of the Uno, shown in Fig. 11.6-1 — and adds the supporting circuitry that makes the chip convenient to use: a USB interface for loading programs, voltage regulation so the board can be powered from several sources, a clock source, and headers that bring the pins out where a wire can reach them.

Photograph

Fig. 11.6-1 – top view of an Arduino UNO board photographed straight down against a plain background; the microcontroller package with its part marking, the USB connector, the barrel power jack, the reset button and both rows of labelled header sockets must be visible and legible. Sourcing note: a plain product or laboratory photograph of a genuine board or an openly licensed compatible board; renderings, illustrations and photographs with shields fitted or wires attached are unusable.

Programs for an Arduino board are called sketches. A sketch is compiled on a computer, transferred over the USB connection, and stored in the chip’s Flash memory, after which the microcontroller executes it directly. There is no operating system between the sketch and the hardware, which is exactly why the timing is dependable.

So the answer is that an Arduino board is not a single-board computer. The test is not how many parts are on the board but whether an operating system runs on it, and on an Arduino board none does. It is a microcontroller with its supporting circuitry laid out conveniently.

Q. The ESP32 has two processing cores, Wi-Fi and Bluetooth. Does that make it a single-board computer?

A. No. Its memory is measured in hundreds of kilobytes rather than gigabytes, it starts within milliseconds, and its software runs either directly on the hardware or under a small real-time scheduler, which arranges tasks by priority but is not a general-purpose operating system with a file system, a desktop and installable applications. It is a capable microcontroller that happens to carry a radio, and it is used and programmed as one.

11.6.3 Using Both Boards in One Robot

The interesting robots are the ones whose hardest requirements are both computation and timing at the same time. A field robot must recognise a weed and hold a straight line down a row. A delivery robot must plan a route and keep its wheel speeds matched. Neither board can do both jobs well.

The standard engineering answer is to use both and give each what it is good at, as Fig. 11.6-2 shows. The single-board computer takes the camera, holds the map, plans the route and decides what should happen. The microcontroller takes the sensors that must be read on time, drives the motor driver, and reports back. A serial link joins them, and the two boards exchange short messages: a target speed going one way, an encoder count and a bumper state coming back.

Diagram

Fig. 11.6-2 – block diagram of a two-board robot controller: a single-board computer block on the left with an arrow in from a camera block labelled image data and an arrow in from a Wi-Fi antenna block labelled commands and telemetry; a two-way arrow labelled UART serial link, with a note that the grounds of the two boards are joined, running to a microcontroller block on the right; arrows from the microcontroller to a motor driver block labelled PWM and direction signals, and from the motor driver to a motors block labelled power from battery; arrows into the microcontroller from an ultrasonic sensor block, an encoder block and a bumper switch block; a battery block at the bottom with dashed arrows to the motor driver and to both boards

the two-board robot controller Working principle: computation and timing are separated onto two boards and joined by a serial link. The single-board computer handles perception, planning and communication, and issues high-level instructions such as a target speed or a heading. The microcontroller receives those instructions and turns them into precisely timed signals for the motor driver, while reading the sensors whose events cannot wait. Components: a single-board computer with a camera and network interface; a microcontroller board; a serial link between them, commonly UART or a USB connection, with the two grounds joined; a motor driver; sensors divided between the two boards according to how urgently each must be read. Advantages: each task runs on hardware suited to it, so motor pulses stay steady while a camera frame is being processed. The microcontroller continues to control the motors even while the operating system is busy or restarting, which is what makes an emergency stop dependable. Development is also simpler, since the two programs can be written and tested separately. Limitations: two programs must be written, matched and kept in step, and a message format between them has to be defined and documented. The link itself becomes a possible point of failure, and the pair costs more, weighs more and draws more current than either board alone. Where it is used: agricultural robots that navigate by vision while driving a straight row; warehouse robots that plan routes while holding wheel speeds; and multirotor drones, where a flight controller built on a microcontroller stabilises the aircraft while a companion computer handles vision and mission planning.

One design rule follows from the arrangement and deserves stating on its own. Anything that must happen for the robot to be safe — stopping on a bumper strike, cutting power when a current limit is exceeded, halting when no command has arrived for a second — belongs on the microcontroller, not on the single-board computer. The board that can be paused by its own operating system is not the board that should be trusted to stop a motor.

11.7 Decision Making with Boolean Operators

11.7.1 A Robot Decision as a Logical Statement

Everything the previous sections described exists so that a controller can do one thing: decide. A robot’s decisions are not vague judgements. Each is a statement that is either true or false at this instant, built out of conditions that are themselves either true or false.

Say aloud what a small press in a workshop must do, and the structure appears on its own: lower the tool only if a part is in position and the guard is closed. There are two conditions, each true or false, joined by a word that says how they combine. A controller can test exactly that.

The branch of mathematics that handles statements of this kind is Boolean logic, in which every value is one of two — true or false, written as 1 and 0. It suits a microcontroller perfectly, since a pin is already either HIGH or LOW and nothing in between.

Three operators are used to combine and modify these values: AND, OR and NOT. Every decision a robot makes, however elaborate, is built from those three.

The behaviour of an operator is set out in a truth table, which lists every possible combination of its inputs together with the resulting output. Because each input has only two possible values, the table is short and complete — there is no case it leaves out, and that completeness is what makes it a design tool rather than an illustration.

NoteDefinition

A truth table is a table listing every possible combination of input values for a logical expression, together with the output the expression produces for each combination.

11.7.2 Turning a Sensor Reading into a Logic Level

Before any operator can be applied, each sensor reading must be reduced to a single true or false. How that is done depends on the sensor.

Some sensors deliver a logic level already. An infrared line sensor module, a bumper switch and a soil moisture module with a digital output all hold their output pin HIGH or LOW, so a single digitalRead() gives the condition directly.

Others deliver a varying voltage, and here a threshold is needed. The analogue-to-digital converter turns the voltage into a number, and the program compares that number with a chosen value: above it means one thing, below it means the other. The comparison is what creates the true or false, as Fig. 11.7-1 shows.

Diagram

Fig. 11.7-1 – flow: analogue sensor produces a varying voltage → analogue-to-digital converter returns a whole number → program compares the number with the chosen threshold → the comparison yields a single true or false condition → the condition is combined with others by Boolean operators → decision reaches the actuator; the comparison block annotated with an example, reading greater than 409 means dark

choosing the converter count that corresponds to a threshold voltage

Given: a light sensor whose output voltage rises as the surroundings darken; the decision is to be taken at 2.00 V; the microcontroller has a 10-bit converter with a reference voltage of 5.00 V, returning counts from 0 to 1023.

Find: the converter count that corresponds to the threshold voltage, so that it can be written into the program.

Method: the converter maps 0 V to a count of 0 and the reference voltage to the highest count, 1023, in proportion. So the count for any voltage is that voltage divided by the reference voltage, multiplied by 1023.

\[\text{count} = \frac{V}{V_{\text{ref}}} \times 1023 = \frac{2.00 \text{ V}}{5.00 \text{ V}} \times 1023\]

\[\text{count} = 0.400 \times 1023 = 409.2 \approx 409\]

the threshold is written into the program as a count of 409.

Check: the figure is sensible, since 2.00 V is two-fifths of the reference and 409 is close to two-fifths of 1023. Note also that one count is worth about 4.9 mV, so writing 409 rather than 410 shifts the decision point by about 5 mV — far less than the noise on a typical sensor wire, and therefore of no practical consequence.

One practical difficulty follows from using a single threshold. When a reading hovers near the threshold, tiny variations push the condition back and forth, and an output driven by it chatters on and off many times a second. The standard remedy is to use two thresholds — one to switch the condition on and a slightly different one to switch it off — so that the reading must move a definite amount before the decision changes.

Q4. A sensor hands the controller a voltage, not a yes or a no. How does that voltage become a decision the robot can act on?

A. in two steps. The analogue-to-digital converter inside the microcontroller measures the voltage on the pin and returns a whole number — one of 1024 levels on a 10-bit converter. The program then compares that number with a threshold count it has been given, and the comparison produces a single true or false. From that point the reading is no longer a voltage at all but a logical condition, which the operators of this section can combine with other conditions to reach a decision.

11.7.3 The AND Operator

The AND operator gives an output of 1 only when every one of its inputs is 1. A single input at 0 forces the output to 0, no matter what the others are doing.

Return to the workshop press. A robotic press lowers its tool onto a component, and it must lower only when the component is properly seated and only when the safety guard across the front is closed. Two sensors report those two facts, and the decision is their AND.

Table 11.7 – truth table of the AND operator, applied to a robotic press with a part-in-position sensor A and a guard-closed sensor B | Part in position (A) | Guard closed (B) | A AND B | Action taken by the controller | |—|—|—|—| | 0 (no part) | 0 (guard open) | 0 | tool stays raised | | 0 (no part) | 1 (guard closed) | 0 | tool stays raised | | 1 (part seated) | 0 (guard open) | 0 | tool stays raised | | 1 (part seated) | 1 (guard closed) | 1 | tool is lowered |

Read the third row carefully, because it is the reason AND is used for safety decisions. The part is correctly seated and the machine is ready in every respect except one — and the tool still does not move. AND is unforgiving by design, and that is precisely what is wanted when the missing condition is a guard between a person and a moving tool.

In embedded C the operator is written &&, and the two conditions are placed on either side of it.

Q5. Why can a robot be made to move forward only when two conditions are true at the same time, and how is that condition written so a controller can test it?

A. because the two conditions are combined with the AND operator, whose output is 1 only when every input is 1. Each sensor is first reduced to a single true or false, and the controller then tests their AND, so a single false condition blocks the action however satisfactory the others are. In a program the test is written with &&, as in if (frontClear && sideClear), and the statement inside runs only when both conditions hold at the same instant.

11.7.4 The OR Operator

The OR operator gives an output of 1 when at least one of its inputs is 1. It produces 0 only when every input is 0.

Where AND is used to insist, OR is used to catch. Consider a warehouse robot that must halt if anything at all indicates trouble. Its front bumper switch closing is reason enough to stop; so is a stop command arriving over the radio link from the supervisor’s console. Neither has to wait for the other.

Table 11.8 – truth table of the OR operator, applied to a warehouse robot with a bumper switch A and a remote stop command B | Bumper struck (A) | Remote stop received (B) | A OR B | Action taken by the controller | |—|—|—|—| | 0 (bumper clear) | 0 (no command) | 0 | robot continues | | 0 (bumper clear) | 1 (stop commanded) | 1 | robot halts | | 1 (bumper struck) | 0 (no command) | 1 | robot halts | | 1 (bumper struck) | 1 (stop commanded) | 1 | robot halts |

Notice the pattern across the two operators. Conditions that must all hold before something is permitted are joined by AND; conditions any one of which is enough to stop or raise something are joined by OR. A great deal of safe design comes down to putting each condition on the correct side of that line.

In embedded C the OR operator is written ||.

11.7.5 The NOT Operator

The NOT operator takes a single input and reverses it. An input of 1 becomes an output of 0, and an input of 0 becomes an output of 1.

It exists because sensors do not always report in the direction the decision needs. A soil moisture module in a nursery outputs 1 when the soil is wet, but the pump must run when the soil is not wet. Rather than rewire anything, the program inverts the reading.

Table 11.9 – truth table of the NOT operator, applied to a nursery irrigation controller whose moisture sensor A outputs 1 when the soil is wet | Moisture sensor (A) | NOT A | Action taken by the controller | |—|—|—| | 0 (soil dry) | 1 | pump runs | | 1 (soil wet) | 0 | pump stops |

The same inversion appears wherever a switch is wired with a pull-up resistor, the arrangement met in section 11.3.5. There the pin reads LOW when the button is pressed, so the program that wants a true for “pressed” applies NOT to what it read. This is so common that a beginner’s first hour with a push button is usually spent discovering it.

In embedded C the NOT operator is written !, placed before the condition it reverses.

11.7.6 Combining the Three Operators

Real decisions rarely use one operator alone. Take the nursery irrigation controller and state its rule in full: run the pump when the soil is not wet, and the tank still holds water, and no one has pressed the manual stop.

Written with the operators, that is a single expression combining all three:

run the pump = (NOT soil wet) AND (tank has water) AND (NOT stop pressed)

A second, separate decision uses OR. An alert lamp should light whenever attention is needed, and there are two independent reasons for that — the tank is empty, or someone has pressed the manual stop:

light the alert = (NOT tank has water) OR (stop pressed)

Diagram

Fig. 11.7-2 – logic diagram of the irrigation controller: three input lines on the left labelled soil wet, tank has water and stop pressed; the soil wet line and the stop pressed line each passing through a small NOT symbol; the inverted soil wet line, the tank has water line and the inverted stop pressed line meeting at a three-input AND symbol whose output is labelled run pump; separately, the tank has water line passing through a NOT symbol and joining the stop pressed line at a two-input OR symbol whose output is labelled light alert

Three inputs give eight possible combinations, and Table 11.10 lists all of them. A table like this is how an engineer checks a rule before writing any code, because it exposes a case that was never considered.

Table 11.10 – complete truth table for the irrigation controller, with W the soil wet condition, T the tank has water condition and S the stop pressed condition | W (soil wet) | T (tank has water) | S (stop pressed) | Run pump = (NOT W) AND T AND (NOT S) | Alert = (NOT T) OR S | |—|—|—|—|—| | 0 | 0 | 0 | 0 | 1 | | 0 | 0 | 1 | 0 | 1 | | 0 | 1 | 0 | 1 | 0 | | 0 | 1 | 1 | 0 | 1 | | 1 | 0 | 0 | 0 | 1 | | 1 | 0 | 1 | 0 | 1 | | 1 | 1 | 0 | 0 | 0 | | 1 | 1 | 1 | 0 | 1 |

Only one row out of eight runs the pump, which is exactly right for a machine that moves water: the permitted case should be narrow and every other case should be safe.

The order in which operators are applied matters, and it is fixed. NOT is applied first, to the condition immediately after it. AND is applied next. OR is applied last. So the expression !a && b || c means “(not a, and b), or c”, which is not what a reader might assume at a glance. Brackets cost nothing and remove the doubt, and a robotics program is a poor place to be clever about precedence.

writing & where && is meant What students do: they write if (soilDry & tankHasWater) with a single ampersand, and the program compiles without complaint. What happens: & is the bitwise operator, which combines the two values bit by bit rather than as logical conditions. With values of 0 and 1 the result often looks correct, which hides the fault. But a condition holding the value 2 — a perfectly ordinary non-zero, and therefore true, value — combined with 1 gives 2 & 1, which is 0, so a test of two true conditions returns false. The fix: use && for logic and || for logical OR, reserving & and | for deliberate bit manipulation. && also stops as soon as the answer is settled, so a false first condition means the second is never even evaluated.

11.7.7 Implementing a Boolean Decision in a Program

The method comes before the code, always. Set out the decision first, and the program becomes a transcription rather than an invention.

deciding whether to run an irrigation pump Input: a soil moisture module giving a digital output, LOW when the soil is wet; a tank level switch closing to ground while water remains; a manual stop button closing to ground while pressed. Output: a control signal to the motor driver that switches the pump, and a signal to an alert lamp. Method:

1. Read the soil moisture pin and set soilWet true if the pin is LOW.
2. Set soilDry to the opposite of soilWet.
3. Read the level switch pin and set tankHasWater true if the pin is LOW.
4. Read the stop button pin and set stopPressed true if the pin is LOW.
5. Set runPump true only if soilDry, tankHasWater and the opposite of stopPressed are all true.
6. Set alert true if the opposite of tankHasWater is true, or if stopPressed is true.
7. Drive the pump control pin high when runPump is true, and low otherwise.
8. Drive the alert pin high when alert is true, and low otherwise.
9. Report all four conditions and the pump state, then wait one second and repeat from step 1.

Why it works: each sensor is reduced to one true or false before any combination is attempted, so the decision is made on conditions with a clear meaning rather than on raw pin states whose polarity is easy to mistake. The pump is permitted only by an AND of every necessary condition, so any single failure stops it. Watch out: a moisture module whose comparator is wired the other way round will invert step 1, and the polarity must be checked against the actual module before the pump is connected. If the level switch is left disconnected, the pull-up holds the pin HIGH, tankHasWater becomes false, and the pump correctly refuses to run — a disconnected sensor should always fail towards the safe state.

This circuit moves water near live electronics. Keep the board, the driver module and the battery pack well clear of the water container and above the level of any spill. Never run a submersible pump dry, since it is cooled by the water it moves. Disconnect the battery before changing any wiring, and have the arrangement checked by your teacher before power is applied.

Diagram

Fig. 11.7-3 – circuit: Arduino UNO powered over USB; soil moisture module VCC to 5V, GND to GND, D0 to digital pin 2; a tactile push button standing in for the tank level switch, one contact to digital pin 3 and the other to GND; a second tactile push button as the manual stop, one contact to digital pin 4 and the other to GND; both button pins marked internal pull-up enabled in software; an alert LED with a 220 ohm series resistor from digital pin 12 to GND; an L298N motor driver module with IN1 to digital pin 8, IN2 to GND, the ENA jumper fitted, the +12V terminal to the positive of a separate 6 V battery pack and the battery negative to the module GND terminal; the mini submersible water pump connected across OUT1 and OUT2; the module GND terminal also wired to the Arduino GND, with that shared line drawn as a single rail labelled common ground; the module’s 5 V output terminal left unconnected and labelled as such

an irrigation controller that combines AND, OR and NOT Problem: run a small pump only while the soil is dry, the tank still holds water and the manual stop is not pressed; light an alert lamp whenever the tank is empty or the stop has been pressed; report the state once a second so that the decision can be watched. Board and components: Arduino UNO; soil moisture sensor module with digital output; two tactile push button switches; one LED with a 220 Ω series resistor; L298N motor driver module; mini micro submersible water pump; separate 6 V battery pack for the pump. Wiring: moisture module VCC to 5V, GND to GND, D0 to pin 2. Tank level switch between pin 3 and GND. Manual stop button between pin 4 and GND. LED anode through the 220 Ω resistor to pin 12, cathode to GND. L298N: IN1 to pin 8, IN2 to GND, ENA jumper fitted, +12V terminal to the 6 V pack positive, battery negative and module GND both to the Arduino GND so that all three share a common ground. Pump across OUT1 and OUT2. The module’s 5 V output terminal is not connected to the board.

// Irrigation controller: three sensor conditions combined with AND, OR and NOT

const int SOIL_PIN = 2;    // moisture module output, LOW when the soil is wet
const int LEVEL_PIN = 3;   // tank level switch, closes to ground while water remains
const int STOP_PIN = 4;    // manual stop button, closes to ground while pressed
const int PUMP_PIN = 8;    // to IN1 of the L298N motor driver
const int ALERT_PIN = 12;  // alert LED through a 220 ohm resistor

void setup() {
    pinMode(SOIL_PIN, INPUT);
    pinMode(LEVEL_PIN, INPUT_PULLUP);
    pinMode(STOP_PIN, INPUT_PULLUP);
    pinMode(PUMP_PIN, OUTPUT);
    pinMode(ALERT_PIN, OUTPUT);
    digitalWrite(PUMP_PIN, LOW);
    Serial.begin(9600);
}

void loop() {
    // Reduce every reading to a single condition before combining any of them
    boolean soilWet = (digitalRead(SOIL_PIN) == LOW);
    boolean soilDry = !soilWet;
    boolean tankHasWater = (digitalRead(LEVEL_PIN) == LOW);
    boolean stopPressed = (digitalRead(STOP_PIN) == LOW);

    boolean runPump = soilDry && tankHasWater && !stopPressed;
    boolean alert = !tankHasWater || stopPressed;

    digitalWrite(PUMP_PIN, runPump);
    digitalWrite(ALERT_PIN, alert);

    Serial.print("Dry=");
    Serial.print(soilDry);
    Serial.print(" Water=");
    Serial.print(tankHasWater);
    Serial.print(" Stop=");
    Serial.print(stopPressed);
    Serial.print(" -> ");
    Serial.println(runPump ? "PUMP ON" : "PUMP OFF");

    delay(1000);
}

Sample output: with the soil dry, the level switch held closed and the stop button untouched, then the stop button pressed and held during the third second, then the stop released and the soil dampened, the Serial Monitor at 9600 baud shows:

Dry=1 Water=1 Stop=0 -> PUMP ON
Dry=1 Water=1 Stop=0 -> PUMP ON
Dry=1 Water=1 Stop=1 -> PUMP OFF
Dry=0 Water=1 Stop=0 -> PUMP OFF

Alongside the printed lines, the pump runs while the first two lines are produced and stops the instant the third is, and the alert LED lights during the third second only.

Identifier description:

[Table:] Table 11.11 – identifiers used in the irrigation controller program | Identifier | Type | Purpose | |—|—|—| | SOIL_PIN | const int | pin number to which the moisture module’s digital output is wired | | LEVEL_PIN | const int | pin number of the tank level switch | | STOP_PIN | const int | pin number of the manual stop button | | PUMP_PIN | const int | pin number carrying the control signal to the motor driver | | ALERT_PIN | const int | pin number driving the alert LED | | soilWet | boolean | true while the moisture module reports wet soil | | soilDry | boolean | the inverse of soilWet, true when watering is wanted | | tankHasWater | boolean | true while the level switch reports water in the tank | | stopPressed | boolean | true while the manual stop button is held down | | runPump | boolean | the combined decision that permits the pump to run | | alert | boolean | the combined condition that lights the alert lamp | [/Table]

Notes: each reading is stored in its own named condition before any operator is applied, which is why the two decision lines can be read aloud as English sentences and checked against Table 11.10. Naming conditions in this way costs two bytes of memory each and saves far more in errors. The one-second delay() is acceptable here because nothing in this system is urgent; on a moving robot the same delay would be a fault, for the reason established by the worked example in section 11.1.1.

the irrigation controller, traced over four passes of loop() for the input sequence in the sample output | Pass | Pin 2 | Pin 3 | Pin 4 | soilDry | tankHasWater | stopPressed | runPump | alert | Pin 8 | Line printed | |—|—|—|—|—|—|—|—|—|—|—| | 1 | HIGH | LOW | HIGH | true | true | false | true | false | HIGH | Dry=1 Water=1 Stop=0 -> PUMP ON | | 2 | HIGH | LOW | HIGH | true | true | false | true | false | HIGH | Dry=1 Water=1 Stop=0 -> PUMP ON | | 3 | HIGH | LOW | LOW | true | true | true | false | true | LOW | Dry=1 Water=1 Stop=1 -> PUMP OFF | | 4 | LOW | LOW | HIGH | false | true | false | false | false | LOW | Dry=0 Water=1 Stop=0 -> PUMP OFF | Result: the pump pin follows the AND of the three permitting conditions and nothing else. Pass 3 shows a single condition — the stop button — overruling two others that are perfectly satisfied, and pass 4 shows the same result reached by a different single condition, the soil having become wet. This is the behaviour Table 11.10 predicted, now confirmed against the code.

With the pump disconnected and the battery pack removed, load the program and watch the Serial Monitor while you press each button in turn. Then change && to || in the line that computes runPump, upload again, and write down which combinations now switch pin 8 high. Predict the answer from Table 11.10 before you look.

11.8 Summary

The computing system of a robot
  1. The controller is the computing element that reads the sensors, decides what should happen next, and issues the signals that make it happen. A robot’s body does nothing until the controller acts.
  2. Sensing, deciding and acting repeat endlessly as the sense–plan–act loop. Because the robot keeps moving while the loop runs, the time one pass takes is a design quantity: at a speed \(v\) and loop time \(t\), the robot travels \(d = v \times t\) on stale information.
  3. A robot controller is an embedded system — a computer built into the device it controls, running one fixed program. That role demands direct connection to electrical signals, predictable latency, low power consumption and instant starting.
  4. Two kinds of board meet those demands. A microcontroller does a small job exactly on time; a single-board computer does a large job whenever the operating system allows it.
The microcontroller
  1. A microcontroller integrates a processor, program memory, data memory, clock circuitry and input-output hardware on one chip, and runs a single stored program with no operating system beneath it. The hardware blocks beside the processor are its peripherals.
  2. Its strengths are deterministic timing, direct hardware access, low power and immediate start-up. Its limitations are severe: memory in kilobytes, no file system, one program at a time, and no capacity for image processing or mapping.
  3. Chips commonly met in robotics include the ATmega328P for first robots, the ATmega2560 where pins and memory run short, the STM32 family for demanding control loops, and the ESP32 where Wi-Fi or Bluetooth is needed on the controller itself.
Inside the chip
  1. Architecture, in its wider sense, is the arrangement of the blocks inside a chip and the paths along which information moves between them. It decides measurable behaviour: how fast a loop completes, how promptly an urgent event is served, and how much memory a program may use.
  2. The processing core is built from a control unit, an arithmetic logic unit and registers, and it executes a program by repeating the fetch–decode–execute cycle for every instruction in turn. Nothing happens in the background unless a peripheral or an interrupt makes it happen.
  3. Three memories serve three purposes. Flash holds the firmware and is non-volatile; SRAM holds variables while the program runs and is volatile; EEPROM holds the few values that must survive a power cut, and tolerates a limited number of writes.
  4. The clock paces every operation, and the period of one clock cycle is \(T = 1/f\). Reset circuitry establishes a known starting state, and brown-out detection prevents the chip from executing instructions on a supply that a motor surge has dragged down.
  5. GPIO pins are read as HIGH or LOW against defined thresholds, and an input connected to nothing floats and reads meaninglessly, which a pull-up resistor prevents. A pin is a signal source of about 20 mA, not a power source, so motors are always driven through a motor driver.
  6. The analogue-to-digital converter turns a voltage into a number, and its resolution in bits fixes how finely it can do so: a 10-bit converter gives \(2^{10} = 1024\) levels across its range. Many microcontrollers have no digital-to-analogue converter at all.
  7. Timers count independently of the program, allowing non-blocking timing, the capture of the moment an input changes, and the generation of precisely timed pulses. Pulse width modulation uses that ability to control average power through the duty cycle, and is not the same as a true analogue output.
  8. Polling means checking an input each time round the loop; an interrupt means the hardware signals the core, which suspends the main program, runs a short interrupt service routine and resumes. Interrupts catch brief and urgent events that polling misses, and where several occur, the interrupt controller ranks them.
  9. Dedicated hardware provides the serial links UART, I2C, SPI and CAN — a two-wire point-to-point link, a two-wire shared bus with addresses, a four-wire fast link, and a robust two-wire bus for noisy environments. Any two boards that exchange signals must have their grounds joined.
  10. The internal bus joins every block on the chip, and the complete block diagram is a map of function, not of physical layout.
How instructions and data are organised
  1. Instructions are read in sequence and never written; data is read and written in any order. The architectural question is whether the two share one address space and one bus or occupy two.
  2. In the Von Neumann architecture, instructions and data share one memory space and one system bus, so transfers are serialised. The hardware is simpler, cheaper and lower in power, but the shared path limits throughput — the Von Neumann bottleneck.
  3. In the Harvard architecture, program memory and data memory are separate, each with its own bus, so an instruction fetch and a data access can proceed in parallel. Throughput is higher, timing is steadier, and the cost is more circuitry and a division between code and data space that is fixed at manufacture.
  4. Robotics controllers, including the AVR and PIC families, generally use the Harvard organisation, chiefly for predictable loop timing, for the natural fit between fixed firmware in Flash and changing values in SRAM, and for prompt interrupt handling. Almost all are modified Harvard designs, able also to read constants out of program memory.
  5. Having two memory devices does not by itself make a chip Harvard. The distinction lies in whether there are two independent buses, not in how many memories exist.
The single-board computer
  1. A single-board computer is a complete computer on one board, running a full operating system, with memory in gigabytes and storage on a card or drive. It buys vision, mapping, multitasking, file storage and networking, and pays in current drawn, start-up time and timing that varies pass to pass.
  2. Boards commonly used include the Raspberry Pi for general-purpose work, the NVIDIA Jetson family for accelerated vision and neural network work on the robot, and the BeagleBone boards for dependable real-time input and output.
  3. The largest chip is a system on a chip, integrating the central processing unit, graphics processing unit, memory controller and high-speed interfaces on one die. Working memory is volatile RAM; the operating system and data live in separate permanent storage.
  4. The supply must be stable and generous, since demand rises sharply under load, which is why such a board should not share an unbuffered supply with motors. Heat sinks and fans keep the processor within its temperature limits, and a board that overheats quietly slows itself rather than failing outright.
  5. Display, camera, network and USB interfaces are what make it a computer, and each has a robotics use — an operator screen, a vision input, a telemetry link, and the port through which many LIDAR units and cameras attach.
  6. The general-purpose input/output header exposes digital pins along with the I2C, SPI and UART buses. Its pins typically operate at 3.3 V, so a 5 V signal applied to one can destroy the board, and many such boards provide no analogue input at all.
  7. On power-up, a bootloader in read-only memory loads the operating system from storage, the operating system starts its services, and only then does the robot’s program run as one of several the scheduler manages. Cutting power without a proper shutdown can corrupt the storage.
Choosing the board
  1. The choice is settled by the robot’s hardest requirement. Exact timing points to a microcontroller; heavy computation points to a single-board computer; battery life and start-up time settle the remaining cases.
  2. Arduino is a microcontroller-based development platform, not a single-board computer. An Arduino board carries one microcontroller chip with supporting circuitry, and its programs run directly on the hardware with no operating system.
  3. Many capable robots carry both boards, joined by a serial link with a common ground: the single-board computer perceives, plans and communicates, while the microcontroller reads urgent sensors and times the motor signals. Anything the robot needs for safety belongs on the microcontroller, since the other board can be paused by its own operating system.
Decision making with Boolean operators
  1. A robot decision is a statement that is either true or false, built from conditions that are themselves true or false. Boolean logic handles such statements with two values, 1 and 0, and a truth table lists every possible combination of inputs with the resulting output.
  2. Before any operator is applied, each sensor reading is reduced to a single condition. A digital sensor gives one directly; an analogue sensor gives a converter count that is compared with a chosen threshold, and a reading hovering at that threshold is steadied by using two thresholds instead of one.
  3. AND gives 1 only when every input is 1, and is used for conditions that must all hold before an action is permitted. OR gives 1 when at least one input is 1, and is used where any single condition is enough to stop or raise something. NOT reverses a single input, and is needed whenever a sensor reports in the opposite sense to the decision.
  4. Operators are applied in a fixed order — NOT first, then AND, then OR — and brackets remove any doubt. In embedded C they are written &&, || and !, and the bitwise operators & and | are not substitutes for them.
  5. A complete truth table is written before the code, because it exposes the combination nobody considered. Naming each condition separately in the program then makes the decision line readable, and lets it be checked directly against that table.

11.9 Key Terms

  1. Address space — the complete set of memory addresses that a processing core is able to use.
  2. ADC — analogue-to-digital converter.
  3. ALU — arithmetic logic unit.
  4. Analogue-to-digital converter (ADC) — the peripheral that measures a voltage on a pin and returns a whole number representing it.
  5. AND — the Boolean operator whose output is 1 only when every one of its inputs is 1.
  6. Architecture — the arrangement of the blocks inside a chip and the paths along which instructions and data move between them.
  7. Arithmetic logic unit (ALU) — the part of the processing core that performs arithmetic, comparison and logical operations.
  8. Boolean logic — the logic of statements that take only two values, true and false, written as 1 and 0.
  9. Brown-out detection — circuitry that resets a chip when the supply voltage falls below the level at which it can operate correctly.
  10. Bus — the set of internal conductors along which addresses, data and control signals travel between the blocks of a chip.
  11. CAN — controller area network; a robust two-wire serial bus used for multi-drop links in vehicles and industrial machines.
  12. Clock — the steady stream of electrical pulses, produced by an oscillator, that paces every operation inside a chip.
  13. Clock cycle — one pulse of the clock, and the unit in which the duration of an operation is counted.
  14. Controller — the computing element of a robot, which reads the sensors, decides what happens next and issues the signals that make it happen.
  15. Data — the values a program works on, which it both reads and writes, as distinct from the instructions it executes.
  16. Deterministic timing — the property of a system in which the same sequence of operations takes the same time on every pass.
  17. Duty cycle — the fraction of each period, expressed as a percentage, for which a pulse width modulated output is on.
  18. EEPROM — electrically erasable programmable read-only memory.
  19. Electrically erasable programmable read-only memory (EEPROM) — small non-volatile memory that a running program can write to, used for values that must survive power-off.
  20. Embedded system — a computing system built into a larger device, dedicated to controlling it and running a fixed program.
  21. Fetch–decode–execute cycle — the three-step sequence, repeated for every instruction, by which a processing core executes a program.
  22. Firmware — the fixed program stored in a device’s program memory, which defines its behaviour.
  23. Flash memory — non-volatile memory that holds the program of a microcontroller and retains it when power is removed.
  24. Floating input — an input pin connected to nothing, which picks up stray voltages and reads meaninglessly.
  25. General-purpose input/output (GPIO) — pins that a program can configure as either inputs to be read or outputs to be driven.
  26. GPIO — general-purpose input/output.
  27. Harvard architecture — an organisation in which program memory and data memory are separate, each reached over its own bus, allowing a fetch and a data access in parallel.
  28. HDMI — high-definition multimedia interface; the connector and standard commonly used for display output on a single-board computer.
  29. I2C — inter-integrated circuit; a two-wire serial bus shared by several devices, each answering to its own address.
  30. IDE — integrated development environment; the software in which a program is written, compiled and transferred to a board.
  31. Instruction — a single command from the program, fetched from program memory and executed by the core.
  32. Interrupt — a hardware signal that suspends the running program, transfers control to an interrupt service routine, and returns to the interrupted point afterwards.
  33. Interrupt service routine (ISR) — the short piece of code executed in response to a particular interrupt.
  34. ISR — interrupt service routine.
  35. Latency — the time between an event occurring and the system responding to it.
  36. LED — light-emitting diode.
  37. LIDAR — light detection and ranging.
  38. MCU — microcontroller unit; the short form of microcontroller.
  39. Memory address — the number identifying one location in memory.
  40. Microcontroller — a complete computing unit on a single chip, integrating a processor, memory, clock circuitry and input-output hardware, running one stored program.
  41. Non-volatile — describing memory whose contents survive when power is removed.
  42. NOT — the Boolean operator that reverses a single input, turning 1 into 0 and 0 into 1.
  43. Operating system — the software that manages a computer’s hardware and shares it among several running programs.
  44. OR — the Boolean operator whose output is 1 when at least one of its inputs is 1.
  45. Peripheral — a block of circuitry beside the processor on the same chip, such as a timer, converter or communication unit.
  46. Polling — repeatedly checking an input in the main program to find out whether an event has occurred.
  47. Pulse width modulation (PWM) — switching an output rapidly between on and off, and controlling the average power delivered by varying the duty cycle.
  48. PWM — pulse width modulation.
  49. RAM — random-access memory.
  50. Random-access memory (RAM) — volatile working memory holding the data of the operating system and the running programs.
  51. Register — a very small, very fast storage location inside the processing core, holding a value the core is working on.
  52. Resolution — for a converter, the number of distinct levels into which it divides its measuring range, stated in bits.
  53. SBC — single-board computer.
  54. Sense–plan–act loop — the repeating cycle in which a robot senses its surroundings, decides what to do, acts, and senses again.
  55. Single-board computer (SBC) — a complete computer built on one printed circuit board, running a full operating system.
  56. SoC — system on a chip.
  57. SPI — serial peripheral interface; a four-wire serial link used where high data rates are needed.
  58. SRAM — static random-access memory.
  59. Static random-access memory (SRAM) — the volatile data memory of a microcontroller, holding variables, arrays and the stack while a program runs.
  60. System on a chip (SoC) — a single die integrating the central processing unit, graphics processing unit, memory controller and high-speed interfaces.
  61. Threshold — the value against which a converted sensor reading is compared in order to produce a single true or false condition.
  62. Timer — a counter inside a chip that increments with the clock independently of the program, used for timing, capture and pulse generation.
  63. Truth table — a table listing every possible combination of input values for a logical expression, with the output produced for each.
  64. UART — universal asynchronous receiver-transmitter; a two-wire serial link between exactly two devices.
  65. USB — universal serial bus.
  66. Volatile — describing memory whose contents are lost when power is removed or the chip is reset.
  67. Von Neumann architecture — an organisation in which instructions and data share one memory space and one system bus, so transfers are serialised.
  68. Von Neumann bottleneck — the limit on throughput that arises because instruction traffic and data traffic compete for the same shared bus.

11.10 Objective Questions

  1. A robot’s servo pulses must be produced at exactly the same moment on every pass of its control loop. Which statement best explains why a microcontroller is preferred over a single-board computer for this task?
  1. Its clock frequency is higher than that of a single-board computer.
  2. It runs one program with no operating system deciding when that program gets the processor.
  3. It has more working memory available for storing pulse values.
  4. It uses the Von Neumann organisation, which serialises memory transfers.
  1. A microcontroller has a 10-bit analogue-to-digital converter working with a reference voltage of 5.00 V. The smallest change in sensor voltage that will alter the reading is closest to:
  1. 0.49 mV
  2. 4.9 mV
  3. 49 mV
  4. 490 mV
  1. Assertion (A): In a Harvard architecture, an instruction can be fetched while a data value is being read or written. Reason (R): A chip built on the Harvard architecture always runs at a higher clock frequency than one built on the Von Neumann architecture.
  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 block of a microcontroller in Column I with the job it does in Column II.
Column I Column II
a. Timer i. reverses the effect of an input that reports in the opposite sense
b. Interrupt controller ii. counts clock pulses independently of the running program
c. Analogue-to-digital converter iii. decides which urgent event is served first when several arrive
d. EEPROM iv. turns a voltage on a pin into a whole number
e. NOT operator v. holds a calibration value so that it survives a power cut
  1. Fill in the blanks.
  1. An input pin that is configured as an input and connected to nothing is said to be ______.
  2. The fraction of each period for which a pulse width modulated output is on is called the ______.
  3. In the ______ architecture, program instructions and data share a single memory space reached over one system bus.
  4. Repeatedly checking an input in the main program to see whether an event has occurred is called ______.
  1. State whether each statement is true or false.
  1. A single-board computer becomes ready to control a robot within a few milliseconds of power being applied.
  2. The contents of SRAM are lost when power is removed from a microcontroller.
  3. Every single-board computer provides analogue inputs on its general-purpose input/output header.
  4. Two boards exchanging serial signals must have their grounds joined.
  5. An Arduino Uno is classified as a single-board computer because it is a computer built on one board.
  1. Give the full form of each of the following abbreviations used in this chapter: SBC, ALU, EEPROM, GPIO, PWM, ISR, SoC, CAN.

11.11 Check Your Concepts

  1. Define an embedded system. State two demands that this role places on the controller of a robot, and give one reason for each.

  2. Differentiate between volatile and non-volatile memory. Name one memory of each kind found inside a microcontroller, and give one value a robot would sensibly store in each.

  3. A student wires a small direct current motor between a digital output pin of an Arduino Uno and ground, and finds that the motor barely turns and the board occasionally restarts. Explain why this happens, and state what should be placed between the pin and the motor.

  4. A robot checks its bumper switch once each time round a main loop that takes 150 ms. Explain why this arrangement may fail to notice a brief bumper strike, and describe how an interrupt avoids the problem. State one precaution to observe when writing an interrupt service routine.

  5. A mobile robot travels at 0.45 m/s, and one complete pass of its sense–plan–act loop takes 120 ms. Calculate the distance the robot travels between one sensor reading and the next, giving your answer in millimetres. Suggest one change to the program that would reduce this distance, and state what it would cost.

  6. A conveyor motor in a packing shed is to run only when the safety guard is closed and the emergency stop is not pressed, and only when either the manual start button is held or the automatic mode signal is active. Write the decision as a Boolean expression using AND, OR and NOT, showing clearly with brackets the order in which the operators apply. State the three operators you would use in embedded C.

  7. Explain the fetch–decode–execute cycle, naming what happens at each step. Using it, justify why a Harvard organisation gives steadier control-loop timing than a Von Neumann organisation, and state one cost of the Harvard arrangement.

11.12 Diagram, Circuit & Output Reading

  1. A block diagram of a microcontroller shows five blocks joined to a central internal bus, labelled P, Q, R, S and T. P holds the firmware and retains it when power is removed. Q holds variables while the program runs and is cleared on reset. R produces a steady stream of pulses that paces all digital operations. S converts a voltage present on a pin into a whole number. T suspends the running program when an urgent event occurs and transfers control to a short routine.
  1. Name each of the five blocks.
  2. State which two blocks would be involved in reading a soil moisture probe that produces a varying voltage.
  3. Explain what the internal bus does, and why the diagram is described as a map of function rather than of physical layout.
  1. A student wires a pump to an Arduino Uno as follows. The L298N module IN1 is connected to digital pin 8 and IN2 to the module’s GND terminal. The ENA jumper is fitted. A separate 6 V battery pack is connected to the module’s +12V terminal, with the battery negative going to the module’s GND terminal. The pump is connected across OUT1 and OUT2. The Arduino Uno is powered from a laptop over USB. Nothing else is connected between the two boards.
  1. Identify the single connection that is missing, and explain why it is necessary.
  2. Predict what the student is likely to observe when the program sets pin 8 high.
  3. State one precaution to observe before altering any wiring in this circuit.
  1. The following fragment appears inside setup() of an Arduino sketch, immediately after Serial.begin(9600);.
int frontDistance = 34;
int sideDistance = 9;
boolean frontClear = (frontDistance > 20);
boolean sideClear = (sideDistance > 20);

Serial.println(frontClear && sideClear);
Serial.println(frontClear || sideClear);
Serial.println(!sideClear);
  1. Write down the exact three lines that appear on the Serial Monitor.
  2. State which one of the three printed values would change if sideDistance were altered to 25, and give the new value.
  3. The robot is to move forward only when both directions are clear. Name the operator that must be used, and explain why the other two would be unsafe here.
  1. A design team is choosing between two microcontrollers for a greenhouse monitor that must read a humidity sensor whose output changes by about 2 mV for each one per cent change in humidity. Both chips will be operated with a 3.30 V reference.
Chip ADC resolution Data memory Clock Radio
Chip A 10-bit 2 KB 16 MHz none
Chip B 12-bit 520 KB up to 240 MHz Wi-Fi and Bluetooth
  1. Calculate the smallest voltage change that each chip can distinguish, giving both answers in millivolts.
  2. State, with a reason drawn from your answers, which chip can resolve a one per cent change in humidity.
  3. The monitor must also send its readings to a phone in the greenhouse office. Explain how this requirement affects the choice, and state one disadvantage of the chip you would select.

11.13 Case-Based Questions

  1. A warehouse fits a robot that drives itself down the aisles, photographs the shelf labels and reports missing stock. Its tasks are these: it must recognise printed labels from a camera image; it must hold its two wheel speeds matched so that it drives straight; it must stop within a few centimetres if its front bumper is struck; and it must send its findings to the office network at the end of each aisle. The battery pack must last a full shift.
  1. State which of the four tasks belongs on a microcontroller and which on a single-board computer, giving a reason for each placement.
  2. The team proposes to let the single-board computer read the bumper switch directly, since it is the board that decides where the robot goes. Explain why this is a poor design decision.
  3. Name a suitable link between the two boards, state one wiring precaution that must be observed when joining them, and describe what messages would travel in each direction.
  1. A farmers’ cooperative fits a controller to a grain-drying shed. A moisture sensor produces a voltage from 0 V to 5.00 V that rises with the dampness of the grain; the controller reads it through a 10-bit analogue-to-digital converter with a 5.00 V reference. A door switch closes to ground while the shed door is shut, and a manual stop button closes to ground while it is held. The drying fan is to run only while the grain is damp, the door is shut and the manual stop is not pressed. A warning lamp is to light whenever the door is open or the manual stop is pressed.
  1. The grain is judged damp when the sensor voltage exceeds 1.50 V. Calculate the converter count that should be written into the program as the threshold.
  2. Write the two decisions — fan and warning lamp — as Boolean expressions, using D for the damp condition, S for the door-shut condition and M for the manual stop condition.
  3. State how many rows a complete truth table for the three inputs would contain, and list every combination of D, S and M for which the fan runs.
  4. Both switches are wired with the internal pull-up resistors enabled. Explain what this means for the value each pin reads, and which operator the program must apply to the manual stop reading.