First Year Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Microcontroller basics

Microcontroller basics: architecture, memory, clocks and cycles, GPIO and peripherals (timers, ADC, serial), interrupts, power, with formulas and worked examples for timing, ADC, and UART.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Microcontrollers are the small computers inside appliances, vehicles, medical devices, and IoT sensors; engineers use them to sense, compute, and control in real time. Understanding microcontroller basics lets you select the right device, configure pins and peripherals, meet timing requirements, and debug embedded systems in labs and industry.

Key ideas

  • Contrast: A microprocessor (μP) is a CPU on a chip without on-chip program memory and peripherals; it relies on external memory and I/O. Assumption: classic general-purpose processors (e.g., early x86) versus embedded MCUs. Conclusion: MCUs suit embedded control with low cost and size; μPs suit high-performance general computing when external components are acceptable.

  • Definition: An embedded system is a combination of hardware and software designed for a specific function within a larger system, often with real-time constraints.

  • Architecture:

    • Von Neumann architecture: single memory and bus for instructions and data; instruction fetch and data access share bandwidth.
    • Harvard architecture: separate memories and buses for instructions and data; instruction fetch and data access can occur in parallel. Assumption: ideal separate buses; benefit: higher throughput at same clock.
    • Diagram to draw and label: “Block diagram of a microcontroller” — draw a central CPU block (with ALU, Control Unit, Registers), two memory blocks (Program Memory/Flash, Data Memory/RAM), non-volatile data block (EEPROM), buses (Address Bus, Data Bus, Control Signals), and peripheral blocks (GPIO Ports, Timers/Counters, ADC, DAC (if present), UART, SPI, I2C, Watchdog Timer), with arrows showing bus connections. Label clock source (Crystal/RC Oscillator) and Reset.
  • CPU internals:

    • Arithmetic Logic Unit (ALU) performs arithmetic and logic operations.
    • Control Unit decodes instructions and sequences operations.
    • Registers are small high-speed storage; include general-purpose registers, Program Counter (PC) (address of next instruction), Status/Flags Register (Z, C, N, V flags), and Stack Pointer (SP) (top of stack address).
  • Memories:

    • Program memory (Flash): non-volatile memory storing code; retains contents without power.
    • Data memory (RAM/SRAM): volatile memory for variables and stack; lost on power-off.
    • EEPROM or data Flash: non-volatile memory for parameters that change rarely (e.g., calibration).
    • Memory map: the arranged address space showing where program memory, data memory, peripherals, and special function registers exist. Diagram to draw: a vertical address space bar labeled with ranges for Flash, SRAM, Peripheral Registers, EEPROM; arrows showing PC to Flash, data bus to SRAM and peripherals.
  • Clocking and timing:

    • System clock (f_clk) is the base frequency driving the CPU and peripheral clock domains before any individual peripheral prescalers. It comes from an internal RC oscillator or external crystal/clock.
    • Definition: A machine cycle (or instruction cycle) is the basic time unit to fetch, decode, and execute an instruction; in many MCUs, instruction execution time = (cycles per instruction)/f_clk. Assumption: fixed cycles per instruction or pipeline fills; vendor specifics vary.
  • I/O and peripherals:

    • GPIO (General-Purpose Input/Output) pins can be configured as digital input or output. Output types: push–pull and open-drain/open-collector. Input options: with or without internal pull-up/pull-down resistors.
    • Timers/Counters increment at a known rate derived from the clock, optionally with a prescaler. Modes: up-counting, down-counting, auto-reload, capture/compare, PWM.
    • Watchdog timer (WDT) resets the MCU if not periodically serviced (“kicked”) within a timeout; improves reliability.
    • ADC (Analog-to-Digital Converter) converts an analog voltage into a digital code. Key parameters: resolution (n bits), reference voltage (Vref), sampling rate.
    • DAC (Digital-to-Analog Converter) converts a digital code to an analog voltage or current (not present in all MCUs).
    • Communication interfaces:
      • UART (Universal Asynchronous Receiver/Transmitter) for serial communication using start/stop bits; configured by baud rate, data bits, parity, stop bits.
      • SPI (Serial Peripheral Interface): synchronous full-duplex master–slave bus with lines SCK, MOSI, MISO, SS; clock polarity (CPOL) and phase (CPHA) define mode.
      • I2C (Inter-Integrated Circuit): synchronous half-duplex two-wire bus (SCL, SDA) with open-drain lines and pull-up resistors; addressing and acknowledgements.
  • Interrupts and reset:

    • Definition: An interrupt is a hardware or software event that temporarily halts the main program, saves context, and transfers control to an Interrupt Service Routine (ISR); after ISR, control returns to the main program. Types: maskable and non-maskable, external and peripheral.
    • Reset initializes the MCU to a known state; sources include power-on reset, brown-out, watchdog, external reset pin.
  • Power and clock features:

    • Power modes: run, sleep/standby/stop; trade performance for power.
    • Prescalers divide clocks to reduce peripheral speeds or save power.
  • Pin multiplexing:

    • Many pins have alternate functions (e.g., a GPIO pin may act as UART TX); configuration selects one function at a time. Beware shared resources.
  • Debouncing and pull resistors:

    • Switch bounce causes rapid toggling when a mechanical button is pressed; handle using RC filters, software delays, or hardware debounce ICs.
    • Pull-up/pull-down resistors define a default logic level when an input is otherwise floating; internal pulls are often configurable.
  • Exact statements useful for exams and typical derivations:

    • Statement: “In an n-bit ADC with reference voltage Vref, the number of quantization levels is 2ⁿ. The quantization step size (LSB) is Vref/2ⁿ. For an input Vin in the range 0 to Vref (unipolar), the ideal output code is floor[(Vin/Vref)·(2ⁿ − 1)].” Assumptions: ideal linear ADC, no offset, unipolar mode, no noise.
    • Statement: “The time for one instruction equals (number of clock cycles per instruction)/f_clk.” Assumptions: fixed cycle count per instruction, no wait states.
    • Derivation (Timer overflow time): For an m-bit timer clocked at f_timer, each increment occurs every 1/f_timer seconds. The timer counts from initial value T0 up to its MOD (maximum, e.g., 2^m for wrap). Number of counts N = MOD − T0. So overflow time T_ovf = N/f_timer. If a prescaler P is applied to the base clock f_clk, then f_timer = f_clk/P, so T_ovf = (MOD − T0)·P/f_clk. Assumptions: simple up-counting, auto-reload at MOD, no clock gating.
    • Derivation (UART bit time): For baud rate B, one bit duration is T_bit = 1/B. A frame of 8N1 (8 data, no parity, 1 stop) has 1 start + 8 data + 1 stop = 10 bits; frame time = 10/B. Assumptions: standard asynchronous framing.
    • Diagram to draw and label: “Harvard vs Von Neumann” — two small diagrams: (1) Von Neumann: single memory block labeled ‘Instructions + Data’, one bus to CPU; (2) Harvard: two memory blocks ‘Program’ and ‘Data’ with two separate buses to CPU.
    • Diagram to draw and label: “GPIO pin circuits” — draw for push–pull (two transistors to VDD and GND), open-drain (only a transistor to GND and an external pull-up resistor to VDD), and an input with an internal pull-up resistor symbol. Label logic levels and current flow directions.
  • Basic development flow:

    1. Select MCU and read its datasheet and reference manual.
    2. Decide clock source and frequency; configure f_clk and prescalers.
    3. Configure pins (multiplexing, direction, pulls).
    4. Configure required peripherals (timers, ADC, UART) and interrupts.
    5. Write firmware (often in C), compile, flash to MCU, and test using debugger and instruments (refer to “Electronic instruments: multimeter and oscilloscope”).

