◆ Rebuild

Part 14 · Electronics and Computing

Microcontrollers

A whole small computer on one chip — processor, program memory, working memory, input and output pins, timers and a voltmeter — that costs little, draws a few thousandths of an ampere and quietly runs one machine for years. How it works inside, how to build a development board and a programmer to load it, how to program it in assembly and in C, and how to build controllers for incubators, pumps and machines that fail safe.

Difficulty
●●●●●
Time
A weekend to build a development board and blink a lamp; a week or two for a working incubator or pump controller; a year for a team with a chip line to make its first microcontroller
Steps from zero
70 prerequisites →

You need first

Microprocessors and Personal ComputersProgramming

This unlocks

Pulse Oximeters and Patient Monitors

Raw materials

quartz
The full path from nothing — 70 steps before this one
  1. Fire
  2. Cordage and Rope
  3. Stone Tools
  4. Finding and Preparing Clay
  5. Finding and Identifying Ores
  6. Sulfur
  7. Writing and Numbers
  8. Hunting and Trapping
  9. Basic Woodworking
  10. The Kiln
  11. Pottery
  12. Charcoal
  13. Arithmetic and Fractions
  14. Hides and Leather
  15. Lime
  16. Bricks
  17. Salt
  18. Mercury
  19. Lye and Potash
  20. Fermentation
  21. The Wheel and Axle
  22. Logic and Binary
  23. Glass
  24. Firebrick and Refractories
  25. Bellows
  26. Saltpeter
  27. The Lathe
  28. Gears
  29. Glass Fibre and Glass Wool
  30. Copper Smelting
  31. Iron (the Bloomery)
  32. Lead
  33. Laboratory Glassware
  34. Sulfuric Acid
  35. Pumps
  36. The Waterwheel
  37. Lenses
  38. Blacksmithing
  39. Gold and Silver
  40. The Blast Furnace and Cast Iron
  41. Bronze
  42. Hydrochloric Acid
  43. The Battery
  44. The Vacuum Pump
  45. Magnets
  46. Steel
  47. Chimneys, Stoves and Heating
  48. Bearings and Lubrication
  49. The Steam Engine
  50. The Light Bulb
  51. Copper Wire
  52. Electrolysis
  53. Photography
  54. Hydrogen, Oxygen and Gases
  55. Centrifugal Pumps and Fans
  56. Machine Tools
  57. The Generator
  58. The Vacuum Tube
  59. The Electric Arc Furnace
  60. Ammonia
  61. Ice and Refrigeration
  62. Pure Silicon
  63. Ventilation and Air Conditioning
  64. Semiconductors and the Transistor
  65. Clean Rooms
  66. Integrated Circuits
  67. Making Microchips
  68. The Computer
  69. Programming
  70. Microprocessors and Personal Computers
  71. Microcontrollers

Do them roughly in this order. See it on the tech tree →

Why it matters

The Microprocessors and Personal Computers chapter builds a computer from a processor chip, memory chips, an input/output chip and a crystal. A microcontroller puts all of those on one chip, with timers and a converter that measures voltages. It is a whole computer the size of a fingernail that costs less than a meal once made in quantity and runs on a few milliamperes at 5 V.

Nobody sits at a microcontroller. It is built into a machine and runs one program for years: the controller of an incubator, a water pump, a kiln, a washing machine, a lathe, a traffic light, a car engine. It replaces cabinets of relays, cams and clockwork (Robots and Automation, Thermostats and Automatic Control), and because the behaviour lives in a program, one board design can run a hundred different machines.

With finished chips, one careful person can build a development board, a programmer and a working controller in a few weeks. Making the chips needs the line of Making Microchips; until then, a small board of separate chips does the same job, only larger.

How it works

