# Worksheet: Microcontrollers

*Tactiverge Academy · Embedded Systems, module 2 · https://tactiverge.win/academy/embedded-systems/#microcontrollers*

Name: ______________________    Date: ____________

## Learning objectives

Tick each one when you can do it without looking at your notes.

- [ ] Identify the main parts of a microcontroller: processor core, memory, clock and peripherals.
- [ ] Compare microcontrollers with general-purpose computers in cost, power and capability.
- [ ] Explain the role of general-purpose input/output pins.
- [ ] Describe how a program is stored and run after power-up.

## Lesson 1: Inside a microcontroller

The processor core, flash, RAM, peripherals and clock packed onto one small chip, what happens when it powers up, and how it differs from the computer on your desk.

Read online: https://tactiverge.win/academy/embedded-systems/microcontrollers/inside-a-microcontroller/

#### Project: Paper project: a memory and time budget

Imagine a microcontroller with **32 KB of flash**, **2 KB of RAM** (2,048 bytes) and a **16 MHz** clock. You want to store the last 500 force readings, each a 2-byte number, so you can send them to a laptop later.

1. How many bytes of RAM does the buffer need? What fraction of RAM is that?
2. Engineers like to keep spare RAM for the stack and other variables. Would you be comfortable with this design? What would you change if you needed 2,000 readings?
3. You sample at 500 readings per second. How many clock cycles are available between readings?

Show every step and its units.

**Deliverables**

- The RAM calculation with units and the fraction of RAM used
- A short judgement on whether the design leaves enough margin, with one alternative
- The number of clock cycles between readings

### Check your understanding

1. Your program's code must still be there after the power is switched off and on again. Where is it stored?
   A) RAM
   B) Flash memory
   C) The CPU's registers
   D) The clock

2. A microcontroller runs at 8 MHz. How long is one clock cycle?
   A) 8 ns
   B) 80 ns
   C) 125 ns
   D) 1.25 µs

3. What does memory-mapped I/O mean?
   A) Peripherals are controlled by reading and writing special addresses, called registers
   B) The program is copied from RAM to flash at start-up
   C) The microcontroller stores a map of the room
   D) Every pin has its own small CPU

4. Why do many robots use a microcontroller for motor control even when they also carry a powerful single-board computer?
   A) Microcontrollers are always faster than single-board computers
   B) Single-board computers cannot run C programs
   C) Microcontrollers have more RAM
   D) Microcontrollers give predictable timing and direct hardware access, without an operating system interrupting

5. What happens first when a microcontroller comes out of reset?
   A) It waits for a user to press start
   B) It reads the reset vector to find the start-up code, which eventually calls main
   C) It downloads its program from the internet
   D) It runs main, then shuts down when main returns

### My notes

______________________________________________

______________________________________________

## Lesson 2: Digital input and output with GPIO

Configuring general-purpose pins as outputs or inputs, driving an LED safely, reading a switch, and respecting the current limits that keep a chip alive.

Read online: https://tactiverge.win/academy/embedded-systems/microcontrollers/digital-input-and-output/

#### Project: Calculate LED resistors, then try it in a simulator or on the bench

Using R = (V_supply − V_LED) / I, calculate the series resistor for each case, round up to the next standard value from this list (100, 150, 220, 270, 330, 470, 680, 1000 Ω) and recompute the actual current:

1. 5.0 V supply, red LED at 2.0 V, target 10 mA.
2. 3.3 V supply, green LED at 2.2 V, target 5 mA.
3. 3.3 V supply, white LED at 3.0 V, target 3 mA.

Then write, on paper or in a free online microcontroller simulator, a program using the illustrative GPIO functions that turns on case 1's LED only while a switch input reads 1. If you build it for real, use only a USB-powered board and the resistor you calculated.

**Deliverables**

- Three resistor calculations with chosen standard values and actual currents
- A short comment on why case 3 leaves so little headroom
- Your input-to-output program, with every pin configured before use

**Safety (adult supervision required):** Real-hardware steps must be done with adult supervision, using only a USB-powered or 5 V-or-less board. Always include the series resistor, disconnect power before changing any wiring, and unplug immediately if a part becomes hot.

### Check your understanding

1. Why can an unconnected (floating) input pin read random values?
   A) It draws so little current that stray electric fields can push its voltage either way
   B) The CPU is too slow to read it
   C) Input pins always output a square wave
   D) Floating inputs are permanently stuck at 1

