Microprocessors and Microcontrollers

Chapter 6
Microcontroller Architecture and Platforms

Diploma in Computer Architecture and Networking
Microprocessors and Microcontrollers   •   Diploma

Microcontroller Architecture and Platforms

Introduction

A microcontroller is a complete small-scale computer integrated into a single semiconductor device. Unlike a general-purpose microprocessor, which commonly depends on external memory and peripheral chips, a microcontroller usually contains a processor core, program memory, data memory, clock circuitry, reset logic, input/output ports, timers, communication interfaces and analog functions. This integration makes microcontrollers suitable for embedded systems such as appliances, industrial controllers, access systems, instruments, vehicles and networking equipment.

Microcontroller architecture is best understood as the relationship between the CPU core, memory system, clock and reset circuits, GPIO, and integrated peripherals. The programmer sees registers, instructions and interrupts; the hardware designer must also understand buses, electrical characteristics, timing, power and reset behaviour. This chapter compares representative 8-bit AVR and PIC devices with 32-bit ARM Cortex-M devices. The term “PIC” covers several families, so exact registers and features vary by device. Similarly, AVR devices differ between classic AVR, tinyAVR and newer AVR Dx families.

Learning Objectives

After studying this chapter, a student should be able to:

  1. Explain the principal blocks of a microcontroller and their interactions.
  2. Compare 8-bit AVR, PIC and 32-bit ARM Cortex-M architectures.
  3. Describe GPIO operation, configuration and electrical limitations.
  4. Distinguish program memory, data memory, non-volatile data memory and memory-mapped peripherals.
  5. Explain clock generation, timer operation, reset sources and watchdog protection.
  6. Select suitable integrated peripherals for a practical embedded application.
  7. Apply safe initialization, interrupt and low-power design practices.

1. The Microcontroller as an Embedded System Platform

A microcontroller executes a stored program while responding to physical events. A typical signal path is:

sensor or switch → GPIO or analog input → CPU/peripheral processing → actuator or communication output

The CPU may execute instructions directly, while peripherals perform repetitive or time-critical tasks independently. For example, a timer can generate a periodic interrupt, a UART can shift serial bits, and an ADC can convert a sensor voltage without requiring the CPU to control every electrical transition.

A useful architectural distinction is between the Harvard architecture and the von Neumann architecture. In a Harvard architecture, program instructions and data use separate memory paths. Many AVR and PIC devices use forms of Harvard organization, although modern implementations may add mechanisms for reading program memory as data. ARM Cortex-M processors generally present a unified memory map to software, while the internal bus structure may still use separate instruction and data paths for performance.

The principal blocks are:

  • CPU core: arithmetic logic unit, registers, control unit, instruction decoder and program counter.
  • Program memory: normally Flash or other non-volatile memory.
  • Data memory: SRAM for variables, stack and temporary data.
  • Non-volatile data memory: EEPROM or Flash emulation in devices that provide it.
  • GPIO: configurable digital input and output pins.
  • Clock system: oscillator, prescalers, clock multiplexer and sometimes a phase-locked loop.
  • Reset system: power-on, brown-out, external, watchdog and software reset sources.
  • Peripherals: timers, PWM, ADC, DAC, comparators, serial interfaces and interrupt controllers.
  • Power-management unit: sleep modes, clock gating and voltage monitoring.
Microcontroller architecture block diagram CPU CoreALU • registerscontrol • interruptsbus interface Flash / program memorySRAM / data memoryGPIOTimers and serial I/OClock and reset
Microcontroller architecture block diagram
Figure: Microcontroller architecture block diagram

Figure: Functional relationship between the CPU core, memory, clock/reset circuits and integrated peripherals.

2. CPU Cores and Instruction Organization

The CPU core determines the instruction set, register model, addressing methods, interrupt behaviour and maximum computational capability. Word size is an important descriptor but not a complete measure of performance. An 8-bit CPU normally processes 8-bit arithmetic efficiently; a 32-bit CPU normally has 32-bit registers and arithmetic paths. Performance also depends on clock frequency, instruction timing, memory wait states, compiler quality and peripheral integration.

2.1 AVR

