# Capstone: Firmware for a smart gripper, tested on your computer

*Tactiverge Academy · about 16 hours*

Write and test the firmware logic for a force-sensing gripper as a portable program on your own computer: a state machine, a calibrated and filtered sensor pipeline, non-blocking timing and a checksummed message protocol.

## Why this project

Embedded firmware is where software meets the physical world, and mistakes there can squeeze, overheat or break things. Professional teams therefore test as much of the logic as possible **off the hardware**, on an ordinary computer, before it ever runs on a microcontroller. In this capstone you will do exactly that for a small robot gripper with a force sensor.

You will write the decision logic, the sensor pipeline and the communication protocol as **pure functions** that do not touch hardware. A small test program will feed them a made-up script of sensor readings and commands and check that they behave correctly. You can write it in portable C99 (compiled with a free compiler using `cc -std=c99 -Wall`) or in Python. Both are fine; C is closer to real firmware.

## The gripper you are designing for

Imagine a gripper with one actuator that opens and closes the fingers, a force sensor in one fingertip read through a 10-bit analog-to-digital converter, an "open" limit switch, and a serial link to a host computer. All of this is imaginary. Your program simulates every input.

## What you will build

### 1. A state machine

Design the gripper's behaviour as a finite state machine on paper first: at least the states `IDLE`, `CLOSING`, `HOLDING`, `OPENING` and `FAULT`. Every arrow needs a label, and every state must say what happens to unexpected events. Include a timeout: if `CLOSING` lasts too long without reaching the target force, go to `FAULT` and stop driving the actuator. Then implement it as a pure `next_state` function.

### 2. A sensor pipeline

Write the chain that turns a raw ADC count into a trustworthy force:

1. Convert counts to volts using the reference voltage and resolution.
2. Apply a two-point calibration (offset and gain) from two made-up reference readings, labelled as made-up.
3. Filter with an exponential low-pass filter, and measure the lag it adds.
4. Reject implausible values: out-of-range readings, sudden impossible jumps and a sensor that stops updating (a timeout).

Decide what the state machine should do when the pipeline reports the sensor as invalid, and justify it.

If you use C, do the force maths in **fixed-point** integers, not floating point, and show one case where a careless choice of type would overflow.

### 3. Non-blocking timing

Your main loop must never call a blocking delay. Schedule the sensor read, the state machine and the status message at different rates using elapsed-time checks. Show that your timing code still works when the millisecond counter wraps around: in C, use a `uint32_t` counter and start your test just before it wraps.

### 4. A message protocol

Design a tiny binary protocol for commands (open, close with target force, request status) and replies (state, filtered force, fault code). A frame might look like this:

```text
START(0xAA) | LENGTH | TYPE | PAYLOAD ... | CHECKSUM
```

Write an encoder and a byte-by-byte decoder that can resynchronise after garbage, reject a frame with a bad checksum, and ignore an unknown message type safely. Include a version number and explain why.

### 5. Tests

Write test cases that run automatically and print PASS or FAIL. At minimum: a normal grasp, a grasp that times out, a sensor that freezes, a corrupted frame, and the counter wrap. Each test should be a short scripted list of inputs with expected states.

## What good work looks like

Good firmware is boring to read: small functions, named states, no magic numbers, and tests that would catch the bugs you are most afraid of. Your write-up should explain one bug you found by testing and how you would have found it on real hardware instead (for example, serial logging or toggling a pin).

## Optional: run it on real hardware

If you already have a low-voltage microcontroller board, you may port the logic and replace the simulated inputs with a push button (as the "force" input) and an LED (as the actuator output) on a breadboard. This is entirely optional and earns no extra marks on its own. Follow the safety guidance and do not connect a motor.

## Milestones

1. **State machine on paper.** A complete diagram with at least five states, labelled transitions, a timeout and a defined response to unexpected events in every state.
2. **Pure state-machine function and first tests.** next_state implemented with no hardware access, and passing tests for a normal grasp and a timeout.
3. **Sensor pipeline.** Counts-to-volts conversion, two-point calibration, exponential filter with measured lag, and plausibility checks for range, jumps and timeouts.
4. **Non-blocking scheduler.** Three tasks at different rates using elapsed-time checks, with a test that passes across a counter wrap-around.
5. **Message protocol.** Encoder and resynchronising decoder with checksum and version field, tested against a corrupted frame and an unknown type.
6. **Test suite and write-up.** All tests run automatically and print PASS or FAIL; the write-up explains one bug found by testing.

## Deliverables

- Source code in portable C99 or Python with the state machine, sensor pipeline, scheduler and protocol in separate, commented functions.
- A photo or scan of the state-machine diagram drawn on paper before coding.
- An automatic test program covering at least five scenarios, with its output pasted into the report.
- A one-page protocol specification: frame layout, message types, checksum method, version field and error handling.
- A 2–3 page write-up explaining design decisions, the invalid-sensor policy and one bug found by testing.

## Safety

The project is designed to be completed entirely in software. If you choose the optional hardware port, work only with adult supervision, use a low-voltage board powered from USB or a small battery pack (5 V or less), never connect anything to mains, and do not connect a motor. Always use a current-limiting resistor with an LED, disconnect power before changing wiring on the breadboard, and stop immediately if anything gets warm or smells hot.

## Rubric

### State machine design

- **Beginning:** Behaviour is a tangle of flags and conditions with no clear states.
- **Developing:** States are named, but some transitions are missing or unexpected events are not handled.
- **Proficient:** Five or more states with every transition labelled, a working timeout to FAULT, and the actuator off in FAULT.
- **Exemplary:** As Proficient, plus the logic is a pure function and the diagram and code match exactly, with a test for every transition.

### Sensor pipeline quality

- **Beginning:** Raw counts are used directly as force.
- **Developing:** Conversion and calibration are present but filtering or plausibility checks are missing.
- **Proficient:** Conversion, two-point calibration, a filter with measured lag, and range, jump and timeout checks all work and are tested.
- **Exemplary:** As Proficient, plus the filter constant is chosen by reasoning about the lag-versus-noise trade-off, and (in C) the maths is in fixed point with an overflow case shown and avoided.

### Timing and robustness

- **Beginning:** The loop uses blocking delays.
- **Developing:** Elapsed-time scheduling is used but wrap-around is not handled or tested.
- **Proficient:** Three tasks run at different rates with no blocking, and a test shows correct behaviour across counter wrap-around.
- **Exemplary:** As Proficient, plus the student explains what happens to each task if one task overruns and how they would detect it.

### Protocol design

- **Beginning:** Messages are plain text with no framing or error check.
- **Developing:** Frames have a start byte and length but no checksum, or the decoder cannot resynchronise.
- **Proficient:** Checksum, length and version are included; the decoder resynchronises after garbage and rejects bad frames, all tested.
- **Exemplary:** As Proficient, plus the specification states the protocol's limits, such as which errors a simple checksum cannot detect.

### Testing and communication

- **Beginning:** No automated tests; correctness is asserted, not shown.
- **Developing:** Some tests exist but must be checked by eye or cover only the normal case.
- **Proficient:** At least five automatic tests including failure cases; the write-up explains one real bug found by testing.
- **Exemplary:** As Proficient, plus tests were written before or alongside the code and the write-up explains how the same bug would be found on real hardware.

## Going further

Add a second, independent safety check that does not trust the state machine: a watchdog-style function that forces the actuator output off if the force estimate exceeds a hard limit or if the main loop stops calling it within a time limit. Write tests showing it still protects the gripper when you deliberately break the state machine.

---

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.