Formulas

T_instr = CPI / f_clk

  • T_instr: instruction execution time (s). CPI: cycles per instruction (dimensionless). f_clk: system clock frequency (Hz). Applies when an instruction needs CPI cycles at clock f_clk.

f_timer = f_clk / P

  • f_timer: timer input frequency (Hz). f_clk: system clock (Hz). P: prescaler division factor (dimensionless). Applies to timers clocked from the system clock through a prescaler.

T_ovf = (MOD − T0) / f_timer

  • T_ovf: time to timer overflow or auto-reload (s). MOD: terminal count (counts) (e.g., 2^m for m-bit timer if starting at 0). T0: initial count loaded (counts). f_timer: timer clock (Hz). Applies to simple up-counters.

N_levels = 2^n

  • N_levels: number of ADC or DAC codes (dimensionless). n: resolution in bits (bits). Applies to ideal n-bit converters.

LSB = Vref / 2^n

  • LSB: quantization step size (V). Vref: reference voltage (V). n: ADC bits (bits). Applies to unipolar ideal ADC.

Code = floor[(Vin / Vref) · (2^n − 1)]

  • Code: digital output code (dimensionless). Vin: analog input voltage (V). Vref: reference voltage (V). n: ADC bits (bits). Applies to unipolar ideal ADC with straight binary output.

