This is the eighth course in University Electrical Engineering: microprocessors
and embedded systems 微处理器与嵌入式系统. Course 3 built the logic gates and
circuits. This course builds the machine that runs programs, and teaches the careful
work of making hardware and software fit together.
Unit 8.1 describes the architecture: the CPU, registers, memory, and the
fetch-decode-execute cycle.
Units 8.2–8.3 program it: embedded C and assembly, then memory-mapped I/O.
Units 8.4–8.5 add timing: interrupts and timers, then the serial protocols.
Units 8.6–8.7 finish with analog interfaces and a method for debugging.
One example runs through the whole course: a small battery-powered sensor node with a
button, an LED, a serial link and a 12-bit sensor. Each unit takes that node one step
further. Every number is checked the way a firmware engineer checks it: by bit widths
and limits (does the value fit?), by the clock it assumes (every timing works from
84 MHz), and by tracing exactly how each piece of code changes the state.
microprocessors and embedded systems/ˌmaɪkrəʊˈprəʊsesəz ænd emˈbedɪd ˈsɪstəmz/
微处理器与嵌入式系统
wēi chǔ lǐ qì yǔ qiàn rù shì xì tǒng
8.1
微控制器体系结构
English
Why it matters. A wall thermostat, a car's anti-lock brake controller and a
wireless earbud each contain one of these: a complete computer on a chip the size of a
grain of rice, which can cost less than the stamp to post it.
A microcontroller board: processor, memory, timers and I/O pins on one chip, with headers to reach themThe cycle every CPU repeats
The idea, with a picture. A microcontroller 微控制器 puts three things on one
chip: flash memory that holds the program, SRAM that holds the data, and a CPU. The
CPU runs the fetch-decode-execute cycle 取指译码执行周期:
The program counter 程序计数器 (PC) holds the address of the next instruction,
and the CPU fetches it.
The control unit decodes it.
The datapath executes it.
The PC moves on to the next instruction, or jumps to a new address.
Every transfer travels on the bus 总线. The address lines say where, the data lines
carry what, and the control lines say read or write. The clock 时钟 sets the
timing of every step.
One instruction per lap: fetch at the PC, decode, execute, advance
The derivation. Addresses are unsigned integers, so an $N$-bit address field can
name exactly $2^{N}$ locations. The size of each memory region follows:
Flash at 0x0000_0000 and SRAM at 0x2000_0000 can never overlap, because their top
bits differ. The address decoder can distinguish the regions using bits [31:16], but must also check bits [15:13] to enforce the 8 KB SRAM boundary.
Worked example 1 (sizing the memory map). The node's chip has 64 KB of flash and
8 KB of SRAM.
Flash: $64\,\text{KB} = 2^{16}$ bytes, so it needs 16 address lines. It occupies
0x0000_0000–0x0000_FFFF.
SRAM: $8\,\text{KB} = 2^{13}$ bytes, so it needs 13 lines. It occupies
0x2000_0000–0x2000_1FFF.
Check: any address with bits [31:16] = 0x0000 lands in flash, and any address
from 0x2000_0000 to 0x2000_1FFF lands in SRAM. The top bits differ, so the regions cannot
overlap ✓.
Worked example 2 (how fast is the loop?). The node's CPU, a Cortex-M class core,
runs at 84 MHz and completes about one instruction per clock cycle.
That is $84 \times 10^{6}$ instructions per second, so one instruction takes
$\dfrac{1}{84 \times 10^{6}} = 11.9$ ns.
A control pass of 100 instructions takes 1.19 µs.
So a 1 ms control loop has room for about 840 passes, if nothing else runs.
Every later unit uses this kind of time budget.
Common mistakes.
Mixing up address bits and data bits. The address lines count locations; the data
lines set how wide each transfer is.
Forgetting that the memory map is fixed by the hardware. The linker script must use
the addresses the chip maker chose, including the boot address.
Giving a program size in bits when flash sizes are in bytes. The factor of eight can
lead to the wrong choice of chip.
Summary. One chip holds flash, SRAM and a CPU that repeats fetch, decode and
execute. An $N$-bit address field names $2^{N}$ bytes. Regions with different top bits
cannot overlap. The clock turns an instruction count into seconds.
Compare the worked 64 KiB flash and 8 KiB SRAM regions. Move from the last mapped byte to the next address, separate the base from the offset bits, and explore why 96 KiB needs 17 offset bits but leaves 32 KiB unused in its address window.
Why it matters. The node's firmware is a few thousand lines of C that write to
hardware registers directly. Nothing stands between your line of code and the
transistors, so you must know exactly what each line of C does in the machine.
The idea, with a picture. A memory-mapped register 存储器映射寄存器 is simply
an address. C reaches it through a volatile pointer. The word volatile tells the
compiler that this memory can change without the program writing to it, so the
compiler must really read or write it every time. The compiler turns C into loads,
stores, arithmetic and branches. Assembly 汇编 is the same program written by hand
in those instructions, one per line.
One C line, one instruction sequence, one register transfer — three views of the same operation
The derivation. Read-modify-write is the basic operation. To change one pin
without changing its neighbours, the CPU must:
load the register,
change the one bit inside the CPU, with a mask,
store the result back.
That is three operations but only two bus transfers, one read and one write. This
example uses a plain register that is read and written as one word. Some real
peripherals also provide separate set and clear registers, which change a bit in one
write.
volatile uint32_t *const GPIO_OUT = (uint32_t *)0x40000000u;
*GPIO_OUT |= (1u << 5); // load, OR, store — set bit 5 only
Worked example 1 (trace the counter). Take the C loop
Compiled as load, increment, store and branch, it gives the values
$0, 1, 2, 3, \ldots$. (A compiler may instead keep this counter in a CPU register,
because it is not volatile.)
The largest value is $2^{32} - 1 = 4\,294\,967\,295$. The next increment wraps it to
zero, after $2^{32}$ increments in total.
If each loop takes four clock cycles at 84 MHz, the wrap comes after
$\dfrac{4\,294\,967\,296 \times 4}{84 \times 10^{6}} \approx 204$ s.
The arithmetic gives the answer; you do not need to wait three minutes with a
stopwatch.
Worked example 2 (a bigger bit mask). In one expression, flip bits 5 and 6 and
clear bit 3.
The flip mask is $(1 \ll 5) \,|\, (1 \ll 6) = 0x60$.
*GPIO_OUT = (*GPIO_OUT & ~0x08) ^ 0x60 clears bit 3 and flips bits 5 and 6 in
one read-modify-write.
Check on paper with GPIO_OUT = 0xCE: 0xCE & ~0x08 = 0xC6, then
0xC6 ^ 0x60 = 0xA6.
Bit 3 is now 0 (it was 1). Bits 6 and 5 have changed from 1, 0 to 0, 1 ✓.
Checking in hex on paper is the fastest debugging tool in this unit.
Common mistakes.
Leaving out volatile. The compiler then keeps the value in a CPU register, and your
loop reads the old copy for ever.
Assuming the compiler keeps two register writes in order when the hardware needs that
order. Add a memory barrier or read the register back.
Writing bit 5 as *GPIO_OUT = 0x20. That clears every other bit on the port.
Summary. Registers are addresses, and volatile makes the compiler really read and
write them. A plain word register is changed by load, mask and store. Trace the state
on paper in hex before you trust the hardware.
Start with the worked low byte 0xCE, clear bit 3 and toggle bits 5 and 6 to get 0xC6 then 0xA6. Step through the load, local CPU operations and store; the GPIO word stays unchanged until the store. Compare OR-setting bit 5 with plain assignment, and set upper neighbours to see which operations preserve them.
Why it matters. The node's button, LED and sensor are all outside the CPU. The way
they connect decides whether the firmware is a clear table of addresses or a mess of
unexplained numbers.
The idea, with a picture.Memory-mapped I/O 内存映射输入输出 makes a peripheral
register look exactly like a memory location: reading a data register receives a
byte, and writing one sends it. A GPIO 通用输入输出 (general-purpose input/output)
port has two such registers. The direction register sets each pin as an input or an
output, one bit per pin. The data register holds each pin's level. You set the
direction once, then read or write the data as often as you need.
The direction bit sets input or output; the data bit holds the pin's level
The derivation.Polling 轮询 is the simplest method: the CPU reads the status
register's "done" bit again and again in a loop. While it waits for $T$ seconds, the
CPU uses
$$T \times f_{\text{clock}}$$
clock cycles, doing nothing else. If each lap of the loop takes $C$ cycles, that is
about $T f_{\text{clock}}/C$ laps. A larger $C$ means fewer checks, but the CPU is still
busy for the whole wait. The CPU only sees a change at one of its checks, so detection
times and timeouts are rounded to the loop's lap time.
Worked example 1 (the cost of asking). The node polls a sensor-ready bit at 84 MHz.
Each lap is 4 cycles (load, AND, branch, increment), so the CPU makes
$84 \times 10^{6}/4 = 21$ million laps per second.
A 1 ms wait is about 21 000 laps, or 84 000 cycles.
For that millisecond the CPU is 100% busy and does no useful work.
Worked example 2 (the whole node's map). The node's peripherals start at
0x4000_0000 (GPIO), 0x4001_0000 (UART), 0x4002_0000 (timer) and 0x4003_0000
(ADC).
A table of constants in the firmware gives each driver its base address.
A typing error in one entry, for example 0x4001_0004 instead of 0x4001_0000,
points four bytes into the UART's registers.
This is why every driver file names its register offsets and never uses raw
addresses.
Check: after start-up, read each peripheral's ID register. A wrong base address
reads a wrong value at the first try.
Common mistakes.
Forgetting the direction register. The pin stays an input, and writing to it does
nothing.
Polling with no timeout. A broken sensor then stops the whole product.
Confusing a port's bit number with the pin number on the chip package. Use the pin
table in the datasheet, not a shortcut macro from the board's header file.
Summary. Peripherals are memory: a base address plus named offsets. Set the
direction once, always poll with a timeout, and read back each ID register to check
the map before the real work starts.
探索
Fewer polling checks do not mean a less busy CPU
$cycles=checks\times C,\quad checks\approx T f_{clock}/C,\quad cycles\approx T f_{clock}$
Start with the worked 1 ms wait at 84 MHz and four cycles per polling lap. The loop makes 21000 checks and occupies 84000 cycles. Increase the lap cost to reduce the number of checks without freeing the CPU during the wait. Put readiness between checks to see detection lag, or remove the ready event and watch the timeout stop the wait.
Why it matters. The node must run for a year on one battery. Polling uses battery
power to keep asking questions. Interrupts let the CPU sleep until something happens,
and that can be the difference between a battery life of a week and a year.
The idea, with a picture. An interrupt 中断 pauses the main program where it
is. The hardware saves the return state and jumps to an interrupt service
routine 中断服务程序 (ISR), using a table of addresses called vectors. On this chip
the NVIC (nested vectored interrupt controller) chooses the ISR and also sets the
priorities. The ISR runs, and the program then continues. A timer 定时器 is a
counter driven by the clock through a divider called the prescaler 分频器. In the
STM32-style up-counter used here, an update event happens when the counter CNT wraps
from the reload value ARR back to zero. If its interrupt is enabled, that event calls
the ISR.
How an interrupt fits into the fetch-execute cycleTwo divisions turn 84 MHz into a 1 Hz interrupt
The derivation. The clock frequency is divided twice:
PSC and ARR are the values stored in two 16-bit registers, so each is at most 65 535.
Each divider factor can reach 65 536, because the count includes zero. A design is
valid when both stored values fit and$PR=f_{\text{clock}}/f_{\text{interrupt}}$. Here ARR is
not zero and the counter runs all the time.
Worked example 1 (a 1 Hz heartbeat). Start from 84 MHz.
A prescaler factor of 8400 gives $84 \times 10^{6}/8400 = 10$ kHz.
A second factor of 10 000 gives exactly 1 Hz.
So write PSC = 8399 and ARR = 9999. Both stored values fit in 16 bits.
The prescaler alone cannot do it: dividing by 84 000 000 would need PSC = 83 999 999,
far more than the 16-bit limit of 65 535. That is why the timer divides twice.
Worked example 2 (interrupt cost against polling). A GPIO interrupt takes 12
cycles to enter, runs a 30-instruction ISR and takes 10 cycles to return.
Each event costs $12 + 30 + 10 = 52$ cycles, which is 0.62 µs at 84 MHz. The polled
wait above used 21 000 laps.
But the ISR cost is paid for every event. At 1000 events per second that is
52 000 cycles/s, 0.06% of the CPU.
At a million events per second it is 62% of the CPU. At such high event rates,
polling a fast peripheral can be cheaper than interrupts.
Working out where the two costs cross is the design decision.
Common mistakes.
An ISR that does not clear its interrupt flag. The CPU returns and at once enters the
ISR again, for ever.
Long ISRs. Do the minimum in the ISR, set a flag, and let the main loop do the work.
Reading a 16-bit timer on an 8-bit bus in two halves. A carry between the two reads
gives a wrong value, so latch the timer or read the high byte twice.
Summary. An interrupt needs a vector, a short ISR and a cleared flag. A timer's
rate is the clock divided by $(PSC+1)(ARR+1)$, with both stored values inside their
registers. Interrupts are cheaper at low event rates; near a million events per second,
polling can be cheaper.
探索
The divider factor includes the zero count
$f_{update}=f_{clock}/[(PSC+1)(ARR+1)]$
Start with the worked 84 MHz to 1 Hz heartbeat. Divider factors 8400 and 10000 require stored PSC = 8399 and ARR = 9999 in this STM32-style upcounter. Advance exact clock edges, counter ticks and update events, then use a small 4 × 5 example to see zero counted. Compare writing the factors directly to the registers and observe the changed rate.
interrupt service routine/ˈɪntərʌpt ˈsɜːvɪs ruːˈtiːn/
中断服务程序
zhōng duàn fú wù chéng xù
timer/ˈtaɪmə/
定时器
dìng shí qì
prescaler/ˈpriːskeɪlə/
分频器
fēn pín qì
8.5
串行协议(UART、SPI、I2C)
English
Why it matters. The node's readings leave on three wires or fewer. Choosing
between UART, SPI and I2C, and weighing the number of wires against the speed, is an
everyday decision in embedded work.
Serial sends one bit at a time down one wire; parallel sends several bits at once down several wires
The idea, with a picture.
UART 通用异步收发器 sends bytes without a shared clock. Each byte has a start
bit, 8 data bits and a stop bit, at a baud rate 波特率 that both ends have agreed.
SPI 串行外设接口 has a shared clock. The master drives the clock SCLK and a
chip-select line. Data goes out on MOSI and comes in on MISO at the same time (full
duplex).
I2C 集成电路总线 needs two wires: SDA for data and SCL for the clock. It
addresses devices with 7 bits. The lines are open-drain, so any device can pull a
line low.
An 8N1 frame: 10 bit times per byte, 86.8 µs at 115 200 baud
The derivation. UART has no clock line, so both ends measure time from the agreed
baud rate. In 8N1 framing (8 data bits, no parity, 1 stop bit) a byte takes exactly 10
bit times:
SPI sends one bit per clock cycle, so a byte takes 8 clock cycles plus a little set-up
time: $T_{\text{byte}} \approx 8/f_{\text{SCLK}}$. The clock rate sets the speed.
Worked example 1 (sizing the UART). Use 115 200 baud, 8N1.
The throughput is $115\,200/10 = 11\,520$ bytes/s, and one byte takes
$10/115\,200 = 86.8$ µs.
In the node's 1 ms control loop, 11 bytes just fit (0.95 ms) ✓.
A blocking burst of 100 bytes takes 8.68 ms, far over the budget. Split it into
smaller pieces or raise the baud rate.
The calculation decides, not personal preference.
Worked example 2 (comparing the three).
SPI at 10 MHz sends a byte in $8/10\,\text{MHz} = 0.8$ µs, about 108 times faster
than the UART above. But it needs one chip-select wire for each device.
I2C at 400 kHz needs 9 clock cycles for 8 data bits plus an acknowledge bit:
$9/400\,\text{kHz} = 22.5$ µs, before the address, start and stop bits are added.
At these rates I2C is between SPI and UART in speed, but its two wires serve the
whole board. A 7-bit address allows up to 112 devices, one address each.
The usual choice is the sensor on I2C, the flash memory on SPI and the debug console
on UART, each chosen by this kind of arithmetic.
Common mistakes.
Different baud rates at the two ends. Frames still arrive, but the bytes are wrong.
Calculate the baud divider from the peripheral's clock, not the CPU clock.
Reading an I2C address as 8 bits. The 7-bit address and the read/write bit together
fill one byte, and datasheets give both forms.
Forgetting the SPI mode (clock polarity and phase). There are four modes because
devices differ, and the wrong mode reads every byte one bit out of place.
Summary. UART: 10 bit times per byte, no clock line, both ends agree the baud rate.
SPI: one bit per clock, one chip-select wire per device. I2C: two wires, 7-bit
addresses, open-drain lines. Compare bytes per millisecond against wires before you
choose.
Start with the worked 115200-baud link and a repeated 0x41 byte. Read the start, least-significant-first data and stop cells; a 100-byte burst occupies 8.68 ms, while only 11 complete frames fit in 1 ms. Change the receiver baud to move its sampling points and distinguish wrong data, a low stop sample and a sample exactly on a transition.
Why it matters. The physical world gives voltages; the CPU works with numbers. The
node's temperature reading is only as good as the converter and its wiring, and errors
here do not announce themselves.
A thermistor: its resistance changes with temperature, so a divider turns it into a voltage the ADC can read
The idea, with a picture. An ADC 模数转换器 (analog-to-digital converter)
quantises its input. An $N$-bit converter with a reference voltage $V_{\text{ref}}$ has
a resolution 分辨率 of one LSB 最低有效位 (least significant bit),
$V_{\text{ref}}/2^{N}$. The choice of $N$ decides how finely the voltage is measured. The
wiring decides whether that fine measurement survives.
Each code owns a one-LSB band of input voltage; mid-scale is code 2048
The derivation. Quantisation gives each voltage the code whose band contains it:
code $= \lfloor V_{\text{in}}/V_{\text{ref}} \times 2^{N} \rfloor$, with small differences at
the ends of the range. If each band is read back as its middle voltage, the
quantisation error is at most half an LSB inside the input range. A particular input
can have zero error.
Worked example 1 (the 12-bit sensor). Take $V_{\text{ref}} = 3.3$ V.
One LSB is $3.3/4096 = 0.806$ mV.
A 1.65 V input reads $1.65/3.3 \times 4096 = 2048$, exactly mid-scale ✓.
The node must measure to 0.1 °C, and the sensor gives 10 mV/°C, so it needs 1 mV of
resolution.
A 12-bit converter (0.806 mV) passes; a 10-bit one (3.22 mV) fails. The requirement
chooses $N$, not the catalogue.
Worked example 2 (the source-resistance trap). The ADC's sample-and-hold capacitor,
about 7 pF on this chip, charges through the resistance of the source. In a simple RC
model, settling to within ½ LSB after a full-scale step needs a sampling time of at
least $R_{\text{source}} C \ln(2^{N+1})$.
For a 50 kΩ source and 12 bits:
$50\,000 \times 7\,\text{pF} \times 9.01 \approx 3.2$ µs.
With a sampling window of only 1 µs, the same bound allows at most 16 kΩ.
A thermistor divider made of two 100 kΩ resistors has a Thevenin resistance of
50 kΩ. So it needs a window of at least 3.2 µs, or the divider resistors must be
smaller.
A DAC 数模转换器 (digital-to-analog converter) does the reverse: writing 2048 to
a 12-bit DAC with $V_{\text{ref}} = 3.3$ V gives 1.650 V.
Common mistakes.
Giving the resolution in bits and forgetting the reference. 0.806 mV is true only at
3.3 V.
Treating the ADC input like a voltmeter. Its sampling current loads a
high-resistance sensor, as the RC bound shows.
Expecting averaging to fix everything. Averaging 16 samples with white noise gives
about 2 more bits of effective resolution, but it cannot remove a constant offset or
a sample that did not settle.
Summary. One LSB is $V_{\text{ref}}/2^{N}$, and the requirement chooses $N$.
Reading each band at its middle gives a quantisation error of at most half an LSB. The
RC bound $t_{s} \ge R C \ln(2^{N+1})$ trades source resistance against sampling time; the
allowed resistance depends on the model and on the sampling window.
探索
Fine ADC steps need time for the sample to settle
$V_{error}=\Delta V e^{-t_s/(RC)},\quad t_s\ge RC\max[0,\ln(2^{N+1}\Delta V/V_{ref})]$
Start with the worked 50 kΩ source and 7 pF sampling capacitor on a 12-bit ADC. A 3.2 µs acquisition window meets the half-LSB settling budget; a 1 µs window misses it. Lower the source resistance or lengthen acquisition, then compare 16 bits to see why finer voltage steps demand a smaller remaining error. Separate acquisition error from quantisation.
Why it matters. Firmware is tested on the exact hardware it will ship on, and bugs
are often first reported as vague stories ("it froze twice last night"). A method is
what lets you actually find and fix the cause, instead of only hiding it.
Measuring a breadboard circuit with a multimeter: check supply rails and node voltages before suspecting the firmware
The idea, with a picture. The debugging loop has four steps:
Reproduce the fault with the smallest possible input.
Find the boundary between code you trust and code you suspect, with a probe: an
LED, a breakpoint or one UART print.
Fix one thing.
Test again.
A watchdog 看门狗 is a safety net that resets a system that has stopped. The
program must reset ("kick") the watchdog counter before it runs out. If the program
hangs, the product restarts as designed, instead of freezing by accident.
Reproduce, bisect, fix one thing, test again, with the watchdog around the whole loop
The derivation. Bisection is the method. Put a probe at the middle of the suspected
code. Use each probe to test whether the program state is already incorrect at that point. If a reproducible fault creates an observable incorrect state that persists, successive probes can narrow down where it first appears. The same halving is used by a successive-approximation ADC.
Worked example 1 (debounce as a state trace). The node's button reads 1, 0, 0, 1 at
four samples 10 ms apart, because the contact bounces. The rule is: accept a new state
only after two equal readings in a row.
t = 0 ms reads 1: no decision yet.
t = 10 ms reads 0: one reading of 0, no decision yet.
t = 20 ms reads 0 again: a stable 0 is accepted.
The 1 at t = 30 ms is only one sample, so it is correctly ignored for now.
Debounce 消抖 uses $N$ equal samples in a row: a timer tick, a GPIO read and a
state decision. It uses almost every idea of this course in one trace.
Worked example 2 (bisecting the freeze). The node freezes within an hour after a
certain sequence of log messages. The suspected code is 1024 instructions of the
communication driver.
Make instruction 512 switch the LED on.
If the LED remains off, investigate why execution did not reach the probe. If it
comes on, check the relevant program state at that point; an earlier defect may
still cause a later freeze.
If a suitable state check reliably halves the suspected region each time, ten checks
can narrow 1024 instructions to one, because $2^{10} = 1024$.
This is why bisection is faster than reading the code again and hoping to see the
bug.
Common mistakes.
Fixing two things at once. If one fix works and the other breaks something else, you
now have three problems to separate.
Debugging on a different board version from the one that fails.
Turning the watchdog off "for now". The failure in the field that the watchdog would
have survived is exactly the one that then ships.
Summary. Reproduce, bisect, fix one thing, test again; $\log_{2}$ of the suspected
size gives the number of probes. Debounce turns a noisy button into clean events by
requiring $N$ equal samples in a row. The watchdog is the last safety net: kick it only
in the main loop, never in an ISR.
探索
One contrary reading does not erase the qualified state
Step through the worked 1,0,0,1 trace at 10 ms intervals with two equal readings required. The first qualified 0 appears at 20 ms; the later single 1 does not reverse it. Edit samples, compare a one-sample pulse and an alternating input, and change N to distinguish input chatter from accepted output changes. Startup remains unqualified until a state earns enough consecutive readings.