Processor core 8-bit, 1–20 MHz Program memory flash, 1–32 KB RAM 64 B – 2 KB EEPROM settings internal bus I/O ports A, B, C Timers count, PWM ADC 10-bit UART serial in/out Reset and brown-out Clock oscillator Watchdog timer I/O pins more switches, lamps, relays +5 V and 0 V power, 5 mA Reset push button Crystal 4 MHz I/O pins switches, lamps, relays, motors Analog inputs sensor voltages Serial transmit, receive One chip about 32 × 8 mm in a 24-leg package; the silicon inside is a few millimetres square
Fig. 1 Inside a microcontroller. The processor, program memory, working memory and all the peripherals share one chip. Most of the legs are general-purpose pins, each of which the program can make an input or an output, or hand over to a timer, the converter or the serial port.

A computer on one chip

Part Typical size What it does
Processor core 8 bits, 1–20 MHz Runs the program, as in Microprocessors and Personal Computers
Program memory 1–32 KB of flash or EPROM Holds the program with power off
Working memory (RAM) 64 bytes–2 KB Variables and the stack; lost at power-off
EEPROM 64 bytes–1 KB Settings that must survive power-off: set points, calibration, counts
Input/output pins 6–40 Read switches and sensors, drive lamps and relays
Timers 2–3 counters, 8 or 16 bits Exact delays, pulses and measurements of time
Analog-to-digital converter (ADC) 10 bits, 4–8 inputs Turns a voltage into a number
Serial port (UART) One or two Sends and receives characters, like a The Teleprinter
Watchdog, brown-out detector, clock — Keep it running safely; see below

Program and working memory have separate buses, so the processor fetches the next instruction while it handles data, and most instructions take one or two clock cycles. A chip at 8 MHz does several million instructions a second — far more than an incubator will ever need. At 4 MHz it draws a few milliamperes; asleep, waiting for a timer or a button, a few millionths of an ampere, so it can run a year on dry cells.

Pins

Each group of 8 pins is a port, which the program sees as three registers (memory cells with special wiring): a direction register (1 makes that pin an output, 0 an input), an output register (1 puts +5 V on an output pin, 0 puts 0 V), and an input register (reading it gives the level on each pin now: above about 3 V reads 1, below about 1.5 V reads 0).

Each output pin can supply or sink about 20 mA, the whole chip 100–200 mA. That lights an LED through a 330 Ω resistor. A relay, motor or heater needs a transistor between pin and load (Semiconductors and the Transistor); anything on the mains needs a relay or an optically isolated switch (Power Electronics and Motor Drives).

An unconnected input floats and reads at random. Switch on the chip's built-in pull-up (30–50 kΩ to +5 V); then a switch from pin to 0 V reads 1 when open and 0 when pressed. Contacts bounce for 1–10 ms, so accept a change only when two readings 20 ms apart agree.

Timers

A timer is a binary counter (Electronic Counters) fed from the clock through a prescaler that passes only every 8th, 64th, 256th or 1024th pulse. With a 4 MHz crystal and a prescaler of 64, a 16-bit timer counts 62,500 times a second. It runs by itself while the program does other work, and can:

  • interrupt the program at exact intervals, say every millisecond, to keep a clock, scan buttons or step a motor;
  • measure the time between edges on a pin: shaft speed, the period of a flow meter;
  • count outside pulses: drops, turns, parts on a conveyor;
  • make pulse-width modulation (PWM), a square wave whose "on" fraction the program sets. Switched hundreds of times a second, it gives a motor, heater or lamp any power from 0 to 100% with almost no loss.

The analog-to-digital converter

A 10-bit ADC on a 5 V reference gives 0 for 0 V and 1023 for 5 V: steps of about 4.9 mV. It works by successive approximation, like weighing on a balance with weights of 2.5 V, 1.25 V, 0.625 V and so on — keep each weight if the input is still heavier — and ten tries take about 100 microseconds. Any sensor that gives a voltage can feed it: a thermistor or strain gauge in a divider (Photocells and Sensors), a photocell, a potentiometer on a shaft. Power the sensor divider from the same 5 V as the reference, so the reading depends only on the ratio of the resistors and not on a wandering supply.

