One firmware binary for the emulator and the real machine: HIL, PIO and deterministic scoring for a kart engine dyno
DEV Community

One firmware binary for the emulator and the real machine: HIL, PIO and deterministic scoring for a kart engine dyno

I have open-sourced the software and design of an engine dyno for Rotax, KZ and OK class kart engines: github.com/oleg-kukharenko/kart-engine-dyno. The mechanics are designed but not built yet. The software runs end to end on a hardware-in-the-loop bench that pretends to be the stand.

This post is about the software side: where the control loop lives, why the sensors moved into PIO, how the HIL bench works, and why the scoring is a table of rules rather than a model.

The one-paragraph context

A karting team does not need an absolute horsepower figure. It needs to know which of its engines is best right now and how each one changes with wear. So the stand measures relatively: same mechanics, same fixed test program every time, so stand losses cancel out between runs.

That lets a used truck eddy-current retarder act as the brake, with torque read by a load cell on a reaction arm. The software has to be repeatable more than anything else.

The speed loop lives on the RP2040, not on the host

The controller is a Raspberry Pi Pico W (RP2040), C with the Pico SDK: about 1,650 lines plus three PIO programs. It sends telemetry at 50 Hz and runs its control cycle every 20 ms.

The obvious design is to stream measurements to a PC and send brake commands back. That puts the OS scheduler, USB latency and, in the Wi-Fi variant, the network inside a closed loop that holds a racing engine at a set speed. Instead, the speed PID runs on the microcontroller with a fixed period.

The host only sends setpoints:

C,<mode>,<setpoint>,<brake>,<run>

C,1,1500,0,1 # hold the shaft at 1500 rpm

C,0,0,0,0 # off

If the host stops sending them, a 100 ms command watchdog takes the stand to a safe state. In practice the host streams setpoints at about 20 Hz, and the firmware treats silence as a fault, not as "keep doing the last thing".

The portable core (control logic, limits, protocol parsing) is separated from the hardware layer and has host tests that build without the SDK.

PIO removed 11 ms of blocking per 20 ms tick

The first version read the HX711 (24-bit load-cell ADC) and the MAX31855 (thermocouple converter) by bit-banging their serial interfaces from the main loop. That held the loop for about 11 ms per tick, more than half the budget, and it showed as jitter in the telemetry. Each sensor now has its own PIO state machine.

Here is the whole HX711 reader:

.program hx711
.side_set 1 ; SCK
.wrap_target
wait 0 pin 0 side 0 ; DOUT low = frame ready
set x, 23 side 0 ; 24 bits
bitloop:
nop side 1 [3] ; SCK high
in pins, 1 side 1
jmp x-- bitloop side 0 [15] ; SCK low
nop side 1 [3] ; 25th pulse: gain 128
push noblock side 0 [15] ; word -> RX FIFO
.wrap

The main loop drains the RX FIFO and keeps the freshest word. A third PIO program captures the period of a 60-2 toothed wheel for shaft speed. The CPU never waits for a sensor.

The HIL bench: one binary, no "test build"

How do you test software that controls a machine that does not exist yet? An Arduino Nano pretends to be the whole stand:

  • it generates the 60-2 tooth signal from a timer compare ISR;
  • it answers the Pico's clock like an HX711 and like a MAX31855 (pin-change interrupts);
  • it reads the throttle and brake outputs through RC filters;
  • it runs a small model of engine and retarder, so more throttle means more speed and more brake means more torque on the "load cell".

The rule: the same firmware binary runs on the emulator and on the real stand. The emulator uses the production pins, with dividers and RC filters for the 5 V / 3.3 V difference.

A test then looks like this: stream setpoints, record frames, check the response.

  • phase throttle 30% - rpm (2nd half) ~1600 - torque, Nยทm 0 - mode 2
    • brake 30% - ~900 - ~65 - 2
  • hold 1500 rpm - ~1470-1500 - 0 - 1
  • stop / silence - coasting - 0 - 0

