跳到主要内容

微处理器与嵌入式系统

大学电气工程知识点 8

本主题的视频课程 打开视频页面
7:37

微处理器与嵌入式系统

数字逻辑课程构建了逻辑门和触发器;本课程要构建一台运行程序的机器。嵌入式系统的工作要从三个方面验证。位宽:每个值都能放进它的寄存器吗?时钟:时序能满足要求吗?执行轨迹:代码是否完成了你声称的任务?本课程中的每一次寄存器计算、每一个定时器设置和每一段代码,都要从这三个方面检查。

英文讲解 · 可切换中英文字幕

8.1

本课程介绍及使用方法

English

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.

词汇 训练
English 中文 拼音
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 them
A microcontroller board: processor, memory, timers and I/O pins on one chip, with headers to reach them
Fetch: copy the next instruction from memory, then PC + 1; Decode: the control unit works out what the instruction means; Execute: carry it out, the ALU may calculate and the result goes to ACC; the cycle repeats millions of times each second
The 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 取指译码执行周期:

  1. The program counter 程序计数器 (PC) holds the address of the next instruction, and the CPU fetches it.
  2. The control unit decodes it.
  3. The datapath executes it.
  4. 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.

Left: the CPU's loop of fetch at the PC, decode, execute and advance the PC. Right: the node's memory map, with flash 64 KB at 0x0000_0000 to 0x0000_FFFF, SRAM 8 KB at 0x2000_0000 to 0x2000_1FFF, and the peripherals GPIO, UART, timer and ADC from 0x4000_0000, with unused addresses between the regions
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:

$$\text{size} = 2^{N} \text{ bytes} \quad\Longleftrightarrow\quad N = \log_{2}(\text{size}) \text{ address lines}.$$

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.

  1. Flash: $64\,\text{KB} = 2^{16}$ bytes, so it needs 16 address lines. It occupies 0x0000_0000–0x0000_FFFF.
  2. SRAM: $8\,\text{KB} = 2^{13}$ bytes, so it needs 13 lines. It occupies 0x2000_0000–0x2000_1FFF.
  3. 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.

  1. That is $84 \times 10^{6}$ instructions per second, so one instruction takes $\dfrac{1}{84 \times 10^{6}} = 11.9$ ns.
  2. A control pass of 100 instructions takes 1.19 µs.
  3. So a 1 ms control loop has room for about 840 passes, if nothing else runs.
  4. 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.

探索

Which byte does this address select?

$address=base+offset,\quad N=\lceil\log_2(size\ in\ bytes)\rceil$

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.

词汇 训练
English 中文 拼音
microcontroller/ˈmaɪkrəʊkəntrəʊlə/ 微控制器 wēi kòng zhì qì
fetch-decode-execute cycle/fetʃ dɪˈkəʊd ˈeksɪkjuːt ˈsaɪkl/ 取指译码执行周期 qǔ zhǐ yì mǎ zhí xíng zhōu qī
program counter/ˈprəʊɡræm ˈkaʊntə/ 程序计数器 chéng xù jì shù qì
bus/bʌs/ 总线 zǒng xiàn
clock/klɒk/ 时钟 shí zhōng
8.2

嵌入式C语言与汇编

English

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.

The C line *GPIO_OUT |= (1u << 5) shown three ways: as C; as four assembly instructions (load the address 0x40000000, load the register, OR with 0x20 inside the CPU, store it back), with one bus read and one bus write; and as the register transfer GPIO_OUT gets GPIO_OUT OR 0x20
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:

  1. load the register,
  2. change the one bit inside the CPU, with a mask,
  3. 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

