メモリとI/O
導入済みこのレッスンの内容
| English | 意味 |
|---|---|
| memory-mapped I/O/ˈmeməri mæpt aɪ əʊ/ | メモリマップI/O |
| base address/beɪs əˈdres/ | The first address of a peripheral's block; each of its registers sits at a fixed offset from it. |
| offsets/ˈɒfsets/ | The distance in bytes from a base address to a particular register. |
| isolated I/O/ˈaɪsəleɪtɪd aɪ əʊ/ | A design with a separate address space for peripherals, reached only by special instructions such as IN and OUT. |
| GPIO/ˌdʒiː piː aɪ ˈəʊ/ | |
| read–modify–write/riːd ˈmɒdɪfaɪ raɪt/ | Reading a register, changing some of its bits and writing the whole value back. |
| bit mask/bɪt mæsk/ | A value with 1s only in the bit positions to be set, cleared, toggled or tested. |
| polling/ˈpəʊlɪŋ/ | ポーリング |
Buttons, LEDs and sensors as memory
- A sensor node's button, LED and temperature sensor all sit outside the CPU. The CPU talks to every one of them by reading and writing addresses, exactly as it reads and writes variables.
- Done well, the firmware is a clean table of names; done badly, a pile of magic numbers. This lesson shows the clean way, in C.
Memory-mapped I/O
- With memory-mapped I/O 内存映射输入输出, each peripheral register appears at an address. A load from a data register receives a value; a store to a control register sends a command.
- The address space is split into regions: program in flash, variables in SRAM, and the peripherals above them. Each peripheral gets a base address 基地址, and its registers sit at fixed offsets 偏移量 from it.

