flowchart TB
subgraph pi["Raspberry Pi"]
backend["FastAPI backend"]
end
subgraph pico["Raspberry Pi Pico — RP2040"]
subgraph c0["Core 0 — protocol"]
parse["line parser<br/>validate, answer OK / ERR"]
emit["telemetry writer<br/>POS · ADC · EVT · VER"]
end
queue[["command queue<br/>(under g_state_mutex)"]]
flags[["result flags<br/>homing · scan · jog timeout"]]
subgraph c1["Core 1 — motion, 1 ms tick"]
tick["endstop debounce<br/>velocity profile<br/>block feeding"]
exec["command execution<br/>HOME · SCAN blocking"]
end
subgraph pioblk["PIO0 — three state machines"]
sm0["SM0 → AZ STEP"]
sm1["SM1 → EL STEP"]
sm2["SM2 → POL STEP"]
end
adc["ADC0 + ping-pong DMA<br/>500 kHz, 2 × 2000 samples"]
end
drivers["3 × DRV8825"]
backend -->|"UART0, 115200 8N1, ASCII"| parse
emit -->|"UART0"| backend
parse --> queue --> exec
exec --> tick
tick -->|"32-bit block descriptor<br/>(half_period, step_count−1)"| sm0
tick --> sm1
tick --> sm2
sm0 -.->|"completion IRQ"| tick
sm1 -.-> tick
sm2 -.-> tick
sm0 --> drivers
sm1 --> drivers
sm2 --> drivers
exec --> flags --> emit
adc --> emit
Real-Time Motion on the RP2040
Somewhere between “point the dish at Cassiopeia A” and a stepper motor turning, a decision has to be made about the next pulse — and it has to be made on time, every time. That is the job of the motor-controller firmware: a small C program on a Raspberry Pi Pico that owns the three axes of the mount and answers to a single ASCII protocol over a serial line.
This article is about how that program is built: why the work is split across two processor cores and a programmable I/O block, how a trapezoidal velocity ramp is produced without a single timer interrupt, why homing deliberately steps backwards out of the hardware it uses for everything else, and how a firmware that needs a microcontroller, three motor drivers and a satellite dish is nevertheless tested on an ordinary laptop.
About This Page
The firmware lives in firmware/pico_motor/ and is about 4,240 lines of C and headers, plus a separate 100-line PIO assembly program. It is the lowest software layer of the Smart Radio Telescope: everything above it — the Raspberry Pi backend, the protocol gateways, the browser control station, the phone app — eventually turns into lines of text arriving on this program’s serial port.
- Rebuilding it? The Reference section at the end has the pin map, every motion constant, the complete command set and the build commands, all taken from the firmware itself.
- Interested in the design? Design Decisions collects the choices that could plausibly have gone the other way, with the reason each one did not.
- Wondering what has actually been proven on hardware? The Status section says so, with dates and links to the test logs.
- Related parts of the series: the project overview puts this layer in context, and the mount and the antenna describes the machine these pulses actually move — including where the step-to-degree calibration below comes from.
Reading it front to back assumes no knowledge of the RP2040, but it does assume you are comfortable with the general idea of a stepper motor: a motor that moves in discrete increments, one per pulse on a STEP line, in a direction given by a DIR line.
Why the Mount Has Its Own Processor
The Raspberry Pi could drive the motors directly. It has the pins, and Linux has libraries for exactly this. The reason it does not is that Linux gives no promise about when a program runs. A step pulse that arrives 20 ms late is not a slightly worse pulse; on an accelerating axis it is a missing pulse, and a missing pulse is permanent position error, because a stepper motor has no idea where it is.
So the system is split at the point where the deadlines start:
- The Raspberry Pi does everything that needs a clock, a catalogue, a network or a filesystem: coordinate transformations, tracking, the web API, the gateways. It has no deadlines tighter than a human can notice.
- The Pico does everything with a deadline. It has exactly one job and no operating system to get in the way of it.
The seam between them is a UART running an ASCII line protocol at 115200 baud. That is a deliberately unfashionable choice, and it earns its place: a serial line with a text protocol can be driven from a terminal, logged verbatim, replayed from a file, and simulated by a Python script — all of which the project does, and all of which are covered later on this page.
Two Cores and a State Machine
The RP2040 has two Cortex-M0+ cores. The firmware uses both, and it uses them for an unusually clean division of labour.
Core 0 talks. Core 1 moves.
Core 0 owns the UART. It parses incoming lines, validates them, answers OK or ERR immediately, and pushes accepted motion commands into a queue. It also emits all outgoing telemetry: a POS status line once per second, the radio signal reading, asynchronous events. Core 0 is the sole writer of the serial port — nothing else in the firmware is allowed to print.
Core 1 owns the motion. It runs a loop with a 1 ms cadence that services the three axes: debouncing endstop switches, computing the next speed for each axis, and feeding the pulse generator. It pops commands from the queue and executes them. It never writes to the UART; when it has something to report — a completed homing run, a scan that finished, a watchdog that fired — it sets a flag, and Core 0 turns that flag into a line of text.
Underneath both of them sits the RP2040’s PIO: two blocks of four small programmable state machines, independent of the CPU cores, with their own instruction set and their own view of the pins. The firmware loads one ten-instruction program into PIO0 and runs three of that block’s four state machines on it, one per axis. The state machines are what actually make the pulses.
The two cores share a handful of variables — the axis state, the command queue — behind a single mutex. Critical sections are deliberately tiny: a position snapshot for the UART is about 5 µs, a queue push or pop about 1 µs. The 1 ms motion computation itself happens outside the lock.
A few pieces of cross-core state skip the mutex entirely, and the code says why each one may: a bool or a word written by one core and read by the other is a single aligned store on a Cortex-M0+, so a stop request or a “homing finished” result needs no lock. The rule the firmware holds itself to is that anything compound — the queue indices, the position and its moving flag together — is always locked, and anything lockless is a single scalar with exactly one writer.
Making Pulses in the PIO
A step pulse is not complicated: drive STEP high for a while, drive it low for a while, repeat. What makes it hard is doing it while also doing everything else, at rates up to 1600 pulses per second per axis, on three axes at once, with the interval changing continuously during acceleration.
The PIO makes this almost boring. The program is a loop that reads one 32-bit word from a FIFO and then produces a burst of pulses:
bits [31:16] half_period — PIO clock cycles per half pulse
bits [15: 0] step_count−1 — number of pulses, minus one
The state machine unpacks the two fields, then loops: drive STEP high and burn half_period cycles, drive STEP low and burn half_period cycles, decrement the pulse counter, repeat. When the count runs out it raises an interrupt flag and stalls on the next FIFO read, leaving STEP low. The pin is driven by the PIO’s side-set mechanism, so the level changes as part of the same instruction that does the counting — no separate write, no jitter.
Two details in that encoding are worth pulling out, because both are the kind of thing that produces a bug exactly once.
The pulse count is stored minus one. The loop ends with jmp y-- step_loop, a post-decrement test, so loading Y = K produces K + 1 pulses. To emit exactly N pulses the CPU writes N − 1. The PIO source says so, the C code that packs the word says so, and a host test pins it.
The clock is divided by 16. The half-period field is 16 bits. At the RP2040’s 125 MHz system clock, the slowest speed the firmware uses — 80 steps per second — would need a half-period of 781,250 cycles, which does not fit. Dividing the state-machine clock by 16 gives an effective 7,812,500 Hz, and at that rate the whole speed range fits comfortably:
| Speed | Half-period in effective cycles | Fits in 16 bits? |
|---|---|---|
| 80 steps/s (slowest) | 48,828 | yes |
| 320 steps/s (homing fast approach) | 12,207 | yes |
| 1600 steps/s (cruise) | 2,441 | yes |
The three state machines share one copy of the program, loaded once at a single offset; the SDK assigns each one its own side-set pin at initialisation. When a state machine finishes a block it raises a relative interrupt, which lands on the flag whose index equals the state-machine index — SM0 on flag 0, SM1 on flag 1, SM2 on flag 2. Core 1 polls those three flags in its 1 ms loop. There is no interrupt handler for motion at all; the polling loop is the whole mechanism.
The Trapezoidal Profile, One Block at a Time
Starting a stepper motor at full speed does not work: the rotor cannot follow, and the axis buzzes without turning. The firmware therefore ramps: start slow, accelerate to cruise, cruise, decelerate, stop. The classical shape is a trapezoid.
What makes the implementation interesting is that the firmware never computes a smooth ramp. It computes one speed per block — a chunk of at most PIO_BLOCK_STEPS = 25 steps — and the ramp emerges as a staircase.
The speed for a block is a straight interpolation over the axis’s ramp length (*_ACCEL_STEPS = 200 steps), and deceleration wins over acceleration whenever both apply:
accel_frac = min(steps_in_motion, ramp);
decel_frac = min(steps_remaining, ramp);
frac = min(accel_frac, decel_frac);
sps = MIN_SPEED_SPS + (v_span * frac) / ramp;With a 200-step ramp and 25-step blocks, that yields eight discrete levels on the way up, each 190 steps per second above the last:
The mechanism that turns this into motion is a two-line contract between Core 1 and the PIO. Core 1 pushes one block descriptor, sets a “busy” flag, and returns. On a later pass through the 1 ms loop it finds the state machine’s completion flag raised, clears it, credits the block’s steps to the position counter, and computes the next speed. At 1600 steps per second a 25-step block lasts about 15.6 ms, so the axis spends the overwhelming majority of its time with a block in flight and Core 1 idle; the gap between one block finishing and the next being pushed is under a millisecond.
That gap is the price of the design, and it is where the trade-off sits. Smaller blocks give a finer ramp and more gaps; larger blocks give smoother cruise and a coarser ramp. The ramp length itself was cut to a quarter of its original 800 steps in July 2026 for snappier moves, and made per-axis at the same time — the three axes have very different gear reductions, so an equal ramp in steps means a very unequal ramp in degrees.
Position is credited on completion, never on push. This is a deliberate choice with a visible consequence: during motion the reported position lags physical reality by up to one block. The alternative — crediting steps when the block is handed to the PIO — would make the counter run ahead of the motor, and every soft-limit check and every subsequent move would be guarding a position the mount had not reached. Lagging is safe; leading is not.
Homing: Three Phases, and a Deliberate Detour
A stepper motor has no absolute position sense. On power-up the firmware knows nothing about where the dish is pointing, and it says so: all three axes report un-homed, all three drivers are left disabled, and GOTO is refused with ERR:not_homed. There is no automatic homing at boot — the mount stays de-energised until the Raspberry Pi asks for motion.
HOME runs three phases per axis:
- Fast approach. Drive toward the endstop at the axis’s fast speed (320 steps/s on azimuth and elevation, 640 on polarization) until the debounced switch asserts.
- Back off. Reverse at the slow speed for a fixed number of steps — 400, or 800 on polarization — to get clear of the switch.
- Slow re-approach. Creep back at 80 steps/s (160 on polarization) until the switch asserts again. That moment defines step zero.
The two-speed approach exists because a switch’s trigger point is only repeatable if you arrive slowly. The fast phase finds the switch; the slow phase measures it.
Between phases 2 and 3 there is a check that looks like paranoia and is not: if the switch has not released after the backoff, homing fails with EVT:homing_timeout rather than continuing. Without it, the slow re-approach would see an already-asserted switch, declare zero on the spot, and report success at a position that is wrong by the whole backoff distance. This was found on the polarization axis at the bench — its high gear reduction meant 400 steps of backoff did not physically clear the switch, which is why its backoff is doubled.
And here is the detour: homing does not use the PIO. For the duration of a homing run the firmware disables the axis’s state machine, takes the STEP pin back into plain GPIO mode, and generates pulses by hand — high for 4 µs, low for 4 µs, then a delay computed from the speed. When homing finishes it hands the pin back and restarts the state machine from the top of the program.
The reason is the shape of the problem. Homing needs to check the endstop between every single step and stop on the one that matters. Expressing that through the PIO means single-step blocks, which means a FIFO round trip and an interrupt per step, for no benefit: at 80 to 640 steps per second a pulse comes every 1.5 to 12.5 ms, which a busy-wait loop handles with enormous margin. The hand-rolled pulse generation is two helpers of a dozen lines — toggle STEP, then wait out the rest of the step period — and the per-axis routine around them reads as the three phases it is.
The cost of blocking Core 1 for the duration is real, and the protocol accounts for it. The three axes are homed one after another, and each one takes as long as it needs to reach its switch, so a full HOME is however long the three take end to end: 28.8 s at the bench, 36.2 s on the dish. For all of that time the motion loop does not run. STOP still works — the homing loops poll the stop flag between steps, so a runaway homing on a broken switch can be aborted without a power cycle — but a jog cannot be accepted, and the protocol refuses one with ERR:busy. That refusal is not tidiness; the consequences of allowing it are worked through in Design Decisions below.
Endstops themselves are polled and debounced in software, on a 5 ms window, rather than wired to an edge interrupt. The board’s RC debounce is defective, so a falling-edge handler would false-trip on contact bounce and de-home an axis in the middle of a move. Debounced polling trades a few steps of stop latency for not doing that.
Raster Scans
A radio map is made by sweeping the beam across a region while sampling the receiver, row by row. The SCAN command does exactly that, in the firmware, so the sweep speed is not at the mercy of the network.
SCAN <sweep-axis> <pattern> <s0> <s1> <t0> <t1> <speed> <rows>
The sweep axis is the fast one; the other axis steps between rows. Two patterns are supported: MEANDER alternates direction row by row, so there is no flyback and no dead time, and UNI sweeps every row in the same direction with a non-measuring return in between — worth its cost when a systematic difference between the two sweep directions would contaminate the map.
The geometry is separated out into pure arithmetic with no hardware dependency: the transverse position of row n, the sweep endpoints for a row given the pattern, the padded physical endpoints, and the check that the padding fits. That separation is what makes it testable on a laptop, and it is also where the one genuinely surprising property of SCAN lives.
The measurement band is not the physical travel. Constant velocity over [s0, s1] requires the axis to already be at cruise speed when it reaches s0, so the physical move extends one full ramp length beyond both ends. With the current 200-step ramp that is 4.5° of overshoot on azimuth and 2.9° on elevation. If the requested band sits closer than that to a travel limit, the command is rejected outright with ERR:no_runup_room rather than quietly clipped.
The bench log from July 2026 shows this constraint biting: a scan of azimuth 10–30° could not use azimuth as its fast axis, because 10° is 444 steps from the endstop and the padding at the time needed 800. Starting at 25° cleared it. Those log figures — ±18° on azimuth, ±11.45° on elevation — are from the old 800-step ramp and are four times the current padding; the August session on the dish measured the present figure, overshooting a 90–100° band to about 85° and 104.5°, against the 85.5° and 104.5° the 200-step ramp predicts.
While a scan runs, Core 1 is inside a blocking state machine, pumping the shared motion tick from within its own loop so the axes keep stepping. It watches for two things between blocks: a stop request, and either scan axis losing its homed state — which is what an endstop hit looks like from here. Both end the scan with EVT:scan_aborted.
Velocity Mode: A Joystick and Two Watchdogs
Everything above is distance mode: a target, a profile, an arrival. A joystick is not that. There is no target — only a speed that changes as long as a thumb is on the screen, and a mount that must stop when the thumb comes off, or when the phone’s battery dies mid-slew.
JOG <az_deg_per_s> <el_deg_per_s> is the velocity-mode command. The client sends it at about 10 Hz, continuously, for as long as the stick is deflected. Each one refreshes the previous. Only azimuth and elevation jog; polarization does not.
Velocity mode shares the ramp arithmetic with distance mode but inverts the control problem: instead of interpolating toward an arrival, it steps the current speed toward a commanded speed, one block at a time. Three properties make it safe.
It stops before the limits, not at them. A jog brakes to rest inside [margin, max_steps − margin] with JOG_LIMIT_MARGIN_STEPS = 25 — one block’s worth of steps, 0.56° on azimuth. The lower end needs the inset because step zero is the debounced trigger point of the endstop switch: an axis that came to rest exactly on zero would be sitting on an asserted switch, and the next motion tick would latch a limit hit and de-home the axis — precisely the outcome velocity mode exists to avoid. The upper end needs it because there is no switch up there at all, only a mechanical hard stop, with nothing to report a collision. Distance mode keeps the full range on purpose, so a GOTO can still reach the physical ends of travel.
Braking is judged against the speed the next block will actually run at, and latched once started. Testing the pre-ramp speed under-counts the stopping distance by a full ramp increment, and without the latch the axis would re-accelerate one block short of the limit — at minimum speed the stopping distance is zero, so the “must brake” test goes false again. The number of steps a block may commit is additionally clamped to the room actually remaining, which is what turns “the axis never steps outside its inset range” from a property of the ramp arithmetic into an invariant.
Nonsense speeds cannot reach the motor. The parser reads the velocity with sscanf("%f"), which accepts the literals nan and inf. A NaN fails every comparison in a naive clamp, falls through, and becomes an arbitrary speed handed to a stepper. The conversion from degrees per second to steps per second is the single choke point for the entire system, so the guard lives there: non-finite input is treated exactly like zero. It is written as dps != dps rather than isfinite(), because on a Cortex-M0+ the latter pulls in soft-float classification helpers for no benefit.
Then there are the watchdogs — and there are two of them, in different processes, on purpose.
The firmware watchdog is the one that cannot be talked out of it. If no JOG arrives within 400 ms — four missed refreshes at 10 Hz — both axes ramp down and EVT:jog_timeout is emitted. It fires regardless of what the Raspberry Pi thinks, which is the point: it is what stops the dish when the backend itself has died. On 2026-08-08 that was tested by stopping the backend service, sending a raw jog on the serial port for 1.2 seconds, and abandoning it. The axis came to rest after 2.81°.
The backend has its own, shorter watchdog. Neither replaces the other; the firmware’s exists because a stopped backend cannot send a stop.
Two details of the firmware watchdog reward a second look. It is edge-triggered, because the ramp-down keeps the axis in motion for a few hundred milliseconds while the timeout condition stays true — a level-triggered flag would emit the event once per millisecond. And it is armed on the commanded speed rather than on “is jogging”, because an explicit JOG 0 0 — what the app sends the instant the stick is released — leaves the axis ramping down for up to 0.60 s, which is longer than the 0.40 s window. Arming on “is jogging” fired on every ordinary release, which trains an operator to ignore the one event that means the link actually died.
Finally, the watchdog runs before the motion tick in Core 1’s loop, not after. Homing can block that loop for half a minute or more; a jog frozen across a homing run would otherwise get one more block pushed at its old cruise speed before the long-expired watchdog could act.
Crediting Steps From a Frozen State Machine
When a move is aborted — by STOP, by an endstop, by a retarget — the state machine is stopped mid-block. Some of that block’s pulses have already gone out to the driver, and the motor has moved. If the firmware simply discards the in-flight block, the position counter is wrong by up to 25 steps, permanently.
So it reconstructs. From the state machine’s program counter and its Y register, the firmware works out how many rising edges the frozen block actually emitted:
- Stalled at the FIFO read, or sitting on the completion instruction: the block finished; credit all of it.
- Still unpacking the descriptor, in the three instructions between the FIFO read and the pulse loop: no pulse of this block has gone out; credit nothing.
- Inside the pulse loop:
Ycounts down from N − 1, so the current pulse index is N − 1 − Y, and the rising edge of that pulse has happened only if the program counter is past the instruction that drives STEP high.
The residual error is at most one step, from a final high pulse that may have been cut short. This is the one place in the firmware where a C constant hard-codes an address in the PIO program, and it is protected accordingly: the instruction indices are defined in a header, the assembler’s generated output is compared against them with _Static_assert, and the arithmetic is a pure function with no SDK dependency and its own host test.
The Radio Signal
The firmware also reads the receiver. ADC channel 0 runs free at 500 kHz — the RP2040’s ADC ceiling, 96 clock cycles per conversion from a 48 MHz clock — into two 2000-sample buffers via a pair of chained DMA channels. When one fills, the other takes over and an interrupt flips which buffer the CPU is allowed to read, so a caller always averages a buffer that DMA is not currently writing. One buffer is 4 ms of signal; 8 KB of the RP2040’s 264 KB goes to holding them.
The mean is pushed to the host as ADC:<volts> at a rate the host chooses, from 1 Hz up to 1 kHz, or switched off entirely. The default is 1 Hz, which is right for watching a level and far too slow for a raster map — the bench log notes that a real scan wants 50 to 100 Hz so each beam position gets enough samples.
The chip’s internal temperature sensor shares the ADC, and reading it means interrupting the free-running radio stream. So it is read rarely — once every five seconds — and the cached value is what the status line reports. Housekeeping does not get to tear holes in science data.
The Protocol, and the Invariant That Holds It Together
Everything the firmware can do is reachable through lines of printable ASCII on a serial port. Commands go one way, five kinds of line come back:
| Line | Meaning | Timing |
|---|---|---|
OK |
command accepted | synchronous — exactly one per command |
ERR:<reason> |
command rejected | synchronous — exactly one per command |
EVT:<name> |
asynchronous event | unsolicited |
POS … |
position and status telemetry | 1 Hz, and on STATUS |
ADC:<volts> |
radio signal mean | at the configured rate |
VER:<string> |
firmware version | at boot, and on VERSION |
The single most important sentence in the protocol document is this: OK and ERR are always the response to the most recent command, and nothing else ever occupies that slot. It is what lets the host pair each command with the next OK/ERR it sees while ignoring any telemetry interleaved between them. Nothing in the protocol correlates a response with its command — no sequence numbers, no tags — so the invariant is the correlation mechanism.
sequenceDiagram
autonumber
participant Pi as Raspberry Pi
participant Pico as Pico (Core 0)
Note over Pico: boot
Pico-->>Pi: VER:0.2.0
Note over Pi,Pico: line noise on RX during power-up
Pico--xPi: (no reply — line was not printable ASCII)
Pi->>Pico: HOME
Pico-->>Pi: OK
Pico-->>Pi: POS AZ:0.00 … MOVING:1 HOMED:0
Pico-->>Pi: EVT:homed
Pi->>Pico: GOTO 180.0 45.0 0.0
Pico-->>Pi: OK
Pico-->>Pi: ADC:1.2345
Pico-->>Pi: POS AZ:180.00 … MOVING:0 HOMED:1
Pi->>Pico: JOG nan 0
Pico-->>Pi: OK
Note over Pico: non-finite velocity treated as zero
Which brings us to the most instructive bug in the project’s history. Line noise while the Pico powers up used to be answered with ERR:unknown_cmd. That line is unsolicited, the host has no way to recognise it as such, and it therefore gets consumed as the response to whatever command the host sends next. The first command after every boot was unreliable — which is exactly how it was found, on the dish, on 2026-08-08: a POST /jog came back unknown_cmd from a firmware that demonstrably knew JOG.
The fix is a rule rather than a filter: a line that cannot be a command gets no reply at all. Input is dropped silently unless every byte of it is printable ASCII. A well-formed line whose keyword is unknown is a different matter and still answers ERR:unknown_cmd — that is a real command from a real host, and silence would be worse. Verified the same day on the dish: noise followed immediately by STOP produced exactly one OK.
The same session produced a second finding of the same family. MOVING was the raw per-axis motion flag, which read 0 for the whole of a homing run — because homing blocks Core 1 — and flickered during a GOTO. It is now “in motion or committed to motion”: any axis stepping, a homing run in progress, an accepted GOTO that Core 1 has not yet popped, a scan between rows. A centred joystick refreshing JOG 0 0 does not raise it, because a stationary mount under active control is exactly what that is. After the fix, 179 status polls across a 36-second homing run returned MOVING:1 every single time.
Refusing Instead of Overriding
The motion core runs one mode at a time. A command that would enter a different mode while one is running is refused with ERR:busy rather than silently taking over — because an overridden command is abandoned with no event, and the host waits forever for an outcome that never comes.
| Running or pending | GOTO, MOVE, SCAN |
JOG |
HOME <axis> |
STOP |
|---|---|---|---|---|
| nothing | accepted | accepted | accepted | accepted |
SCAN |
ERR:busy |
ERR:busy |
accepted | accepted, aborts |
GOTO / MOVE |
accepted, retargets | ERR:busy |
accepted | accepted |
HOME |
accepted, queued | ERR:busy |
accepted, queued | accepted, aborts |
JOG, either axis |
ERR:busy |
accepted, refreshes | ERR:busy |
accepted |
The word “pending” carries weight. A command counts as running from the moment it is accepted, not from the moment Core 1 starts it — and those are separated by the queue. A conflicting command slipped into that window would have been queued behind the first and then overridden it. So Core 0 keeps counters of accepted-but-not-yet-executed moves and jogs, incremented inside the same critical section as the queue push and decremented only after the handler has run, so there is no instant in which neither the counter nor the axis flag shows the command.
STOP is never refused. It ends every mode, including velocity mode, so it is always the way out of a busy state — and a jog additionally clears itself within its 400 ms window once the host stops refreshing it, so no ERR:busy caused by a jog can persist.
Testing a Microcontroller Without a Microcontroller
The firmware needs a Pico, three drivers and a dish to run. Its logic does not, and the project exploits that hard: four test binaries compile with plain gcc on any Linux machine and run in well under a second, covering 50 test cases across the scan geometry, the jog arithmetic, the step-credit reconstruction and the protocol parser.
Three of the four need nothing at all, because the modules they test were written to be pure: scan geometry is integer arithmetic on step positions, the jog ramp is arithmetic on speeds, step crediting is arithmetic on a program counter and a register. No SDK headers, no hardware, no mocks.
The fourth is the interesting one. The protocol parser is 744 lines of C that genuinely does touch the SDK, so the tests compile it against a small set of stub headers standing in for pico/stdlib.h, hardware/gpio.h, hardware/pio.h, hardware/uart.h and pico/mutex.h. Most of those stubs do nothing but satisfy the compiler and record what was called.
The mutex stub does not. The RP2040’s mutex is not recursive: a second mutex_enter_blocking() from the same core deadlocks the firmware outright. That failure mode is invisible in a host test unless the stub goes looking for it — a no-op mutex would let the deadlocking code pass — so this one counts nesting depth and asserts as soon as depth exceeds one. It is the only reason the mutex is stubbed rather than compiled away, and it is a good example of what a stub is actually for: not to make the code compile, but to make a target-only failure visible on the host.
What is not covered on the host is anything that needs real timing, real pins or a real state machine — the 1 ms loop, the PIO program itself, the DMA ping-pong, the interaction of the two cores. Those are verified on hardware, in bench sessions with a written log, and the Status section below says which ones and when.
Design Decisions
Why a Pico and not the Raspberry Pi’s own GPIO. Linux offers no scheduling guarantee, and a late step pulse is a lost step. The Pico costs a few euros and removes the entire class of problem. The project’s original plan used an STM32F411; the RP2040 replaced it before the schematic was drawn, largely for the PIO block and for how much easier it is to obtain.
Why polling and not interrupts, for motion. The 1 ms loop polls the PIO completion flags. An interrupt-driven design would save nothing here — Core 1 has no other work — and would introduce a concurrency boundary in the middle of the position counter. The one place the firmware does use an interrupt is the ADC’s DMA completion, where the deadline is genuinely tight and the shared state is a single buffer index.
Why GPIO stepping during homing. Homing needs a switch check between every step. Through the PIO that means single-step blocks and a FIFO round trip per step; at 80 to 640 steps per second, direct GPIO with a busy-wait is simpler, deterministic and entirely fast enough.
Why homing blocks Core 1 rather than running as a mode of the motion loop. It keeps the routine readable as a linear sequence of three phases, which is how a person thinks about homing. The price is that the motion loop stalls for the whole homing run — half a minute on the measured mount, and bounded above only by the per-phase step budget — and the protocol pays that price explicitly: HOME in any form is refused while a jog is active — even HOME POL, which shares no axis with a jog.
The reason is worth spelling out, because it is the least obvious rule in the protocol. Homing never services the motion tick, so a jogging axis’s in-flight PIO block simply drains and the motor stops — while the firmware’s own record still says the axis is moving at cruise speed. When homing returns, the jog watchdog’s stop request sees a “moving” axis and takes the ramp-down path instead of the already-stopped path, commanding a cruise-range speed to a motor that is standing still. That is a guaranteed stall and silent step loss, with HOMED:1 still cheerfully reported. Refusing the command is much cheaper than detecting the aftermath.
Why ERR:busy rather than pre-emption. A command that is overridden mid-flight produces no event. The host is left waiting for an outcome that will never arrive, and there is nothing in the protocol it could poll to discover this. Refusal is a worse user experience and a much better contract — and STOP is always available as the escape hatch.
Why an ASCII line protocol rather than something binary and efficient. At 115200 baud a POS line costs well under a millisecond, and the traffic is a few lines per second. What the text buys is enormous: the protocol can be driven from a serial terminal, logged verbatim, diffed, replayed, and — crucially — simulated by an 800-line Python script that the backend cannot distinguish from real hardware. Every bench log in this repository is a transcript, readable years later by someone who has never seen the code.
Why degrees on the wire, not steps. The firmware owns the degrees-to-steps conversion, through a two-point linear calibration per axis. This puts the one piece of knowledge that is genuinely about this mount — how many steps make a degree — next to the hardware it describes, and lets the Raspberry Pi speak the language of astronomy throughout. It also means a re-geared axis is a firmware constant, not a change propagating through four codebases.
Why the version number is bumped by hand. It is deliberately not derived from a git commit: the repository moves constantly for backend, gateway and app work that never reaches the Pico, and a commit-derived version would keep changing while the firmware stayed identical. The one question this number answers is “does what is flashed match what the repository says?”, and only a human edit answers it honestly. The simulator mirrors the same version with a -sim suffix, so a simulator can never be mistaken for real hardware.
Why there is no fault reporting. The DRV8825 carrier boards used here are clones that expose VDD on the pin where the genuine part has its fault output. There is no fault signal to read, so the protocol does not pretend to have one.
Reference
Pin assignment
Authoritative source is the KiCad netlist in hardware/motor/; the firmware’s config.h mirrors it.
| Axis | DIR | STEP | RST | EN | Endstop |
|---|---|---|---|---|---|
| AZ (azimuth) | GP6 | GP7 | GP8 | GP9 | GP14 |
| EL (elevation) | GP10 | GP11 | GP12 | GP13 | GP15 |
| POL (polarization) | GP5 | GP4 | GP3 | GP2 | GP16 |
| Function | Pin |
|---|---|
| UART0 TX / RX | GP0 / GP1 |
| Endstop-hit LEDs, AZ / EL / POL | GP17 / GP18 / GP19 |
| Homing LED | GP20 |
| Moving LED | GP21 |
| Tracking LED (reserved) | GP22 |
| Onboard heartbeat LED | GP25 |
Azimuth and elevation are wired with reversed polarity, so the firmware inverts their DIR line; polarization is not inverted.
Motion parameters
| Parameter | Value |
|---|---|
| Microsteps | 8 (M0 = H, M1 = H, M2 = L) |
| Steps per motor revolution | 1600 |
| Start / stop speed | 80 steps/s |
| Cruise speed | 1600 steps/s (1 revolution/s) |
| Ramp length, per axis | 200 steps |
| Speed-update granularity | 25 steps per PIO block (≈ 8 levels per ramp) |
| PIO clock | 125 MHz ÷ 16 = 7,812,500 Hz |
| Endstop debounce | 5 ms, software |
| Jog watchdog | 400 ms |
| Jog limit standoff | 25 steps (0.56° on AZ) |
| DRV8825 wake-up delay | 1000 µs |
| Radio ADC | 500 kHz free-running, 2 × 2000-sample DMA buffers |
| Temperature read cadence | 5 s |
Axis calibration and travel
Bench-measured 2026-06-30; azimuth and polarization home offsets are bench conventions pending field-north alignment. How these numbers were obtained — which instrument was held against which part of the mount — is described in the mount and antenna article.
| Axis | Steps per degree | Angle at endstop | Hard limit (steps) | Travel |
|---|---|---|---|---|
| AZ | 44.444444 | 0.0° | 16,500 | 0 … 371.25° |
| EL | 69.879518 | 7.0° (measured) | 5,800 | 7 … 90° |
| POL | 215.555556 | −45.0° | 22,000 | −45 … 57.06° |
One azimuth step is 0.0225°, which is why a GOTO can settle 0.01–0.02° off the requested angle. That is quantisation, not error.
Homing constants
| Axis | Fast approach | Slow re-approach | Backoff | Step budget |
|---|---|---|---|---|
| AZ, EL | 320 steps/s | 80 steps/s | 400 steps | 32,000 |
| POL | 640 steps/s | 160 steps/s | 800 steps | 64,000 |
Commands
| Command | Synchronous reply | Later event |
|---|---|---|
HOME / HOME <axis> |
OK, ERR:bad_axis, ERR:busy |
EVT:homed, EVT:homing_timeout, EVT:homing_aborted |
GOTO <az> <el> <pol> |
OK, ERR:bad_args, ERR:out_of_range, ERR:not_homed, ERR:busy |
EVT:limit_<axis> |
MOVE <axis> <±steps> <sps> |
OK, ERR:bad_args, ERR:bad_axis, ERR:bad_sps, ERR:not_homed, ERR:busy |
EVT:limit_<axis> |
JOG <az_dps> <el_dps> |
OK, ERR:bad_args, ERR:not_homed, ERR:busy |
EVT:jog_limit, EVT:jog_timeout |
SCAN <sweep> <pattern> <s0> <s1> <t0> <t1> <speed> <rows> |
OK, ERR:bad_args, ERR:bad_axis, ERR:bad_pattern, ERR:bad_rows, ERR:bad_speed, ERR:out_of_range, ERR:no_runup_room, ERR:not_homed, ERR:busy |
EVT:scan_done, EVT:scan_aborted |
STOP |
OK, always |
EVT:homing_aborted, EVT:scan_aborted |
STATUS |
a POS line — no OK |
— |
VERSION |
a VER line — no OK |
— |
SLEEP / WAKE |
OK, ERR:busy |
— |
ENABLE <axis> / DISABLE <axis> |
OK, ERR:bad_axis, ERR:bad_args, ERR:busy |
— |
SET ADC_RATE <0…1000> |
OK, ERR:bad_rate |
— |
SET POS_RATE <0…1000> |
OK, ERR:bad_rate |
— |
<axis> is AZ, EL or POL. Outgoing lines end in a single \n; incoming lines may end in \n, \r or \r\n. The full specification, including the HOMED lifecycle and every error reason, is in UART_PROTOCOL.md.
Building and testing
The firmware itself needs the Pico SDK and CMake, and is flashed by dragging the .uf2 onto the RPI-RP2 mass-storage volume after entering BOOTSEL. The host tests need only gcc:
gcc -Wall -Wextra -I firmware/pico_motor -o /tmp/t \
firmware/pico_motor/test/test_scan_plan.c firmware/pico_motor/scan.c && /tmp/t
gcc -Wall -Wextra -I firmware/pico_motor -o /tmp/t \
firmware/pico_motor/test/test_jog.c firmware/pico_motor/jog.c && /tmp/t
gcc -Wall -Wextra -I firmware/pico_motor -o /tmp/t \
firmware/pico_motor/test/test_step_credit.c firmware/pico_motor/step_credit.c && /tmp/t
gcc -Wall -Wextra -I firmware/pico_motor -I firmware/pico_motor/test/stubs -o /tmp/t \
firmware/pico_motor/test/test_uart_protocol.c firmware/pico_motor/uart_protocol.c \
firmware/pico_motor/scan.c firmware/pico_motor/test/stubs/fake_pico.c && /tmp/tAll four run in continuous integration on every pipeline. The full SDK build does not — it needs PICO_SDK_PATH and is done locally.
Status
Bench bring-up, 2026-07-04 (test log) — UART in both directions, all three endstops, per-axis and combined homing, multi-axis GOTO, and SCAN in both sweep-axis roles. Homing took 14.1 s on azimuth, 19.1 s on elevation and 19.3 s on polarization, and 28.8 s for a full HOME — figures that do not add up, and are not meant to: each run takes as long as the distance from wherever that axis happens to be standing. GOTO 15 45 0 arrived within 0.01° in about 8.7 s.
Full stack on the dish, 2026-08-08 (test log) — homing, GOTO, a three-row raster scan, STOP, and all three jog stop paths. The jog soft limit halted azimuth at 0.56°, exactly the 25-step standoff. With the backend deliberately stopped, the firmware’s own dead-man watchdog brought the axis to rest 2.81° after the last refresh.
Two protocol defects were found in that session — the boot-noise ERR occupying a response slot, and an unreliable MOVING flag — and both were fixed and re-verified on the dish the same day.
- The mount’s own open items — field-north alignment and the unset reference current on the polarization axis — are mounting problems rather than firmware problems, and are tracked in the mount and antenna article. Both bound what the calibration constants above actually mean: until the mount is aligned against a known azimuth, this firmware moves the correct relative distances at an uncalibrated absolute azimuth.
- The motion profile has not been re-evaluated by ear since the ramp was shortened and made per-axis in July 2026. The expectation is that it is quieter than the ramp-less bring-up tool; that is an expectation, not a measurement.
- Concurrent clients are not arbitrated. The phone app and both gateways can all issue motion commands at once, with no lock; commands interleave. The firmware’s mode arbitration prevents incoherent motion, but it does not decide who is in charge.
References
- Project repository: https://gitlab.com/radio-science-institute/projects/smart-radio-telescope
- RP2040 datasheet, including the PIO chapter: https://datasheets.raspberrypi.com/rp2040/rp2040-datasheet.pdf
- Raspberry Pi Pico C/C++ SDK documentation: https://www.raspberrypi.com/documentation/microcontrollers/c-sdk.html
- TI DRV8825 stepper driver datasheet: https://www.ti.com/lit/ds/symlink/drv8825.pdf