T_bit = 1 / B

  • T_bit: duration of one serial bit (s). B: baud rate (bits/s). Applies to asynchronous serial like UART.

f_SPI = f_periph / P

  • f_SPI: SPI clock frequency (Hz). f_periph: peripheral clock for SPI (Hz). P: SPI prescaler (dimensionless). Applies to master SPI.

I_pull = (VDD − V_in) / R_pull

  • I_pull: current through pull-up/down (A). VDD: supply voltage (V). V_in: pin voltage (V). R_pull: pull resistor (Ω). Applies to estimating input current via pull resistors.

Programming syntax to remember (generic C-like; vendor specifics vary):

  • Configure a GPIO pin as output and set it high:
    • DIR_REG |= (1u << PIN);
    • OUT_REG |= (1u << PIN);
  • Configure a GPIO pin as input with pull-up:
    • DIR_REG &= ~(1u << PIN);
    • PULL_EN_REG |= (1u << PIN); and PULL_SEL_REG |= (1u << PIN);
  • Enable a timer with prescaler and auto-reload:
    • TMR_PSC = P − 1; TMR_ARR = MOD − 1; TMR_CNT = T0; TMR_CR1 |= EN;
  • Enable UART at baud B (conceptual):
    • UART_BRR = round(f_periph / (OSR * B)); UART_CR |= TE | RE;
  • Define an Interrupt Service Routine (ISR):
    • void ISR_Name(void) { /* clear flag */ /* service */ } // attach via vector table

Worked examples

Example 1: Timer preload for LED blink Given: 16-bit timer (counts 0 to 65535 then overflows), system clock f_clk = 8.0 MHz, prescaler P = 64, desired LED toggle period = 0.5 s (i.e., interrupt every 0.5 s). Find the initial count T0 to load so that overflow occurs every 0.5 s.

  1. Compute timer clock: f_timer = f_clk / P = 8.0×10^6 Hz / 64 = 125000 Hz.
  2. Compute counts needed for 0.5 s: N = T_ovf · f_timer = 0.5 s · 125000 Hz = 62500 counts.
  3. For a 16-bit timer with MOD = 65536 counts (0 to 65535), N = MOD − T0.
  4. Solve for T0: T0 = MOD − N = 65536 − 62500 = 3036 counts.
  5. Load T0 = 3036 (decimal) at start of each period.

Answer: Preload the timer with 3036 (0x0BDC) to get a 0.5 s overflow at 8 MHz with prescaler 64.

Check: From T0=3036 to 65535 is 65536−3036 = 62500 counts; 62500 / 125000 Hz = 0.5 s — correct.

Example 2: ADC code and resolution Given: n = 10-bit ADC, Vref = 3.300 V, input Vin = 1.200 V. Find LSB size and output code (ideal unipolar, straight binary).

  1. Compute number of levels: N_levels = 2^n = 2^10 = 1024.
  2. LSB size: LSB = Vref / 2^n = 3.300 V / 1024 = 0.00322265625 V ≈ 3.223 mV.
  3. Ideal code: Code = floor[(Vin / Vref) · (2^n − 1)] = floor[(1.200 / 3.300) · 1023].
  4. Compute ratio: 1.200 / 3.300 = 0.363636….
  5. Multiply: 0.363636… · 1023 = 372.0 (exact, since 0.363636… = 4/11 and 1023 = 93·11).
  6. Apply floor: Code = 372 (decimal).

Answer: LSB ≈ 3.223 mV; digital code = 372 (0x174).

Check: Ideal analog reconstructed = Code·LSB ≈ 372×3.22265625 mV ≈ 1.198828 V — correct within 1 LSB.

