Skip to content
Tactiverge

Textbooks/Electrical and Embedded Systems/Chapter 5Lite (plain text) version

5Inside a microcontroller

Version 1 · Technically checked (automated checks only) · 5 source lessons · 8 practice items

Text
All chapters and search
  1. 1. Charge, current and voltage
  2. 2. Ohm's law and real components
  3. 3. Series, parallel and dividers
  4. 4. Power, energy and batteries
  5. 5. Inside a microcontroller
  6. 6. Pins, inputs and sensors
  7. 7. PWM, state machines and actuators
  8. 8. Talking between chips
  9. 9. Registers, interrupts and integration

Introduction

A microcontroller is a whole small computer on one chip: processor, flash for the program, RAM for the variables and a crowd of peripherals. Its clock ticks millions of times a second, which sets an instruction budget for every loop. Programs run as a super-loop that sets up once and repeats forever, and hardware timers count ticks for you, so the loop can juggle several tasks without ever stopping to wait.

Divide the clock, count the ticks16 MHzCPU clock÷ 64prescaler250 kHz4 µs/tick1 ms = 250 ticks8-bit overflow: 256 ticks = 1.024 ms
Figure 5.1. Divide the clock, count the ticks. A 16 MHz CPU clock divided by a prescaler of 64 gives timer ticks at 250 kHz, one every 4 µs. 1 ms is 250 ticks, and an 8-bit timer overflows after 256 ticks, which is 1.024 ms.

Explanation

This chapter is built from 5 School lessons. Each part below is the lesson's own explanation; open the lesson for its predict-and-discover activities.

5.1 A whole computer on one chip

Your washing machine, your bike light and a Mars rover's wheel all hide the same kind of tiny computer. What is inside it?

Five parts, one chip

A microcontroller (MCU) packs a whole computer onto one chip. The CPU follows instructions one at a time. Flash memory stores the program, even with the power off. RAM holds the variables while it runs. The clock is a steady tick that keeps everything in step. Peripherals are small helper circuits for the outside world: pins that read buttons and drive LEDs, an ADC that measures voltages, timers that count time, and serial ports that talk to other chips.

Microcontroller or laptop?

A laptop processor is fast and general: it runs many programs, needs lots of separate memory chips and uses tens of watts. A microcontroller is small, cheap and dedicated: it runs one program forever, starts in a fraction of a second and can run for months on a coin cell. It is slower, but a washing machine does not need to edit video; it needs to read a door switch reliably, millions of times.

Following the instructions

The CPU repeats one cycle: fetch the next instruction from flash, decode what it means, execute it (add, compare, read a pin), then move on. A special register called the program counter remembers where it is. A jump instruction changes the program counter, which is how loops and decisions work underneath your code.

Common mix-ups

  • A microcontroller is just a slow, cheap laptop chip.
    ✓ It is designed differently: memory, clock and peripherals are built in, so one chip can run a machine by itself.
  • RAM and flash are the same thing.
    ✓ Flash keeps the program with the power off; RAM is fast working memory that forgets on power-down.

Open the full lesson: A whole computer on one chip →

5.2 Counting in nanoseconds

A 16 MHz chip ticks sixteen million times a second. Is that fast enough to catch a button, run a motor or record music?

Frequency and period are flip sides

The clock frequency is how many ticks happen each second, in hertz (Hz). Mega means million, so 16 MHz is 16,000,000 ticks a second. The period is how long one tick lasts: 1 ÷ 16,000,000 s = 62.5 nanoseconds. Light travels only about 19 metres in that time.

Instructions cost cycles

Simple instructions on many small chips take one clock cycle; others (dividing, reading slow memory) take several. Engineers use an average cycles per instruction to estimate. A 16 MHz chip at 1 cycle per instruction runs about 16 million instructions a second, which is 16,000 every millisecond.

Budgets and deadlines

Machines have deadlines: check the button every 10 ms, update the motor every 1 ms, take an audio sample every 22.7 µs. Divide the time per loop pass by the deadline to see how much of the budget you use. Leave a margin: real code has surprises, and a loop at 95% of its budget will overrun one day.