Classic AVR is an 8-bit RISC architecture with a relatively large register file. It provides 32 general-purpose 8-bit registers, several of which support efficient pointer addressing. Many instructions execute in a single clock cycle, although instruction length and timing vary. Program memory is commonly Flash, while SRAM holds variables and the stack. EEPROM is available on many classic devices for non-volatile data.

AVR’s register-oriented design makes operations such as loading, adding and storing relatively transparent. However, the 8-bit data path means that a 16-bit or 32-bit calculation requires multiple instructions. AVR devices commonly use memory-mapped or I/O-mapped control registers depending on the family and register location.

2.2 PIC

PIC microcontrollers include several architectural families. Baseline and mid-range devices traditionally use an 8-bit core with banked registers and a small instruction set. Enhanced mid-range devices improve addressing and instruction capability. PIC18 devices provide a more capable 8-bit architecture, while dsPIC devices combine a 16-bit CPU with digital-signal-processing features.

A central design issue in many PIC devices is bank selection. Control and data registers may be distributed across banks, so software must select the correct bank before accessing a register. Modern devices often reduce this burden with linear addressing or more flexible register layouts. PIC peripherals are frequently highly integrated and may include configurable logic cells, multiple capture/compare/PWM channels and sophisticated clock systems.

2.3 ARM Cortex-M

ARM Cortex-M is a 32-bit RISC processor family intended for embedded systems. Cortex-M0/M0+ target low cost and low power; Cortex-M3 and M4 add broader capability, with M4 commonly including DSP instructions and an optional floating-point unit; Cortex-M7 provides higher performance and caches on many implementations. The exact features depend on the microcontroller vendor and model.

Cortex-M processors use a standardized programmer’s model with general-purpose registers, a stack pointer, link register, program counter and status register. The Nested Vectored Interrupt Controller (NVIC) supports prioritized interrupts and rapid exception entry. The SysTick timer is commonly used for operating-system ticks or periodic software timing. A memory protection unit may be available for separating protected and unprotected regions.

Cortex-M devices generally use a memory-mapped address space. Peripheral registers are accessed using addresses, and software libraries often provide symbolic structures and bit definitions. This improves portability within a product family, but code remains dependent on the vendor’s clock tree, pin multiplexing and peripheral registers.

2.4 Architectural comparison

FeatureAVRPICARM Cortex-M
Typical core width8 bit8, 16 or related families32 bit
Typical strengthsSimple control, low cost, accessible registersBroad device range and configurable peripheralsPerformance, standardized core, advanced interrupts
Program memoryFlashFlashFlash, often with cache or accelerator in higher-end devices
Data memorySRAM; EEPROM on many partsSRAM; EEPROM or data Flash on selected partsSRAM; non-volatile data depends on device
Interrupt systemDevice-specific vectors and flagsDevice-specific vectors and prioritiesNVIC with standardized exception model
Common developmentC, assembly, vendor toolsC, assembly, vendor toolsC/C++, CMSIS, vendor SDKs and RTOSs

3. GPIO: Digital Interaction with the Outside World

General-purpose input/output is the most direct interface between software and electrical signals. A GPIO pin is normally configured as an input, output, alternate-function pin or analog pin. Its control commonly involves three concepts:

  • Direction: whether the output driver is enabled.
  • Data value: the value driven or latched for output.
  • Input sense: the logic level currently observed at the pin.

A pull-up or pull-down resistor establishes a defined input state when an external switch is open. Internal pulls simplify circuits but have wide tolerance and relatively weak drive capability. A switch input also requires debouncing because mechanical contacts can oscillate electrically for several milliseconds.

Output pins may be push-pull or open-drain/open-collector style. A push-pull output actively drives both logic levels. An open-drain output actively pulls low but requires an external or internal pull-up to produce a high level. Open-drain signalling is useful for wired-AND buses such as I²C, provided voltage, current and rise-time requirements are satisfied.

GPIO pins have absolute maximum ratings and recommended operating conditions. The maximum source or sink current is not the same as the total permissible current for an entire port or device. Driving an LED therefore requires a series resistor and must respect pin voltage, current and power limits.

For a resistive LED-limiting circuit, an approximate design relation is:

R = (VOH − VF) / ILED

