嵌入式 C 代码跟读目录

第 0 课 · 七个阶段 · STM32 结课项目

点题名看源码。从 main 的输入开始手推,核对主机运行输出,再尝试变式。

导读

第一次读 C

阶段 1

表达式与控制流

阶段 2

数组、字符串与指针

阶段 3

位操作与二进制数据

阶段 4

对象、内存与模块接口

阶段 5

有状态的嵌入式模块

阶段 6

资源约束、协作与故障分析

阶段 7

从 C 源码读到编译产物

结课

从主机代码到 STM32

导读 · 第一次读 C

00 第一次顺着 main 读 C 程序

从 main 开始,只在遇到调用时跳到另一个函数。

main.c

#include <stdio.h>

static unsigned twice(unsigned value)
{
    return value * 2u;
}

int main(void)
{
    unsigned reading = 17u;
    unsigned result = twice(reading);
    printf("%u\n", result);
    return 0;
}

主机运行输出

34

手推 stdio.h 提供 printf 的声明。unsigned 表示无符号整数,变量 reading 保存 17。twice 收到一份值的副本,返回 34。%u 以十进制输出 unsigned,最后的 return 0 表示正常结束。

变式练习 把 17 改成 0 和 21,各手推一次。

阶段 1 · 表达式与控制流

01 整数换算:毫伏拆成伏和毫伏

观察整数除法和余数各自保留哪一部分。

main.c

#include <stdio.h>

int main(void)
{
    unsigned mv = 3305;
    printf("%u.%03u V\n", mv / 1000u, mv % 1000u);
    return 0;
}

主机运行输出

3.305 V

手推 3305 / 1000 得到 3,余数是 305。%03u 把小数部分补足三位。

变式练习 把输入改成 3005,预测小数点后会显示几位。

02 条件分支:温度分档

顺着 if 的判断顺序找出边界属于哪一档。

main.c

#include <stdio.h>

static const char *level(int celsius)
{
    if (celsius >= 40) {
        return "hot";
    }
    if (celsius >= 30) {
        return "warm";
    }
    return "normal";
}

int main(void)
{
    printf("%s %s %s\n", level(29), level(30), level(40));
    return 0;
}

主机运行输出

normal warm hot

手推 29 走到最后一个分支,30 命中 warm,40 优先命中 hot。

变式练习 加入负温档,并检查 -1 与 0。

03 for 循环:累加四次读数

跟踪循环下标与累加器。

main.c

#include <stdio.h>

int main(void)
{
    int samples[] = {10, 20, 30, 40};
    int sum = 0;
    for (size_t i = 0; i < 4; ++i) {
        sum += samples[i];
    }
    printf("sum=%d mean=%d\n", sum, sum / 4);
    return 0;
}

主机运行输出

sum=100 mean=25

手推 sum 依次成为 10、30、60、100。整数平均值是 25。

变式练习 把最后一个值改成 43,预测整数平均值。

04 while 循环:拆出十进制各位

跟踪每次除以 10 后还剩几位。

main.c

#include <stdio.h>

int main(void)
{
    unsigned value = 507;
    do {
        printf("%u", value % 10u);
        value /= 10u;
    } while (value != 0u);
    putchar('\n');
    return 0;
}

主机运行输出

705

手推 507 依次取出 7、0、5。do 循环让输入 0 也能输出一位。

变式练习 把输入改成 1000,记录每次的余数。

05 函数:把 PWM 占空比限制在范围内

观察提前返回和合法区间的两个端点。

main.c

#include <stdio.h>

static int clamp_duty(int duty)
{
    if (duty < 0) {
        return 0;
    }
    if (duty > 100) {
        return 100;
    }
    return duty;
}

int main(void)
{
    printf("%d %d %d\n", clamp_duty(-4), clamp_duty(35), clamp_duty(120));
    return 0;
}

主机运行输出

0 35 100

手推 -4 小于下界,35 在区间内,120 超过上界。

变式练习 把上限改为函数参数,并约定它的合法范围。

06 switch 与枚举:把工作模式变成文本

读出枚举常量和各个 case 的对应关系。

main.c

#include <stdio.h>

enum Mode { MODE_IDLE, MODE_RUN, MODE_FAULT };

static const char *mode_name(enum Mode mode)
{
    switch (mode) {
    case MODE_IDLE:  return "idle";
    case MODE_RUN:   return "run";
    case MODE_FAULT: return "fault";
    default:         return "unknown";
    }
}

int main(void)
{
    puts(mode_name(MODE_RUN));
    return 0;
}

主机运行输出

run

手推 MODE_RUN 命中第二项,返回指向字符串字面量的指针。

变式练习 加入 MODE_SLEEP,并补上对应文本。

阶段 2 · 数组、字符串与指针

07 一维数组:查找第一次越限的位置

数组传给函数后,由调用者另外传入元素数。

main.c

#include <stdio.h>

static size_t first_high(const int *a, size_t n, int limit)
{
    for (size_t i = 0; i < n; ++i) {
        if (a[i] >= limit) {
            return i;
        }
    }
    return n;
}

int main(void)
{
    int a[] = {18, 20, 25};
    size_t n = sizeof a / sizeof a[0];
    printf("%zu\n", first_high(a, n, 20));
    return 0;
}

主机运行输出

1

手推 第 1、2 号元素都达到 20,第一次命中下标 1。没有匹配时返回 n。

变式练习 阈值改成 26,推算返回值。

07A 数组与指针对照:下标、地址和元素个数

让同一组样本分别出现在声明处和函数参数中。

main.c

#include <stddef.h>
#include <stdio.h>

static void show(const int p[], size_t count)
{
    printf("%d %d\n", p[1], *(p + 1));
    printf("count=%zu pointer=%d\n", count, sizeof p == sizeof(const int *));
}

int main(void)
{
    int a[] = {12, 24, 36, 48};
    show(a, sizeof a / sizeof a[0]);
    return 0;
}

主机运行输出

24 24
count=4 pointer=1

手推 a[1] 与 *(a + 1) 都取到 24。调用方的 sizeof a 覆盖整个数组。show 的形参调整为指针,sizeof p 得到指针的大小,所以元素数由调用方另外传入。