Example 3: UART divisor for a target baud Given: Peripheral clock f_periph = 16.000 MHz, desired baud B = 9600 bits/s, typical UART oversampling OSR = 16. Many MCUs set a baud-rate register BRR ≈ f_periph/(OSR·B). Find the nearest integer divisor and resulting baud.

  1. Compute ideal divisor: Div = f_periph / (OSR · B) = 16,000,000 / (16 · 9600).
  2. Denominator: 16 · 9600 = 153,600.
  3. Division: 16,000,000 / 153,600 ≈ 104.1667.
  4. Nearest integer choices: 104 or 105.
  5. Resulting baud for 104: B_actual = f_periph / (OSR · 104) = 16,000,000 / (16 · 104) = 16,000,000 / 1,664 ≈ 9615.385 bits/s.
  6. Error: (B_actual − B)/B ≈ (9615.385 − 9600)/9600 ≈ +0.16%.
  7. Resulting baud for 105: B_actual = 16,000,000 / (16 · 105) = 16,000,000 / 1,680 ≈ 9523.810 bits/s.
  8. Error: (9523.810 − 9600)/9600 ≈ −0.79%.

Choose divisor 104 for lower error.

Answer: Set BRR ≈ 104, giving ≈9615.4 bps (+0.16% error), acceptable for many UART links.

Note: Some MCUs support fractional divisors; then set integer=104 and fractional≈0.1667 to get near-exact 9600 bps.

Example 4 (theory): Compare microcontroller and microprocessor for an embedded application Model answer points:

  • A microcontroller integrates CPU, program memory (Flash), data memory (RAM), and peripherals on one chip, optimized for control tasks and low power. A microprocessor provides only the CPU core and needs external memory and peripherals, offering higher flexibility and performance at the cost of more components.
  • For a washing machine controller: MCU is preferred due to on-chip timers, GPIO, ADC (for sensors), low cost, small PCB area, and deterministic real-time control. A μP would require external RAM/ROM/I/O, increasing cost, size, and power without benefit for such fixed-function tasks.
  • Conclude: MCUs suit embedded, cost- and power-sensitive designs; μPs suit compute-intensive applications (e.g., laptops) where external memory bandwidth and OS support are needed.

Common mistakes

  • Forgetting that Flash/EEPROM are non-volatile while RAM is volatile; writing that “RAM stores program permanently.”
  • Ignoring prescalers in timer calculations, leading to wrong overflow times or preload values.
  • Assuming 2^n − 1 steps for ADC LSB; correct step size uses 2^n in the denominator for ideal quantization step.
  • Confusing UART frame length (e.g., 8N1 is 10 bits total including start/stop) and calculating data rate incorrectly.
  • Not enabling internal pull-up/pull-down on input pins, causing floating inputs and random behavior in experiments.
  • Forgetting to clear interrupt flags inside ISRs, leading to re-entry or lock-ups.
  • Misconfiguring pin multiplexing (e.g., trying to use the same pin as GPIO and UART simultaneously).
  • Assuming all MCUs execute one instruction per clock; CPI varies and pipelines/stalls exist.

For your exam

  • Short notes: Harvard vs Von Neumann, GPIO modes, timers and PWM, UART/SPI/I2C basics, watchdog and reset sources, power modes. Full-marks: key features, advantages, and simple labeled diagram.
  • Derivations/numericals: timer overflow/preload, instruction time from clock, ADC resolution and code, serial bit-time and frame time, UART divisor calculation. Full-marks: write formula first with symbols and units, substitute numbers with units, final answer highlighted.
  • Diagrams: microcontroller block diagram, memory map, GPIO pin types, Harvard vs Von Neumann. Full-marks: neat, all blocks labeled, arrows for buses, legend for signals.
  • Programs/pseudocode: initialize GPIO, blink LED with timer interrupt, read ADC and send over UART. Full-marks: correct register use sequence (enable clock, configure pin direction and pulls, set baud, enable interrupts), and comment on clearing flags and ISR attachment.

Quick check

  1. Define a microcontroller and list two on-chip peripherals commonly available.
  2. A 12-bit ADC uses Vref = 5.0 V. What is the LSB size? If Vin = 2.00 V, what is the ideal code?
  3. With f_clk = 10 MHz and prescaler P = 100, how many timer counts occur in 25 ms on an up-counter starting from 0?

Answers: 1) An IC integrating CPU, program memory, data memory, and peripherals; peripherals: timers, GPIO, ADC, UART. 2) LSB = 5.0 V/4096 = 0.0012207 V ≈ 1.221 mV; Code = floor[(2.00/5.0)·(4095)] = floor[1638.0] = 1638. 3) f_timer = 10 MHz/100 = 100 kHz; counts = 0.025 s · 100000 Hz = 2500 counts.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?