Serial port, interrupts and the watchdog

  • The UART sends characters bit by bit as a teleprinter does: a start bit, 8 data bits, a stop bit. At 9,600 bits a second each bit lasts 104 microseconds. It lets the controller print readings to a terminal or The Computer and take commands, or join other controllers in a network. SPI and I²C, two other serial links of 2–4 wires, connect memory, display and sensor chips on the same board.
  • An interrupt is an outside event — a timer overflowing, a pin changing, a character arriving — that makes the processor run a short routine and return.
  • The watchdog is a separate timer that resets the chip unless the program "kicks" it regularly, typically within 0.1–2 seconds. If a bug or electrical noise locks the program up, the watchdog restarts it. Every unattended controller must use it.
  • The brown-out detector holds the chip in reset while the supply is too low (say below 4.3 V), because a processor on a sagging supply does unpredictable things.

What you need

Item Notes
Microcontroller chips 8-bit, 18–40 pins, in dual in-line packages that fit a socket; several spares
Crystal 4 MHz, or 3.6864 MHz, which divides exactly into standard serial speeds; two 22 pF capacitors (Quartz Crystals and Frequency Control)
Regulated 5 V supply 200–500 mA (Power Supplies and Regulators) or a battery
Passive parts 0.1 μF capacitors, 10 kΩ and 330 Ω resistors, LEDs, push buttons (Resistors, Capacitors and Coils)
Board Stripboard or an etched board, a chip socket, pin headers at 2.54 mm spacing (Building Circuits: Boards, Connectors and Cables)
A computer To assemble or compile programs and drive the programmer (Microprocessors and Personal Computers)
Test gear Meter and logic probe; an oscilloscope if you have one (Electronic Test Equipment)

The microcontroller itself

A microcontroller is an integrated circuit of roughly 5,000–50,000 transistors plus memory cells, well within a 10-micrometre line (Making Microchips): Intel's 8048 of 1976 held 1 KB of program ROM, 64 bytes of RAM and 27 input/output lines. Design it by the road in Microprocessors and Personal Computers — small chips first, simulate everything, expect three rounds of masks. The program memory is the main choice:

  1. Mask ROM: the program is fixed by one mask layer when the chip is made. Cheapest by the thousand, simplest to make, but every program change needs a new mask. Right for a washing-machine timer.
  2. EPROM in the chip, erased through a quartz window by ultraviolet (Microprocessors and Personal Computers). Reprogrammable, so it is the development chip. Without the window it is "one-time programmable", cheaper for small runs.
  3. Flash, erased electrically on the board. It needs thinner insulating layers and comes later, but makes development very quick.

Before you have chips, build the same thing from separate parts: the single-board computer of Microprocessors and Personal Computers with an EPROM, a small static RAM, a parallel port chip and a counter chip as timer. It is the size of a book instead of a fingernail but runs the same kind of program, and the rest of this chapter applies to it.

The development board

Power in 7–12 V Diode stops reversed power 5 V regulator 100 μF either side Crystal, 4 MHz two 22 pF capacitors Reset button 10 kΩ to +5 V Pin headers every chip pin, 2.54 mm Programming header, 6 pins Microcontroller in its socket Serial header transmit, receive, 0 V 0.1 μF capacitor across the power legs Test lamp LED and 330 Ω Test button on a spare pin Board about 100 × 80 mm
Fig. 2 A development board. The microcontroller sits in a socket in the middle; around it are everything it needs to run (power, crystal, reset) and everything you need to talk to it (programming header, serial header, a lamp and a button). Every pin is brought out to a header so that experiments plug in.

A development board gives a microcontroller everything it needs to run, plus easy ways to load programs and plug in experiments. Use it for every new design; when the program works, make a smaller board with only what the machine needs. It carries:

  • a socket for the chip, ideally one with a lever that clamps the legs;
  • power: an input for 7–12 V, a diode against reversed polarity, a 5 V regulator with 100 μF on each side, and a power LED;
  • a 0.1 μF decoupling capacitor straight across the chip's power legs, leads as short as possible — without it the chip resets at random;
  • the crystal and its two 22 pF capacitors, within 1–2 cm of the clock legs;
  • reset: 10 kΩ from the reset leg to +5 V and a push button to ground;
  • a 6-pin programming header and a 3-pin serial header;
  • one LED with its 330 Ω resistor and one push button on spare pins;
  • headers carrying every chip pin, at 2.54 mm spacing.