变式练习 把数组扩成 8 个元素。再把 show 的形参写成 const int *p,推算哪些输出会变。

08 二维数组:按通道统计采样值

区分通道下标和时间下标。

main.c

#include <stdio.h>

int main(void)
{
    int samples[2][3] = {{1, 2, 3}, {4, 5, 6}};
    for (size_t channel = 0; channel < 2; ++channel) {
        int sum = 0;
        for (size_t tick = 0; tick < 3; ++tick) {
            sum += samples[channel][tick];
        }
        printf("%d\n", sum);
    }
    return 0;
}

主机运行输出

6
15

手推 第 0 行累加为 6,第 1 行累加为 15。

变式练习 把遍历顺序改成每个时刻汇总两个通道。

09 字符串:找到命令中的分隔符

沿着字符读到等号或字符串结束符。

main.c

#include <stdio.h>

static const char *value_of(const char *p)
{
    while (*p != '\0' && *p != '=') {
        ++p;
    }
    if (*p == '=') {
        return p + 1;
    }
    return NULL;
}

int main(void)
{
    const char *value = value_of("rate=50");
    puts(value ? value : "missing");
    return 0;
}

主机运行输出

50

手推 指针从字符 r 走到 =,p + 1 指向字符 5。

变式练习 输入 rate 和 rate=,分别判断会返回空指针还是空字符串。

10 字符数组:识别格式化输出截断

比较缓冲区容量和 snprintf 返回的所需字符数。

main.c

#include <stdio.h>

int main(void)
{
    char text[4];
    const char *message = "ERR42";
    int needed = snprintf(text, sizeof text, "%s", message);
    if (needed >= 0 && (size_t)needed >= sizeof text) {
        printf("%s %d truncated\n", text, needed);
    }
    return 0;
}

主机运行输出

ERR 5 truncated

手推 完整文本需要 5 个字符外加结束符,4 字节数组只能保存 ERR 和结束符。

变式练习 把数组容量改成 5 和 6,分别推算返回值和实际文本。

11 指针与输出参数:一次取到最小值和最大值

看清 & 取得谁的地址,* 写回谁的对象。

main.c

#include <stdio.h>
#include <stdbool.h>

static bool minmax(const int *a, size_t n, int *lo, int *hi)
{
    if (n == 0) {
        return false;
    }
    *lo = *hi = a[0];
    for (size_t i = 1; i < n; ++i) {
        if (a[i] < *lo) *lo = a[i];
        if (a[i] > *hi) *hi = a[i];
    }
    return true;
}

int main(void)
{
    int a[] = {8, 3, 12};
    int lo, hi;
    if (minmax(a, 3, &lo, &hi)) {
        printf("%d %d\n", lo, hi);
    }
    return 0;
}

主机运行输出

3 12

手推 从 8 初始化两个极值,3 更新最小值,12 更新最大值。约定两个输出指针指向不同的有效对象。

变式练习 传入长度 0,检查输出会不会被写入。

12 指针与长度:递归折半查找有序表

每次递归只保留一个更小的有序区间,并观察终止条件。

main.c

#include <stdio.h>
#include <stdbool.h>

static bool contains(const int *a, size_t n, int key)
{
    if (n == 0) {
        return false;
    }
    size_t mid = n / 2;
    if (a[mid] == key) {
        return true;
    }
    if (key < a[mid]) {
        return contains(a, mid, key);
    }
    return contains(a + mid + 1, n - mid - 1, key);
}

int main(void)
{
    int table[] = {2, 5, 8, 13};
    puts(contains(table, 4, 13) ? "yes" : "no");
    return 0;
}

主机运行输出

yes

手推 在 2、5、8、13 中查 13,先比较 8,再在右侧长度为 1 的区间命中。

变式练习 用空区间和目标值 7 手推;再用循环改写,比较临时状态放在哪里。

阶段自测 把第 07 题改为寻找最后一次越限,手推长度为零、全部未命中和末元素命中。

阶段 3 · 位操作与二进制数据

13 整型提升:两个字节相减

先判断表达式的类型,再看赋值给窄类型后的值。

main.c

#include <stdio.h>
#include <stdint.h>

int main(void)
{
    uint8_t a = 0, b = 1;
    int difference = a - b;
    uint8_t wrapped = (uint8_t)difference;
    printf("%d %u\n", difference, (unsigned)wrapped);
    return 0;
}

主机运行输出

-1 255

手推 uint8_t 的 0 和 1 提升为 int 后相减得到 -1。转换到 uint8_t 得到 255。

变式练习 将 a 改成 200,b 改成 250,分别预测两行计算。

14 位掩码:置位、清位和查询

从最低位编号 0,写出每个掩码的二进制形式。

main.c

#include <stdio.h>

int main(void)
{
    unsigned flags = 0x08u;
    flags |= 1u << 1;
    flags &= ~(1u << 3);
    printf("%02X %d\n", flags, (flags & (1u << 1)) != 0u);
    return 0;
}

主机运行输出

02 1

手推 0x08 置位 bit 1 得到 0x0A,再清 bit 3 得到 0x02。

变式练习 用异或连续翻转 bit 1 两次,记录两次结果。

15 连续位域:更新配置字中的模式

把旧字段清零,再将新字段移到目标位置。本题操作普通变量。

main.c

#include <stdio.h>

static unsigned with_mode(unsigned word, unsigned mode)
{
    const unsigned mask = 3u << 4;
    return (word & ~mask) | ((mode & 3u) << 4);
}

int main(void)
{
    printf("%02X\n", with_mode(0xB5u, 2u));
    return 0;
}

主机运行输出

A5

手推 0xB5 清除 bit 5 和 bit 4 得到 0x85,写入模式 2 后为 0xA5。

变式练习 把字段移到 bit 3 至 bit 1,允许写入 0 至 7。

16 字节序:读取大端 16 位数

由字节顺序组装整数,不依赖缓冲区对齐方式。

main.c

#include <stdio.h>
#include <stdint.h>

static uint16_t read_be16(const uint8_t data[2])
{
    return (uint16_t)(((unsigned)data[0] << 8) | data[1]);
}

int main(void)
{
    uint8_t data[] = {0x12, 0x34};
    printf("%u\n", (unsigned)read_be16(data));
    return 0;
}

