# Worksheet: Programming foundations

*Tactiverge Academy · Embedded Systems, module 3 · https://tactiverge.win/academy/embedded-systems/#programming-foundations*

Name: ______________________    Date: ____________

## Learning objectives

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

- [ ] Describe the setup-then-loop structure of typical embedded programs.
- [ ] Use variables, conditionals and loops to respond to inputs.
- [ ] Explain why blocking delays cause problems and how to schedule tasks using elapsed time.
- [ ] Debug a program using printed messages and step-by-step reasoning.

## Lesson 1: From source code to firmware

What happens between typing C and a microcontroller running it: preprocessing, compiling, linking, memory sections, flashing and bootloaders.

Read online: https://tactiverge.win/academy/embedded-systems/programming-foundations/from-code-to-firmware/

#### Project: Break the build on purpose

Create the three files from this lesson and build them stage by stage. Then cause, and record, one error from each stage:

1. **Preprocessor:** misspell the header name in `#include "scale.h"`.
2. **Compiler:** delete a semicolon in `scale.c`.
3. **Linker:** link without `scale.o`.
4. **Warning:** declare an unused variable inside `main` and compile with `-Wall`.

For each, copy the key line of the message and write one sentence saying which stage produced it and how you could tell. Finally, run `cc -E main.c` and describe what happened to the `#include` lines.

**Deliverables**

- Four recorded messages, each labelled with the stage that produced it
- One sentence per message explaining how you identified the stage
- A short description of the preprocessor output

### Check your understanding

1. Both main.c and scale.c compile without errors, but building the program fails with "undefined reference to counts_to_mv". Which stage failed?
   A) The preprocessor
   B) The compiler
   C) The linker
   D) The bootloader

2. What is a cross-compiler?
   A) A compiler that runs on one kind of computer and produces machine code for a different kind
   B) A compiler that checks code written in two languages
   C) A tool that copies firmware into flash
   D) A compiler that only produces warnings

3. A global variable is declared as int samples[400]; with no starting value. Which section does it go in?
   A) text, in flash
   B) data, stored in flash and copied to RAM
   C) The bootloader
   D) bss, in RAM, zeroed at start-up

4. What does a bootloader do?
   A) It translates C into machine code
   B) It runs first after reset, can receive and write new firmware, and otherwise jumps to the application
   C) It converts analog voltages into numbers
   D) It checks code for warnings

### My notes

______________________________________________

______________________________________________

## Lesson 2: C types, sizes and integer overflow

Why embedded C uses fixed-width types like uint8_t and int32_t, what happens when a value no longer fits, and how to write arithmetic that stays correct.

Read online: https://tactiverge.win/academy/embedded-systems/programming-foundations/c-types-and-overflow/

#### Project: Find the limits

Write a short C99 program, compiled with `cc -std=c99 -Wall -Wextra`, that:

1. Stores 65,535 in a `uint16_t`, adds 1, and prints the result. Predict the answer first.
2. Counts milliseconds in a `uint16_t`. Calculate by hand how many seconds pass before it wraps, and how many days a `uint32_t` millisecond counter lasts.
3. Computes a 12-bit ADC reading of 4,095 times a reference of 3,300 mV, first entirely in `uint16_t` and then with a `uint32_t` cast. Print both and explain the difference.
4. Fixes the signed/unsigned comparison from this lesson so it prints `true`, without changing the values.

This is a software-only activity.

**Deliverables**

- Your program and its output
- Your hand calculations for the 16-bit and 32-bit millisecond wrap times
- One or two sentences explaining each surprising result

### Check your understanding

1. A uint8_t variable holds 200. You add 100 and store the result back in it. What does it hold?
   A) 300
   B) 255
   C) 44
   D) −56

2. Why do embedded programmers prefer int16_t or int32_t over plain int?
   A) The size of int depends on the compiler and chip, while fixed-width types are the same everywhere
   B) int cannot hold negative numbers
   C) Fixed-width types are always faster
   D) int is not part of C99

3. What does the C standard say happens when a signed int overflows?
   A) It always wraps to the most negative value
   B) It saturates at the maximum value
   C) The program always stops with an error
   D) The behaviour is undefined, so the compiler may assume it never happens

4. Which expression correctly converts a 10-bit reading counts (a uint16_t) to millivolts with a 3,300 mV reference?
   A) counts / 1024 * 3300
   B) (uint32_t)counts * 3300 / 1024
   C) (uint8_t)counts * 3300 / 1024
   D) counts * (3300 / 1024)