About 100 × 80 mm is comfortable. Keep the ground track wide and continuous, with +5 V beside it.

Step by step

  1. Build the power section alone. With a 100 Ω, 1 W resistor as load, check 5.0 ± 0.25 V and that nothing gets hot.
  2. Add socket, decoupling, crystal and reset, but no chip. Measure +5 V and 0 V on the socket itself, against the chip's pin diagram. A chip powered backwards dies at once.
  3. Add LED, button and headers; check each header pin goes where its label says.
  4. Touch the board's ground (static kills chips), insert the chip. Nothing should get warm; current should be under 20 mA.

A good board starts the same way every time, restarts cleanly on reset, and is not upset by touching it or switching a nearby motor. A bad one runs sometimes — almost always a missing decoupling capacitor, a loose crystal, a long ground path or a floating reset pin.

The programmer

A programmer puts machine code from your computer into the chip's program memory. Build them in this order:

  1. Parallel programmer, like the EPROM programmer in Microprocessors and Personal Computers. The chip sits in a socket; a higher voltage on one leg (usually 12–13 V, from the data sheet) puts it in programming mode; address and byte are set on its pins and a timed pulse writes each byte. The first one can be worked by hand switches. Read every byte back and compare.
  2. In-circuit serial programmer. Most chips can be programmed in their board through 3–4 wires: hold reset, then clock in a command, the address and the data one bit at a time. The programmer is a dozen parts — a few transistors on a computer's output port, a supply for the programming voltage if needed, and a program that sends the bit patterns. A 4 KB chip takes a few seconds.
  3. Bootloader. Put a short routine (256 bytes to 2 KB) in a corner of each chip's memory. At reset it waits half a second for a special character on the serial port; if it comes, it accepts a new program and writes it into the rest of the flash. After that a plain serial cable is the programmer, and machines in the field can be updated without opening them.

Warning Configuration bits. Each chip also has a few fuse bits that choose its clock source, enable the watchdog, or lock the memory against reading. The wrong clock setting (say "external clock" on a board with a crystal) leaves the chip apparently dead, and only a parallel programmer can rescue it. Write the right settings for your board on a card taped to the programmer and check them before every write.

A good programmer verifies every byte after writing and reports the first mismatch. Record a checksum (the sum of all bytes, Programming) and version number of every released program in the machine's log book.

Programming it

In assembly

This example is in the style of one common 8-bit family; others differ in detail. It makes pin 0 of port B an output and blinks an LED on it. Text after a semicolon is a comment.

        LDI   R16, 0b00000001
        OUT   DDRB, R16        ; direction: bit 0 is an output
LOOP:   SBI   PORTB, 0         ; set bit 0: LED on
        RCALL WAIT
        CBI   PORTB, 0         ; clear bit 0: LED off
        RCALL WAIT
        RJMP  LOOP

WAIT:   LDI   R18, 6           ; three nested countdowns
W1:     LDI   R17, 222
W2:     LDI   R16, 250
W3:     DEC   R16              ; 3 clock cycles per inner turn
        BRNE  W3
        DEC   R17
        BRNE  W2
        DEC   R18
        BRNE  W1
        RET

The inner loop runs 6 × 222 × 250 = 333,000 times at 3 cycles (one to count, two to branch back): about a million cycles, a quarter of a second at 4 MHz, so the lamp blinks twice a second. Check it against a watch: four or eight times too slow means the chip is on its internal slow clock (see the warning above). The two-pass assembler of Programming, run on your computer, turns this into machine code; one that makes code for a different chip is a cross-assembler.

In C

C is a compact language close enough to the machine to set single bits in a port register, yet with the variables, loops, if and functions of the simple language in Programming. A compiler for a useful subset of C fits in a few thousand lines; once you have one, programs are written several times faster than in assembly and move to a new chip by recompiling. An even smaller first step is Forth, whose whole interpreter fits in 2–4 KB of the chip: you type commands over the serial port and it runs them at once.

The heart of an incubator controller in C (text between /* and */ is a comment):

