# 23. Code generation and FMU export

A simulated controller is only half done until it runs as firmware against the power stage. Voltecx takes it there in three steps, each a command you can run from the **Tools** menu, the command line, Python or a script: it writes the controller as C for a microcontroller, runs that firmware against a fixed-step model of the power stage on this computer (processor-in-the-loop), and exports the power stage itself, as C for a real-time rig, as Verilog for an FPGA's solve, or as an FMU for a system tool.

This chapter walks one shipped example through all of them, from the command line, and says what each step checks and what it does not. [Chapter 13](https://voltecx-web.nguyenvanqui291.workers.dev/docs/manual/13-tools-menu/#code-generation) is the reference: every parameter, the microcontroller targets register by register, and how each export was checked. Every number below is from a run of version 0.9.0 on a Linux computer with `cc` (GCC); your runs on another computer can differ in the last digits.

## 1. The commands

List them with `powercraft-cli commands --filter codegen` (and `--filter hil`, `--filter realtime`, `--filter Fmu`).

| Command | Menu | What it does |
|---|---|---|
| `tools.codeGeneration` | **Tools › Code Generation** | Returns the controller's C files (`<prefix>.h`, `<prefix>.c`, and the target's files). |
| `file.exportCode` | | Writes the same files, and `<prefix>_map.json`, into a folder. |
| `codegen.ranges` | | Says, before any run, which values may saturate in fixed point and which divisions may divide by zero. |
| `codegen.verify` | | Compiles the code with this computer's C compiler and runs it on the model's inputs, sample by sample. |
| `codegen.closedLoop` | **Tools › Generated Code in the Loop** | Runs the compiled code in place of the control blocks, in a closed loop with the circuit. |
| `codegen.evidence` | | Writes the code, runs the checks above and writes one `<prefix>_evidence.json` for a review. |
| `codegen.diff` | | Compares the code generated for two versions of a circuit: which blocks, fields, files and options changed. |
| `codegen.misra` | | Checks the generated C against MISRA C:2012 with cppcheck's MISRA addon and marks each finding against the published deviation list. |
| `codegen.isrCycles` | | Counts the interrupt's cycles in a Cortex-M4 build listing. |
| `codegen.pil` | **Tools › Processor-in-the-Loop** | Runs the microcontroller firmware against the real-time model of the plant and compares with the circuit's own run. |
| `tools.realtimeModel` | | Turns the power stage into fixed-step C (`pc_plant.h`, `pc_plant.c`) and, with `check`, compares it with the reference solver. |
| `file.exportRealtimeModel` | | Writes the real-time model into a folder. |
| `file.exportFmu` | | Packs the real-time model as an FMI 2.0 or 3.0 co-simulation FMU. |

The commands that write files need a folder you allow: in the app, the folder you choose; on the command line, `--root DIR`, and every path is then inside `DIR`. None of these commands edits the circuit.

## 2. Generate the controller's C code

Open **File › Open Example** and pick `buckClosedLoop`: a 48 V to 12 V buck at 100 kHz whose output is regulated by a sampled PI controller (`Ref`, `Err` and `PI`, run every 10 µs). The same from the command line:

```sh
powercraft-cli run --root w \
  --cmd file.openExample --param name=buckClosedLoop \
  --cmd file.exportCode --params '{"dir":"ctl","target":"stm32g474"}'
```

This first attempt fails, on purpose:

```text
error: file.exportCode: the reference `Ref` of `Err` is 12, above the 3.3 the ADC reads for `vout` at its full scale: set `fullScale` to the range of the board's sense network, or scale the feedback in the circuit
```

The circuit compares the output voltage itself with 12 V, but a microcontroller's ADC reads at most 3.3 V. `fullScale` says what value the ADC's code 4095 stands for, that is, the range of the board's sense divider. With `"fullScale": 20` the export succeeds and `w/ctl` holds seven files:

| File | What it is |
|---|---|
| `pc_control.h`, `pc_control.c` | The controller: `pc_control_init`, `pc_control_reset` and `pc_control_step`, C99, no `malloc`, no globals. |
| `pc_control_stm32g474.h`, `_init.c`, `_isr.c` | TIM1 at 100 kHz (period 1699 counts at 170 MHz), ADC1 triggered by TIM1, and the ADC interrupt that runs `pc_control_step` and writes the duty into `TIM1_CCR1`. |
| `pc_control_params.csv` | The tunable gains: `PI_kp` = 0.01 and `PI_ki_half_t` = 2e-4 (Ki·T/2, from the Tustin method). |
| `pc_control_map.json` | Which field of the code belongs to which block and which circuit signal, and the hash of every file written. |