A bug the bench found in itself

While writing this post I ran that test again and saw something ugly: at idle, up to 40% of the frames had a non-zero torque, some clamped at 400 Nยทm. The values were not random. 65.5, 196.6 and 262.1 Nยทm are raw words 0xFFFF, 0x2FFFF and 0x3FFFF at 1000 counts per Nยทm: a frame that ends in a run of ones.

That is the signature of a bit slip: one side of the serial link is a bit or two behind, and the tail of the frame is read from an idle-high line. The firmware was fine. Two bugs were in the emulator:

  • The frame was re-armed one clock too early. The Nano started a new HX711 frame as soon as it had shifted out bit 24, but the Pico still had to send the 25th (gain-select) pulse. That pulse then counted as bit 0 of the next frame. There was also a "stuck frame" timeout of 5 ms, and a Pico frame takes about 5 ms, so the safety net sometimes tore a healthy frame.
  • A soft UART with interrupts off. The Nano also sends engine-side torque on a second line as a tiny text frame. Each byte went out bit-banged under cli() for about 260 ยตs. The Pico's HX711 clock has a phase of about 200 ยตs, and the MAX31855 clock about 100 ยตs. With interrupts off, the pin-change ISR missed edges.

The fix: re-arm only after the 25th pulse, make the timeout 20 ms, and clock the UART bits out of a Timer2 compare ISR (CTC, 26 ยตs per bit) instead of a blocking loop. After that, a full loop test had zero torque or temperature outliers, and the ratio of shaft torque to engine torque came out at 4.68 against the expected 4.7 (ratio 5 ร— chain efficiency 0.94).

The lesson I keep relearning: an emulator is a second piece of firmware, with its own timing bugs. When a HIL bench shows a glitch, decode the bad values before you blame the device under test. Here the bit pattern told the whole story.

Host: Go, TimescaleDB, one cockpit for any source

The host runtime is Go: about 8,400 lines and 100 test functions. It takes telemetry from USB serial, MQTT or a built-in simulator, sends setpoints in four load modes, records runs into PostgreSQL with TimescaleDB, and serves a REST API and a WebSocket stream.

Everything runs in Docker Compose, and you can try it without any hardware:

cd 03_software
cp deploy/.env.example deploy/.env # replace every change-me value
echo "ROTAX_SIL=1" >> deploy/.env # built-in simulator instead of a stand
./deploy/mqtt_passwd.sh
docker compose -f deploy/docker-compose.yml up -d --build

CI builds and tests every part, including a check that each database migration rolls back and re-applies cleanly.

Scoring is a table you can read

The core workflow is a canonical test: a fixed multi-stage program, so two runs of the same template can be compared directly. A run is split into stages by its setpoint marks, metrics are computed per stage, and rules turn them into a 0-100 score and recommendations.

A rule is plain JSON:

{
  "code": "temperature_watch",
  "severity": "warning",
  "when": [
    { "feature": "max_temp_c", "op": "gte", "value": 70 },
    { "feature": "max_temp_c", "op": "lt", "value": 90 }
  ],
  "title": "Watch retarder temperature",
  "explanation": "Maximum temperature reached {max_temp_c:.1f} C; allow cooldown between runs."
}

The same run always gets the same score. An LLM can afterwards retell the computed result in plain language and help word new rules, but it is called from the backend, never sits in the control loop and never changes a score. The system works fully without it. I wanted the part that makes decisions to be auditable line by line.

Status and what I would like feedback on

Software: complete and verified on the HIL bench. Mechanics: calculations, a STEP assembly, a bill of materials and drawings, not built yet. Every mechanical number is a design value until the stand exists.

Code is Apache-2.0, hardware CERN-OHL-P-2.0, docs CC BY 4.0. I would especially welcome comments on the failsafe design and on the HIL approach. Issues and Discussions are open: github.com/oleg-kukharenko/kart-engine-dyno.

Parts of the code and documentation were written with an AI coding assistant and reviewed by the author.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.