2. A 5 V pin drives a red LED (forward voltage 2.0 V) at a target of 10 mA. What resistance do you calculate?
   A) 200 Ω
   B) 500 Ω
   C) 300 Ω
   D) 700 Ω

3. When choosing a standard resistor value, why round the resistance up rather than down?
   A) Larger resistors are cheaper
   B) More resistance means slightly less current, which keeps the LED and pin within limits
   C) The LED will be brighter
   D) Rounding down is not allowed by Ohm's law

4. You want a microcontroller to switch a small DC motor on and off. What is the correct approach?
   A) Connect the motor directly to a GPIO output pin
   B) Use two GPIO pins in parallel to double the current
   C) Connect the motor to an input pin instead
   D) Use the GPIO pin to control a transistor or motor driver that switches a separate supply

### My notes

______________________________________________

______________________________________________

## Lesson 3: Buttons, pull-up resistors and debouncing

Why a button needs a pull-up or pull-down resistor, how active-low logic works, and how to turn a bouncing mechanical contact into one clean press in software.

Read online: https://tactiverge.win/academy/embedded-systems/microcontrollers/buttons-pullups-debouncing/

#### Project: Experiment with the debouncer

Copy the debouncer program above into a file, compile it with `cc -std=c99 -Wall` and run it. Then experiment:

1. Change `STABLE_MS` to 2. Predict how many presses will be detected, then run it and explain the result.
2. Change it to 12. What happens now, and why?
3. Edit `debounce_update` so it also reports releases (for example by returning 2 for a release). Print both events.
4. Write your own bouncing sample array for a *double* press, two quick presses about 40 ms apart, and check that your chosen `STABLE_MS` separates them.

This is a software-only activity: no hardware is needed.

**Deliverables**

- Your predictions and actual outputs for STABLE_MS = 2 and 12, with explanations
- The modified function that reports releases
- Your double-press test data and its output

### Check your understanding

1. A button connects a pin to ground, with a 10 kΩ pull-up resistor to 3.3 V. What does the pin read while the button is released?
   A) 0, because the button is open
   B) 1, because the resistor holds the pin near 3.3 V
   C) A random value, because the pin is floating
   D) Half of 3.3 V, which reads as neither

2. Why not use a 10 MΩ pull-up resistor to save even more current?
   A) The pull would be so weak that leakage and noise could drag the pin to the wrong level
   B) It would short the supply to ground
   C) It would make the button active-high
   D) Large resistors cannot be used with microcontrollers

3. A counter increases by 4 every time a button is pressed once. What is the most likely cause?
   A) The pull-up resistor is too small
   B) The clock is too slow
   C) Contact bounce
   D) The pin is configured as an output

4. In the software debouncer, what must happen before a new level is accepted?
   A) The button must be pressed twice
   B) The CPU must be reset
   C) The interrupt must fire
   D) The raw level must stay unchanged for STABLE_MS consecutive samples

### My notes

______________________________________________

______________________________________________

## Lesson 4: Timers and pulse-width modulation

How hardware timers count clock pulses to measure time, and how pulse-width modulation uses fast on–off switching to dim LEDs and control motor speed.

Read online: https://tactiverge.win/academy/embedded-systems/microcontrollers/timers-and-pwm/

#### Project: Design two PWM signals on paper

Using frequency = clock / prescaler / (top + 1) and a 16 MHz clock:

1. **LED dimmer.** Choose a prescaler from 1, 8, 64, 256 or 1024, and a top value no greater than 255, that gives a frequency between 200 Hz and 2 kHz. Work out the compare value for 40 % duty and the average voltage on a 3.3 V pin.
2. **Motor driver.** Find a prescaler and top value that give a frequency within 5 % of 20 kHz. How many distinct duty-cycle steps does your choice allow? Explain the trade-off between frequency and resolution.
3. Optional: modify the C program in this lesson to check your answers.

This activity is calculation only. If you later try it on a real board, follow the safety text.

**Deliverables**

- Prescaler, top value, frequency, compare value and average voltage for the LED dimmer
- Prescaler, top value, frequency and number of duty steps for the motor signal
- Two or three sentences explaining the frequency–resolution trade-off

**Safety (adult supervision required):** Any real-hardware follow-up must be done with adult supervision, using a USB-powered board at 5 V or less. Drive LEDs through a series resistor, and drive any motor only through a proper motor driver with its own low-voltage supply, never directly from a pin. Keep fingers clear of moving parts and disconnect power before changing wiring.

### Check your understanding

1. A 5 V PWM signal has a duty cycle of 60 %. What is its average voltage?
   A) 0.6 V
   B) 2.0 V
   C) 3.0 V
   D) 5.0 V