uint32_t count = 0;
while (1) { count = count + 1; }
  1. 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.)
  2. The largest value is $2^{32} - 1 = 4\,294\,967\,295$. The next increment wraps it to zero, after $2^{32}$ increments in total.
  3. 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.
  4. 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.

  1. The flip mask is $(1 \ll 5) \,|\, (1 \ll 6) = 0x60$.
  2. *GPIO_OUT = (*GPIO_OUT & ~0x08) ^ 0x60 clears bit 3 and flips bits 5 and 6 in one read-modify-write.
  3. Check on paper with GPIO_OUT = 0xCE: 0xCE & ~0x08 = 0xC6, then 0xC6 ^ 0x60 = 0xA6.
  4. Bit 3 is now 0 (it was 1). Bits 6 and 5 have changed from 1, 0 to 0, 1 ✓.
  5. 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.

探索

Mask the CPU copy, then store the whole word

$result=(original\;\&\;\sim clearMask)\;\oplus\;toggleMask$

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.

词汇 训练
English 中文 拼音
memory-mapped register/ˈmeməri mæpt ˈredʒɪstə/ 存储器映射寄存器 cún chǔ qì yìng shè jì cún qì
assembly/əˈsemblɪ/ 汇编 huì biān
8.3

存储器与输入/输出

English

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.

A GPIO port as two registers with one bit per pin: pin 0 has direction 0, so it is an input and its level is read into data bit 0; pin 1 has direction 1, so it is an output and data bit 1 drives the pin high
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.

  1. Each lap is 4 cycles (load, AND, branch, increment), so the CPU makes $84 \times 10^{6}/4 = 21$ million laps per second.
  2. A 1 ms wait is about 21 000 laps, or 84 000 cycles.
  3. 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).

  1. A table of constants in the firmware gives each driver its base address.
  2. A typing error in one entry, for example 0x4001_0004 instead of 0x4001_0000, points four bytes into the UART's registers.
  3. This is why every driver file names its register offsets and never uses raw addresses.
  4. 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.

词汇 训练
English 中文 拼音
polling/ˈpəʊlɪŋ/ 轮询 lún xún
GPIO/ˌdʒiː piː aɪ ˈəʊ/ 通用输入输出 tōng yòng shū rù shū chū
memory-mapped I/O/ˈmeməri mæpt aɪ əʊ/ 内存映射输入输出 nèi cún yìng shè shū rù shū chū
8.4

中断与定时器

English

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.

Flowchart of interrupt handling: the running program is interrupted, the CPU finishes the current instruction, saves its state (PC and registers) on the stack, runs the interrupt service routine, restores the state and resumes
How an interrupt fits into the fetch-execute cycle
Block chain: 84 MHz clock, prescaler dividing by 8400 (PSC = 8399) to 10 kHz, counter dividing by 10 000 (ARR = 9999) to 1 Hz, then the interrupt
Two divisions turn 84 MHz into a 1 Hz interrupt

The derivation. The clock frequency is divided twice:

$$f_{\text{interrupt}} = \frac{f_{\text{clock}}}{P R},\qquad P=PSC+1,\quad R=ARR+1.$$

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.

  1. A prescaler factor of 8400 gives $84 \times 10^{6}/8400 = 10$ kHz.
  2. A second factor of 10 000 gives exactly 1 Hz.
  3. So write PSC = 8399 and ARR = 9999. Both stored values fit in 16 bits.
  4. Check: $8400 \times 10\,000 = 84 \times 10^{6}$ ✓.
  5. 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.

  1. Each event costs $12 + 30 + 10 = 52$ cycles, which is 0.62 µs at 84 MHz. The polled wait above used 21 000 laps.
  2. 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.
  3. 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.
  4. 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.

词汇 训练
English 中文 拼音
interrupt/ˈɪntərʌpt/ 中断 zhōng duàn
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 transmission as bits in a line on one wire, and parallel transmission as several bits travelling together on several wires
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.
One UART frame: idle high, start bit low, eight data bits of 0x41 sent least significant first, stop bit high
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:

$$T_{\text{byte}} = \frac{10}{\text{baud}}, \qquad \text{throughput} = \frac{\text{baud}}{10} \text{ bytes/s}.$$

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.

  1. The throughput is $115\,200/10 = 11\,520$ bytes/s, and one byte takes $10/115\,200 = 86.8$ µs.
  2. In the node's 1 ms control loop, 11 bytes just fit (0.95 ms) ✓.
  3. A blocking burst of 100 bytes takes 8.68 ms, far over the budget. Split it into smaller pieces or raise the baud rate.
  4. The calculation decides, not personal preference.

Worked example 2 (comparing the three).

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

探索

Eight useful bits occupy ten bit times

$T_{frame}=10/B_t,\quad t_{sample,i}=(1.5+i)/B_r,\quad t_{stop}=9.5/B_r$

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.

词汇 训练
English 中文 拼音
UART/ˌjuː eɪ ɑː ˈtiː/ 通用异步收发器 tōng yòng yì bù shōu fā qì
SPI/ˌes piː ˈaɪ/ 串行外设接口 chuàn xíng wài shè jiē kǒu
I2C 集成电路总线 jí chéng diàn lù zǒng xiàn
baud rate/bɔːd reɪt/ 波特率 bō tè lǜ
8.6

模数转换器、数模转换器与传感器

English

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.

Small bead thermistors with two wire legs each, on a white background
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.

The 12-bit ADC transfer: over 0 to 3.3 V the 4096 steps look like a straight line; zoomed near mid-scale, each step is one LSB (0.806 mV) wide and one code high, and 1.65 V reads code 2048
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.

  1. One LSB is $3.3/4096 = 0.806$ mV.
  2. A 1.65 V input reads $1.65/3.3 \times 4096 = 2048$, exactly mid-scale ✓.
  3. The node must measure to 0.1 °C, and the sensor gives 10 mV/°C, so it needs 1 mV of resolution.
  4. 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})$.

  1. For a 50 kΩ source and 12 bits: $50\,000 \times 7\,\text{pF} \times 9.01 \approx 3.2$ µs.
  2. With a sampling window of only 1 µs, the same bound allows at most 16 kΩ.
  3. 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.
  4. 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.

词汇 训练
English 中文 拼音
ADC/ˌeɪ diː ˈsiː/ 模数转换器 mó shù zhuǎn huàn qì
resolution/ˌrezəˈluːʃn/ 分辨率 fēn biàn lǜ
LSB/ˌel es ˈbiː/ 最低有效位 zuì dī yǒu xiào wèi
DAC/ˌdiː eɪ ˈsiː/ 数模转换器 shù mó zhuǎn huàn qì
8.7

调试与集成

English

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.

A small circuit on a breadboard: a resistor and a glowing red LED are plugged into the rows, wired to a microcontroller, while the red and black probes of a multimeter touch the circuit to take a reading
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:

  1. Reproduce the fault with the smallest possible input.
  2. Find the boundary between code you trust and code you suspect, with a probe: an LED, a breakpoint or one UART print.
  3. Fix one thing.
  4. 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.

The debug loop: reproduce with the smallest input, bisect with a boundary probe, fix one thing, test again, and go round again if it still fails; a dashed watchdog box around the loop resets the system if it hangs
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.

  1. t = 0 ms reads 1: no decision yet.
  2. t = 10 ms reads 0: one reading of 0, no decision yet.
  3. t = 20 ms reads 0 again: a stable 0 is accepted.
  4. The 1 at t = 30 ms is only one sample, so it is correctly ignored for now.
  5. 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.

  1. Make instruction 512 switch the LED on.
  2. 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.
  3. If a suitable state check reliably halves the suspected region each time, ten checks can narrow 1024 instructions to one, because $2^{10} = 1024$.
  4. 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

$N\text{ equal sampled readings span }(N-1)\Delta t$

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.

词汇 训练
English 中文 拼音
watchdog/ˈwɒtʃdɒɡ/ 看门狗 kān mén gǒu
debounce/ˈdebaʊns/ 消抖 xiāo dǒu

该知识点的互动课程

逐步完成,配合即时检查练习。

更多 大学电气工程 知识点

登录或创建账户

IGCSE, A-Level & AP