Here, R is the series resistance in ohms, VOH is the output-high voltage in volts, VF is the LED forward voltage in volts, and ILED is the desired LED current in amperes. The relation assumes a steady-state resistive approximation and must be checked against the microcontroller’s guaranteed output voltage and current ratings.

For example, with VOH = 5.0 V, VF = 2.0 V and ILED = 0.010 A, the calculated resistance is 300 Ω. A standard 330 Ω resistor gives approximately 9.1 mA under the same simplified assumptions, usually a conservative practical choice.

Many modern pins support alternate functions such as UART transmit, SPI clock, timer output or ADC input. Pin multiplexing must be configured carefully: selecting an analog function may disable the digital input buffer, while selecting a peripheral function may disconnect the GPIO data register from the physical pin.

4. Internal Memory and Addressing

4.1 Program memory

Flash memory retains contents without power and stores executable code, constants and sometimes calibration data. It is organized into erase and program units. Flash writes are slower and have limited endurance compared with SRAM, so frequent data logging should not be placed directly in ordinary program Flash without wear management.

4.2 SRAM and the stack

SRAM stores variables, buffers and the run-time stack. The stack records return addresses, saved registers and local variables. Stack overflow can overwrite data or peripheral-control structures, producing difficult-to-diagnose failures. Embedded systems should estimate worst-case nested calls, interrupt usage and local-buffer requirements.

4.3 EEPROM and data Flash

EEPROM, where provided, supports non-volatile storage of configuration values and calibration constants. It has finite write endurance. A robust design uses wear levelling, validity markers, version fields and redundant records rather than rewriting one address continuously.

4.4 Memory-mapped peripherals

In a memory-mapped design, a peripheral register occupies an address range. A write may start a conversion, clear an interrupt flag or alter a pin configuration rather than simply storing data. Software must therefore use documented access width, ordering and reserved-bit rules. Read-modify-write operations can be unsafe when hardware changes bits asynchronously; dedicated set, clear or toggle registers are safer where available.

5. Clock Systems and Timing

The clock system provides the timing reference for instruction execution and peripheral operation. Sources may include an internal RC oscillator, an external crystal, an external clock input, a low-frequency oscillator or a PLL. Internal oscillators are inexpensive and start quickly but generally have greater tolerance and temperature dependence than crystals.

A clock divider reduces a source frequency. If a source clock of frequency fSRC is divided by an integer N, the resulting clock is:

fOUT = fSRC / N

The variables are frequencies in hertz and N is dimensionless. This formula assumes an ideal integer divider. For a 16 MHz source and divide-by-8 setting, fOUT = 2 MHz. A timer may then apply a further prescaler.

Timer overflow frequency depends on timer width, clock frequency, prescaler and counting mode. For a timer that counts from zero to a terminal value TOP inclusively:

fOV = fTIMER / (TOP + 1)

Here, fTIMER is the timer input frequency in hertz. In a normal up-counting mode, TOP is the largest count before overflow. For an 8-bit timer with fTIMER = 1 MHz and TOP = 255, overflow occurs at approximately 3,906.25 Hz. PWM frequency depends on the specific waveform-generation mode, so the device data sheet must be consulted rather than assuming all modes use the same formula.

Clock accuracy matters in asynchronous serial communication. A UART receiver samples according to its local clock, so excessive transmitter-receiver frequency error can cause framing errors. Crystal oscillators are preferred when tighter frequency accuracy is needed, whereas calibrated internal oscillators may be adequate for moderate-speed links.

Clock startup and switching are safety issues. Software should wait for oscillator-ready or PLL-lock indicators before depending on the new clock. During clock changes, peripheral timing and watchdog servicing must be considered.

6. Reset Circuits and Reliable Startup

Reset places the microcontroller into a known initial state. Common reset sources include power-on reset, external reset pin, brown-out reset, watchdog reset, software reset and reset caused by debugging or voltage-monitor circuitry.

  • Power-on reset holds the device in reset while supply voltage rises.
  • Brown-out reset responds when supply voltage falls below a selected threshold.
  • External reset allows a switch, supervisor or other circuit to request reset.
  • Watchdog reset occurs when software fails to service a watchdog within its permitted interval.
  • Software reset is intentionally requested by firmware.