主机运行输出

4660

手推 12 34 表示十六进制 0x1234,即十进制 4660。

变式练习 交换高低字节的位置,改成小端读取。

17 有符号采样:解释 12 位补码

先屏蔽无关高位,再按照协议的符号位解释数学值。

main.c

#include <stdio.h>

static int decode12(unsigned raw)
{
    int value = (int)(raw & 0xFFFu);
    if (value >= 2048) {
        value -= 4096;
    }
    return value;
}

int main(void)
{
    printf("%d %d %d\n", decode12(0xFFF), decode12(0x800), decode12(0x7FF));
    return 0;
}

主机运行输出

-1 -2048 2047

手推 0xFFF 表示 -1,0x800 表示 -2048,0x7FF 表示 2047。

变式练习 检查 0xF001,判断高四位会不会影响结果。

18 校验:按位计算 CRC-8

跟踪最高位、左移和异或。参数为多项式 0x07、初值 0、无反射、结果无异或。

main.c

#include <stdio.h>
#include <stdint.h>

static uint8_t crc8(const uint8_t *data, size_t size)
{
    uint8_t crc = 0;
    for (size_t i = 0; i < size; ++i) {
        crc ^= data[i];
        for (unsigned bit = 0; bit < 8; ++bit) {
            unsigned polynomial = (crc & 0x80u) ? 0x07u : 0u;
            crc = (uint8_t)(((unsigned)crc << 1) ^ polynomial);
        }
    }
    return crc;
}

int main(void)
{
    uint8_t data[] = {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39};
    printf("%02X\n", (unsigned)crc8(data, sizeof data));
    return 0;
}

主机运行输出

F4

手推 输入 ASCII 字节 31 至 39,校验结果为 F4。空输入保留初值 0。

变式练习 只输入一个 0x01,列出连续八轮的 crc。

阶段 4 · 对象、内存与模块接口

19 结构体与生命周期:两路独立计数

上下文由调用者持有,通过指针传给同一个更新函数。

main.c

#include <stdio.h>

typedef struct {
    unsigned count;
} Channel;

static void record(Channel *channel)
{
    ++channel->count;
}

int main(void)
{
    Channel a = {0}, b = {0};
    record(&a);
    record(&b);
    record(&a);
    printf("%u %u\n", a.count, b.count);
    return 0;
}

主机运行输出

2 1

手推 a 收到两次采样,b 收到一次,两份状态独立。

变式练习 把两个对象放入数组,按通道下标选取上下文。

20 枚举与联合体:表示不同种类的事件

用标签记录当前有效成员,按标签读取。

main.c

#include <stdio.h>

enum Kind { BUTTON, TEMPERATURE };
typedef struct {
    enum Kind kind;
    union {
        unsigned button;
        int celsius;
    } data;
} Event;

static void show(Event e)
{
    switch (e.kind) {
    case BUTTON:      printf("key %u\n", e.data.button); break;
    case TEMPERATURE: printf("%d C\n", e.data.celsius); break;
    }
}

int main(void)
{
    Event e = {.kind = TEMPERATURE, .data.celsius = -5};
    show(e);
    return 0;
}

主机运行输出

-5 C

手推 事件的标签是 TEMPERATURE,读取同一次初始化的 celsius 成员。

变式练习 增加一个电压事件,追踪构造和读取两端要改的地方。

21 静态存储期:跨调用保存计数

比较函数内 static 对象和普通局部变量的初始化时机。

main.c

#include <stdio.h>

static unsigned next_id(void)
{
    static unsigned count;
    return ++count;
}

int main(void)
{
    unsigned first = next_id();
    unsigned second = next_id();
    printf("%u %u\n", first, second);
    return 0;
}

主机运行输出

1 2

手推 两次调用共享同一个 count,值从 0 变成 1,再变成 2。两个调用分开成两条语句。

变式练习 去掉 static 再推算两次返回值,对比第 19 题的显式上下文。

22 堆内存:复制一批采样并交付所有权

先检查大小乘法,再分配和复制。调用者负责 free。

main.c

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

static uint16_t *copy_samples(const uint16_t *src, size_t n)
{
    if (n == 0 || n > SIZE_MAX / sizeof *src) {
        return NULL;
    }
    uint16_t *copy = malloc(n * sizeof *copy);
    if (copy != NULL) {
        memcpy(copy, src, n * sizeof *copy);
    }
    return copy;
}

int main(void)
{
    uint16_t source[] = {10, 20};
    uint16_t *copy = copy_samples(source, 2);
    if (copy == NULL) {
        return 1;
    }
    source[1] = 99;
    printf("%u\n", (unsigned)copy[1]);
    free(copy);
    return 0;
}

主机运行输出

20

手推 复制后修改源数组,副本仍保存原先的 20。这里约定空输入返回 NULL。

变式练习 把元素数改成 0,跟踪释放路径。

22A 调用者提供缓冲区:容量、写入长度与失败约定

用三个字节编码帧头、数据和校验。由调用者拥有存储,函数只在容量足够时写入。

main.c

#include <stdint.h>
#include <stdio.h>

static size_t encode(uint8_t *dst, size_t capacity, uint8_t value)
{
    if (dst == NULL || capacity < 3) {
        return 0;
    }
    dst[0] = 0xA5;
    dst[1] = value;
    dst[2] = (uint8_t)(value ^ 0xFFu);
    return 3;
}

int main(void)
{
    uint8_t frame[3];
    uint8_t small[2] = {0xCC, 0xCC};
    size_t n = encode(frame, sizeof frame, 0x2A);
    printf("%zu %02X %02X %02X\n", n, (unsigned)frame[0],
           (unsigned)frame[1], (unsigned)frame[2]);
    n = encode(small, sizeof small, 0x2A);
    printf("%zu %02X\n", n, (unsigned)small[0]);
    printf("%zu\n", encode(NULL, 0, 0x2A));
    return 0;
}

主机运行输出

3 A5 2A D5
0 CC
0

手推 容量 3 时返回 3。容量 2 和 0 时返回 0,调用者用哨兵值 CC 核对短缓冲区未被部分写入。零容量演示允许传入空指针。