Derivation: From MHz to an instruction budget
  1. Frequency f counts ticks per second; 1 MHz = 1,000,000 ticks per second.

  2. One tick lasts the period T = 1 ÷ f. At 16 MHz: T = 1 ÷ 16,000,000 s = 0.0000000625 s = 62.5 ns (1 ns = 0.000000001 s).

  3. If each instruction needs c clock cycles on average, the chip runs f ÷ c instructions per second.

  4. In a time window t, it runs N = f × t ÷ c instructions. At 16 MHz, c = 1, t = 1 ms: N = 16,000,000 × 0.001 ÷ 1 = 16,000.

  5. A loop of n instructions takes n × c ÷ f seconds per pass. It meets a deadline D only if n × c ÷ f ≤ D, and wise engineers keep it well under.

Common mix-ups

  • A 100 MHz chip runs 100 million lines of my program every second.
    ✓ One line of Python or C becomes many instructions, and instructions can take several cycles each.
  • Higher frequency means a longer period.
    ✓ Period = 1 ÷ frequency: they move in opposite directions.

Open the full lesson: Counting in nanoseconds →

5.3 Set up once, loop forever

Your laptop's programs start and stop. A microcontroller's program never ends. How do you write a program that runs forever, on purpose?

Two parts: setup and loop

Embedded programs have a setup part that runs once at power-on (set pin modes, start the ADC, set variables) and a loop that runs forever. In Python-style code:

setup_pins()
while True:
    temp = read_temperature()
    if temp < 18:
        heater_on()
    else:
        heater_off()

There is no 'end of program': if the loop ever stopped, the machine would stop responding.

Read, decide, act

Each pass of the loop is one turn of sense–think–act: read the inputs, decide with ifs and comparisons, then set the outputs. Keep each pass short. A greenhouse loop that takes 5 ms reacts within 5 ms; one that sleeps for a minute is blind for a minute.

Why delays hurt

A delay(500) freezes the CPU for half a second. Nothing else runs: no buttons, no sensors, no safety checks. One delay is fine for blinking a single LED, but a machine doing several jobs needs a loop that never waits. You will build that in week 25 with timers.

Common mix-ups

  • A program that never ends has a bug.
    ✓ On a laptop, maybe. In a machine, the endless loop is the design: it keeps sensing for as long as the power is on.
  • Adding delays makes a program more reliable.
    ✓ Long delays make the machine blind while it waits. Short loop passes make it responsive.

Open the full lesson: Set up once, loop forever →

5.4 Timers: hardware that counts for you

Your loop is busy reading sensors. Who is keeping track of the time?

A counter in hardware

A timer is a peripheral that adds 1 to a counter on every tick, whatever the CPU is doing. Firmware reads the counter to know how much time has passed, or asks the timer to raise a flag (or an interrupt) when it reaches a value. Because it is hardware, its timing does not wobble when the loop gets busy.

The prescaler

Counting at the full 16 MHz would fill a 16-bit counter in about 4 ms. A prescaler divides the clock first: ÷8, ÷64, ÷256, ÷1,024 are common. Dividing by 64 gives 4 µs ticks and about 0.26 s before overflow; dividing by 1,024 gives 64 µs ticks and about 4.2 s.

Overflow and wrap-around