### My notes

______________________________________________

______________________________________________

## Lesson 3: Bitwise operations and hardware registers

Using masks and the bitwise operators to set, clear, toggle and test individual bits, and reading a datasheet's register map to control hardware.

Read online: https://tactiverge.win/academy/embedded-systems/programming-foundations/bitwise-operations-and-registers/

#### Project: Decode and encode a register by hand

Use the made-up TIMER_CTRL register from this lesson.

1. Decode these values by hand, stating PRESCALE, IRQ_EN and EN for each: 0x00, 0x31, 0x72, 0x7F. Which one breaks the datasheet's "always write 0" rule for the reserved bits?
2. Starting from 0x51, write the single C statement that sets PRESCALE to 2 without changing any other bit. What is the new value in hex?
3. Extend the program in this lesson with a function `void set_prescale(uint8_t *reg, unsigned value)` and test it with values 0, 7 and 9. What does your function do with 9, and is that what you want?

Check your hand answers by running the program.

**Deliverables**

- A decoded breakdown of the four values, with the rule-breaking value identified
- Your C statement and the resulting hex value
- The set_prescale function, its test output and a sentence on handling 9

### Check your understanding

1. reg holds 0x0F. What is reg after reg &= ~(1u << 2)?
   A) 0x0B
   B) 0x04
   C) 0x0F
   D) 0x1F

2. Which statement toggles bit 5 of reg and leaves the other bits unchanged?
   A) reg |= (1u << 5);
   B) reg = (1u << 5);
   C) reg &= (1u << 5);
   D) reg ^= (1u << 5);

3. A register reads 0x53. Its PRESCALE field occupies bits 6 to 4. What value does PRESCALE hold?
   A) 3
   B) 5
   C) 53
   D) 6

4. Why are hardware registers accessed through volatile pointers?
   A) To make them faster
   B) So that they are stored in flash
   C) So the compiler performs every read and write exactly as written, because the hardware can change or react to them
   D) Because volatile is required for all pointers in C

5. What is the difference between 6 & 1 and 6 && 1 in C?
   A) 6 & 1 is 0 (bitwise AND of 110 and 001); 6 && 1 is 1 (both values are non-zero, so logically true)
   B) There is no difference
   C) 6 & 1 is 1 and 6 && 1 is 0
   D) Both are errors

### My notes

______________________________________________

______________________________________________

## Lesson 4: Super-loops and finite state machines

How most firmware is structured as a loop that runs forever, and how a finite state machine keeps complicated behaviour clear, testable and safe.

Read online: https://tactiverge.win/academy/embedded-systems/programming-foundations/super-loops-and-state-machines/

#### Project: Design a state machine for a robot charging dock

A small mobile robot drives back to a charging dock when its stored charge is low. Design the firmware's state machine.

1. On paper, draw states such as WORKING, RETURNING, DOCKING, CHARGING and FAULT, with labelled arrows for events like "charge below 20 %", "dock in sight", "contacts touching", "fully charged" and timeouts.
2. Decide what happens if the dock is not found within 60 seconds.
3. Write `next_state` in C99 using an `enum` and `switch`, adapting the gripper example.
4. Write a scripted test in `main` with made-up inputs that exercises at least one normal charge cycle and one fault, and print every transition.

This is a paper and software activity; no hardware is needed.

**Deliverables**

- A labelled state diagram with every transition named
- Your next_state function, compiled with cc -std=c99 -Wall without warnings
- Printed transitions from your scripted test, covering a normal cycle and a fault

### Check your understanding

1. What is the most important rule for code inside a super-loop?
   A) It must use interrupts for everything
   B) Each part must finish quickly, because while one part runs every other part waits
   C) It must never read inputs
   D) It must return from main after each pass

2. Why is a single state variable better than four separate true/false flags for the gripper?
   A) Flags use more flash memory
   B) C does not support booleans
   C) Four flags allow 16 combinations, most meaningless, while one state variable allows exactly one valid situation at a time
   D) State variables are faster to read

3. In the gripper machine, what is the purpose of the CLOSING-to-FAULT timeout?
   A) To stop the gripper squeezing forever if the force target is never reached, for example because the object slipped or a sensor failed
   B) To save battery during HOLDING
   C) To make the gripper close faster
   D) To debounce the close command

