Memória e E/S
Introduzido
7:37
Microprocessadores e Sistemas Embarcados
The digital logic course built gates and flip-flops; this course builds the machine that runs programs. Embedded work is verified from three directions.…
Narração em inglês · legendas em inglês e 中文 que você pode alternar
Nesta aula
| English | Significado |
|---|---|
| firmware/ˈfɜːmweə/ | Software stored in a device to control its hardware and basic operation. |
| memory-mapped I/O/ˈmeməri mæpt aɪ əʊ/ | E/S mapeado em memória |
| register/ˈredʒɪstə/ | A group of storage elements holding a binary word, often loading its bits together on a clock event. |
| 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ɪŋ/ | sondagem |
| Interrupts/ˈɪntərʌpts/ |
Botões, LEDs e sensores como memória
- Os botões, LED e sensor de temperatura de um nó sensor estão fora da CPU. A CPU comunica-se com cada um deles lendo e escrevendo endereços.
- Bem feito, o firmware é uma tabela limpa de nomes; mal feito, um amontoado de números mágicos. Esta lição mostra o modo correto.
E/S mapeada em memória
- Com E/S mapeada em memória, cada registro periférico aparece em um endereço. Ler um registro de dados recebe um valor; escrever envia-o.
- Cada periférico tem um endereço base, e seus registros ficam em offsets nomeados a partir dele.

With memory-mapped I/O, the CPU uses ordinary load and store instructions to talk to a peripheral.
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
The peripheral's registers sit at addresses, so a read or write to that address reaches the hardware instead of RAM.
Porta GPIO
- Uma porta GPIO possui um registro de direção (um bit por pino: entrada ou saída) e um registro de dados (o nível do pino).
- Defina a direção uma vez na inicialização, depois leia ou escreva o registro de dados tantas vezes quanto necessário.

A polling loop while (!(ADC_STATUS & 1u)) { } never ends, although the scope shows DONE going high. The most likely cause:
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
Without volatile the optimiser may load the register once and loop on the stale copy. volatile forces a real read on every lap.
Polling
- Polling aguarda um periférico lendo seu bit de status em loop até que o bit "concluído" seja definido.
- É simples, mas cada volta do loop consome tempo de CPU para perguntar. Aguardar $T$ segundos custa $T \times f_{\text{clock}}$ ciclos.

A pin stays an input no matter what you write to its data register. The likely cause is
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
The direction register decides which way the pin works; the data register only carries the level. Set the direction first.
Exemplo resolvido: o custo de perguntar
- Em 84 MHz com um loop de 4 ciclo, a CPU executa 21 milhões de voltas por segundo. Um espera de 1 ms equivale a 21 000 voltas, ou 84 000 ciclos.
- Isso representa 100% da CPU durante todo o milissegundo, sem realizar trabalho útil. Interruptos, na próxima lição, eliminam esse custo.
GPIO_DATA reads 0x2D. After GPIO_DATA &= ~(1u << 0); it reads:
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
~(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.
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
Plain = writes the whole register: only pin 3 stays high and pins 0, 2 and 5 go low. Use |= to change one bit.
Exemplo resolvido: o mapa do nó
- GPIO em
0x4000_0000, UART em0x4001_0000, timer em0x4002_0000, ADC em0x4003_0000. Cada driver usa sua base mais offsets nomeados. - Um erro de digitação como
0x4001_0004para a base da UART desloca todos os registros em quatro bytes. Lendo novamente o registro ID de cada periférico após a inicialização, detecta-se o erro imediatamente.
A 4-cycle polling loop at 84 MHz waits 1 ms. How many CPU cycles does it use?
Dificuldade 2/5 · Moedas 140 + pequeno bônus na primeira conclusão hoje
$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.
Este cartão foi corrigido, por isso aparece em inglês até que a tradução seja atualizada.
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?
Dificuldade 2/5 · Moedas 140 + pequeno bônus na primeira conclusão hoje
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?
Dificuldade 2/5 · Moedas 140 + pequeno bônus na primeira conclusão hoje
21 million laps a second, so $21 \times 10^6 \times 0.002 = 42\,000$ laps.
Resumo
- Periféricos são memória: um endereço base mais offsets nomeados.
- GPIO: defina a direção uma vez, depois leia ou escreva os dados.
- Pesquise com um tempo limite e valide o mapa com uma verificação de leitura posterior.
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
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
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.
Este cartão é novo, por isso aparece em inglês até que a tradução esteja pronta.
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
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
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.
Dificuldade 2/5 · Moedas 140 + pequeno bônus na primeira conclusão hoje
A driver is mostly these registers at a base address plus named offsets.
Este cartão é novo, por isso aparece em inglês até que a tradução esteja pronta.
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.
O que deu errado? Somente a equipe do site vê isso.