Catto / Topic Map · Digital Electronics II Year 5
Digital Electronics II · 96 h · Topic 4 of 4

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.

Microcontrollers CPU Buses Memories Instruction cycle

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.

The stored-program idea

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 logicProcessor
How it is changedBy redesigning the circuitBy rewriting the program
SpeedMaximum: everything happens in parallelLower: operations are performed one at a time
Cost per unitGrows with complexityAlmost constant: the same chip does a lot or a little
Development timeLong for complex functionsShort, and you test without soldering
Where it winsSimple, very fast functions, glue logicEverything 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.

ALU · Arithmetic logic unit

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.

Registers

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.

Program counter (PC)

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.

Instruction register and decoder

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.

The three buses
  • 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.

Memory $0002 MOV A,#5 $0003 ADD A,B $0004 OUT P1 $0005 JMP $02 CPU PC $0002 $0003 $0004 $0005 IR instruction Decoder control unit ALU add, compare Registers A · B · flags address data address instruction control result 1 · the PC puts the address on the bus 2 · memory returns the instruction to the IR 3 · the decoder interprets it 4 · the ALU executes and the PC advances
Figure 1. The instruction cycle, animated. The PC puts the address on the bus, the memory returns the instruction, the decoder interprets it and the ALU executes it; at the end the PC advances to the next one. A processor never does anything else.
PhaseWhat happensWho does the work
1 · FetchThe PC puts its value on the address bus and the read is activated.PC, address bus, memory
2 · ReceiveThe memory returns the instruction code and it is stored in the IR.Memory, data bus, IR
3 · DecodeThe control unit interprets the code and prepares the internal signals.Decoder
4 · ExecuteThe operation is carried out: a calculation in the ALU, a memory read, a change on a port.ALU, registers, peripherals
5 · AdvanceThe PC is incremented (or loaded with the jump address) and the cycle starts over.PC
Worked example · How long it takes to turn on an LED

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.

A clock cycle is not an instruction cycle

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.

Von Neumann CPU Memory instructions and data together single bus instr data Instructions and data take turns: the bus is the bottleneck General-purpose computers Harvard CPU Program Flash Data SRAM instr data Both travel at the same time: it fetches the next one while executing this one PIC · AVR · almost all microcontrollers
Figure 2. The two architectures, animated. In Von Neumann, instructions and data share the bus: they have to take turns, and that turn-taking is the bottleneck. In Harvard each has its own bus and they travel at the same time.
Von Neumann
  • 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.
Harvard
  • 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

TypeVolatileRewritableWhat it is used for
SRAMYesUnlimitedProgram variables and the stack. Fast, expensive, takes up space: that is why a small micro has 2 KiB.
DRAMYesUnlimitedMain memory of a computer. Needs constant refreshing.
Mask ROMNoNeverProgrammed at the factory. Only for huge production runs.
EPROM (UVPROM)NoErased with UV lightHistorical: the little quartz window. It took about 20 minutes under the lamp to erase.
EEPROMNoByte by byte, ~106 timesStoring the configuration, the serial number, the last setpoint.
FlashNoBy blocks, ~104–105The program. It is what gets written when you “burn” the micro.
FRAMNoPractically unlimitedContinuous data logging without wear. More expensive.
EEPROM wears out

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.

a single package CPUALU · registerscontrol unit Flashthe program2 to 512 KiB SRAMvariables and stack128 B to 64 KiB EEPROMconfigurationthat survives power loss Timersand PWMcount without the CPU A/D converter10 or 12 bitsmultiplexed I/O portseach pin: input,output or peripheral CommunicationsUSART · SPI · I²Cand watchdog A microprocessor has only the green block: everything else goes outside, on the circuit board
Figure 3. What a microcontroller has built in. The orange blocks —the peripherals— are what allow a chip costing a few dollars to replace an entire circuit board, and the ones studied one by one in Year 6.
MicroprocessorMicrocontroller
MemoryExternal, in separate chipsInternal: Flash, SRAM and EEPROM
PeripheralsExternalIntegrated: A/D, timers, ports, communications
Computing powerHigh: GHz, 32 and 64 bitsModest: MHz, 8 to 32 bits
Power consumptionWattsMilliwatts, and microamperes when sleeping
StartupOperating system, secondsRuns the program in microseconds
Typical useComputers, servers, cell phonesAppliances, cars, instruments, control
System costHighVery low: the chip and little else
Families you will see in the workshop
  • 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.
The datasheet is the tool, not the tutorial

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

Lab 1 · Seeing the clock

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.

Lab 2 · The buses, with LEDs

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.

Lab 3 · Library versus register

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.

Lab 4 · Power consumption

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

SymptomUsual cause
The micro does not startThe 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 oftenThe 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 boardReal-world timing: pushbutton bounce, wiring capacitances, or a delay calculated with the wrong clock.
Variables get corrupted for no reasonStack overflow: SRAM is small and a large array or a recursion eats all of it.
An A/D reading is always lowSource impedance too high for the sample & hold. See A/D converters.
The equipment fails months after installationRepeated writes to EEPROM: the cycles of a cell have been used up.
The pin does not drive the relayA 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.

Development of the topic “Microprocessor and microcontroller architecture” of Digital Electronics II (Year 5), based on the “Curriculum Proposal – Second Cycle of the Technical-Vocational Track, Secondary Education – Electronics,” Ministry of Education of the Province of Córdoba, DGETyFP. Back to the Topic Map · catto.ar