变式练习 加入独立的长度字段,把帧扩成四字节。先写出容量 3 和 4 两种情况的预期结果。

23 函数指针:把数据交给回调

函数指针决定调用谁,用户上下文决定结果写到哪里。

main.c

#include <stdio.h>

typedef void (*Visitor)(int sample, void *context);

static void visit(const int *a, size_t n, Visitor fn, void *context)
{
    for (size_t i = 0; i < n; ++i) {
        fn(a[i], context);
    }
}

static void accumulate(int sample, void *context)
{
    int *sum = context;
    *sum += sample;
}

int main(void)
{
    int a[] = {2, 4, 6};
    int sum = 0;
    visit(a, 3, accumulate, &sum);
    printf("%d\n", sum);
    return 0;
}

主机运行输出

12

手推 visit 对 2、4、6 分别调用 accumulate,sum 最终为 12。

变式练习 换成计数回调,保留 visit 的实现。

24 多文件模块:头文件、实现与调用方

先读 main.c 的调用,再对照头文件声明和 .c 中的定义。

main.c

#include <stdio.h>
#include "counter.h"

int main(void)
{
    Counter counter = {0};
    counter_add(&counter, 60);
    printf("%u ", counter.value);
    counter_add(&counter, 60);
    printf("%u\n", counter.value);
    return 0;
}

counter.h

#ifndef COUNTER_H
#define COUNTER_H

typedef struct {
    unsigned value;  /* 合法范围 0..100 */
} Counter;

void counter_add(Counter *counter, unsigned delta);

#endif

counter.c

#include "counter.h"

void counter_add(Counter *counter, unsigned delta)
{
    unsigned room = 100u - counter->value;
    counter->value += delta > room ? room : delta;
}

主机运行输出

60 100

手推 模块上限为 100,两次增加 60 后依次为 60、100。

变式练习 加入 counter_reset,并分别补上声明、实现和调用。

阶段自测 把第 11 题拆成头文件、实现和调用方,分别核对声明、长度和输出参数。

阶段 5 · 有状态的嵌入式模块

25 计时器回绕:判断是否超时

使用指定宽度的无符号差值表示经过的时间。

main.c

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main(void)
{
    uint32_t start = UINT32_MAX - 3u;
    uint32_t now = 3u;
    uint32_t elapsed = (uint32_t)(now - start);
    printf("%" PRIu32 " %s\n", elapsed, elapsed >= 7u ? "due" : "wait");
    return 0;
}

主机运行输出

7 due

手推 起点为 0xFFFFFFFC,当前为 3,经过 7 个 tick。前提是实际间隔小于一个完整的 32 位计数周期。

变式练习 分别用超时间隔 7 和 8 测试同一组时间戳。

26 按键消抖:连续三次一致才切换

每次调用代表一次等间隔采样。返回值只报告稳定电平发生变化的那一次。

main.c

#include <stdio.h>
#include <stdbool.h>

typedef struct {
    bool stable;
    unsigned different;
} Button;

static bool update(Button *b, bool level)
{
    if (level == b->stable) {
        b->different = 0;
        return false;
    }
    if (++b->different < 3) {
        return false;
    }
    b->stable = level;
    b->different = 0;
    return true;
}

int main(void)
{
    Button b = {0};
    bool input[] = {1, 0, 1, 1, 1};
    for (size_t i = 0; i < 5; ++i) {
        if (update(&b, input[i])) {
            printf("%zu:%d\n", i + 1, b.stable);
        }
    }
    return 0;
}

主机运行输出

5:1

手推 输入 1、0、1、1、1,在第 5 次采样才稳定按下。

变式练习 继续输入三个 0,判断何时报告释放。

27 滑动平均:固定窗口和运行和

覆盖旧槽位前先扣除旧值。启动阶段按已有样本数取平均。

main.c

#include <stdio.h>
#include <stdint.h>

enum { WINDOW = 3 };
typedef struct {
    uint16_t values[WINDOW];
    uint32_t sum;
    unsigned pos, used;
} Filter;

static uint16_t push(Filter *f, uint16_t sample)
{
    f->sum -= f->values[f->pos];
    f->values[f->pos] = sample;
    f->sum += sample;
    f->pos = (f->pos + 1u) % WINDOW;
    if (f->used < WINDOW) ++f->used;
    return (uint16_t)(f->sum / f->used);
}

int main(void)
{
    Filter f = {0};
    for (unsigned i = 1; i <= 4; ++i) {
        printf("%u%c", (unsigned)push(&f, (uint16_t)(10u * i)), i == 4 ? '\n' : ' ');
    }
    return 0;
}

主机运行输出

10 15 20 30

手推 窗口长 3。加入 10、20、30、40,最后窗口为 20、30、40。

变式练习 加入第五个样本 5,追踪被移除的值。

28 环形队列:回绕、判空与判满

预留一个空槽位,next == read 表示满,read == write 表示空。本例在同一执行上下文中运行。

main.c

#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>

enum { CAP = 4 };
typedef struct {
    uint8_t data[CAP];
    unsigned read, write;
} Ring;

static bool push(Ring *r, uint8_t value)
{
    unsigned next = (r->write + 1u) % CAP;
    if (next == r->read) return false;
    r->data[r->write] = value;
    r->write = next;
    return true;
}

static bool pop(Ring *r, uint8_t *value)
{
    if (r->read == r->write) return false;
    *value = r->data[r->read];
    r->read = (r->read + 1u) % CAP;
    return true;
}

int main(void)
{
    Ring r = {0};
    uint8_t value;
    push(&r, 10);
    push(&r, 20);
    push(&r, 30);
    if (!push(&r, 40)) puts("full");
    pop(&r, &value);
    push(&r, 40);
    while (pop(&r, &value)) {
        printf("%u%c", (unsigned)value, r.read == r.write ? '\n' : ' ');
    }
    return 0;
}

主机运行输出

full
20 30 40

手推 长度 4 可存 3 个字节。第一次写 40 遇满,读走 10 后重试成功。

变式练习 实现 count,分别手推 write 大于和小于 read 两种情况。

29 零复制解析:返回报文数据区视图

检查帧头和长度后,交付指向原缓冲区的指针。视图只在原存储有效且内容满足约定时可用。