2. What does a timer's prescaler do?
   A) It divides the clock so the counter ticks more slowly, extending its range
   B) It sets the PWM duty cycle
   C) It stops the CPU while the timer runs
   D) It converts analog voltages to numbers

3. A timer with a 16 MHz clock, a prescaler of 8 and a top value of 99 produces PWM at what frequency?
   A) 2 kHz
   B) 200 kHz
   C) 160 kHz
   D) 20 kHz

4. Why do many motor drivers use a PWM frequency around 20 kHz?
   A) Motors only work above 20 kHz
   B) It is near the upper limit of human hearing, so the motor's whine becomes inaudible
   C) It gives the finest possible duty-cycle resolution
   D) Lower frequencies cannot change speed

### My notes

______________________________________________

______________________________________________

## Lesson 5: Interrupts and event-driven code

How interrupts let a microcontroller react to events the moment they happen, why handlers must be short, and how volatile and critical sections keep shared variables safe.

Read online: https://tactiverge.win/academy/embedded-systems/microcontrollers/interrupts/

#### Project: Paper trace: find the lost update

Draw a timeline with two rows, **main** and **handler**. The handler does `count = count + 1`. The main program does `count = count - 5` (it has just processed five events). On this chip, each of those lines compiles into three steps: *load* count into a register, *change* the register, *store* it back.

1. Start with count = 10. Trace the case where the handler fires *between* main's load and main's store. What is the final value? What should it be?
2. Find a second interleaving that gives a different wrong answer, or explain why there is none.
3. Rewrite main's line using a critical section, and show on your timeline that the problem disappears.

No hardware is needed for this activity.

**Deliverables**

- A labelled two-row timeline for the faulty interleaving and its final value
- Your answer to question 2 with reasoning
- The corrected code and a timeline showing it working

### Check your understanding

1. Which of these belongs inside an interrupt handler?
   A) A 100 ms delay so the button can settle
   B) Printing a long message over the serial port
   C) Setting a flag and incrementing a counter
   D) Recalculating the robot's whole path

2. Why must a variable shared between a handler and the main loop be declared volatile?
   A) So the compiler reads it from memory every time instead of reusing a cached copy
   B) So it is stored in flash
   C) So the interrupt fires faster
   D) So the variable can never change

3. An 8-bit chip reads a 16-bit counter one byte at a time. The counter is 0x00FF, and an interrupt increments it between reading the low and high bytes. What value is assembled?
   A) 0x00FF
   B) 0x0100
   C) 0x0000
   D) 0x01FF

4. When is simple polling a perfectly reasonable choice?
   A) When events are slow compared with how often the loop checks
   B) Never: interrupts are always better
   C) When the event lasts much less time than one pass of the loop
   D) When the variable is volatile

### My notes

______________________________________________

______________________________________________

## Lesson 6: Analog-to-digital conversion

How an ADC turns a voltage into a number: resolution, reference voltage, sampling and quantisation, and how to convert counts back into volts correctly.

Read online: https://tactiverge.win/academy/embedded-systems/microcontrollers/analog-to-digital-conversion/

#### Project: Build an ADC conversion table

Using the program in this lesson as a starting point, write a C or Python program that:

1. Prints the step size in millivolts for 8-, 10- and 12-bit ADCs with a 3.3 V reference.
2. Converts a list of 10-bit readings, (0, 100, 230, 620, 1023), to millivolts, and then to temperature using the made-up sensor in this lesson (500 mV at 0 °C, 10 mV per °C).
3. Repeats step 2 assuming the reference has sagged to 3.1 V while the code still assumes 3.3 V. How many degrees of error does that cause at a reading of 230?

This is a software-only activity.

**Deliverables**

- Step sizes for the three resolutions
- A table (printed by your program) of counts, millivolts and temperature
- The temperature error caused by the sagging reference, with a sentence explaining it

### Check your understanding

1. How many distinct codes does a 12-bit ADC have?
   A) 12
   B) 1,024
   C) 4,096
   D) 65,536

2. A 10-bit ADC with a 5.0 V reference reads 256. What is the input voltage, approximately?
   A) 1.25 V
   B) 2.56 V
   C) 0.5 V
   D) 5.0 V

3. Why does the conversion code compute counts × V_ref before dividing by 1,024?
   A) Multiplication is always faster than division
   B) Dividing first would make the result negative
   C) The ADC requires it
   D) With integers, dividing first throws away the fractional part and loses almost all precision