A 16-bit counter can only hold 65,536 values (0–65,535). One tick after 65,535 it wraps back to 0: an overflow. Firmware either counts overflows to extend the range, or measures intervals with subtraction that copes with wrap-around (week 25's non-blocking pattern does this with a 32-bit millisecond clock).

Derivation: Ticks, prescalers and overflow
  1. Tick rate: f_tick = f_clock ÷ prescaler. 16 MHz ÷ 64 = 250,000 ticks per second.

  2. Ticks in a time t: ticks = f_tick × t. In 20 ms: 250,000 × 0.020 = 5,000 ticks.

  3. Resolution (time per tick) = 1 ÷ f_tick = 4 µs.

  4. A 16-bit counter holds 0 to 65,535 and then wraps to 0: it overflows every 65,536 ÷ f_tick seconds = 65,536 ÷ 250,000 ≈ 0.262 s.

  5. Bigger prescaler: coarser ticks but a longer time before overflow. Choose the smallest prescaler whose range covers the longest interval you need.

Common mix-ups

  • The CPU has to count time itself in a loop.
    ✓ Timers are hardware: they count on their own and the CPU just reads them.
  • Overflow means the timer broke.
    ✓ Overflow is normal wrap-around. Good firmware expects it and handles it.

Open the full lesson: Timers: hardware that counts for you →

5.5 Doing several things at once (without waiting)

Blink an LED every half second, read a sensor ten times a second and never miss a button press. With one CPU and no waiting. How?

Check the clock, don't wait for it

Instead of delay(500), each task remembers when it last ran. Every pass of the loop asks 'has enough time passed?' and only then does the work:

last_blink = 0
while True:
    now = millis()
    if now - last_blink >= 500:
        last_blink += 500
        toggle_led()
    if now - last_read >= 100:
        last_read += 100
        read_sensor()
    check_button()   # every pass

Why subtraction?

now - last >= period measures elapsed time, which keeps working even when the millisecond counter wraps around past its largest value (with unsigned integer maths in C). Adding the period to last (rather than setting last = now) stops small delays piling up, so a 500 ms blink stays at 500 ms on average.

Tasks are tiny state machines

Each task's 'last run time' is its memory, like a state. Longer jobs (a wash stage, a door opening) become state machines whose transitions fire on elapsed time or sensor events. Nothing ever waits, so every task gets a turn within a millisecond or two.

Common mix-ups

  • To do two things at once you need two processors.
    ✓ One CPU can interleave many short tasks so quickly that they all appear simultaneous.
  • Non-blocking code never runs late.
    ✓ A task can be late by up to one loop pass. Keep passes short and measure them.

Open the full lesson: Doing several things at once (without waiting) →

Worked examples

A whole computer on one chip: example 1

A bike light flashes, reads a button and dims when the battery is low. Which microcontroller parts are involved?

Solution

Flash holds the program. The CPU runs it. A timer peripheral sets the flash rhythm. A GPIO pin reads the button and another drives the LED. The ADC measures the battery voltage. RAM holds variables such as the current mode.

Counting in nanoseconds: example 1

A 48 MHz chip averages 2 cycles per instruction. Can a 30,000-instruction loop run 1,000 times a second?

Solution

Instructions per second = 48,000,000 ÷ 2 = 24,000,000. One pass = 30,000 ÷ 24,000,000 = 0.00125 s = 1.25 ms. The deadline is 1 ms, so no: it overruns by 25%. Halve the work, or use a faster chip.

Counting in nanoseconds: example 2

How long is one period of a 240 MHz clock?

Solution

T = 1000 ÷ 240 ns ≈ 4.17 ns.

Set up once, loop forever: example 1

Write pseudocode for a night light: an LED should be on when a light sensor reads below 300 counts.

Solution

set_pin_output(LED)
while True:
    light = read_adc(LIGHT_SENSOR)
    if light < 300:
        write(LED, HIGH)
    else:
        write(LED, LOW)

Setup once; then read, decide, act, every pass.

Timers: hardware that counts for you: example 1

You need to time intervals up to 2 s with a 16-bit timer on a 16 MHz clock. Which prescaler from 1, 8, 64, 256, 1,024 should you choose?

Solution

Overflow time = 65,536 × prescaler ÷ 16,000,000. ÷256: 1.05 s (too short). ÷1,024: 4.19 s (enough), with 64 µs resolution. Choose 1,024.

Doing several things at once (without waiting): example 1

Tasks every 20 ms, 100 ms and 500 ms run from t = 0. How many total task runs by t = 1,000 ms?

Solution

20 ms: ⌊1000/20⌋ + 1 = 51. 100 ms: 11. 500 ms: 3. Total 65 runs.

Interactive figures

Figure 5.2 from Counting in nanosecondsChoose the 1,000-times-a-second motor deadline. Find the smallest clock that lets a 2,000-instruction loop fit. Then switch to the audio deadline and see what it would take.
Can't use the interactive? Read a description instead

The budget calculator takes a clock frequency, cycles per instruction and loop size. It shows the clock period (1 ÷ frequency), instructions per millisecond, the time for one loop pass (instructions × cycles ÷ frequency) and compares it with a chosen deadline, saying whether it fits and what fraction of the deadline it uses.

Interactive figure (online). Description: The budget calculator takes a clock frequency, cycles per instruction and loop size. It shows the clock period (1 ÷ frequency), instructions per millisecond, the time for one loop pass (instructions × cycles ÷ frequency) and compares it with a chosen deadline, saying whether it fits and what fraction of the deadline it uses.

Figure 5.3 from Set up once, loop foreverChoose 'Blocking: delay(500)'. Scrub the time from 0 to 2,000 ms and watch when each job in the loop runs. Did the loop notice the two button presses? Now switch to the non-blocking loop and compare.
Can't use the interactive? Read a description instead

The timing scrubber shows three jobs (toggle an LED, read a sensor, read a button) on a 0–2,000 ms timeline. With a blocking delay of 500 ms, every job runs only once every 500 ms, and two short button presses (70 ms and 50 ms long) fall between reads and are missed. With a non-blocking loop, the button is read every 20 ms and both presses are seen.

Interactive figure (online). Description: The timing scrubber shows three jobs (toggle an LED, read a sensor, read a button) on a 0–2,000 ms timeline. With a blocking delay of 500 ms, every job runs only once every 500 ms, and two short button presses (70 ms and 50 ms long) fall between reads and are missed. With a non-blocking loop, the button is read every 20 ms and both presses are seen.

Laboratory

Everything runs in your browser. No kit, nothing mains-powered. Simulations are simplified educational models.

  • Studio

    Code Lab

    Write a non-blocking loop that blinks one light every 500 ms and checks a button every 10 ms, using elapsed time instead of delays.

    Open Code Lab →
  • BUILD level

    BUILD: Washing machine, level 2

    Write the controller's loop so it keeps reading the door sensor while the drum is running.

    Open BUILD: Washing machine, level 2 →

Guided practice

Answers are checked on the server; wrong answers get a hint and another try. Signed in, solved items also count towards the source lesson.

Practice 1

A variable counting button presses is lost every time the device is switched off. Which memory is it stored in?

Practice 2 · a fresh version every time

A microcontroller's clock runs at 160 MHz. How long is one clock period, in nanoseconds?

ns

Practice 3 · a fresh version every time

A 16 MHz microcontroller needs about 4 clock cycles per instruction on average. Roughly how many instructions can it run in 1 ms?

instructions

Practice 4

Where should 'set pin 3 as an output' go?

Practice 5 · a fresh version every time

A timer counts at 16 MHz divided by a prescaler of 1. How many ticks does it count in 20 ms?

ticks

Practice 6

A 16-bit timer counts at 16 MHz ÷ 256. How long until it overflows, in seconds? (Give 3 decimal places.)

s

Practice 7

A loop calls `delay(1000)` once per pass. What is the main problem when you add a safety button?

Practice 8

One loop pass takes at most 3 ms. A task is due at t = 400 ms and the loop checks at 399 ms. At the latest, by how many ms is the task late?

ms
  1. A variable counting button presses is lost every time the device is switched off. Which memory is it stored in?
    • Flash
    • RAM
    • The clock
  2. A microcontroller's clock runs at 160 MHz. How long is one clock period, in nanoseconds? (ns)
  3. A 16 MHz microcontroller needs about 4 clock cycles per instruction on average. Roughly how many instructions can it run in 1 ms? (instructions)
  4. Where should 'set pin 3 as an output' go?
    • In setup, once
    • Inside the loop, every pass
    • After the loop ends
  5. A timer counts at 16 MHz divided by a prescaler of 1. How many ticks does it count in 20 ms? (ticks)
  6. A 16-bit timer counts at 16 MHz ÷ 256. How long until it overflows, in seconds? (Give 3 decimal places.) (s)
  7. A loop calls `delay(1000)` once per pass. What is the main problem when you add a safety button?
    • The button is only checked once a second, so a short press can be missed
    • delay uses too much memory
    • The LED gets brighter
  8. One loop pass takes at most 3 ms. A task is due at t = 400 ms and the loop checks at 399 ms. At the latest, by how many ms is the task late? (ms)

Engineering applications

  • Everywhere, unseen

    Washing machines, keyboards, toothbrushes and car windows each hide a microcontroller running a super-loop. Most never run an operating system; they simply set up their pins once and loop for years.

  • Why delays hurt

    A program that waits one second in a delay cannot notice a button press during that second. Non-blocking timing checks the clock on every pass instead, so a stop button always works.

Watch

Optional verified videos. Nothing loads from YouTube until you press play.

A chip maker's beginner tour that compares the parts of a microcontroller with the parts of an ordinary computer.

Length: see YouTube · captions on YouTube · source

Nothing loads from YouTube until you press play.

Walks through the CPU, memory and peripherals of a microcontroller one at a time, with where each one earns its place.

Length: see YouTube · captions on YouTube · source

Nothing loads from YouTube until you press play.

How hardware timers count clock cycles to measure time without stalling the processor.

31 min 17 s · captions on YouTube · source

Nothing loads from YouTube until you press play.

  • What is a Microcontroller? (Microchip Technology, Inc.)
  • What is an MCU? - Micro Controller Units Explained (Transfer Multisort Elektronik)
  • How do hardware timers work? (Ben Eater)

Chapter summary

  • A microcontroller combines a CPU, flash, RAM and peripherals on one chip.
  • Clock period = 1 / frequency; the loop rate times the work per pass must fit the instruction budget.
  • A super-loop runs setup once, then repeats loop forever.
  • Timers count prescaled clock ticks; non-blocking code compares elapsed time instead of waiting.

Glossary

RAM, flash and EEPROM
RAM is fast, volatile working memory that loses its contents without power; flash and EEPROM are non-volatile and keep data, but are slower to write and wear out after many write cycles.
Clock speed, cycles and CPI
Execution time equals the number of instructions times the average cycles per instruction (CPI) divided by the clock frequency.
Registers
Registers are a small number of very fast storage locations inside the processor that hold the values it is working on right now.
Interrupts
An interrupt is a hardware signal that makes the processor pause the main program, run a short interrupt service routine (ISR), and then resume where it left off.

Definitions from the Field Guide.

Project: Three tasks, one loop

Design a super-loop that blinks a status light at 1 Hz, samples a sensor at 50 Hz and checks a stop button at 100 Hz, without delays. Give the timer settings you would use, the time budget for each pass and how you would detect a pass that overruns.

Deliverables

  • Pseudocode or code for the loop
  • Timer and prescaler choices with tick calculations
  • An overrun check and what it does

Keep your work in your Engineering Journal; it stays private unless you choose to share it.

References

  • Elecia White (2011). Making Embedded Systems: Design Patterns for Great Software. O'Reilly Media.
  • Edward A. Lee and Sanjit A. Seshia (2017). Introduction to Embedded Systems: A Cyber-Physical Systems Approach, 2nd edition. MIT Press.

Publication record

Version
1
Status
Technically checked (automated checks only)
Technical review
Automated checks only, last run 2026-11-29. No human, educator or mentor review is claimed.src/content/textbooks/textbooks.test.ts: schema, every lesson, diagram, practice item, video, Field Guide entry, lab and reference resolves; figure numbers recomputed; no practice answers in client payloads.
Written by
Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.
Licence
All rights reserved by the founders unless a licence is approved.
Corrections
None recorded yet.Spotted a mistake? Use “Report a problem” on any chapter, or see the corrections page.