Learn & build · Electronics · Chapter 13

Microcontrollers and buses

Chapter 12's toy CPU, shrunk onto one chip with its own memory, a clock, and pins that reach the outside world: that's a microcontroller (an Arduino's ATmega, an ESP32, a Raspberry Pi Pico). Its pins can switch an LED, read a button, fake an analog voltage with fast pulses, and talk to other chips over a few wires. This chapter covers each of those, and then you read the conversations on a logic analyzer yourself.

In plain words: a microcontroller is a tiny computer whose memory has a few special addresses wired straight to its pins. Write a 1 to the right bit and a pin goes to 3.3 V; read a bit and you learn whether a pin is high or low. Everything else in this chapter is built on that one trick.

1. Pins are bits in a register

A GPIO (general-purpose input/output) port is a byte in memory where each bit drives one pin. Writing PORT = 0b00000101 lights the LEDs on pins 0 and 2 and turns the others off (0b marks a number written in binary, chapter 12; the rightmost bit is pin 0). Eight bits are hard to read at a glance, so programmers write them in hexadecimal, marked 0x: each hex digit stands for four bits, with 0–9 and then A–F for ten to fifteen. 0000 0101 is 0x05; 1111 1111 is 0xFF. Click the bits, or set the byte directly.

🎯 Challenge: make the port read 0xA5 (alternating pattern, 1010 0101).

2. Reading a button, and why inputs float

As an input, a pin is a CMOS gate (chapter 12): almost no current flows in, so it reads whatever voltage is near it. A button between the pin and ground pulls it to 0 when pressed, but when released the pin is connected to nothing, and it picks up hum from mains wiring and your finger: it floats and reads random 1s and 0s. The fix is a pull-up resistor (about 10 kΩ, built into most chips) from the pin to the supply. Released: the resistor holds it at 1. Pressed: the button wins, because it's a near-zero resistance to ground, and the resistor only passes 3.3 V / 10 kΩ = 0.33 mA.

With the pull-up enabled, what does the program read while the button is pressed?

"Active low": pressed = 0. It looks backwards but it's the standard wiring, because a pin pulled to ground by a switch is cheap and robust. Real buttons also bounce for a few milliseconds when pressed (the contacts chatter), so code waits ~10 ms before trusting a change, or uses chapter 2's RC filter.

3. PWM: faking an analog voltage

A digital pin is either 0 or 3.3 V. To dim an LED or slow a motor, the chip switches the pin on and off thousands of times a second: pulse-width modulation. The fraction of time it's on is the duty cycle. Your eye (and a motor's inertia, or an RC filter) averages the pulses, so 25% duty looks like a quarter of the brightness.

\[ V_\text{avg} = D \cdot V_\text{high} \]

A 3.3 V pin runs at 25% duty. What's the average voltage, in volts?

\(0.25 \times 3.3 = 0.825\) V. Pass it through an RC low-pass (chapter 2) with a time constant much longer than one period, and you get a steady 0.825 V: a cheap digital-to-analog converter.

The other direction, voltage to number, is the ADC from chapter 11: a 12-bit ADC on 3.3 V splits the range into 4,096 steps of 0.8 mV each, and analogRead() returns which step the pin is on.

4. UART: two wires, agreed speed

The simplest way two chips talk. No clock wire: both sides agree on a speed in advance (the baud rate, bits per second, e.g. 9600 or 115200). The line idles high. A byte starts with a start bit (low), then 8 data bits, least significant first, then a stop bit (high). The receiver sees the falling edge of the start bit, waits half a bit, and then samples once per bit time. (Many receivers take several samples around the middle of each bit and go with the majority, so a single noise spike can't flip it.) This is what a USB-serial adapter, a GPS module and the Arduino's Serial Monitor all speak. Type text and watch it go out.

At 9600 baud with 8 data bits, 1 start and 1 stop bit, how many bytes per second can you send at most?

Each byte costs 10 bit times: \(9600 / 10 = 960\) bytes per second. The framing bits are the price of not having a clock wire.

Decode one yourself. Here's a single byte caught on the analyzer. Find the start bit, read the 8 data bits (the first one is the 1s place), and give the byte's value.

What number (decimal) is the mystery byte? (Bonus: which ASCII letter?)

Data bits in time order: 1 1 0 1 0 0 1 0. That's least significant first, so reversed it reads 0100 1011 = 64 + 8 + 2 + 1 = 75 = 0x4B, ASCII K.
Where it breaks: two clocks that disagree

With no clock wire, the receiver times every bit with its own clock and hopes it matches the sender's. It resyncs only at each start bit, then samples in the middle of each bit time. Any mismatch piles up across the frame:

  1. The last sample, the stop bit's, lands 9.5 bit times after the start bit's falling edge.
  2. It still reads the right bit as long as it's off by less than half a bit.
  3. So the two clocks may disagree by at most \(0.5 / 9.5 \approx 5.3\%\) in total, before counting how sharp the edges are.

A microcontroller running from a crystal is off by thousandths of a percent (chapter 9's 20 ppm is 0.002%), no problem at all. One timed by its built-in RC oscillator is far less exact, and drifts as it warms (chapter 9 again); past the limit, a serial monitor prints garbage: the same bits, sampled at the wrong moments. The fix is a crystal, or a bus with a clock wire.

5. I²C: many chips on two shared wires

Sensors (temperature, pressure, accelerometers) usually speak I²C: one clock line SCL and one data line SDA, shared by up to ~100 devices, each with a 7-bit address. The controller starts a message with a start condition (SDA falls while SCL is high), clocks out the address and a read/write bit, and the device that recognizes its address pulls SDA low for one bit: the ACK. Then bytes follow, each acknowledged, and a stop condition (SDA rises while SCL is high) ends it. Data only changes while SCL is low; a change while it's high is a start or stop.

On I²C, no device ever drives a line high: they only pull it low, and a resistor pulls it up (open drain). Why build a bus that way?

Because many chips share the same wire. If one drove it high while another drove it low, there'd be a short from supply to ground through two transistors. With open drain, "anyone pulls low" is safe: low simply wins. That's also what makes the ACK work (the device pulls low during a bit the controller leaves high) and lets a slow device hold SCL low to say "wait" (clock stretching). The cost is speed: the pull-up resistor charges the wire's capacitance slowly (chapter 2's RC), which caps I²C at about 400 kHz to 1 MHz.

6. SPI: fast, with a wire per device

SPI drops the addresses and the open drain for speed (tens of MHz: displays, SD cards, the flash chip that holds a microcontroller's program). Four wires: SCK (clock), MOSI (controller to device), MISO (device to controller), and a chip-select CS per device, pulled low to pick who's listening. Every clock tick moves one bit each way at once, so sending a byte is receiving one. Below, the controller sends register number 0xD0 and then a dummy byte; the sensor answers in the second byte with its chip ID.

You need a small OLED status display and five sensors on one board, all low-speed. Which bus suits the sensors best?

I²C: two wires for all of them, each sensor with its own address. SPI shines when speed matters (a big color display, an SD card), UART when it's one partner (a GPS module, a PC).

A pin is a bit in memory, and a bus is an agreement about when each bit is valid: UART by an agreed speed, I²C and SPI by a clock wire.

The site's own radio dongle is the extreme case of all this: its tuner chip is set up over I²C, and samples stream over USB, which the radio course decodes from zero. Next: motors, where PWM gets to push something.

Previous: From gates to a computer · All chapters: Learn & build.

Last updated