4. Why is next_state written as a pure function that touches no hardware?
   A) Hardware access is not allowed inside switch statements
   B) Pure functions use less RAM
   C) It makes the code run faster on the microcontroller
   D) It can be tested on a desktop computer with scripted inputs, including rare faults, before running on real hardware

### My notes

______________________________________________

______________________________________________

## Lesson 5: Non-blocking timing and timer wrap-around

Why delay functions freeze the whole program, how to schedule several tasks by checking elapsed time, and how unsigned arithmetic handles timer wrap-around correctly.

Read online: https://tactiverge.win/academy/embedded-systems/programming-foundations/non-blocking-timing/

#### Project: Three tasks and a wrap test

Extend the two-task simulation in this lesson:

1. Add a third task that "prints a status report" every 1,000 ms. Predict how many times each task runs in 5 seconds, then run it and compare.
2. Start the pretend clock at 4,294,965,000 instead of 0 and run for 5,000 passes, so the counter wraps during the run. Confirm the counts are unchanged.
3. Change one task to the wrong test, `now >= last + interval`, and repeat step 2. Describe what goes wrong.
4. Repeat the wrap test using `uint16_t` for the clock and timestamps, with and without the `(uint16_t)` cast on the subtraction. Explain any difference.

This is a software-only activity.

**Deliverables**

- Predicted and actual run counts for all three tasks
- Output showing correct behaviour across the wrap with the good test
- Output and explanation for the wrong test and for the 16-bit experiment

### Check your understanding

1. A super-loop blinks an LED with delay_ms(1000) and also checks a stop button. What is the problem?
   A) The LED will blink too fast
   B) delay_ms uses too much RAM
   C) During each delay the button is not checked, so a press can be missed or noticed up to a second late
   D) There is no problem

2. Roughly how long does a uint32_t millisecond counter take to wrap around?
   A) About 65 seconds
   B) About 49.7 days
   C) About 136 years
   D) It never wraps

3. last = 4,294,967,000, interval = 500 and now = 4,294,967,100 (no wrap yet). Why does now >= last + interval wrongly report the task as due?
   A) last + interval wraps to 204, and 4,294,967,100 is greater than 204
   B) now is negative
   C) The interval is too short
   D) Unsigned subtraction is undefined

4. Why might you write last += interval instead of last = now after running a periodic task?
   A) It uses less memory
   B) It makes the task run less often
   C) It prevents wrap-around
   D) It keeps the schedule locked to the original timeline, so small lateness does not accumulate into drift

### My notes

______________________________________________

______________________________________________

## Lesson 6: Debugging embedded code

A systematic way to find bugs in firmware: reproduce, hypothesise and test; serial logging and LEDs as windows into the chip; divide and conquer; and the bugs that catch everyone.

Read online: https://tactiverge.win/academy/embedded-systems/programming-foundations/debugging-embedded-code/

#### Project: Bug hunt on paper

This made-up firmware fragment is meant to average eight ADC readings and turn on a warning output if the average exceeds 3,000 mV. It contains **at least four bugs** drawn from this lesson. Find them on paper first, then compile a desktop version (replacing `adc_read` with values from an array) to confirm.

```c
#define N 8
uint16_t samples[N];
int alarm_flag;                 /* also set by an interrupt handler */

void update(void) {
    uint16_t total = 0;
    for (int i = 0; i <= N; i++) {
        samples[i] = adc_read(0);
        total += samples[i];
    }
    uint16_t avg_mv = total / N / 1024 * 3300;
    if (alarm_flag = 1 || avg_mv > 3000) {
        set_warning(1);
    }
}
```

For each bug, name the category from "the usual suspects", explain what would go wrong on a real robot, and write the corrected line.

**Deliverables**

- A list of at least four bugs, each with its category and real-world effect
- Corrected code that compiles with cc -std=c99 -Wall without warnings
- A short note on how you would confirm each fix

### Check your understanding

1. Your control loop's timing problem disappears when you add a print statement, and returns when you remove it. What is the most likely explanation?
   A) The print statement fixed the bug permanently
   B) The compiler ignores print statements
   C) Serial printing takes milliseconds, which changes the loop's timing and hides the real timing bug
   D) Print statements reset the microcontroller

2. You change the sensor code, the filter and the motor gain at once, and the bug disappears. What is the problem with this approach?
   A) You cannot tell which change fixed it, or whether the other changes introduced new problems
   B) Nothing: the bug is gone
   C) Changing code is not allowed while debugging
   D) It will make the compiler produce warnings