The reply lists what was generated (`supported`: `Ref`, `Err`, `PI`), what was not and why (`unsupported`, empty here), how each continuous block was discretized (`discretized`: `PI` by `tustin`), and the register values (`mcu`). Leave out `target` (or give `portable`) for the two portable files alone, or give `f28379d` for TI's F28379D and a Code Composer Studio project ([chapter 13](https://voltecx-web.nguyenvanqui291.workers.dev/docs/manual/13-tools-menu/#microcontroller-targets)).

### Check fixed point before you run

On a microcontroller without a floating-point unit you want fixed point, and fixed point can overflow. `codegen.ranges` finds where before any run:

```sh
--cmd codegen.ranges --params '{"precision":"q15","fullScale":20}'
```

`q15` chooses a 16-bit word with the fewest integer bits that hold every constant, here `q4.11`, which holds −16 to 15.9995. The reply has one finding: the input `vout` may reach 20, so it `saturates`. A wider integer part, `q5.10`, removes the finding (`saturates` 0), but [`codegen.verify`](#check-the-code-against-the-model) then refuses it for another reason:

```text
the fixed-point format cannot hold the constant 2e-4 rounds to 0
```

With 10 fraction bits the smallest step is about 1e-3, so the integral gain becomes 0 and the loop would never remove its error. This controller needs `float` (the default) or `double`. `codegen.ranges` is sound for overflow (a value it does not list cannot leave its range), but it does not judge resolution: that is what the run below is for.

### Check the code against the model

`codegen.verify` compiles the generated code with this computer's C compiler and runs it on the inputs the model's own simulation gave it, sample by sample. On `buckClosedLoop` in `float` it runs 1001 samples, and the largest difference of `duty` from the model is 1.7e-7, under the tolerance of 1e-4: `pass` is true. A failure says where the code first leaves the tolerance, for example `` signal `duty` first leaves the tolerance … at sample 6 ``.

`codegen.closedLoop` (**Tools › Generated Code in the Loop**) goes one step further: it replaces `Ref`, `Err` and `PI` with the compiled code and simulates the circuit in a closed loop for the circuit's end time (10 ms, 100 000 samples here), with a step of the load and of the input voltage at 5 ms. The output means are 11.447 V with the code and 11.432 V with the model blocks, a relative RMS difference of 0.36 %, under the 0.5 % tolerance. Both commands also report `coverage`: which decisions of each block the run took. Here the PI limiter never reached either limit (`missed`: `below`, `above`), so the run says nothing about the anti-windup.

The outputs a back-to-back test compares do not show what happens inside the code. `codegen.verify` takes `contracts` for that: bounds on what a generated block writes, such as `"contracts":[{"block":"PI","min":0,"max":0.9},{"block":"Err","max":5,"from":"2m"}]`. Every signal the block writes must stay finite and within the bounds at every call (from `from` to `to`, when given), observed inside the generated program on the test's inputs. A broken contract fails the call and names the block, the sample and the value; `contracts.results` also gives the lowest and highest value each block wrote, which shows how close an integrator came to its clamp.

`codegen.evidence {"dir":"review","target":"stm32g474","fullScale":20}` writes the code again, checks that a second generation gives the same files, runs both checks and writes `pc_control_evidence.json`, with `status` `passed`. Keep it with the firmware's sources: it ties them to the circuit's hash and the Voltecx version. To trace requirements, give `codegen.verify`'s `expect` with a `requirement` ID and `blocks` on each assertion, and `requirements` for ones checked by inspection, e.g. `"requirements":[{"id":"SRS-4","blocks":["PI"]}]` (`file.exportCode` takes it too). The map then names the requirements each block serves, and the bundle lists each requirement's verdict on the model and the code and the generated blocks no requirement covers.

`codegen.diff {"from":"old/pc_control_map.json"}` compares the code the open circuit generates now with an earlier `<prefix>_map.json` (from `file.exportCode` or `codegen.evidence`). It lists the blocks added, removed or changed, the inputs and outputs fields, and each file's size and hash, so a reviewer sees which part of the firmware an edit touched before reading the C. When the old map traces requirements, the new code keeps its links (or give `requirements` again), and `requirements` in the reply names the requirements an edit touched (a block of theirs added, removed or changed), the ones it left alone, whose earlier verdicts still stand, and the changed blocks no requirement covers. It changes nothing.

`codegen.misra` takes the same params as `tools.codeGeneration`, generates the code and runs cppcheck's MISRA C:2012 addon on it, when this computer has cppcheck 2.x (`CPPCHECK` names another binary). Each finding is reported by rule number, file and line, and marked against the deviation list in [`docs/workflows/misra-deviations.md`](https://voltecx-web.nguyenvanqui291.workers.dev/docs/workflows/misra-deviations/). `status` is `passed`, `failed` (`violations` counts the findings that no deviation covers) or `skipped` when cppcheck or its addon is missing; a skipped check is never a pass. It is a check by an open-source tool, not a certification, and the rule texts belong to your licensed copy of the standard. It changes nothing.

## 3. Run the firmware against the plant (processor-in-the-loop)

`codegen.pil` (**Tools › Processor-in-the-Loop**) compiles the firmware written for the `stm32g474` (or with `"target":"f28379d"` the F28379D) together with the real-time model of the power stage into one program on this computer. A stand-in for the microcontroller's timer and ADC plays the hardware: once every PWM period the ADC samples the plant's output into a 12-bit code, the interrupt runs the control step and writes the compare register, and the new duty drives the switch from the next period. Then the circuit's own simulation runs for as long, and the two are compared.

```sh
--cmd codegen.pil --params '{}'
```

On `buckClosedLoop` it runs 1000 PWM periods at the default plant step of 50 ns (200 steps per period). `fullScale` defaults to 1.5 times the native run's peak of `vout`, 18.0 V here (an LSB of 4.4 mV). The steady state is averaged over the last 200 periods:

| Signal | Firmware | Circuit | Difference |
|---|---|---|---|
| `vout` (mean) | 11.9950 V | 11.9999 V | −4.9 mV (0.04 %) |
| duty (mean) | 0.2479 | 0.2501 | −0.0021 |

`pass` is true: every measured signal is within the 1 % `tolerance` of the native run, no plant step hit the switching-iteration limit (`unsettled` 0), and no ADC sample left 0 to `fullScale` (`clipped` 0). Some difference is expected: the firmware regulates the sample at the start of each period, not the average, the ADC rounds it to one LSB, and the plant reads the gate once per step. A coarser step makes the duty coarser: at `"step":"1u"` the run has 10 steps per period and `dutyResolution` is 0.1.

What this run is not: the compiler, the floating-point unit and the interrupt's timing are this computer's, not the microcontroller's, and the conversion takes no time. To learn whether the interrupt fits its period on the real part, build the firmware for it and give the listing to `codegen.isrCycles` ([chapter 13](https://voltecx-web.nguyenvanqui291.workers.dev/docs/manual/13-tools-menu/#code-generation)).

## 4. The real-time model

`tools.realtimeModel` turns the power stage into a fixed-step model in C. Each switch and diode is a low or a high resistance, so a circuit with `n` of them has `2^n` circuit matrices, and the export inverts each one in advance: a step on the target only multiplies. Run it with `check` on the open-loop `buck` example:

```sh
powercraft-cli run --cmd file.openExample --param name=buck --cmd tools.realtimeModel --params '{"check":true}'
```

The reply names the gate input `g` and eleven outputs (`v(out)`, `i(L1)` and the rest), the step (50 ns, the circuit's maximum step), and the slowest possible step, `worstCase`: 100 solves of 25 multiply-adds, 2500 in all, which your target must finish within 50 ns. `check` replays the reference solver's gates through the model for the whole run: every output agrees within 5e-8 of its peak. On `buckClosedLoop` the same check shows `v(sw)` and the switch currents off by their full swing, because the controller's PWM edges fall between the model's steps and a switched quantity is then up to one step late; judge the model by the smooth signals (inductor current, capacitor voltage) instead.

`file.exportRealtimeModel {"dir":"plant"}` writes `pc_plant.h` and `pc_plant.c`. On the target, call `pc_plant_init` once, then `pc_plant_step` every step with the gate levels, and read the outputs with `pc_plant_outputs`. `numbers: "f32"` writes the model in single precision, and `bfp24` or `bfp18` with block-floating-point tables for an FPGA's multipliers ([chapter 13](https://voltecx-web.nguyenvanqui291.workers.dev/docs/manual/13-tools-menu/#real-time-model)).

## 5. FMU export

An FMU (Functional Mock-up Unit, FMI standard) is a model that system-simulation tools import and co-simulate. `file.exportFmu` packs the real-time model as a co-simulation FMU:

```sh
powercraft-cli run --root w --cmd file.openExample --param name=buck \
  --cmd file.exportFmu --params '{"path":"buck.fmu","fmiVersion":"3.0","outputs":["v(out)","i(L1)"],"parameters":["Vin"]}'
```

The archive holds `modelDescription.xml`, the C sources in `sources/` (with `buildDescription.xml` for FMI 3.0) and `documentation/index.html`. Its input is the gate `g` (on above 0.5, held through each communication step), and its outputs are the two signals named; without `outputs` it exposes all of them. Leave out `fmiVersion` for FMI 2.0. The FMU carries sources, not a compiled library: the importing tool compiles them. The outputs do not depend directly on the inputs at the same communication point, so connecting the FMU to a controller makes no algebraic loop. Until the first communication step the outputs read the circuit's solution at the start time, fixed at export (the reply's `startValues`); from the first step on they follow the circuit. A communication step that is not a whole number of model steps advances to the last whole step before it.

Each output whose quantity the model fixes carries its unit: `V` for a node voltage, `A` for a part's current, `rad/s`, `rad` and `N.m` for a machine's speed, angle and torque (the reply's `units`, `null` for a meter's or sensor's signal). `parameters` names DC sources of the circuit, here `Vin`; each becomes a tunable parameter of the FMU, after the outputs, whose start is the source's value in the circuit (48 V) and whose unit is `V` or `A`. The importing tool can set it before the run, during initialisation and at any communication point, and the model holds the source at that value from the next step on, so a study that sweeps the bus voltage or sags the supply mid-run needs one export. A sine, pulse or other varying source cannot be a parameter. The start values are those of the exported parameter values: an output read before the first step with a parameter set away from its start returns a warning status.

## 6. Limits

- **Code generation** covers the sampled control blocks and the step-advancing blocks that feed a PWM's duty ([chapter 13](https://voltecx-web.nguyenvanqui291.workers.dev/docs/manual/13-tools-menu/#what-is-generated) lists them). Anything else is listed in `unsupported` with the reason, and with a microcontroller target a block that cannot be generated but feeds a duty is refused by name (`strict`), since the firmware would run the loop open.
- **The checks run on this computer.** `codegen.verify`, `codegen.closedLoop`, `codegen.pil`, `codegen.evidence` need a C compiler; without one (and in the browser) they answer an error that says so, and `codegen.evidence` reports `incomplete`. No check runs on a microcontroller, an FPGA or a rig.
- **Processor-in-the-loop** takes one `pwm` block that drives every gate (on the `stm32g474`, or one `pwm3` block on TIM1's three channels), and no supervisor. The ADC reads each input from `offset` at the code 0 to `fullScale` at 4095, so a phase current reads from mid-scale on either target; a sample outside that range clips and is counted in `clipped`.
- **The real-time model** takes at most 12 switches and saturating inductors together. Inductors on a linked catalogue core, nonlinear parts, machines other than PM synchronous ones, and reverse recovery have no real-time model. Losses and temperatures are not computed, and the control blocks are not part of the plant: the firmware replaces them.
- **FMU**: export only, co-simulation only. Only DC sources can be parameters (no resistor, capacitor or switch values), and Voltecx does not import FMUs (#4402).

## 7. Error messages

Each error names what is wrong and, where it can, what to change. The ones you are most likely to meet:

| Message | What to do |
|---|---|
| `` the reference `Ref` of `Err` is 12, above the 3.3 the ADC reads for `vout` at its full scale: set `fullScale` … `` | Give `fullScale`, the value the ADC's full code stands for (the range of your sense network), or scale the feedback in the circuit. |
| `the fixed-point format cannot hold the constant 2e-4 rounds to 0` | The format has too few fraction bits for a gain. Use `float` or `double`, or a format with more fraction bits. |
| `` the code differs from the model: signal `duty` first leaves the tolerance … at sample 6 … `` | `codegen.verify` found where the code and the model part. Compare the precision with `double`, then look at that block. |
| `` prefix `9abc`: it must start with a letter `` | The prefix is a C identifier: letters, digits and `_`, starting with a letter. |
| `no processor-in-the-loop run: the firmware measures nothing, so there is no loop to close` | The circuit's control reads no measured signal (the open-loop `buck` example, or `boost`). Close the loop through a meter first. |
| `` no real-time model: `M1`: an induction machine has no real-time model; the export takes PM synchronous machines (surface and interior) `` | The named part has no fixed-step model (section 6). |
| `` the model has no output `v(nope)`; its outputs are v(in), v(sw), v(out), … `` | `file.exportFmu`'s `outputs` names a signal the model lacks; pick from the list. |
| `` `fmiVersion` must be "2.0" or "3.0", not "1.0" `` | FMI 1.0 is not written. |