#define SET_POINT   375    /* 37.5 °C, in tenths of a degree */
#define BAND          2    /* heater on below 37.3, off above 37.7 */
#define TOO_HOT     395    /* 39.5 °C: shut down and sound the alarm */
#define TOO_COLD    340

int main(void) {
    setup_pins();  setup_adc();  setup_timer();  watchdog_on();
    for (;;) {
        int t = read_temperature();     /* average of 16 readings */
        if (t < SET_POINT - BAND) heater_on();
        if (t > SET_POINT + BAND) heater_off();
        if (t > TOO_HOT || t < TOO_COLD || sensor_broken()) {
            heater_off();  alarm_on();
        } else {
            alarm_off();
        }
        if (minutes_since_turn() >= 288 && day_of_incubation() < 18)
            turn_eggs();                /* 5 times a day */
        kick_watchdog();
        wait_ms(500);
    }
}

Each name (read_temperature, turn_eggs) is a small function kept in a library for the next machine. The program is a loop that reads, decides, acts and repeats, like the scan of the programmable controller in Robots and Automation.

Building controllers

The incubator controller

+5 V 5.6 kΩ fixed Thermistor 10 kΩ at 25 °C, at egg height about 2.5 V 0 V Micro- controller ADC in out 1 out 2 out 3 on below 37.3 °C off above 37.7 °C serial Relay driver transistor, diode Motor driver M mains circuit, enclosed Backup thermostat, 39.5 °C Heater 25–40 W relay contact Egg-turning motor limit switch at each end Alarm buzzer and red lamp Log every 10 minutes
Fig. 3 An incubator controller. A thermistor in a divider gives the converter a voltage that falls as the eggs warm. One output pin works the heater relay through a transistor; another turns the egg tray; a buzzer sounds on any fault. A separate bimetal thermostat in series with the heater cuts it off if the controller ever fails with the heater on.

An incubator controller does the job of the bimetal thermostat in Thermostats and Automatic Control, but tighter, with a turner, an alarm and a log.

  1. Sensor. A thermistor of about 10 kΩ at 25 °C (about 5.9 kΩ at 37.5 °C), with a 5.6 kΩ resistor from +5 V, so the junction sits near 2.5 V at the set point. Each 0.1 °C then moves the reading by about one step of the converter. Seal it in a thin glass or metal sleeve at egg-top height, in moving air.
  2. Calibrate against a good The Thermometer at two temperatures, say 30 °C and 40 °C; the program draws a straight line between them, good to 0.1–0.2 °C over this range. Store the two numbers in EEPROM.
  3. Average 16 readings a few milliseconds apart to smooth out noise.
  4. Heater. On below 37.3 °C, off above 37.7 °C (the differential of Thermostats and Automatic Control). Drive a relay through a transistor with a diode across the coil, or an optically coupled triac (Power Electronics and Motor Drives). For smoother control, use PWM: 20% power near the set point, full power far below, or the proportional control of Process Controllers and Control Valves.
  5. Turning. A small geared motor tilts the egg tray side to side between two limit switches, 5 times a day, stopping on day 18 for chickens (Poultry and Eggs).
  6. Alarm. Buzzer and red lamp for too hot, too cold, sensor open or shorted (readings near 0 or 1023), or turner not reaching its limit switch within 30 seconds.
  7. Backup. Wire a separate bimetal thermostat set at 39.5 °C in series with the heater. Programs freeze and relays weld shut; the backup depends on neither.

The pump controller

A pump controller starts and stops a water pump and protects its motor (Centrifugal Pumps and Fans, The Electric Motor).

  • Inputs: low and high float switches in the tank (or a pressure sensor on the pipe), a current sensor on the motor supply (a small current transformer and rectifier into the ADC), and a run/stop switch.
  • Rules: start below LOW, stop at HIGH. Never restart within 3 minutes of stopping — a motor started more than 6–10 times an hour overheats. Current below about 60% of normal for 10 seconds means the pump is running dry or has lost its prime: stop and alarm. Above 120% for 5 seconds means it is jammed: stop and alarm. Running half as long again as the longest fill ever logged probably means a burst pipe: stop and alarm.
  • Output: a relay working the motor's contactor (Motor Starters, Contactors and Protection), whose own overload relay stays in circuit.
  • Log: count starts and running hours in EEPROM; a sudden rise in daily starts shows a leak.