main.c

#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>

typedef struct {
    const uint8_t *data;
    size_t size;
} View;

static bool parse(const uint8_t *p, size_t n, View *out)
{
    if (n < 2 || p[0] != 0xA5 || p[1] != n - 2) return false;
    out->data = p + 2;
    out->size = p[1];
    return true;
}

int main(void)
{
    uint8_t frame[] = {0xA5, 2, 0x11, 0x22};
    View view;
    if (parse(frame, sizeof frame, &view)) {
        printf("%zu %02X ", view.size, (unsigned)view.data[0]);
        frame[2] = 0x99;
        printf("%02X\n", (unsigned)view.data[0]);
    }
    return 0;
}

主机运行输出

2 11 99

手推 A5 02 11 22 的长度匹配。随后原缓冲区改写为 99,视图看到新值。

变式练习 加入只有帧头、零长度帧和多余尾字节三组输入。

30 逐字节状态机:拼接分批到达的帧

协议为 A5、长度、数据。上下文保存当前进度,长度最大为 4。

main.c

#include <stdio.h>
#include <stdint.h>

enum State { HEADER, LENGTH, PAYLOAD };
typedef struct {
    enum State state;
    unsigned used, expected;
    uint8_t data[4];
} Parser;

static void feed(Parser *p, uint8_t byte)
{
    switch (p->state) {
    case HEADER:
        if (byte == 0xA5) p->state = LENGTH;
        break;
    case LENGTH:
        p->used = 0;
        p->expected = byte;
        if (byte == 0) puts("0");
        p->state = byte > 0 && byte <= sizeof p->data ? PAYLOAD : HEADER;
        break;
    case PAYLOAD:
        p->data[p->used++] = byte;
        if (p->used == p->expected) {
            printf("%u", p->used);
            for (unsigned i = 0; i < p->used; ++i) {
                printf(":%02X", (unsigned)p->data[i]);
            }
            putchar('\n');
            p->state = HEADER;
        }
        break;
    }
}

int main(void)
{
    Parser parser = {0};
    uint8_t first[] = {0, 0xA5, 2, 0x11};
    uint8_t second[] = {0x22, 0xA5, 0};
    for (size_t i = 0; i < sizeof first; ++i) feed(&parser, first[i]);
    for (size_t i = 0; i < sizeof second; ++i) feed(&parser, second[i]);
    return 0;
}

主机运行输出

2:11:22
0

手推 第一批在首个数据字节后结束。第二批补齐 22,随后一个零长度帧也完成。

变式练习 输入 A5 05 A5 01 77,标记非法长度后何时重新识别帧头。

阶段 6 · 资源约束、协作与故障分析

31 固定块内存池:耗尽与归还

每个槽位能容纳一个对象。获取和归还按槽位管理,使用方在归还后放弃该槽位。

main.c

#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>

enum { SLOTS = 2 };
typedef struct {
    uint8_t data[SLOTS][16];
    bool used[SLOTS];
} Pool;

static int acquire(Pool *p)
{
    for (int i = 0; i < SLOTS; ++i) {
        if (!p->used[i]) {
            p->used[i] = true;
            return i;
        }
    }
    return -1;
}

static void release(Pool *p, int id)
{
    if (id >= 0 && id < SLOTS) p->used[id] = false;
}

int main(void)
{
    Pool p = {0};
    int a = acquire(&p);
    int b = acquire(&p);
    int c = acquire(&p);
    p.data[a][0] = 42;
    release(&p, a);
    printf("%d %d %d %d\n", a, b, c, acquire(&p));
    return 0;
}

主机运行输出

0 1 -1 0

手推 前两次取到 0、1,池满返回 -1。归还 0 后再次取到 0。

变式练习 让 release 返回布尔值,区分重复归还和成功归还。

32 寄存器语义:写 1 清除事件标志

用主机模型表示写 1 清零寄存器。volatile 限定对状态对象的访问,写入语义由模型实现。

main.c

#include <stdio.h>

typedef struct {
    volatile unsigned status;
} DeviceModel;

/* 模拟外设收到一次写操作后的内部动作。 */
static void bus_write(DeviceModel *dev, unsigned written)
{
    dev->status &= ~written;
}

static void acknowledge_rx(DeviceModel *dev)
{
    bus_write(dev, 1u << 0);
}

int main(void)
{
    DeviceModel dev = {.status = 0x05u};
    acknowledge_rx(&dev);
    printf("%02X\n", dev.status);
    return 0;
}

主机运行输出

04

手推 初值 0x05。同时挂起 bit 0 和 bit 2。总线上写 0x01 后只剩 bit 2。

变式练习 从同一初值开始,把传给 bus_write 的值改成 status | 1u,再算剩余标志。

33 C11 原子操作:单槽生产者与消费者

限定一个生产者和一个消费者。发布满标记前写入数据,发布空标记前读完数据。

main.c

#include <stdio.h>
#include <stdatomic.h>
#include <stdbool.h>

typedef struct {
    atomic_bool full;
    unsigned value;
} Mailbox;

static bool publish(Mailbox *m, unsigned value)
{
    if (atomic_load_explicit(&m->full, memory_order_acquire)) return false;
    m->value = value;
    atomic_store_explicit(&m->full, true, memory_order_release);
    return true;
}

static bool take(Mailbox *m, unsigned *value)
{
    if (!atomic_load_explicit(&m->full, memory_order_acquire)) return false;
    *value = m->value;
    atomic_store_explicit(&m->full, false, memory_order_release);
    return true;
}

int main(void)
{
    Mailbox m;
    atomic_init(&m.full, false);
    unsigned value = 0;
    publish(&m, 7);
    if (!publish(&m, 8)) printf("busy ");
    if (take(&m, &value)) printf("%u ", value);
    if (publish(&m, 8)) puts("accepted");
    return 0;
}

主机运行输出

busy 7 accepted

手推 先发布 7,槽满时发布 8 失败。读取 7 并归还后,发布 8 成功。示例用顺序调用演示接口。

变式练习 标出两对 release/acquire,使数据写入先于读取、读取先于复用。

34 双缓冲:观察生产速度超过消费速度