A reset does not necessarily erase SRAM or return every peripheral to an identical state. The reset-status register should be examined early in startup so that firmware can distinguish a power failure from a watchdog event. Reset pins may require pull-up resistors, filtering or a voltage supervisor, depending on the electrical environment.

Brown-out protection is especially important where the CPU may execute incorrectly at low voltage. Disabling it can reduce power consumption but increases the risk of corrupted writes and uncontrolled outputs. Safety-critical or unattended equipment should use a deliberate reset strategy, not rely only on compiler-generated startup code.

7. Integrated Peripherals

Timers, counters and PWM

Timers count clock events or external transitions. They support delays, event measurement, input capture, output compare and PWM generation. PWM controls average power by changing duty cycle. If a periodic waveform has period T and the active interval is tON, its duty cycle is:

D = tON / T

D is dimensionless and is often expressed as a percentage by multiplying by 100. This relationship assumes a stable periodic waveform and does not by itself guarantee a proportional motor speed or LED brightness; the load and driver must also be considered.

ADC and analog peripherals

An ADC converts an analog input into a digital code. For an ideal ADC with n bits and reference voltage VREF, the code range is from 0 to 2n − 1. A common approximation for the input represented by code C is:

VIN ≈ C × VREF / (2n − 1)

The formula assumes an ideal converter, a stable reference and an input within the specified range. Real accuracy is affected by quantization, offset, gain error, noise, source impedance and reference tolerance. The ADC input must not exceed its permitted voltage, and an analogue input often requires settling time after channel selection.

Serial interfaces

UART is asynchronous and normally uses transmit, receive, baud-rate and frame-format settings. SPI is synchronous and typically uses clock, data-in, data-out and chip-select signals; it is fast but usually requires a separate select line per slave. I²C uses two open-drain lines and device addresses, making it efficient for multiple low-speed peripherals. CAN, USB and Ethernet are available on selected devices and involve more complex protocol, electrical and software requirements.

Interrupt systems

An interrupt allows hardware to request service without continuous polling. Good interrupt service routines are short, deterministic and clear the relevant source correctly. Shared data between an interrupt routine and main code should be protected against inconsistent access. A multi-byte variable may require atomic handling on an 8-bit CPU, whereas a naturally aligned word may be atomic on a 32-bit CPU; atomicity must never be assumed without consulting the core and compiler documentation.

Watchdog and safety peripherals

A watchdog timer detects software that has stopped making progress. It should be serviced only after essential tasks have completed, not blindly in a high-frequency interrupt. More advanced devices may provide windowed watchdogs, clock monitors, CRC engines, error-correcting memory, independent voltage monitors and configurable logic.

8. Platform Selection and Development Practice

Platform selection should begin with requirements rather than popularity. Relevant criteria include computation, Flash and SRAM capacity, pin count, ADC resolution, timer channels, communication interfaces, voltage range, package, power budget, tool support, unit cost, availability and expected product lifetime.

A professional firmware workflow normally includes:

  1. Read the device data sheet, reference manual and errata.
  2. Define clock, reset and power assumptions.
  3. Configure pins so unused or hazardous outputs cannot activate actuators at startup.
  4. Initialize clocks and wait for readiness indicators.
  5. Initialize GPIO and peripherals in a documented order.
  6. Clear and enable interrupts only after software state is ready.
  7. Test reset causes, watchdog behaviour and low-voltage operation.
  8. Use a debugger, logic analyser, oscilloscope and current measurement where appropriate.
  9. Record compiler, linker, device revision and configuration-fuse settings.

Direct register programming offers control and small overhead. Hardware-abstraction layers and vendor libraries improve readability and portability but may conceal timing, register side effects or power consumption. A balanced design uses abstraction for application logic while retaining datasheet-level understanding of critical initialization and timing.

9. Illustrative Case: Temperature-Controlled Network Cabinet Fan

Background

A small network cabinet requires a fan to start when temperature rises above a set point. The controller must measure temperature, drive a fan, indicate status and report measurements through a serial link.

Problem

The design must operate reliably after power interruptions, avoid damaging the GPIO pin, and continue controlling the fan if the communication link is temporarily unavailable. A direct connection between a motor and a GPIO pin is unsafe because the pin cannot supply motor current and inductive switching can generate voltage transients.

Analysis