4. A robot's ADC readings all jump whenever its motors start, even though the sensor output has not changed. What is the most likely cause?
   A) The ADC's resolution is too high
   B) The supply voltage, used as the ADC reference, sags under the motor current
   C) Quantisation error always increases with motor speed
   D) The sample rate is exactly right

5. What is quantisation error?
   A) The rounding that occurs because every voltage within one step gives the same code
   B) Damage caused by exceeding the input range
   C) An error caused by reading the wrong pin
   D) A delay between sampling and conversion

### My notes

______________________________________________

______________________________________________

---

## Answer key (for self-checking after you try)

**Lesson 1: Inside a microcontroller**

1. B — Flash is non-volatile, so it keeps the program without power. RAM and registers are volatile and lose their contents at power-off.
2. C — 1 / 8,000,000 Hz = 0.000000125 s = 125 ns. Faster clocks give shorter cycles.
3. A — Writing to a peripheral's register address changes the hardware, such as setting a pin high. Reading a register reports its state. The datasheet lists the addresses and bits.
4. D — A motor loop needs to run on time, every time. A bare-metal microcontroller is deterministic, while a full operating system may pause your program to do other work.
5. B — The reset vector points to start-up code that prepares RAM and then calls main. Embedded programs normally loop forever rather than returning.

**Lesson 2: Digital input and output with GPIO**

1. A — An input has very high impedance, so almost nothing holds its voltage in place. Nearby wires or your hand can move it across the threshold.
2. C — R = (5.0 − 2.0) / 0.010 = 3.0 / 0.010 = 300 Ω. You would then choose the next standard value up, such as 330 Ω.
3. B — I = V / R, so a larger R gives a smaller current. Rounding up errs on the safe side.
4. D — Motors need far more current than a pin can supply, and their coils create voltage spikes when switched off. A driver handles the power; the pin only sends the control signal.

**Lesson 3: Buttons, pull-up resistors and debouncing**

1. B — With the button open, almost no current flows, so almost no voltage drops across the resistor. The pin sits near the supply and reads 1. Pressing pulls it to 0: active-low.
2. A — A very large resistor barely holds the pin at the supply voltage, so tiny currents and noise can move it. A few kilohms to about 100 kΩ is the usual range.
3. C — The contacts chatter when they meet, producing several quick transitions. Debouncing turns them into one press.
4. D — Any change restarts the count. Only a level that stays steady for the whole stable time is treated as real, so short bounce spikes are ignored.

**Lesson 4: Timers and pulse-width modulation**

1. C — V_average = duty × V_high = 0.60 × 5 V = 3.0 V.
2. A — A prescaler of 64 means the counter advances once every 64 clock cycles. That gives a longer range but coarser ticks.
3. D — 16,000,000 / 8 / (99 + 1) = 2,000,000 / 100 = 20,000 Hz = 20 kHz.
4. B — PWM at audible frequencies makes motor coils whine. Around 20 kHz the sound is above most people's hearing, though higher frequencies increase driver switching losses.

**Lesson 5: Interrupts and event-driven code**

1. C — Handlers block the main program and often other interrupts, so they should do the minimum and return. Slow work belongs in the main loop.
2. A — Without volatile, the compiler may assume nothing in the loop changes the variable and keep it in a register, so the handler's update is never seen.
3. D — The low byte read before the change is 0xFF; the high byte read after it is 0x01. Combined, 0x01FF = 511, a value the counter never held. A critical section prevents it.
4. A — Polling is simple and predictable. If the loop checks far more often than events happen, and each event lasts longer than a loop pass, nothing is missed.

**Lesson 6: Analog-to-digital conversion**

1. C — An N-bit ADC has 2^N codes: 2^12 = 4,096, numbered 0 to 4,095.
2. A — V = 256 × 5.0 / 1024 = 1.25 V. 256 is a quarter of 1,024, so the voltage is a quarter of the reference.
3. D — For example, 230 / 1024 is 0 in integer arithmetic, so 0 × 3300 = 0. Multiplying first gives 759,000 / 1024 = 741 mV.
4. B — If V_ref is the supply and the supply drops, the same input voltage becomes a larger fraction of V_ref, so the code changes. A stable dedicated reference avoids this.
5. A — The ADC can only report whole codes, so the true voltage can be up to about half a step away from what the code represents.

---

This work is licensed under the Creative Commons Attribution 4.0 International licence (CC BY 4.0): https://creativecommons.org/licenses/by/4.0/. Attribute as: Tactiverge Academy, https://tactiverge.win.
