Microprocessor and microcontroller architecture
Until now, changing what a digital circuit does meant changing the wires. A processor turns that around: the circuit stays fixed and what changes is the contents of a memory. That is the whole idea, and the last fifty years of electronics come out of it.
01From hardwired circuit to program
A ten-step sequencer built with counters and gates works perfectly. The problem shows up when the customer asks for step 4 to last twice as long, or for the sequence to change when a sensor is activated. With hardwired logic, that means redesigning the circuit board.
Instead of wiring gates for each function, you build a single machine able to execute a short repertoire of elementary operations —add, compare, move a piece of data, jump— and you store in a memory the list of operations to execute. Changing the behavior becomes changing that list. The hardware stays the same.
| Hardwired logic | Processor | |
|---|---|---|
| How it is changed | By redesigning the circuit | By rewriting the program |
| Speed | Maximum: everything happens in parallel | Lower: operations are performed one at a time |
| Cost per unit | Grows with complexity | Almost constant: the same chip does a lot or a little |
| Development time | Long for complex functions | Short, and you test without soldering |
| Where it wins | Simple, very fast functions, glue logic | Everything else |
Today hardwired logic survives in tasks where time is measured in nanoseconds or where safety independent of software is needed: a safety interlock, the protection of a power supply, the startup logic. Everything else is done by a two-dollar microcontroller.
02The blocks inside
Every CPU, from the 6502 to the processor in a laptop, has the same five elements. The size and the quantity change, not the function.
It is the only block that does the math: add, subtract, AND, OR, XOR, shifts. Its inputs come from the registers; its output goes back to a register. It also generates the flags: zero, carry, negative, overflow. Inside there is nothing you have not already seen in combinational logic: a ripple-carry or carry-lookahead adder and a few multiplexers.
Internal memory with immediate access, one word each. The accumulator is the one that takes part in almost every operation; the general-purpose registers hold intermediate values; the status registers hold the flags. They are the flip-flops of sequential logic, grouped in eights or sixteens.
A binary counter that holds the address of the next instruction. It increments
by itself; jumps and subroutine calls are nothing more than loading it with a different value. All
the flow control of a program —an if, a while, a function— boils down
to that.
The IR holds the binary code that has just been read and the decoder translates it into control signals: open this bus, enable that register, tell the ALU to add. It is a state machine: the control unit.
- Address bus: unidirectional, leaves the CPU. Its width sets how much memory can be addressed: 16 lines → 216 = 64 KiB; 20 lines → 1 MiB.
- Data bus: bidirectional. Its width is the word size: 8, 16, 32 bits.
- Control bus: read/write, clock, reset, interrupts, wait.
03The instruction cycle
It is the only thing a processor does, millions of times per second, from the moment it is switched on until it is switched off: fetch, decode, execute. Understanding it well makes everything else transparent.
| Phase | What happens | Who does the work |
|---|---|---|
| 1 · Fetch | The PC puts its value on the address bus and the read is activated. | PC, address bus, memory |
| 2 · Receive | The memory returns the instruction code and it is stored in the IR. | Memory, data bus, IR |
| 3 · Decode | The control unit interprets the code and prepares the internal signals. | Decoder |
| 4 · Execute | The operation is carried out: a calculation in the ALU, a memory read, a change on a port. | ALU, registers, peripherals |
| 5 · Advance | The PC is incremented (or loaded with the jump address) and the cycle starts over. | PC |
On an 8-bit microcontroller at 16 MHz, with an instruction cycle of one clock cycle:
- Each instruction takes 1/16 MHz = 62.5 ns.
- Setting a pin high is one instruction: 62.5 ns.
- The typical “turn on, wait, turn off, wait” loop with a 500 ms delay executes about 8 million instructions for each blink, almost all of them doing nothing.
That is why the first optimization of any embedded program is not to wait doing nothing: that is what timers and interrupts are for, which are covered in Year 6.
They are different things and they get mixed up all the time. A classic PIC divides the clock by four: with a 20 MHz crystal it executes 5 million instructions per second, not twenty. An AVR executes most instructions in a single cycle, and that is why at 16 MHz it outperforms a PIC at 20. The figure to look for in the datasheet is MIPS, not the crystal frequency.
04Von Neumann and Harvard
The difference lies in how many paths there are between the CPU and the memory, and it has a direct practical consequence on speed.
- A single memory and a single bus for instructions and data.
- Simpler and cheaper; the program can be treated as data (which is why a PC can compile and run what it compiled).
- The CPU cannot read an instruction and a piece of data at the same time.
- It is the architecture of general-purpose computers and of many ARM Cortex-M parts.
- Separate program memory and data memory, each with its own bus.
- Fetch and execution overlap: more speed with the same clock.
- The buses can have different widths: in a PIC, 14 bits for instructions and 8 for data.
- The program cannot easily modify itself, which is also a security advantage.
- It is the architecture of the PIC, the AVR and almost all microcontrollers.
05Memories and the memory map
| Type | Volatile | Rewritable | What it is used for |
|---|---|---|---|
| SRAM | Yes | Unlimited | Program variables and the stack. Fast, expensive, takes up space: that is why a small micro has 2 KiB. |
| DRAM | Yes | Unlimited | Main memory of a computer. Needs constant refreshing. |
| Mask ROM | No | Never | Programmed at the factory. Only for huge production runs. |
| EPROM (UVPROM) | No | Erased with UV light | Historical: the little quartz window. It took about 20 minutes under the lamp to erase. |
| EEPROM | No | Byte by byte, ~106 times | Storing the configuration, the serial number, the last setpoint. |
| Flash | No | By blocks, ~104–105 | The program. It is what gets written when you “burn” the micro. |
| FRAM | No | Practically unlimited | Continuous data logging without wear. More expensive. |
It is specified in write cycles, not in years. A program that saves a variable to EEPROM inside the main loop, a hundred times per second, uses up the 100,000 cycles of that cell in less than twenty minutes. Write only when the value has changed, and if you need to log continuously, rotate among several locations. It is a classic mistake and the equipment only fails months later, once it is already installed.
The memory map is the table that says what is at each address: a stretch of RAM, one of Flash, and —the most distinctive part of microcontrollers— the peripheral registers, which are read and written as if they were memory locations. Turning on an LED means writing a 1 to a bit at a specific address. That is what any library function does underneath.
// Both lines do the same thing on an AVR: set bit 5 of port B
digitalWrite(13, HIGH); // library: convenient, a few microseconds
PORTB |= (1 << PB5); // direct register access: 62.5 ns
The second form is the one used when timing matters. It requires reading the datasheet, which is precisely the skill developed in Year 6.
06Microprocessor and microcontroller
A microprocessor is a CPU and nothing more: it needs external memory, controllers and a circuit board around it. A microcontroller is an entire computer on a chip: CPU, memory, clock and peripherals.
| Microprocessor | Microcontroller | |
|---|---|---|
| Memory | External, in separate chips | Internal: Flash, SRAM and EEPROM |
| Peripherals | External | Integrated: A/D, timers, ports, communications |
| Computing power | High: GHz, 32 and 64 bits | Modest: MHz, 8 to 32 bits |
| Power consumption | Watts | Milliwatts, and microamperes when sleeping |
| Startup | Operating system, seconds | Runs the program in microseconds |
| Typical use | Computers, servers, cell phones | Appliances, cars, instruments, control |
| System cost | High | Very low: the chip and little else |
- PIC (Microchip): Harvard, widely used in Argentine industry, a huge number of models. It is the one covered in Digital Electronics III.
- AVR (Microchip/Atmel): the one in the Arduino UNO. One cycle per instruction and free tools.
- ARM Cortex-M (STM32, RP2040, ESP32 with its own core): 32 bits, a lot of power for little money, the current industry standard.
- ESP32: adds WiFi and Bluetooth on the same chip; it is what makes any connected project possible.
A microcontroller is learned by reading its datasheet and its reference manual: that is where the memory map, the registers of each peripheral and the timings are. Examples from the internet solve one case; the datasheet solves them all. Learning to read it is part of the trade, and it is practiced with C, the language in which almost all those examples are written —which was already covered in basic elements of the C language.
07In the lab
With a working microcontroller, measure the crystal frequency with the oscilloscope and compare it with what the circuit says. Then write a program that toggles a pin as fast as possible and measure the frequency of that signal: from it you get how many cycles the loop takes. It is the direct way to verify that the CPU executes one instruction at a time and how long each one takes.
On a system with external memory (or with a simulator), connect LEDs to the low lines of the address bus and run a very slow program. You can see the PC's binary count advancing: it is Figure 1 on the bench.
Write the same blink in two ways: with the library function and by writing the port register directly. Measure with the oscilloscope the maximum frequency achievable in each case and note the difference. It is usually twenty to fifty times.
Measure the microcontroller's current with the program running, and then with the micro in a low-power mode waiting for an interrupt. It goes from tens of milliamperes to a few microamperes. It is the reason a battery-powered sensor lasts for years.
08Common mistakes
| Symptom | Usual cause |
|---|---|
| The micro does not start | The 100 nF capacitor next to the supply pin is missing, the reset pin was left floating, or the fuses are configured for a clock that does not exist on the board. |
| It resets by itself every so often | The watchdog is enabled and the program does not refresh it, or there are voltage dips from a poorly decoupled inductive load. |
| The program works in the simulator but not on the board | Real-world timing: pushbutton bounce, wiring capacitances, or a delay calculated with the wrong clock. |
| Variables get corrupted for no reason | Stack overflow: SRAM is small and a large array or a recursion eats all of it. |
| An A/D reading is always low | Source impedance too high for the sample & hold. See A/D converters. |
| The equipment fails months after installation | Repeated writes to EEPROM: the cycles of a cell have been used up. |
| The pin does not drive the relay | A pin delivers 20 mA at most. Anything that draws more goes through a transistor, and with a flyback diode if it is inductive: transistor as a switch. |
| “It has spare memory but won't compile” | Flash and SRAM are being confused. Text strings live in Flash, but many libraries copy them to SRAM at startup. |
09Self-assessment
How much memory can a 16-line address bus address?
216 = 65,536 locations, that is, 64 KiB. With 20 lines it would be 1 MiB and with 32, 4 GiB.
What does the program counter hold and what happens on a jump?
The address of the next instruction. Normally it increments by itself; a jump is simply loading it with another value, and a subroutine call is saving the current value on the stack before loading it, so that execution can return.
A PIC with a 20 MHz crystal that divides the clock by four: how many instructions per second does it execute?
20 MHz / 4 = 5 MIPS, and each instruction takes 200 ns. A 16 MHz AVR with one cycle per instruction executes 16 MIPS: faster with a slower crystal.
What is the concrete advantage of the Harvard architecture?
That it can fetch the next instruction while executing the current one, because instructions and data travel on separate buses. In addition, each bus can have the width that suits it best.
Why is it a bad idea to store a counter in EEPROM inside the main loop?
Because EEPROM withstands a limited number of writes per cell (105 to 106). Writing a hundred times per second wears it out in minutes. Save only when the value changes, or rotate among several locations.
What is the difference between Flash, SRAM and EEPROM in a microcontroller?
Flash: the program, non-volatile, written in blocks. SRAM: the variables while it runs, volatile, erased when the power is cut. EEPROM: data that must survive a power loss —configuration, calibration—, writable byte by byte.
What are the ALU flags and what are they for?
Status bits that the ALU leaves after each operation: zero, carry, negative,
overflow. Conditional jump instructions check them, so they are the bridge between
arithmetic and the if of a program.
When is hardwired logic preferable to a microcontroller?
When the response has to be in nanoseconds, when the function is so simple that a single gate solves it, and above all when safety cannot depend on a program running: an interlock or a protection is hardwired.
Why is writing a port register directly much faster than using the library function?
Because the function checks the pin number, looks up in a table which port and bit it corresponds to and only then writes: that is dozens of instructions. The direct write is one.
An output pin has to drive a 500 mA motor. How is it connected?
Never directly: a pin delivers about 20 mA. It goes through a transistor or a MOSFET as a switch, with its base resistor, the flyback diode across the inductor and, if isolation is advisable, an optocoupler. The motor's power supply must be independent of the micro's.