用串行事件模拟采集完成、消费者读取和释放槽位。显式记录没有空槽位时丢弃的新样本。

main.c

#include <stdio.h>
#include <stdbool.h>

typedef struct {
    unsigned slots[2];
    unsigned read, write, used, lost;
} Capture;

static void complete(Capture *c, unsigned sample)
{
    if (c->used == 2) {
        ++c->lost;
        return;
    }
    c->slots[c->write] = sample;
    c->write ^= 1u;
    ++c->used;
}

static bool consume(Capture *c, unsigned *out)
{
    if (c->used == 0) return false;
    *out = c->slots[c->read];
    c->read ^= 1u;
    --c->used;
    return true;
}

int main(void)
{
    Capture c = {0};
    unsigned value;
    complete(&c, 10);
    complete(&c, 20);
    complete(&c, 30);
    if (consume(&c, &value)) printf("%u ", value);
    complete(&c, 40);
    while (consume(&c, &value)) printf("%u ", value);
    printf("lost=%u\n", c.lost);
    return 0;
}

主机运行输出

10 20 40 lost=1

手推 两个槽位收到 10、20,30 遇满被丢弃。消费 10 腾出空间,40 写入,随后依序读到 20、40。

变式练习 写出在真实 DMA 启动前必须预留槽位的原因,并区分填充中与可读两个状态。

35 故障定位:给队列添加高水位和丢弃计数

通过深度、高水位和累计丢弃次数区分当前状态与历史压力。这里用计数模型观察队列占用。

main.c

#include <stdio.h>

enum { CAPACITY = 3 };
typedef struct {
    unsigned depth, peak, dropped;
} QueueStats;

static void arrive(QueueStats *s)
{
    if (s->depth == CAPACITY) {
        ++s->dropped;
        return;
    }
    ++s->depth;
    if (s->depth > s->peak) s->peak = s->depth;
}

static void depart(QueueStats *s)
{
    if (s->depth != 0) --s->depth;
}

int main(void)
{
    QueueStats stats = {0};
    for (unsigned i = 0; i < 4; ++i) arrive(&stats);
    depart(&stats);
    depart(&stats);
    printf("depth=%u peak=%u dropped=%u\n", stats.depth, stats.peak, stats.dropped);
    return 0;
}

主机运行输出

depth=1 peak=3 dropped=1

手推 容量 3,连续到达 4 次后丢 1 次;取走 2 项后当前深度 1,历史峰值仍为 3。

变式练习 构造一次无丢弃的满队列,比较两个指标各能说明什么。

36 综合:可注入故障的传感器轮询模块

函数指针接入数据源,上下文保留上次有效读数和连续失败次数。连续失败两次进入故障状态,有效读数到来后恢复。

main.c

#include <stdio.h>
#include <stdbool.h>

typedef bool (*ReadSensor)(void *context, int *value);

typedef struct {
    ReadSensor read;
    void *context;
    unsigned failures;
    bool valid;
    int last;
} Monitor;

static const char *poll_sensor(Monitor *m)
{
    int value;
    if (m->read(m->context, &value)) {
        m->last = value;
        m->valid = true;
        m->failures = 0;
        return "ok";
    }
    if (m->failures < 2) ++m->failures;
    return m->failures == 2 ? "fault" : "retry";
}

typedef struct {
    bool ok;
    int value;
} Reading;

typedef struct {
    const Reading *steps;
    size_t count, next;
} Script;

static bool scripted_read(void *context, int *value)
{
    Script *s = context;
    if (s->next == s->count) return false;
    Reading step = s->steps[s->next++];
    if (!step.ok) return false;
    *value = step.value;
    return true;
}

int main(void)
{
    Reading steps[] = {{true, 25}, {false, 0}, {false, 0}, {true, 27}};
    Script script = {steps, sizeof steps / sizeof steps[0], 0};
    Monitor m = {.read = scripted_read, .context = &script};
    for (size_t i = 0; i < script.count; ++i) {
        const char *status = poll_sensor(&m);
        if (m.valid) printf("%s %d\n", status, m.last);
        else printf("%s --\n", status);
    }
    return 0;
}

主机运行输出

ok 25
retry 25
fault 25
ok 27

手推 用脚本喂入成功 25、失败、失败、成功 27。两次失败期间上次有效值保持 25,恢复后更新为 27。

变式练习 把脚本改成从失败开始,检查首次成功之前打印的是空值。再设计需要连续两次成功才恢复的版本。

阶段 7 · 从 C 源码读到编译产物

37 宏与内联函数:参数何时求值

宏参数按文本替换;内联函数的形参接收求值后的值。MAX2 在本题选中的分支会再次读取数据。

main.c

#include <stdio.h>

#define MAX2(a, b) ((a) > (b) ? (a) : (b))

static unsigned sample(unsigned *counter)
{
    return ++*counter;
}

static inline unsigned max2(unsigned a, unsigned b)
{
    return a > b ? a : b;
}

int main(void)
{
    unsigned reads = 0;
    unsigned macro_value = MAX2(sample(&reads), 0u);
    reads = 0;
    unsigned function_value = max2(sample(&reads), 0u);
    printf("%u %u\n", macro_value, function_value);
    return 0;
}

主机运行输出

2 1

手推 模拟读数从 1 开始递增。宏比较时读 1,返回时再读出 2;重置后函数只读取 1。

变式练习 用 gcc -E main.c 查看 main 内的宏展开,再判断哪次读取可以省掉。

38 对象布局:对齐、填充与线上格式

用 offsetof 观察成员位置,再显式写入三个协议字节。结构体占用的内存由 ABI 决定。

main.c

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>

typedef struct {
    uint8_t type;
    uint16_t seq;
} Header;

_Static_assert(offsetof(Header, type) == 0, "first member offset");

static void encode(uint8_t out[3], const Header *h)
{
    out[0] = h->type;
    out[1] = (uint8_t)(h->seq >> 8);
    out[2] = (uint8_t)h->seq;
}

int main(void)
{
    Header h = {.type = 0x2A, .seq = 0x1234};
    uint8_t wire[3];
    encode(wire, &h);
    printf("%02X %02X %02X\n", (unsigned)wire[0], (unsigned)wire[1], (unsigned)wire[2]);
    return 0;
}