An 8-bit AVR or PIC is adequate if the application requires modest sampling and simple control. A Cortex-M is preferable if the design later requires a graphical protocol stack, filtering, multiple communication channels or an RTOS. Required resources include one ADC channel, one PWM output, one UART, a timer interrupt and a watchdog.

Approach and solution

The temperature sensor output is connected to an ADC input within the permitted voltage range. A timer triggers sampling once per second. Firmware averages several samples to reduce noise, compares temperature with separate ON and OFF thresholds, and changes PWM duty cycle gradually. Separate thresholds provide hysteresis and prevent rapid switching near one temperature.

The PWM output drives a transistor or dedicated motor driver. A flyback path and suitable supply decoupling protect against inductive transients. UART reports temperature and fault status. The watchdog is enabled after initialization and is serviced only when the main control loop confirms that sampling, communication handling and safety checks have completed.

At startup, the fan-control pin is configured to a safe inactive level before the output driver is enabled. Brown-out reset is enabled, and reset-cause information is logged in non-volatile storage only when necessary to avoid excessive write wear.

Outcome

The resulting system separates low-voltage logic from motor power, maintains control during communication failures, and provides diagnosable reset and sensor faults. The design can be implemented on AVR, PIC or Cortex-M, but register configuration, interrupt setup, ADC behaviour and PWM calculations must be adapted to the selected device.

Learning points

The case demonstrates that platform selection is only one part of embedded design. GPIO electrical limits, clock and timer configuration, reset strategy, watchdog use, ADC assumptions and peripheral independence all affect reliability.

10. Limitations, Safety and Contemporary Development

Microcontrollers are constrained systems. Limited RAM restricts buffers and operating systems; Flash endurance limits persistent logging; ADCs are not precision laboratory instruments; internal oscillators may be inaccurate; and peripheral behaviour can differ between silicon revisions. Datasheet errata are therefore engineering documents, not optional reading.

Security is increasingly relevant even in small controllers. Firmware should protect update mechanisms, authenticate critical updates where feasible, disable unnecessary debug access in production and avoid exposing secrets in unprotected Flash. Secure boot, memory protection, cryptographic accelerators and hardware random-number generators are more common in newer 32-bit platforms, but their presence does not automatically produce a secure system.

AI tools can assist with register summaries, test generation and code review, but generated code must be checked against the exact device reference manual. An AI-generated register name, clock formula or interrupt flag may belong to a different model. Engineering responsibility remains with the designer.

Best practice is to design for determinism, document assumptions, measure actual timing and power, validate boundary conditions, and test abnormal states such as brown-out, unplugged sensors, stuck communication lines and repeated resets.

Chapter Summary

A microcontroller integrates a CPU core, program and data memory, GPIO, clock and reset circuits, and application-specific peripherals. AVR platforms provide accessible 8-bit RISC control; PIC families offer a broad range of 8-, 16- and specialized architectures; ARM Cortex-M platforms provide standardized 32-bit processing, prioritized interrupts and scalable performance. GPIO requires attention to direction, alternate functions, pull resistors, current limits and safe startup states. Flash, SRAM and EEPROM or data Flash have different purposes and endurance characteristics. Clock dividers, timers and PWM establish time and control energy, while ADCs connect digital software to analogue measurements. Reset sources and watchdogs support reliable operation, especially during power disturbances and software faults. Professional platform selection considers requirements, electrical limits, tools, availability, security and lifecycle support. Reliable embedded products result from integrating architectural knowledge with measurement, documentation and systematic testing.

Key Terms

CPU core: The processing unit that fetches, decodes and executes instructions.

GPIO: A configurable digital input/output connection to an external circuit.

Harvard architecture: Organization using separate instruction and data memory paths.

Flash memory: Non-volatile memory commonly used to store firmware.

SRAM: Volatile read/write memory used for variables, buffers and the stack.

EEPROM: Non-volatile memory suited to relatively small persistent data storage.

Memory-mapped peripheral: Hardware register accessed through an address in the processor’s memory space.

Alternate function: A peripheral function assigned to a physical GPIO pin.

Clock prescaler: A circuit that divides an input clock frequency.

PLL: Phase-locked loop used to generate or multiply a clock frequency.

Power-on reset: Reset action applied as supply voltage rises during startup.