Machine controllers

For a feeder, a saw, a winding machine or a small milling machine, the microcontroller reads limit switches and encoders and drives stepper motors through power transistors (Robots and Automation). A timer interrupt every 0.1–1 ms sends the step pulses; the main loop reads buttons and plans moves.

Danger Safety must not depend on the program. Emergency stops, guard switches and over-temperature cut-outs must break the power to the motor or heater directly, in wiring, not by asking the microcontroller. Design every controller so that a dead, frozen or confused chip leaves the machine off and safe: relays energised to run, so they drop out when the controller dies; springs that close valves; heaters that need a fresh "keep on" signal every second.

How to tell it worked

  • Blink test: the LED blinks at the calculated rate, unchanged when the chip is warmed in your hand.
  • Reset and watchdog: press reset 20 times; it starts cleanly each time. Put a deliberate endless loop behind a button: the chip must restart within the watchdog time, with the machine safe meanwhile.
  • Noise: switch a motor and a soldering iron on and off beside it many times. Nothing should change.
  • Incubator: run it empty for 48 hours beside a thermometer, logging every 10 minutes. It should hold 37.5 ± 0.3 °C and turn on time. Pull the sensor plug: the alarm must sound and the heater stop.
  • Pump: close the inlet valve so it runs dry. It must stop within 15 seconds and alarm.

Note Troubleshooting. Chip does nothing → power on the wrong legs, reset held low, or clock fuses wrong; check 5 V at the chip's own legs and look for oscillation at the crystal. Runs 4, 8 or 16 times too slow or fast → wrong clock source or prescaler. Resets when a relay or motor switches → no diode across the relay coil, no decoupling capacitor, or motor current sharing the controller's ground wire. Give power wiring its own return and add 100 μF across the supply. Readings jump about → long sensor wires picking up noise: twist them, add 0.1 μF from the ADC pin to ground, average more readings. Serial port gives garbage → wrong speed or crystal; a timing error above 2–3% garbles every character. Worked yesterday, not today → an old version was loaded. Number every version and keep checksums.

Dangers

Danger Mains wiring. The controller is low voltage, but the heaters, pumps and motors it switches are not. Keep mains and low-voltage wiring well apart (at least 6–8 mm of clear board), switch through relays or optical isolators, enclose everything, earth the case (Wiring and Electrical Safety), and never work on the board with the mains side connected.

  • A trusted controller makes people stop watching. That is its purpose, so test it as hard as any safety device, and keep the backup thermostat, overload relay and overflow float switch even when the program "already does that".
  • Lost programs. A controller whose source program is lost cannot be fixed or copied. Keep printed listings, version numbers and checksums with each machine, and copies in two buildings (Programming).

Going further

How it was first done

Gary Boone and Michael Cochran at Texas Instruments designed a calculator chip with processor, ROM, RAM and input/output together around 1971; sold from 1974 as the TMS1000, it went into calculators, toys and microwave ovens by the million. Intel's 8048 (1976) and 8051 (1980) set the pattern for decades. In the 1990s chips with electrically rewritable program memory, such as Microchip's PIC16C84 (1993) and the AVR family designed by Norwegian students Alf-Egil Bogen and Vegard Wollan and sold by Atmel from 1996, let anyone reprogram a chip on its board in seconds. C was created by Dennis Ritchie at Bell Laboratories around 1972, and Ron Cain's Small-C (1980) showed that a useful subset could run on a small computer. Charles Moore developed Forth around 1970; it was soon used to run radio telescopes (Radio Telescopes and Microwave Links) and many other instruments. In 2005 a group at the Interaction Design Institute in Ivrea, Italy, released the Arduino, a cheap open board with a bootloader and a simple library, which put microcontrollers in the hands of artists, farmers and schoolchildren.

Source: content/entries/electronics/microcontrollers.md