TactivergeLite

Lite / Textbooks / Electrical and Embedded Systems / Chapter 5

5. Inside a microcontroller

Version 1 · Technically checked (automated checks only) · 5 source lessons · Full interactive version

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.

Figure 5.1. Divide the clock, count the ticks (described in words)

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

Built from 5 School lessons. Each part is the lesson's own explanation.

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

Open the Lite 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

Open the Lite 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

Open the Lite 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

Open the Lite 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

Open the Lite 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, in words

Figure 5.2 from Counting in nanoseconds

Choose 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.

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 forever

Choose '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.

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.

The interactive versions are in the full chapter.

Laboratory

These run in a browser on the full site (they need a faster connection). Simulations are simplified educational models.

Practice

Each question links to its Lite lesson, where your answer is checked on our server and a wrong answer gets a hint. Answers are never sent to your device.

  1. A variable counting button presses is lost every time the device is switched off. Which memory is it stored in?
    Answer it in “A whole computer on one chip”
  2. A microcontroller's clock runs at 160 MHz. How long is one clock period, in nanoseconds?
    Answer it in “A whole computer on one chip”
  3. A 16 MHz microcontroller needs about 4 clock cycles per instruction on average. Roughly how many instructions can it run in 1 ms?
    Answer it in “Counting in nanoseconds”
  4. Where should 'set pin 3 as an output' go?
    Answer it in “Set up once, loop forever”
  5. A timer counts at 16 MHz divided by a prescaler of 1. How many ticks does it count in 20 ms?
    Answer it in “Timers: hardware that counts for you”
  6. A 16-bit timer counts at 16 MHz ÷ 256. How long until it overflows, in seconds? (Give 3 decimal places.)
    Answer it in “Timers: hardware that counts for you”
  7. A loop calls `delay(1000)` once per pass. What is the main problem when you add a safety button?
    Answer it in “Doing several things at once (without waiting)”
  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?
    Answer it in “Doing several things at once (without waiting)”

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)

Streaming video uses a lot of data. Everything you need is in the text.

Summary

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. Field Guide
Clock speed, cycles and CPI
Execution time equals the number of instructions times the average cycles per instruction (CPI) divided by the clock frequency. Field Guide
Registers
Registers are a small number of very fast storage locations inside the processor that hold the values it is working on right now. Field Guide
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. 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

Write it up on paper or in your own notes. Lite never stores what you write.

References

← 4. Power, energy and batteries6. Pins, inputs and sensors →