Brown-out reset: Reset action caused by supply voltage falling below a threshold.

Watchdog timer: Timer that resets or flags the system when software fails to respond.

PWM: Pulse-width modulation used to control average power or represent a duty cycle.

ADC: Analogue-to-digital converter.

UART: Asynchronous serial communication peripheral.

SPI: Synchronous serial interface using clock and data signals.

I²C: Addressed two-wire, open-drain serial bus.

NVIC: Nested Vectored Interrupt Controller in ARM Cortex-M processors.

Wear levelling: Technique that distributes non-volatile writes to extend memory life.

Review Questions

Short Answer Questions

  1. What are the principal functions of a microcontroller CPU core?
  2. Why is a pull-up resistor used with an open-drain signal or switch input?
  3. Distinguish Flash memory from SRAM in an embedded system.
  4. Name four possible sources of microcontroller reset.
  5. What is the purpose of a timer prescaler?

Long Answer Questions

  1. Compare AVR, PIC and ARM Cortex-M architectures in terms of core width, memory organization, interrupt handling and typical applications.
  2. Explain the electrical and software considerations involved in configuring a GPIO pin as an output for an LED.
  3. Describe a microcontroller clock system from oscillator source to CPU and peripheral clocks.
  4. Explain how ADCs, timers, PWM and serial interfaces cooperate in an embedded control application.
  5. Discuss why watchdogs, brown-out reset and reset-cause registers are important for dependable products.

Analytical / Application Questions

  1. A controller uses a 16 MHz clock and an 8-bit timer with a divide-by-8 prescaler in normal overflow mode. Calculate the overflow frequency and explain one practical use for it.
  2. Design the main hardware and firmware blocks for a temperature-controlled fan using either an AVR, PIC or Cortex-M device. Justify the platform and identify at least three failure modes.
  3. A product repeatedly writes a temperature record to one EEPROM address every minute. Analyse the reliability problem and propose a better storage strategy.

Multiple Choice Questions with Answers

Question 1

Which memory type normally stores the firmware program in a microcontroller?

A. SRAM

B. Flash

C. CPU register file

D. GPIO latch

Correct Answer: B. Flash

Question 2

What is the main purpose of a GPIO direction configuration?

A. To select the oscillator frequency

B. To select ADC resolution

C. To determine whether the pin is input or output

D. To erase program memory

Correct Answer: C. To determine whether the pin is input or output

Question 3

A 16 MHz clock is divided by 8. What is the resulting frequency?

A. 125 kHz

B. 500 kHz

C. 2 MHz

D. 128 MHz

Correct Answer: C. 2 MHz

Question 4

Which reset source is intended to detect an inadequate supply voltage during operation?

A. Brown-out reset

B. UART reset

C. PWM reset

D. ADC reset

Correct Answer: A. Brown-out reset

Question 5

Which ARM Cortex-M component manages prioritized processor interrupts?

A. EEPROM

B. NVIC

C. PLL

D. GPIO latch

Correct Answer: B. NVIC

Question 6

Why is a transistor or motor driver commonly placed between a microcontroller PWM pin and a fan motor?

A. To increase Flash endurance

B. To provide suitable load current and switching protection

C. To convert UART into SPI

D. To reduce ADC resolution

Correct Answer: B. To provide suitable load current and switching protection

Question 7

For an ideal 8-bit ADC, how many distinct output codes are available?

A. 8

B. 128

C. 255

D. 256

Correct Answer: D. 256

Question 8

Which interface typically uses two open-drain lines and device addressing?

A. SPI

B. UART

C. I²C

D. Parallel GPIO

Correct Answer: C. I²C

Question 9

A watchdog timer is most useful for detecting which condition?

A. A completed ADC conversion

B. Software that has stopped making expected progress

C. A valid Flash read

D. A correctly transmitted UART frame

Correct Answer: B. Software that has stopped making expected progress

Question 10

Why should frequent data logging not repeatedly target one EEPROM address?

A. EEPROM cannot store binary values

B. EEPROM has finite write endurance

C. EEPROM is always volatile

D. EEPROM operates only during reset

Correct Answer: B. EEPROM has finite write endurance

Microprocessors and Microcontrollers
Chapter 6 of 14