主机运行输出

2A 12 34

手推 类型 2A、序号 1234 要发送的三个字节是 2A 12 34。结构体的成员偏移可以因平台改变。

变式练习 用 printf 打印 sizeof(Header)、_Alignof(Header) 和 offsetof(Header, seq),再换编译目标比较。

39 有符号边界:先检查再加

C 的有符号加法超出可表示范围会产生未定义行为。分别在正增量与负增量路径检查边界。

main.c

#include <stdio.h>
#include <limits.h>
#include <stdbool.h>

static bool checked_add(int a, int b, int *out)
{
    if (b > 0 && a > INT_MAX - b) return false;
    if (b < 0 && a < INT_MIN - b) return false;
    *out = a + b;
    return true;
}

int main(void)
{
    int out = 11;
    if (!checked_add(INT_MAX, 1, &out)) printf("overflow %d\n", out);
    if (checked_add(5, -2, &out)) printf("%d\n", out);
    return 0;
}

主机运行输出

overflow 11
3

手推 INT_MAX 加 1 进入失败路径,输出保留为 11;5 加 -2 得到 3。

变式练习 尝试 INT_MIN 加 -1、INT_MIN 加 1、0 加 INT_MIN。解释为什么检查本身也在可表示范围内。

40 优化与调试:追踪一次循环

用同一组输入比较 -O0 与 -O2 的可观察结果,再查看对应汇编。

main.c

#include <stdio.h>

static unsigned count_high(const int *a, size_t n, int limit)
{
    unsigned count = 0;
    for (size_t i = 0; i < n; ++i) {
        if (a[i] >= limit) ++count;
    }
    return count;
}

int main(void)
{
    int a[] = {2, 3, 7, 1};
    printf("%u\n", count_high(a, 4, 3));
    return 0;
}

主机运行输出

2

手推 网关收到 2、3、7、1,满足阈值 3 的元素有 2 个。编译器可以内联或折叠计算。

变式练习 分别执行 gcc -O0 -S main.c -o slow.s 和 gcc -O2 -S main.c -o fast.s,在 main 附近找计数循环或已经算出的结果。

41 存储期与链接:在 map 中找对象

对照已初始化可写对象、零初始化对象、只读对象和自动对象。实际段名与放置由目标工具链和链接脚本决定。

main.c

#include <stdio.h>

unsigned gain = 3;
unsigned cache[8];
const unsigned table[] = {5, 7};

int main(void)
{
    unsigned total = cache[0] + gain + table[1];
    printf("%u\n", total);
    return 0;
}

主机运行输出

10

手推 零初始化缓存的第 0 项为 0,gain 初值 3,table 第 1 项为 7,相加得到 10。

变式练习 执行 gcc -O0 main.c -Wl,-Map=lesson.map -o lesson,在 map 中查全局符号 gain、cache、table,再用调试器查看局部变量 total。

42 综合验收:分块解码与故障恢复

固定资源,逐字节处理。帧为 A5、单字节数据、校验字节(数据 XOR FF)。统计好帧和坏帧,只交付校验通过的数据。

main.c

#include <stdio.h>
#include <stdint.h>

enum Phase { SYNC, DATA, CHECK };
typedef struct {
    enum Phase phase;
    uint8_t pending, last;
    unsigned good, bad;
} Decoder;

static void decode(Decoder *d, const uint8_t *bytes, size_t n)
{
    for (size_t i = 0; i < n; ++i) {
        uint8_t byte = bytes[i];
        switch (d->phase) {
        case SYNC:
            if (byte == 0xA5) d->phase = DATA;
            break;
        case DATA:
            d->pending = byte;
            d->phase = CHECK;
            break;
        case CHECK: {
            uint8_t expected = (uint8_t)(d->pending ^ 0xFFu);
            if (byte == expected) {
                ++d->good;
                d->last = d->pending;
            } else {
                ++d->bad;
            }
            d->phase = SYNC;
            break;
        }
        }
    }
}

int main(void)
{
    Decoder decoder = {0};
    uint8_t a[] = {0x00, 0xA5, 0x10};
    uint8_t b[] = {0xEF, 0xA5, 0x11, 0x00, 0xA5};
    uint8_t c[] = {0x2A, 0xD5};
    decode(&decoder, a, sizeof a);
    decode(&decoder, b, sizeof b);
    decode(&decoder, c, sizeof c);
    printf("good=%u bad=%u last=%u\n", decoder.good, decoder.bad, (unsigned)decoder.last);
    return 0;
}

主机运行输出

good=2 bad=1 last=42

手推 三批输入包含噪声、一个坏帧和两个好帧。第一帧跨批完成,坏帧丢弃后继续接收,末帧交付 42。

变式练习 把每个字节单独分批,结果应相同。再截掉最后一个校验字节,检查好帧数、坏帧数、上次有效值与当前状态。

阶段自测 尝试将第 28 题与第 42 题连接,覆盖正常帧、坏帧和队列满,再打开结课项目对照。

结课 · 从主机代码到 STM32

43 结课项目:STM32 串口中断接收与故障观察

沿着 USART2_IRQHandler → rx_push → rx_pop → decode 阅读。复用第 28 题的队列思想和第 42 题的校验协议。

板端使用 STM32F407 的独立 CMSIS 启动工程,保持复位时钟配置(HSI、PCLK1 均为 16 MHz)。将 board_main.c、rx.c、rx.h 加入工程,使用 STM32F407 对应的启动文件和链接脚本,确保只有一个 main 和 USART2_IRQHandler。主机入口 host_main.c 单独与 rx.c 编译。

用 3.3 V USB 转串口的 TX 接 PA3(USART2_RX,AF7),共地。串口设为 115200、8N1,以十六进制字节发送。板端只接收;在调试器中观察 decoder.good、decoder.bad、decoder.last、queue.peak、queue.dropped 和 uart_errors。

复位后发送 00 A5 2A D5 A5 01 00,然后暂停观察。预期 good=1、bad=1、last=42。队列峰值取决于实际时序。主机例程能确定性复现队列溢出和缺口恢复;uart_errors 记录外设错误事件,两种计数各有用途。