3. A loop writes samples[i] for i from 0 to N inclusive, where samples has N elements. What can happen?
   A) The compiler always refuses to build it
   B) The extra write is ignored
   C) The microcontroller always resets immediately
   D) It writes one element past the end, silently corrupting whatever variable is stored next in RAM

4. How can a spare GPIO pin help measure how long a function takes?
   A) Set the pin high at the start and low at the end, and measure the pulse width with an oscilloscope or logic analyser
   B) Connect the pin to the reset line
   C) Read the pin as an analog input
   D) Pins cannot help with timing

5. What does a watchdog timer do?
   A) It speeds up the main loop
   B) It resets the chip if the program stops feeding it regularly, recovering from hangs
   C) It finds bugs automatically
   D) It logs every variable to flash

### My notes

______________________________________________

______________________________________________

---

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

**Lesson 1: From source code to firmware**

1. C — Each file compiled, so syntax is fine. The linker could not find a definition for a function that was declared and called, usually because an object file or library was left out.
2. A — Embedded developers compile on a laptop for a microcontroller whose instruction set is different, so they need a cross-compiler.
3. D — Globals that start at zero go in bss. They use RAM but need no flash, because start-up code simply fills them with zeros.
4. B — A bootloader lives in protected flash and lets you update firmware over USB or serial without a separate programmer.

**Lesson 2: C types, sizes and integer overflow**

1. C — uint8_t holds 0 to 255 and wraps modulo 256: 300 − 256 = 44.
2. A — int is at least 16 bits but often 32 on a laptop and 16 on small microcontrollers. Fixed-width types remove the guesswork.
3. D — Unsigned overflow is defined (it wraps); signed overflow is undefined behaviour. Use unsigned types if you need wrap-around, and keep signed arithmetic within range.
4. B — Widen to 32 bits so the product fits, and multiply before dividing so integer division does not throw the value away. 3300 / 1024 alone is 3 in integer arithmetic.

**Lesson 3: Bitwise operations and hardware registers**

1. A — 1u << 2 is 0000 0100, and ~ of that has a 0 only in bit 2. 0000 1111 AND ...1111 1011 = 0000 1011 = 0x0B: bit 2 is cleared and the others are unchanged.
2. D — XOR with 1 flips a bit and XOR with 0 leaves it alone. The other options set bit 5, overwrite the whole register, or clear every bit except bit 5.
3. B — 0x53 is 0101 0011. Bits 6..4 are 101, which is 5. In code: (0x53 & 0x70) >> 4 = 0x50 >> 4 = 5.
4. C — Without volatile, the compiler might merge, reorder or skip accesses it thinks are redundant. With hardware, every access can matter.
5. A — & compares bit by bit, and 110 and 001 share no 1 bits. && treats each whole value as true or false, and both are non-zero.

**Lesson 4: Super-loops and finite state machines**

1. B — The loop handles everything in turn. A long delay or slow calculation in one place delays every other job, including safety checks.
2. C — Contradictory flag combinations, such as closing and opening at once, become impossible when the state is a single value from a fixed list.
3. A — Timeouts turn "waiting for something that never happens" into a detectable fault, which is an important safety property.
4. D — Separating decisions from input and output means the logic can be checked thoroughly and safely, without moving any motors.

**Lesson 5: Non-blocking timing and timer wrap-around**

1. C — A blocking delay stops the whole loop. Checking elapsed time instead keeps the loop running so every task, including safety checks, gets attention.
2. B — 2^32 ms = 4,294,967,296 ms ≈ 4,294,967 s ≈ 49.7 days. A 16-bit counter would wrap after about 65.5 seconds.
3. A — The sum exceeds the 32-bit range and wraps to a small number. The elapsed-time form, now − last = 100, correctly says the task is not yet due.
4. D — With last = now, each late check pushes every later run later. Adding the interval keeps runs at fixed multiples of the interval.

**Lesson 6: Debugging embedded code**

1. C — Logging is not free. A 40-character line at 115,200 baud takes about 3.5 ms, enough to change the behaviour you are trying to observe.
2. A — Changing one thing at a time is what turns a fix into knowledge. Otherwise the cause stays unknown and may return.
3. D — C does not check array bounds. The write lands on neighbouring memory, causing strange bugs in unrelated variables.
4. A — A pin change costs only a few clock cycles, so it measures timing with very little disturbance, unlike serial logging.
5. B — A watchdog is a safety net, not a fix. Logging a message at each boot tells you when it has had to step in.

---

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.