- The other design: x86 PCs also have isolated I/O 独立编址: a separate port space reached only by special instructions (
IN,OUT). Memory-mapped I/O needs no special instructions, so plain C can drive the hardware.
With memory-mapped I/O, the CPU uses ordinary load and store instructions to talk to a peripheral.
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
The peripheral's registers sit at addresses, so a read or write to that address reaches the hardware instead of RAM.
Reaching a register from C
- As in lesson 8.2, a register is an address, so the driver turns the address into a
volatilepointer and reads or writes through it:
#define GPIO_BASE 0x40000000u
#define GPIO_DIR (*(volatile uint32_t *)(GPIO_BASE + 0x00))
#define GPIO_DATA (*(volatile uint32_t *)(GPIO_BASE + 0x04))
GPIO_DIR = 0x01; /* pin 0 becomes an output */
uint32_t pins = GPIO_DATA; /* read every pin's level */
volatiletells the compiler that the value can change, or that the write matters, even though the program cannot see why. Without it, the compiler may keep a status value in a register and never read the hardware again, or drop a write it thinks is useless.
A polling loop while (!(ADC_STATUS & 1u)) { } never ends, although the scope shows DONE going high. The most likely cause:
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
Without volatile the optimiser may load the register once and loop on the stale copy. volatile forces a real read on every lap.
The GPIO port
- A GPIO 通用输入输出 port has a direction register (one bit per pin: 1 = output, 0 = input) and a data register (the pins' levels).
- Set the direction once at start-up, then read or write the data register as often as needed.

A pin stays an input no matter what you write to its data register. The likely cause is
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
The direction register decides which way the pin works; the data register only carries the level. Set the direction first.
One pin at a time: masks on the GPIO port
- One data register holds 32 pins, so a write must change only the pin you mean. Use the read–modify–write idea from lesson 8.2 with a bit mask 位掩码 that has a 1 in that pin's place,
(1u << n):
| Goal | C | What it does |
|---|---|---|
| Set bit 3 (LED on) | GPIO_DATA |= (1u << 3); |
OR forces bit 3 to 1 |
| Clear bit 3 (LED off) | GPIO_DATA &= ~(1u << 3); |
AND with 0 forces bit 3 to 0 |
| Toggle bit 3 | GPIO_DATA ^= (1u << 3); |
XOR flips bit 3 |
| Test bit 5 (button) | if (GPIO_DATA & (1u << 5)) |
non-zero if pin 5 is high |
- Each of the first three is a read–modify–write 读-改-写. Writing
GPIO_DATA = (1u << 3);instead would switch every other output pin off.
- DATA reads
0x0000_0025(binary ...0010 0101). Turn on the LED on pin 3. - Mask:
1u << 3=0x08. OR:0x25 | 0x08 = 0x2D. Pins 0, 2 and 5 keep their levels; pin 3 is now high.
GPIO_DATA reads 0x2D. After GPIO_DATA &= ~(1u << 0); it reads:
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
~(1u << 0) has every bit 1 except bit 0. AND keeps the other bits and clears bit 0: 0x2D becomes 0x2C.
With pins 0, 2 and 5 high, GPIO_DATA = (1u << 3); turns on pin 3 and leaves the others as they were.
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
Plain = writes the whole register: only pin 3 stays high and pins 0, 2 and 5 go low. Use |= to change one bit.
Polling, with a timeout
- Polling 轮询 waits for a peripheral by reading its status bit in a loop until the "done" bit is set. A good loop also counts, so that a dead sensor cannot hang the product:
ADC_CTRL = 1u; /* START a conversion */
uint32_t n = 100000u; /* timeout, in loop laps */
while (!(ADC_STATUS & 1u) && --n) { } /* wait for DONE (bit 0) */
if (n == 0) report_fault(); /* gave up: sensor is dead */
else value = ADC_RESULT & 0xFFFu; /* keep the 12 result bits */
- It is simple, but every lap is CPU time spent asking. Waiting $T$ seconds costs $T \times f_{\text{clock}}$ cycles.
A 4-cycle polling loop at 84 MHz waits 1 ms. How many CPU cycles does it use?
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
$84 \times 10^{6} \div 4 = 21 \times 10^{6}$ laps a second; 1 ms is 21 000 laps × 4 cycles = 84 000 cycles, all of that millisecond.
Worked example: the cost of asking
- Laps per second: at 84 MHz with a 4-cycle loop, the CPU runs $84 \times 10^6/4 = 21$ million laps a second.
- A 1 ms wait: $21 \times 10^6 \times 10^{-3} = 21\,000$ laps, or 84 000 cycles.
- The timeout above: 100 000 laps is $100\,000/21 \times 10^6 = 4.8$ ms, a safe limit for a conversion that takes 1 ms.
- During the wait the CPU does nothing useful: 100% busy, 0% work. Interrupts, in the next lesson, remove that cost.
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.
The same 4-cycle loop at 84 MHz waits 250 µs for a sensor. How many laps does it run?
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
21 million laps a second × 250 µs = 5250 laps.
At 84 MHz with a 4-cycle loop, how many laps give a 2 ms timeout?
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
21 million laps a second, so $21 \times 10^6 \times 0.002 = 42\,000$ laps.
Worked example: the node's map
- GPIO at
0x4000_0000, UART at0x4001_0000, timer at0x4002_0000, ADC at0x4003_0000. Each driver uses its base plus named offsets, often as astructlaid over the registers:
typedef struct { volatile uint32_t CTRL, STATUS, RESULT; } adc_regs;
#define ADC ((adc_regs *)0x40030000u)
ADC->CTRL = 1u; /* CTRL at +0x00, STATUS at +0x04, RESULT at +0x08 */
- A typo such as
0x4001_0004for the UART base shifts every register by four bytes. Reading back each peripheral's ID register after start-up catches it at once.
The UART's base is 0x4001_0000 and its status register sits at offset 0x04. A driver that wrongly uses 0x4001_0004 as the base reads "status" from
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
Every register shifts by four bytes, so the status read lands at 0x4001_0008, a different register. An ID read-back at start-up catches it.
Four common slips
- Forgetting the direction register. The pin stays an input, and writes to it do nothing.
- Leaving out
volatile. The optimiser reads a status register once, and the polling loop never ends. - Writing
=where you meant|=. One LED goes on and every other output goes off. - Polling without a timeout. A dead sensor then hangs the whole product.
The one safeguard every polling loop must carry is
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
A timeout bounds the wait, so a dead sensor returns an error instead of hanging the product. The watchdog is the outer safety net, not the loop guard.
Match each register to its job.
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
A driver is mostly these registers at a base address plus named offsets.
Recap
- Peripherals are memory: a base address plus named offsets, reached through
volatilepointers.
| Peripheral | Base address |
|---|---|
| GPIO | 0x4000_0000 |
| UART | 0x4001_0000 |
| Timer | 0x4002_0000 |
| ADC | 0x4003_0000 |
- Bits: set with
|= mask, clear with&= ~mask, toggle with^= mask, test with& mask. - GPIO: set the direction once, then read or write the data. Poll with a timeout, and prove the map with a read-back of each ID register.
何が問題でしたか?この内容はサイトの運営チームだけが確認します。