Встраиваемый C и ассемблер
ВведеноВ этом уроке
| English | Значение |
|---|---|
| memory-mapped register/ˈmeməri mæpt ˈredʒɪstə/ | Регистр с адресацией памяти |
| assembly/əˈsemblɪ/ | ассемблер |
Nothing between code and transistor
- A sensor node's firmware is a few thousand lines of C that write hardware registers directly. There is no operating system in between.
- So every line must map onto the machine exactly. This lesson shows how one C line becomes instructions and bus transfers.
Registers are addresses
- A memory-mapped register 存储器映射寄存器 is a hardware control word that lives at a fixed address. C reaches it through a pointer to that address.
- The pointed-to register must be
volatile: it tells the compiler the value can change outside the program, so every read and write must really happen.
Почему указатель на регистр статуса оборудования должен иметь модификатор volatile?
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Без volatile компилятор может считать значение один раз и использовать его повторно, поэтому цикл ожидания флага статуса может выполняться бесконечно.
From C to assembly
- The compiler turns C into loads, stores, arithmetic and branches. Assembly 汇编 is that same program written one machine instruction per line.
- Reading the assembly is how you check what the hardware will actually do.

Каждая строка ассемблера соответствует одной машинной инструкции.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Именно это делает ассемблер полезным для проверки вывода компилятора; одна строка C часто преобразуется в несколько инструкций.
Read-modify-write
- A normal word write replaces the whole register. In this plain read/write example, the CPU loads the word, changes selected bits locally and stores it back.
*GPIO_OUT |= (1u << 5);sets bit 5 and leaves the others unchanged.*GPIO_OUT = 0x20;would clear every other pin.
Какая строка устанавливает бит 5 GPIO_OUT, не изменяя остальные биты?
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
OR с маской устанавливает выбранный бит и сохраняет остальные. Присваивание обнуляет остальные; AND с маской обнуляет всё, кроме бита 5.
Worked example: masks in hex
- Toggle bits 5 and 6 and clear bit 3 in one step:
(*GPIO_OUT & ~0x08) ^ 0x60. - From
0xCE:0xCE & ~0x08 = 0xC6, then0xC6 ^ 0x60 = 0xA6. Bit 3 went from 1 to 0; bits 6 and 5 went from 1, 0 to 0, 1.
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.
GPIO_OUT содержит 0xCE. После операции (0xCE & ~0x08) ^ 0x60 он содержит
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
0xCE & ~0x08 = 0xC6 обнуляет бит 3; 0xC6 ^ 0x60 = 0xA6 инвертирует биты 6 и 5.
Регистр содержит 0xFF. Каково его значение в десятичной системе после reg &= ~(1u << 7)?
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
Сброс бита 7 в 0xFF даёт 0x7F = 127.
Worked example: when does a counter wrap?
count = count + 1in a loop: an unsigned 32-bit counter starting at zero wraps after $2^{32} = 4\,294\,967\,296$ steps.- At 84 MHz, assuming four clock cycles per iteration, that takes $\dfrac{2^{32} \times 4}{84 \times 10^{6}} \approx 204\,\text{s}$. Arithmetic beats waiting with a stopwatch.
16-битный счётчик увеличивается на единицу каждую микросекунду. Через сколько миллисекунд он переполнится? Укажите 3 знака после запятой.
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
$2^{16} = 65\,536$ отсчётов по 1 мкс составляют 65.536 мс.
Three common slips
- Dropping
volatile. The compiler may keep the value in a CPU register and never read the hardware again. - Plain assignment for one bit.
= 0x20clears every other bit; use|=,&= ~or^=. - Assuming write order. When the hardware needs two writes in sequence, add a barrier or a read-back.
Соотнесите каждую операцию с тем, что она делает с битом k.
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
Эти четыре идиомы охватывают почти все операции с регистрами в драйвере.
Recap
- Registers are addresses, reached through
volatilepointers. - In this plain word-register model, changing a bit is load, mask, store: read-modify-write. Some peripherals also provide atomic set/clear registers.
| Bit 5 | Code |
|---|---|
| Set | *R |= 1u << 5; |
| Clear | *R &= ~(1u << 5); |
| Toggle | *R ^= 1u << 5; |
-
All three leave the other bits alone;
*R = 0x20;would clear them. -
Check masks in hex on paper before trusting the hardware.
Что пошло не так? Это увидит только команда сайта.