板端两份 C 实现已通过 Cortex-M4 目标编译,尚未在开发板实测。

芯片资料见 STM32F407 数据手册 与 RM0090 参考手册。

board_main.c

#include "stm32f407xx.h"
#include "rx.h"

static volatile RxQueue queue;
static volatile Decoder decoder;
static volatile unsigned uart_errors;

/* Standalone startup using reset clock settings: PCLK1 = 16 MHz. */
static void uart_init(void)
{
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
    (void)RCC->AHB1ENR;
    RCC->APB1ENR |= RCC_APB1ENR_USART2EN;
    (void)RCC->APB1ENR;
    GPIOA->MODER = (GPIOA->MODER & ~(3u << 6)) | (2u << 6);
    GPIOA->AFR[0] = (GPIOA->AFR[0] & ~(15u << 12)) | (7u << 12);
    GPIOA->PUPDR = (GPIOA->PUPDR & ~(3u << 6)) | (1u << 6);

    USART2->CR1 = 0;
    USART2->CR2 = 0;
    USART2->CR3 = 0;
    USART2->BRR = (16000000u + 115200u / 2u) / 115200u;
    USART2->CR1 = USART_CR1_UE | USART_CR1_RE | USART_CR1_RXNEIE;
    NVIC_EnableIRQ(USART2_IRQn);
}

void USART2_IRQHandler(void)
{
    uint32_t status = USART2->SR;
    const uint32_t errors = USART_SR_ORE | USART_SR_FE | USART_SR_NE | USART_SR_PE;
    if ((status & (errors | USART_SR_RXNE)) == 0u) return;
    uint8_t byte = (uint8_t)USART2->DR;
    if ((status & errors) != 0u) {
        ++uart_errors;
        queue.gap_pending = true;
        return;
    }
    rx_push(&queue, byte);
}

int main(void)
{
    uart_init();
    for (;;) {
        RxByte byte;
        uint32_t mask = __get_PRIMASK();
        __disable_irq();
        bool ready = rx_pop(&queue, &byte);
        __set_PRIMASK(mask);
        if (ready) decode(&decoder, byte);
    }
}

rx.h

#ifndef RX_PIPELINE_H
#define RX_PIPELINE_H

#include <stdbool.h>
#include <stdint.h>

enum { RX_SLOTS = 16 };
typedef struct {
    uint8_t value;
    bool gap_before;
} RxByte;

typedef struct {
    RxByte slots[RX_SLOTS];
    unsigned read, write, depth, peak, dropped;
    bool gap_pending;
} RxQueue;

typedef enum { WAIT_HEADER, WAIT_DATA, WAIT_CHECK } Phase;
typedef struct {
    Phase phase;
    uint8_t pending, last;
    unsigned good, bad, gaps;
} Decoder;

/* Queue operations require a single context or external exclusion. */
void rx_push(volatile RxQueue *q, uint8_t value);
bool rx_pop(volatile RxQueue *q, RxByte *out);
void decode(volatile Decoder *d, RxByte byte);

#endif

rx.c

#include "rx.h"

void rx_push(volatile RxQueue *q, uint8_t value)
{
    if (q->depth == RX_SLOTS) {
        ++q->dropped;
        q->gap_pending = true;
        return;
    }
    q->slots[q->write].value = value;
    q->slots[q->write].gap_before = q->gap_pending;
    q->gap_pending = false;
    q->write = (q->write + 1u) % RX_SLOTS;
    ++q->depth;
    if (q->depth > q->peak) q->peak = q->depth;
}

bool rx_pop(volatile RxQueue *q, RxByte *out)
{
    if (q->depth == 0) return false;
    *out = q->slots[q->read];
    q->read = (q->read + 1u) % RX_SLOTS;
    --q->depth;
    return true;
}

void decode(volatile Decoder *d, RxByte byte)
{
    if (byte.gap_before) {
        d->phase = WAIT_HEADER;
        ++d->gaps;
    }
    switch (d->phase) {
    case WAIT_HEADER:
        if (byte.value == 0xA5) d->phase = WAIT_DATA;
        break;
    case WAIT_DATA:
        d->pending = byte.value;
        d->phase = WAIT_CHECK;
        break;
    case WAIT_CHECK: {
        uint8_t check = (uint8_t)(d->pending ^ 0xFFu);
        if (byte.value == check) {
            d->last = d->pending;
            ++d->good;
        } else {
            ++d->bad;
        }
        d->phase = WAIT_HEADER;
        break;
    }
    }
}

host_main.c

#include "rx.h"
#include <stdio.h>

static void drain(RxQueue *queue, Decoder *decoder)
{
    RxByte byte;
    while (rx_pop(queue, &byte)) decode(decoder, byte);
}

int main(void)
{
    RxQueue queue = {0};
    Decoder decoder = {0};
    uint8_t input[] = {0, 0xA5, 0x2A, 0xD5, 0xA5, 1, 0};
    for (size_t i = 0; i < sizeof input; ++i) rx_push(&queue, input[i]);
    drain(&queue, &decoder);
    printf("good=%u bad=%u last=%u\n", decoder.good, decoder.bad, (unsigned)decoder.last);

    for (unsigned i = 0; i < RX_SLOTS - 1u; ++i) rx_push(&queue, 0);
    rx_push(&queue, 0xA5);
    rx_push(&queue, 0x11);  /* full, simulate a lost byte */
    drain(&queue, &decoder);
    rx_push(&queue, 0xA5);
    rx_push(&queue, 0x07);
    rx_push(&queue, 0xF8);
    drain(&queue, &decoder);
    printf("good=%u bad=%u last=%u peak=%u dropped=%u gaps=%u\n",
           decoder.good, decoder.bad, (unsigned)decoder.last,
           queue.peak, queue.dropped, decoder.gaps);
    return 0;
}

主机运行输出

good=1 bad=1 last=42
good=2 bad=1 last=7 peak=16 dropped=1 gaps=1

手推 主机先送一帧正确数据和一帧坏数据。第二轮故意让队列装满并丢掉一个字节,下次入队带上缺口标记,解码器从新帧头恢复。

变式练习 画出 ISR 与主循环各自访问的字段,解释为什么仅在出队时进入临界区。再尝试分批发送和错误校验字节。