# 13. The Tools menu: Parameter Sweep, scripts and C code

The **Tools** menu has six items: the five below, and **Board**, the project's board canvas (last section). **Parameter Sweep** runs one simulation for each value of a variable and tabulates a measurement. **Scripting** replays a list of commands from a text file. **Code Generation** writes C code for the digital part of your controller. **Generated Code in the Loop** (`codegen.closedLoop`) and **Processor-in-the-Loop** (`codegen.pil`) run the generated controller in a closed loop with the circuit, the second compiled on this computer (below).

![The Tools menu, marked 1 to 6](https://voltecx-web.nguyenvanqui291.workers.dev/docs/manual/img/en/tools-menu/01-menu.png)

1. Parameter Sweep.
2. Scripting.
3. Code Generation.
4. Generated Code in the Loop.
5. Processor-in-the-Loop.

## Parameter Sweep

Use it when you want to see how one result changes as one circuit variable goes from A to B, without writing JSON. It is a form for `analysis.paramSweep` (chapter 6).

Choose **Tools > Parameter Sweep**. The window has the setup on the left, under **Vary** and **Measure each run**, and the results on the right. Fill in:

![The Parameter Sweep window, filled in for a sweep of D from 0.2 to 0.8, marked 1 to 6](https://voltecx-web.nguyenvanqui291.workers.dev/docs/manual/img/en/tools-menu/02-batch.png)

1. Variable.
2. Start.
3. End.
4. Points.
5. Signal.
6. Run sweep.

| Field | Meaning |
|---|---|
| Variable | A circuit variable, for example `D`, or a part's parameter written `Part.param`, such as `L1.l`. The window lists the variables of the open circuit |
| Start, End | The first and last value. Start must be below End. SI suffixes work (`3.3`, `4.7u`, `25µ`, `10k`); Sweep fills them in that form. A part's parameter shows its name and unit beside the fields |
| Points | How many values, from 2 to 1000 |
| Spacing | **Linear** steps evenly from Start to End. **Log** keeps an equal ratio between neighbours (10 to 100 µ in 7 points is 10, 14.7, 21.5, 31.6, 46.4, 68.1 and 100 µ), so Start must be above zero. The line under it lists the values |
| Signal | The signal to measure, for example `v(out)` |
| Measure | One of `mean`, `rms`, `max`, `min`, `pp` or `last` |
| Add a measurement | Another signal and statistic, measured in the same runs, up to 16 in all. The table gets a column for each. A row left without a signal is skipped |
| Window start, end (s) | Optional. Measure only between these two times. Use it to skip the start-up transient |
| Overlay each run's waveform on the scope | Keeps the signal of every run (`keepWaveforms`), so the scope draws them as a family, one trace per value |

Press **Run sweep**. The sweep runs as a background job, so the status bar shows progress and a **Cancel** button. The results appear on the right. A header names the swept variable and counts the runs that measured everything ("7 of 7 runs · log spacing"). Under it is a plot of each measurement against the variable, on a log axis for a log-spaced sweep, with the point nearest the circuit's value marked and the ripple limit drawn as a dashed line. Then comes a table, with one row for each value of the variable and a column for each measurement. Every number reads with its unit (`39.69 µH`, `105.7 mV`), right-aligned so the digits line up; a part's parameter is named as in Properties (`L1 inductance`, the key `L1.l` on hover), and a measurement by its signal and statistic (`v(out) p-p`). In the result window, a log-spaced sweep is plotted on a log axis. When the circuit has a design spec with a ripple limit (`ripple.maxPp`, set by the Test Bench or Auto Design) and one measurement is `pp` of the output voltage, the table gets a **Ripple** column that reads PASS or OVER for each run, and a line under it names each range of swept values that keeps under the limit ("L1 inductance from 39.7 µH to 159 µH keeps ripple under 100 mV"), or says that none does. The row nearest the variable's value in the circuit now is shown in bold with a dot. **Copy CSV** puts it on the clipboard, ready for a spreadsheet. The form refuses an empty or reversed range, a bad number of points and a reversed window before it starts anything, and tells you why.

**Sweep a part's value from Properties.** Right-click a number in Properties (the name of the row, for example L1's **Inductance**) and choose **Sweep**. The form opens filled in for that parameter: `L1.l` from a tenth to ten times its value (a value that is not positive goes ±50 %), 5 points, the scope's first signal as the measure (before any run, the output voltage), and the overlay ticked. Press **Run sweep**: the table fills in, and the scope shows each run's waveform labelled with its value. A value that is an expression or a variable has no Sweep; sweep the variable instead.

The points run in parallel on all your cores. For several variables, tolerances or random draws, use `analysis.monteCarlo` or the commands in chapter 6 directly.

## Scripting

A script is a plain text file with one engine command on each line. Use one when you repeat the same steps: open a circuit, change a value, run, measure, and do it again for other values. A script can do exactly what you can do by hand, nothing more. It has no access of its own to files or the network.

### Run a script

| Where | How |
|---|---|
| Desktop app | **Tools > Scripting** opens a window. Type or paste the script and press **Run**. A list shows the line, the command and the result of each step |
| Command line | `powercraft-cli script FILE [--root DIR]` prints one line of JSON for each step. It exits with code 1 at the first error and names the line. `--root` is the folder the script may read and write, as for the other commands |
| Command | `script.run {"text": "..."}`, for assistants and the control channel |

![The Scripting window after a run, marked 1 to 4](https://voltecx-web.nguyenvanqui291.workers.dev/docs/manual/img/en/scripting/01-script.png)

1. The script: the example below.
2. **Run**.
3. How many steps ran.
4. One row per step: the line, the command and its result.

### The format

```text
# A comment. Empty lines are skipped.
file.openExample {"name": "buck"}
simulation.settings {"tEnd": "5m"}

for d in 0.2, 0.25, 0.3
  circuit.variables {"set": {"D": ${d}}}
  simulation.run
  scope.measure {"signals": ["v(out)"], "t0": "3m"}
end
```

The part names and parameters in this example are an illustration. Look up the real ones with `command.list` and `circuit.inspect`.

| Line | Meaning |
|---|---|
| `command.id {JSON}` | Run one command. The parameters are a JSON object. Leave them out when there are none |
| `# text` | A comment |
| `let name = /pointer` | Keep a value from the result of the previous command. The pointer is a JSON pointer (RFC 6901), for example `/name` or `/a/0/b`. An empty pointer keeps the whole result |
| `${name}` | Use the kept value in a later line |
| `for name in a, b, c` ... `end` | Repeat the lines in between once for each value. Loops can be nested two deep, and loops and `if` blocks together eight deep |
| `let name = var/pointer` | Read a value from a kept variable instead (`let r =` keeps a whole result; `let eta = r/efficiencyPercent` reads it later) |
| `set name = expression` | Compute a number: `+ - * / % ^`, comparisons, `&&`, `\|\|`, `!`, functions such as `min`, `abs` and `if(c, a, b)`, and suffixes such as `100u`. Variables are used by name, without `${}` |
| `if expression` ... `else if expression` ... `else` ... `end` | Run the first branch whose expression is true |
| `break` | Leave the innermost `for` at once |

A value in a `for` line is read as JSON when it is valid JSON (`3`, `"text"`, `[1, 2]`). Otherwise it is a string, so `for r in 1k, 2.2k` gives `"1k"` and `"2.2k"`. In an expression such a string counts as its number.

This script sweeps the switching frequency of the `buck` example and stops at the first point whose output ripple is under 0.5 % of the output. The window and the command line list the variables the script ended with:

```text
# Sweep fsw on the buck example; stop at the first point whose output ripple is under 0.5 % of the mean.
file.openExample {"name": "buck"}
simulation.settings {"tEnd": "6m", "maxStep": "100n"}
set limit = 0.5
for f in 20k, 50k, 100k, 200k
  circuit.variables {"set": {"fsw": ${f}}}
  simulation.run
  scope.measure {"signals": ["v(out)"], "t0": "5m"}
  let m = /stats/v(out)
  let pp = m/peakToPeak
  let mean = m/mean
  set ripple = 100 * pp / mean
  if ripple < limit
    set best = f
    break
  else if ripple < 2 * limit
    set close = f
  end
end
set bestKHz = best / 1k
```

Saved as `ripple.pcs`, `powercraft-cli script ripple.pcs` runs two simulations: at 20 kHz the output ripple is 0.283 V (2.4 %), at 50 kHz 0.045 V (0.38 %), so the loop stops there and 100 kHz and 200 kHz never run. The last line lists the variables: `best` 50000, `bestKHz` 50, `ripple` 0.377. The window measures from 5 ms because the example's output filter rings for the first few milliseconds after start-up; measured from 1 ms the ringing, not the switching, sets the ripple.

`script.run` answers with `steps` (one row per command: `line`, `command`, `ok` and `result` or `error`), `ok`, `vars` (the variables the script ended with that hold a number, a boolean or a short string; whole results kept with `let` are not listed) and `used` (the steps counted). For example:

```sh
powercraft-cli run --cmd script.run --params '{"text": "set x = 2.2k * 2\nif x > 4k && x < 5k\n  set y = sqrt(x)\nelse\n  set y = 0\nend"}'
```

gives `"ok": true`, `"steps": []` (no command ran), `"used": 3` and `"vars": {"x": 4400.0, "y": 66.33…}`.

### Safety

- The whole script is checked before anything runs. A syntax error stops everything and names the line (`line 5: ...`). The circuit is not touched.
- Every name an expression or `${}` uses must be set on an earlier line, and `break` must be inside a `for`; both are checked before the run. A variable set only inside an `if` branch passes that check, but when the branch did not run, a later line that reads it stops the script there.
- The first command that fails stops the script. It is the last step in the report, and the steps before it stay in the circuit.
- A script can run at most 10,000 steps (each command, `let`, `set`, `if` test and loop pass counts as one), and at most 10 minutes, checked between steps. `script.run` takes `maxSteps` and `maxSeconds` to set lower or higher limits (up to 10,000 steps and 24 hours; the browser has no time limit). The text is limited to 1 MiB. A script cannot call `script.run`. A script stopped by a limit, a failed command or an unknown variable answers with `ok` false and an `error` naming the line, not with an error of the command itself. There is no `while`: every script ends.
- Commands run one after another. A simulation finishes before the next line starts, and in the desktop app the window does not update meanwhile.

### Undo

A script is one undo step, so one Undo takes back everything it changed. The step is called Script, or the `label` you give `script.run`. When a command fails, the step is called `Script (stopped at line N)`, and one Undo still returns the circuit to how it was before the script. Inside a script, `edit.undo` and `edit.redo` work as usual. A script that changes nothing adds no step. A circuit that the script opens gets one step after the one it was opened with.

The longer guide is [`docs/workflows/scripting.md`](https://voltecx-web.nguyenvanqui291.workers.dev/docs/workflows/scripting/) (in Traditional Chinese).

## The console

The console is a command line inside the window. Open it with View > Console or ⌘⇧Y (Ctrl+Shift+Y on Windows and Linux; Ctrl+`` ` `` opens the terminal, chapter 11). It sits under the schematic. Type one command on the line and press Enter. The result is printed above the line.

A line is one engine command, written as a script line or in a short form:

```text
circuit.setParam {"component": "R1", "key": "r", "value": "2k"}
circuit.setParam component=R1 key=r value=2k
```

In the short form each parameter is `name=value`. A number, `true`, `false` and `null` are read as JSON. A value with an SI prefix, such as `2k` or `100u`, stays text, and the engine reads the prefix. Put text with spaces in quotes: `label="input filter"`. Lists and objects are written as JSON: `components=["R1","C1"]`.

`let name = /pointer` keeps a value from the last result, `let name = var/pointer` reads one from a kept variable, `set name = expression` computes a number, and `${name}` uses a value in a later line, as in a script. `for`, `if`, `else`, `end` and `break` need several lines, so the console refuses them and points to Tools > Scripting.

| Key or word | What it does |
|---|---|
| Enter | Runs the line |
| Up, Down | Brings back earlier lines. The last 500 lines are kept when you quit |
| Tab | Completes a command, then a parameter name, then a part or net name after `component=` or `net=`. When several match, they are listed |
| Esc | Stops a simulation or sweep that the console started |
| `help` | Lists the commands by area |
| `help command.id` | Shows the menu item, the shortcut and the parameters of one command |
| `history` | Lists the lines you typed |
| `clear` | Empties the console |

A command runs the same way as its menu item. Each change to the circuit is one undo step. A simulation or a sweep runs in the background with progress in the status bar, and the console prints its result when it ends. A line that fails says why and changes nothing.

When you use a menu, a toolbar button or a shortcut, the console prints the command line that does the same thing. This is a quick way to learn the commands. To turn it off, clear Echo menu actions in the console in Edit > Preferences.

## Code Generation

When your controller is digital, you eventually need the control code in C. **Tools > Code Generation** turns the sampled control blocks of the active circuit into portable C99 code.

Choose the menu item. A window shows two files, `pc_control.h` and `pc_control.c`, one under the other, with the prefix `pc_control`. Above them, **Precision** picks the number format (`float`, the default, `double`, `q15` or `q31`) and writes the code again in it, and **Save Files…** writes each file into a folder you choose, under its own name (in the browser, each file downloads). **Copy** copies the text. Once you have built the code for a Cortex-M4, **ISR Execution Time** reads the listing of your build (`arm-none-eabi-objdump -d --no-show-raw-insn`, saved to a file) and shows under the buttons how many cycles the interrupt takes, in µs at 170 MHz, and its share of the PWM period, in red when it takes the whole period (`codegen.isrCycles`; the browser does not offer it). For the F28379D, call `codegen.isrCycles` with `{"core": "c28x"}` and the `.asm` file the TI C28x compiler keeps with `--keep_asm`: it counts each instruction at TI's published cycle counts at 200 MHz, names the run-time support functions it cannot see (such as a software divide), and gives no stack depth. Check the result with `isrGpio` and an oscilloscope. To change the prefix, give a `qM.N` format, or write the files from a script, use the commands:

| Command | What it does |
|---|---|
| `tools.codeGeneration` | Returns the text of the two files. `{"precision": "double", "prefix": "drive_ctl"}` |
| `file.exportCode` | Writes `<prefix>.h` and `<prefix>.c` (and the target's files) into the folder `dir`, within the folders you allow, then `<prefix>_map.json`: which state, signal, input and calibration fields belong to each block, the circuit signal behind each input and output field, the options, the circuit's hash, the Voltecx version and the hash of every other file written. `{"dir": "ctl", "precision": "double", "prefix": "drive_ctl"}` |
| `codegen.evidence` | Writes what `file.exportCode` writes, checks that the code is the same when generated again, with another prefix and (with a microcontroller target) on the portable target, runs `codegen.verify` and `codegen.closedLoop`, and writes `<prefix>_evidence.json`: the version, the circuit's hash, the options, every file's hash, the map and both replies with their coverage. `status` is `passed`, `failed`, or `incomplete` when a check could not run on this computer (no C compiler). The bundle has no time stamp, so the same circuit gives the same file. `{"dir": "review", "target": "stm32g474", "fullScale": 20}` |
| `codegen.ranges` | Before any run, says which values of the code may saturate in fixed point and which divisions may divide by zero. Give each measured input its range in `inputs`, or `fullScale` for every input read by the ADC (0 to the full scale). The reply lists, per block, the operations that may leave the format (with the values they may reach), the inputs the format cannot hold, the divisions whose divisor may be 0, and the range of every output and state. A value not listed cannot leave its range; a listed one may, so check it with `codegen.verify`. `{"precision": "q15", "fullScale": 20}` |

`precision` is `float` (the default), `double`, `q15`, `q31` or a fixed-point format such as `q7.24`. `q15` and `q31` choose the integer bits that hold every constant of the code, and the reply's `format` names the result (chapter 16, `design.digitalize`). The prefix must be a C identifier: letters, digits and `_`, starting with a letter.

The generated code has no `malloc` and no global variables. You use `<prefix>_init(&state)` once at start-up, `<prefix>_reset(&state)` to restart without losing gains tuned at run time (see below), and `<prefix>_step(&state, &inputs, &outputs)` at every sample. The header declares the state, input and output structures.

### Microcontroller targets

`target` adds the set-up and the interrupt of one microcontroller to the two files. The default `portable` adds nothing.

| `target` | Extra files | What they do |
|---|---|---|
| `stm32g474` | `<prefix>_stm32g474.h`, `_init.c`, `_isr.c` | TIM1 makes the PWM (CH1, its complement CH1N with the dead time) and triggers ADC1. The ADC interrupt scales the codes into the inputs, runs `<prefix>_step` and writes the duty into TIM1_CCR1. |
| `f28379d` | `<prefix>_f28379d.h`, `_init.c`, `_isr.c`, `_main.c`, `<prefix>_f28379d.projectspec` | ePWM1 makes the PWM (EPWM1A, its complement EPWM1B through the dead band). SOCA at CTR = ZERO starts ADC-A, and its interrupt 1 runs `<prefix>_step` and writes the duty into the shadowed CMPA. The CLA is not used. Import the `.projectspec` into Code Composer Studio (File > Import > CCS Projects) after setting `C2000WARE_ROOT` in it. |
| `f280049c` | `<prefix>_f280049c.h`, `_init.c`, `_isr.c`, `_main.c`, `<prefix>_f280049c.projectspec` | The TI F280049C (LaunchPad LAUNCHXL-F280049C). One to three `pwm` blocks on ePWM1 to ePWM3 (EPWMxA, and EPWMxB through the dead band with a `deadtime` block). ADC-A runs on its internal 3.3 V reference, so `fullScale` defaults to 3.3; up to 10 inputs on A0 to A6 and A8 to A10, then ADC-B (B0, B2 to B4) and ADC-C (C0 to C5, C14), 21 inputs in all. Name `PGA1` to `PGA7` in `adcChannels` to read an input through that on-chip amplifier (the signal on its PGAn_IN pin) at the gain `pgaGain` sets (3, 6, 12 or 24, default 3); that input's full scale is `fullScale` divided by the gain. SOCA at CTR = ZERO starts every ADC in use, and ADC-A's interrupt 1 waits for ADC-B and ADC-C, then runs `<prefix>_step` and writes the duties into the shadowed CMPA. The ePWM runs on SYSCLK (100 MHz), so `timerClock` is not taken, nor are the f28379d-only options. With a `supervisor` the files also run the start-up sequence, the soft start and the fault states: the outputs stay low (a one-shot trip) until `<prefix>_f280049c_enable(1)`, the measured input voltage, output voltage and temperature go on the ADC-A pins the code's inputs leave free, and the current limit is CMPSS1's high comparator on the A2 pin, which ends a PWM period early on every ePWM without software (a blanking time needs a sawtooth carrier). Set `C2000WARE_ROOT` in the `.projectspec`, then import it into Code Composer Studio. |

The timer counts follow the circuit's `pwm` block: its frequency, a sawtooth carrier (counting up) or a triangle (counting up and down), and the dead time of a `deadtime` block, rounded up to whole timer counts so it is never shorter. A `deadtime` block whose `tdn` gives the complement `outn` its own dead time (one block driving both switches of a half bridge) sets the F28379D's DBFED from `tdn` and DBRED from `td`, and `mcu.deadTime` gives both (`counts` and `fedCounts`); the STM32G474's TIM1 has one dead time for both edges and refuses it. `timerClock` is the timer's clock (TIM1 at 170 MHz, or EPWMCLK at 100 MHz, the most the F28379D allows). `fullScale` is the value of an input when the ADC reads 4095 (3.3 on the STM32G474, 3.0 on the F28379D). On the F28379D, `isrGpio` names a GPIO (0 to 168) that the ADC-A interrupt sets high on entry and clears on exit: a scope on that pin shows how long the control step takes and how often it runs. It cannot be an EPWM pin the code drives (EPWMmA is GPIO 2m − 2, EPWMmB GPIO 2m − 1). `adcTrigger` sets where ePWM1 starts ADC-A: `valley` (the default) at the counter's zero, which is the middle of the on pulse on a triangle carrier and its start on a sawtooth; `peak` at the counter's period, the middle of the off pulse on a triangle carrier, so the new duty cycle starts half a period after the sample. `peak` needs a triangle carrier. `midPulse` samples in the middle of ePWM1's on pulse on a sawtooth carrier: the interrupt also writes half of the new CMPA (at least 1) into CMPB, and ADC-A starts when the counter reaches CMPB counting up. It needs a sawtooth carrier; on a triangle `valley` is already the middle of the on pulse. When the code runs faster than the PWM, a whole number of times per period (2 to 8, for example an interleaved converter whose `zoh` or `dpi` per phase samples at its own carrier, k/n of a period after the first), ePWM1 starts nothing: the next ePWM module after the ones the circuit drives counts up on the same clock at that multiple of the PWM frequency, and its zero starts the ADCs, so the step runs at ePWM1's zero and every 1/n of a period after it. The period's counts must divide by n (pick the PWM frequency so they do); `adcTrigger` stays `valley`, and CPU2, `syncInGpio`, the supervisor, `pwmStart` `firstDuty`, `startStop` and `codegen.pil` refuse it. `mcu.stepsPerPeriod` and `mcu.stepTrigger` (`module`, `tbprd`, `trigsel`) give it. On the STM32G474 the code may run twice per period (one sample per carrier: TIM1 and TIM8): TIM1's channel 4 starts nothing, TIM20 counts up on TIM1's counter clock at twice the PWM frequency, and its update event (tim_trgo) starts ADC1 and ADC2, one counter clock after each phase's start, since TIM20 is preset to its ARR so its first update comes right after TIM1 starts. The period's counts must divide by 2; the supervisor and `codegen.pil` refuse it, and `mcu.stepTrigger` gives `timer` and `arr`. `adcChannels` lists the board's ADC pin of each conversion: the code's inputs in the order the reply's `mcu.adcInputs` gives, then the supervisor's input voltage, output voltage and temperature. A number is an ADC-A CHSEL, 0 to 5 for ADCINA0 to ADCINA5 or 14 and 15 for ADCIN14 and ADCIN15; a name such as `"ADCINB2"` picks a pin of any of the four ADCs: ADCINA0 to ADCINA5, ADCIN14, ADCIN15, ADCINB0 to ADCINB5, ADCINC2 to ADCINC5 and ADCIND0 to ADCIND5 (the 337-ball package). No pin may be named twice, and the supervisor's measurements stay on ADC-A. A conversion past the end of the list takes the first of those pins, in that order, the list leaves free, so leaving it out keeps the order ADCINA0 to ADCINA5, ADCIN14, ADCIN15 and puts a ninth input and more on ADC-B, then ADC-C and ADC-D, up to 24. The same ePWM1 SOCA starts every ADC used, each from its own SOC0, and the ADC-A interrupt waits for the others to finish before it reads them; when no input is on ADC-A, its SOC0 converts a free pin only so that its end runs the step. The pins become the defaults of the channel macros, and `mcu.adcChannels` and `mcu.adcPins` give the CHSEL and the name of every conversion's pin. `pwmPolarity` sets which pin level turns a switch on: `activeHigh` (the default) or `activeLow`, for a gate driver with inverting inputs. Active low makes the dead band active low complementary (DBCTL[POLSEL] = 1; with no `deadtime` block it inverts EPWMxA with no delay), and every trip, the supervisor's included, forces the pins high, their off level. The duty cycle and the timing do not change, and `mcu.pwmPolarity` echoes the choice. For a single switch with no `deadtime` block, `pwmPins` (f28379d only) drives one pin of each module: `aOnly` sets up only EPWMxA (GPIO 2m − 2), and `bOnly` only EPWMxB (GPIO 2m − 1), which AQCTLB sets and clears on the same CMPA events. The pin left out stays a GPIO for your board, and `isrGpio` may use it. The default `both` sets up both pins, and `aOnly` or `bOnly` is refused when the circuit has a `deadtime` block, whose complement needs EPWMxB. `independent` drives two switches from each module, a two-phase PWM: the `pwm` blocks are taken two to a module in block order, the first on EPWMxA at CMPA and the second on EPWMxB at CMPB, both on the module's carrier, so the two blocks of a pair need the same frequency and phase. With a wired `freq` input each pair's CMPB is scaled to the period the code writes, as its CMPA is, and a wired `phase` input moves a pair's module when both blocks of the pair read the same phase signal. It is refused with a `deadtime` block, an odd number of legs, a pair whose phases differ (drawn phases, or `phase` inputs on different signals or on one block only), the `midPulse` ADC trigger, a phased step and the PIL backend. With the supervisor, its trip holds both pins of each module off and the interrupt clears CMPB with CMPA while the PWM is off, and CMPSS1's current limit trips both legs of a module. `mcu.pwmPairs` lists each module's two blocks. `mcu.pwmPins` echoes the choice. `pwmPinBank` (f28379d only) picks the GPIOs the ePWM pins go out on: `gpio0` (the default) puts EPWMmA on GPIO 2m − 2 and EPWMmB on GPIO 2m − 1, and `gpio145` puts them on GPIO145 to GPIO160 (EPWM1A on GPIO145, EPWM8B on GPIO160). Those pins exist only on the 337-ball ZWT package, and choosing them frees GPIO0 to GPIO15 for `isrGpio`, `digitalOut` or EXTSYNCOUT on GPIO6 with four or more modules. `mcu.pwmPinBank` echoes the choice and `mcu.pwmGpios` lists each driven pin with its GPIO. `pll` (f28379d only) sets the system clock instead of `InitSysCtrl`'s 200 MHz: `{"source": "xtal", "oscHz": 20e6, "imult": 10, "div": 2}` gives SYSCLK = 20 MHz × 10 / 2 = 100 MHz, and CPU1's `main` calls C2000Ware's `InitSysPll` after `InitSysCtrl`. The source is `xtal` (a 10 to 20 MHz crystal), `x1` (a 2 to 25 MHz clock on X1) or `intosc2` (the 10 MHz internal oscillator, no `oscHz`), and `fmult` adds 0.25, 0.5 or 0.75 to `imult`. Settings the PLL or the data sheet do not allow are refused by name: the oscillator times the multiplier must be 120 to 400 MHz, and SYSCLK 20 to 200 MHz (194 MHz from `intosc2`). The ePWM clock is then SYSCLK / 2, so leave `timerClock` out; the step timer, the ADC sample windows, the SCI baud rate, the APWM and eCAP counts and the `digitalIn` qualification are all worked out at the new SYSCLK. `mcu.sysclkHz` and `mcu.pll` echo it. For an encoder read by eQEP1 or eQEP2, `eqep1Gpio` (f28379d only: 20, the default, 50 or 10) and `eqep2Gpio` (24, the default, 54 or 78) pick the GPIO of the module's A input, and with it the B, strobe and index pins next to it: eQEP1 on GPIO20 to 23, GPIO50 to 53 or GPIO10 to 13, eQEP2 on GPIO24 to 27, GPIO54 to 57 or GPIO78 to 81 (TI data sheet SPRS880P, table 5-3). GPIO10 to 13 are refused while the code drives ePWM6 or ePWM7 on GPIO0 to 15. `mcu.eqepGpios` lists each counting module with its four pins. `pwmStart` (f28379d only) sets when the gate pins start switching. With `immediate` (the default) they follow the PWM as soon as the time bases start, at the duty of 0 that the init writes until the first step's duty loads; with a `deadtime` block the complement EPWMxB is then on. `firstDuty` holds both pins of every module at their off level (low, or high with `pwmPolarity` `activeLow`) by a software one-shot trip from the init until the second interrupt, the first one after the first step's duty has loaded, which releases them, so the pins first switch at the code's own duty. It is refused with the supervisor, which already holds the outputs off until its soft start, and with a wired `freq`, whose step does not follow the PWM period. `mcu.pwmStart` echoes the choice. `startStop` (f28379d only) adds two calls for your own firmware code: `<prefix>_f28379d_pwm_stop()` holds every module's pins at their off level at once by the same one-shot trip and stops running the control step, so the controller keeps its state; `<prefix>_f28379d_pwm_start()` has the next interrupt reset the controller and run the step again, and the one after it, once that duty has loaded, release the pins. A start while the pins run does nothing, and a stop drops a start the interrupt has not taken yet. It is refused with the supervisor, whose `<prefix>_f28379d_enable()` already starts and stops the outputs, and with a wired `freq`. `initialDuty` (f28379d only, 0 to 1, default 0) is the duty cycle whose compare value the init writes into every module before the first step writes the code's own, rounded to whole counts. `mcu.startStop`, `mcu.initialCmpa` and `mcu.initialDuty` echo them. To run one board's PWM in step with another's (f28379d only), `syncInGpio` names a GPIO whose rising edge restarts ePWM1's period: the code routes it through INPUT5 of the Input X-BAR to EXTSYNCIN1, ePWM1 loads a phase of 0 on it, and the other modules follow ePWM1 as before. Send one pulse per PWM period; without one, ePWM1 runs on its own clock. `syncOut: true` sends ePWM1's sync at the start of each period out on EXTSYNCOUT, GPIO6, for the other board's `syncInGpio`. GPIO6 is also EPWM4A, so `syncOut` is refused when the code drives a fourth module. Neither works on CPU2 or with a pin the code already uses, and `syncInGpio` is refused with a wired `freq`. `mcu.syncIn` and `mcu.syncOut` echo them. With more than three modules, `syncChain` picks the sync that ePWM4 (heading ePWM4 to ePWM6) and ePWM7 (heading ePWM7 and ePWM8) follow: `epwm1`, ePWM1's sync, as before; `epwm4` (ePWM7 only), so ePWM7's chain follows whatever ePWM4's does; `extsyncin1`, the `syncInGpio` edge that ePWM1 follows too; or `extsyncin2`, a second pin named by `sync2InGpio` (INPUT6 of the Input X-BAR). A chain on the second pin counts its phases from that pin's rising edge instead of ePWM1's carrier, so it cannot take a wired phase. `mcu.syncChain` and `mcu.syncIn2` echo the choice. A `pwm` block whose carrier spans its input's units (`offset` and `vpp`, chapter 10) is mapped in the interrupt on the STM32G474 and the F28379D: it writes the compare of (duty − offset)/vpp, and `mcu.legs` gives each leg's `offset` and `vpp`. With the default carrier the interrupt is the same as before. On any target, `comment` puts your own text (the project, the board revision, who generated the code) in a block comment under the banner of every generated `.c` and `.h` file, so the firmware says where it came from; it may have up to 20 lines and 2000 characters, `*/` and `/*` are split so it cannot change the code, and characters outside printable ASCII become `_`. On the F28379D, up to eight `pwm` blocks at one frequency and carrier (interleaved phases, a DAB's two bridges, several converters on one controller) run on ePWM1 to ePWM8 in the order of the blocks, each module's counter loaded with its block's carrier phase on ePWM1's sync; ePWM4 and ePWM7 start the second and third sync chains and take ePWM1's sync through SYNCSELECT. EPWMmA and EPWMmB are GPIO 2m − 2 and 2m − 1 (GPIO0 to GPIO15), and a ninth block is refused. A later block's `phase` input may be wired on the F28379D (a phase-shifted full bridge or a DAB whose controller moves the shift): the control computes the phase in degrees, and each step turns it into the fraction of a period the module runs ahead of the first block's carrier and writes it into the module's phase count (TBPHS, and on a triangle carrier the direction PHSDIR, counting down past the peak), which ePWM1's next sync loads. Until the first step the module runs in step with ePWM1, and a phase that is not a number is 0. With a wired `freq` too, the phase count follows the new period. `mcu.wiredPhases` names each block, its module and the output field. The first block keeps a fixed phase, since the others count from its sync; the STM32G474 and `codegen.pil` refuse a wired phase. A `pwm` block whose `freq` input is wired (an LLC or a CRM PFC whose controller sets the switching frequency) runs on the F28379D only: the control computes the frequency, and each step turns it into ePWM1's period, clamped to what ePWM1 counts (`mcu.variableFrequency` gives `minHz` and `maxHz`, at least a quarter of the block's own frequency up to where a period has 64 counts), and scales every duty cycle to that period; a frequency that is not a positive number keeps the block's own. The period and the duty load together at the next counter zero. The step no longer follows the PWM: CPU Timer 0 starts the ADCs at the code's sample time (the block's own period when nothing in the control has one), so `adcTrigger` stays `valley`. Several `pwm` blocks must read the same frequency signal. A block whose carrier is shifted against the first keeps that fraction of a period: each step scales its phase count (TBPHS) to the new period, and the module loads its period on ePWM1's sync together with the phase. the supervisor and `codegen.pil` refuse a wired frequency, and so does the STM32G474. The reply's `mcu` object gives the register values. The `supervisor` is generated for `stm32g474` and `f28379d`. On the F28379D, CMPSS1's high comparator compares the current sense on the ADCINA2 pin with its DAC (`ocpThreshold`, below the 3.3 V VDDA reference) and trips every ePWM module cycle by cycle through the ePWM X-BAR and the digital compare; the outputs are forced low and come back at the next period start once the current is below the threshold. A `blanking` time is counted from the period start and needs a sawtooth carrier. ADC-A converts the input voltage, the output voltage and the temperature after the control's inputs, and a software one-shot trip keeps the outputs low until `<prefix>_f28379d_enable(1)` and the soft start.

A PSIM or PLECS C block's own persistent state (a `static` it declares) is moved into the state struct too, so `<prefix>_reset` clears it along with every other state, unless the code declares one codegen cannot place there (an array, several names on one declaration, an initialiser that is not a plain number, or one at file scope in a PLECS block's `declarations` section) — such a block is left out with the reason, rather than shipping a value a restart can never reach.

#### Running from RAM or from flash (F28379D)

The `.projectspec` has four build configurations. Pick one in Code Composer Studio with Project > Build Configurations > Set Active (or the arrow beside the hammer):

| Configuration | Linker file (C2000Ware `device_support/f2837xd/common/cmd/`) | Compiler options | Use it to |
|---|---|---|---|
| `RAM-Debug` | `2837xD_RAM_lnk_cpu1.cmd` | `--opt_level=off` | step through the code; it is loaded by the debugger and lost at power-off |
| `RAM-Release` | `2837xD_RAM_lnk_cpu1.cmd` | `--opt_level=2` | measure the interrupt's time with the optimiser on |
| `Flash-Debug` | `2837xD_FLASH_lnk_cpu1.cmd` | `--opt_level=off --define=_FLASH` | debug the flash image |
| `Flash-Release` | `2837xD_FLASH_lnk_cpu1.cmd` | `--opt_level=2 --define=_FLASH` | ship: the firmware runs on its own after a reset |

All four keep `-v28 -ml -mt --float_support=fpu32 --tmu_support=tmu0 --define=CPU1`. `--opt_level=2` is the compiler's `-O2` (TI SPRU514AA, section 3.1). In the flash configurations `main` copies the `.TI.ramfunc` section from flash to RAM (`memcpy` of `RamfuncsLoadStart`, `RamfuncsLoadSize`, `RamfuncsRunStart`, the symbols of the FLASH linker file) before it enables the interrupts, and C2000Ware's `InitSysCtrl` sets the flash wait states. To run a flash build without the debugger, set the boot-mode pins of the board to boot from flash (see your board's guide) and reset it.

#### Running the controller on CPU2 (F28379D)

The F28379D has two C28x cores. With `cpu` set to `cpu2` (Code target form: Controller CPU core; the default is `cpu1`) the controller runs on CPU2 and leaves CPU1 free for your own code. The set-up and interrupt files are the same as on CPU1; `<prefix>_f28379d_main.c` gives way to two programs, and the `.projectspec` holds one CCS project per core, `<prefix>_f28379d_cpu1` and `<prefix>_f28379d_cpu2`, the way C2000Ware's dual-core examples are laid out:

- `<prefix>_f28379d_cpu1_main.c` sets the clocks and muxes the ePWM pins, which only CPU1 can do, then gives the ePWM modules and the ADCs the code uses to CPU2 (`DevCfgRegs.CPUSEL0` and `CPUSEL11`). In the flash configurations it also boots CPU2 from its flash (`IPCBootCPU2`, under `_STANDALONE`). Last it sets IPC flag 17. Add your own CPU1 code after that.
- `<prefix>_f28379d_cpu2_main.c` waits for IPC flag 17, clears it, and then sets up and runs the controller as on CPU1.

From RAM, load each project onto its own core in the debugger and run both, in either order. From flash, program CPU2's flash first, then CPU1's; after a reset CPU1 starts CPU2. Some things only CPU1 can reach, so `cpu2` refuses them by name: the supervisor (its trip goes through the ePWM X-BAR), `isrGpio` (the GPIO mux), a `pwm` with a wired frequency (CPU1's Timer 0 starts the ADCs), and more than three ePWM modules (ePWM4 and later sync through `SYNCSELECT`). `mcu.cpu` in the reply echoes the choice.

On the f28379d target, `dac` shows up to three of the code's values on the buffered DAC pins, so a scope can watch an error, a duty or a sampled current while the board runs. Each entry names a field of the outputs struct (or of the inputs struct) and the two values that map to the pin's ends: `{"field": "duty", "low": 0, "high": 0.5}` puts a duty of 0 at 0 V and 0.5 at VREFHI. The first entry goes to DAC-A (the ADCINA0 pin), the second to DAC-B (ADCINA1) and the third to DAC-C (ADCINB1). Each step writes them after the duty, clamped to the 12-bit range. The DAC drives that pin, so a measurement the code takes there is refused; move it with `adcChannels`. The pin is linear from 0.3 V to VDDA − 0.3 V.

On the f28379d target, `adcDifferential` puts ADC-B, ADC-C or ADC-D in 16-bit differential mode, for a sensor with a differential output such as a shunt amplifier: `{"adcChannels": ["ADCINB2"], "adcDifferential": ["ADC-B"]}` measures the first input as ADCINB2 minus ADCINB3. On such an ADC each measurement is a pin pair named by its even pin (the positive input); the odd pin next to it is the negative input, so it cannot be another measurement or a DAC output. The code reads 0 at -VREFHI between the pins and 65535 at +VREFHI, so the input's `FULL_SCALE` macro is its value at +VREFHI and its `OFFSET` defaults to minus that: 0 V between the pins reads 0. Each conversion samples for at least 320 ns, and an ADC whose conversions do not end within one step is refused. ADC-A stays 12-bit single-ended. On the board, VREFLO must be tied to VSSA and each pair's common mode must sit within 50 mV of VREFHI/2, so do not ground the negative input. `mcu.adcPairs` in the reply lists each pair (TI SPRUHM8K 11.2.4, table 11-6; SPRS880P p.109).

Each of the f28379d's four ADCs has its own reference pin, VREFHIA to VREFHID, which the board drives (the part has no internal reference). When they differ, `adcVrefhi` gives them in volts: `{"adcChannels": ["ADCINB2"], "adcVrefhi": {"ADC-B": 2.5}}` measures the first input on ADC-B with a 2.5 V reference while ADC-A stays at 3.0 V. Each value must be from 2.4 V to VDDA (at most 3.47 V); an ADC left out keeps 3.0 V. `fullScale` is the input value at ADC-A's full-scale code and defaults to ADC-A's VREFHI, and an input on another ADC reads its full scale at `fullScale` times its ADC's VREFHI divided by ADC-A's, written as that input's `FULL_SCALE` macro. The supervisor's measurements keep their own scales. `mcu.adcFullScales` in the reply lists each input's full scale (TI SPRS880P 6.10 and 6.10.1.2.3; SPRUHM8K table 11-2).

Also on the f28379d target, `apwm` puts up to six of the code's values out as the duty cycle of a fixed-frequency PWM, for a fan, a relay driver, a level through an RC filter or another stage's set point. Each entry names a field, the values at a duty of 0 and of 1, the frequency and the pin: `{"field": "duty", "low": 0, "high": 0.5, "freq": "25k", "gpio": 24}`. The first entry runs on eCAP1 in APWM mode, the next on eCAP2 and so on, and each goes out through the Output X-BAR, so the pin must be one that carries an Output X-BAR output (GPIO24 to GPIO31, 34, 37, 48, 49, 58 to 61, or an ePWM pin the code does not drive). Two entries cannot share an OUTPUTXBAR output. The frequency is rounded to whole 200 MHz clock cycles, from 12 Hz to 100 MHz, and each step loads the new duty at the end of the APWM's period. `mcu.apwm` shows each module's pin, period and frequency. The f280049c target takes `apwm` too, up to seven entries on eCAP1 to eCAP7: the frequency is rounded to whole 100 MHz clock cycles, from 6 Hz to 50 MHz, and the pin must be one of the 100-pin package's Output X-BAR pins (GPIO2 to GPIO7, 9, 11, 14 to 17, 24 to 31, 33, 34, 58 or 59) that the code does not already use.

The eCAP modules can also measure. `capture` reads up to six of the code's measured inputs from a pulse train on a GPIO, such as a tachometer, a Hall sensor or another stage's PWM, instead of from the ADC. Each entry names the input, the pin, what to measure and a gain: `{"field": "tach", "gpio": 40, "measure": "frequency", "gain": 60}` reads a one-pulse-per-turn tachometer on GPIO40 as revolutions per minute. `measure` is `frequency` (Hz, the default), `period` (s) or `duty` (the high time over the period, 0 to 1). The inputs take the eCAP modules after those `apwm` uses, six in all, and any free GPIO up to GPIO168 reaches them through the Input X-BAR. Each module times the high and the low part of every pulse with the 200 MHz clock. When the train slows down or stops, the frequency falls with the time since the last edge, and it reads 0 before the first whole pulse and after 21 s without an edge. Two entries can measure one pin, for its frequency and its duty. The code must be float or double. `mcu.capture` shows each module, its pin and its Input X-BAR input.

An entry with `"count": true` also counts the pulses, for a flow meter, an energy meter's pulse output or a tachometer's revolutions. The module raises its interrupt (ECAP1_INT to ECAP6_INT) on each falling edge, and `<prefix>_f28379d_ecap<m>_pulse_count()` returns the edges since the start, wrapping at 2^32, so the pulses between two reads are the difference. Two edges that come while the control interrupt is running count once, so the count is exact for pulses longer than the step's run time. `mcu.capture` adds the interrupt and its PIE line.

Plain on/off signals go out with `digitalOut`. Each entry names a field, a GPIO and an optional threshold: `{"field": "fault", "gpio": 40}` drives GPIO40 high while `fault` is above 0.5 and low otherwise, so a logic block's 0 and 1 become low and high. Up to eight pins, for a relay, a fan enable, a status LED or a fault line to another board. The init clears each pin's latch before making it an output, so it starts low; the interrupt writes it after each step. A pin the code already uses is refused by name; `mcu.digitalOut` echoes the pins.

On/off signals come in with `digitalIn`. Each entry names one of the code's measured inputs and a GPIO: `{"field": "enable", "gpio": 40, "pullup": true}` reads `enable` as 1 while GPIO40 is high and 0 while it is low, instead of from the ADC. Add `"activeLow": true` for a line that is active when low, such as a gate driver's fault output, and `"pullup": true` for a switch or an open-drain line to ground; without the pull-up the board must drive the pin. Up to eight pins. The interrupt reads each pin before the step. A pin the code already uses, a digital output's included, is refused by name; `mcu.digitalIn` echoes the pins.

A noisy line, such as a mechanical switch or a long cable, can be filtered in the pin itself with `"qualify": {"samples": 6, "samplePeriod": 1e-7}`: a change only passes once 3 or 6 samples in a row agree, here 100 ns apart, so glitches shorter than the window are ignored. The period is 5 ns (one 200 MHz SYSCLK cycle) or an even number of cycles up to 2.55 µs; another value is refused with the two nearest. Pins GPIO0–7, 8–15 and so on share one period, so qualified pins in one group of eight must ask for the same one. `mcu.digitalIn` gives each window and how long the pin must hold for a change to pass for sure (SPRUHM8K 8.4.3).

An input can count a pin's edges instead of reading its level: `{"field": "trips", "gpio": 40, "edges": "falling"}` reads `trips` as the number of falling edges on GPIO40 since the previous step, so a fault pulse shorter than one step is never missed (compare it with 0.5 for a latch), and a pulse train is counted. `edges` is `rising`, `falling` or `both`; it does not go with `activeLow`, so name the pin's own edge. Each counting pin takes one of the CPU's five external interrupts, XINT1 to XINT5, through its fixed Input X-BAR input, whose small handler counts the edge (held at 65535); the step's interrupt reads the count and clears it. `syncInGpio` and `sync2InGpio` hold the inputs of XINT2 and XINT3, which are then skipped, so at most five pins count edges. `qualify` filters a counting pin too. `mcu.digitalIn` names each pin's XINT (SPRUHM8K 3.17.6, table 9-1).

An isolated measurement from a sigma-delta modulator comes in with `sdfm`. Each entry names one of the code's measured inputs, the modulator's data pin, its clock and its clipping voltage: `{"field": "ia", "gpio": 16, "clock": 20e6, "vclip": 0.32, "gain": 500}` reads `ia` from SDFM1 filter 1 (data on GPIO16, clock on GPIO17) instead of the ADC, for a modulator that clips at 0.32 V across a 2 mΩ shunt (500 A per volt). The data pin is an even pin of GPIO16–30, GPIO48–62 or GPIO122–136, which also picks the filter, and the clock comes in on the next pin. `filter` (`sinc1`, `sinc2`, `sinc3` or `sincfast`; Sinc3 by default) and `osr` (1 to 256; 128 by default) set the data filter, and `mode` (0, 1 or 3) says whether the clock runs at, at half of or at twice the data rate. Take the clock and the clipping voltage from the modulator's data sheet and your board: Voltecx has no default for them. The interrupt reads the filter's 32-bit output before each step and scales it by the clipping voltage over the filter's peak (SPRUHM8K 14.7, table 14-3). A clock outside the data sheet's range, mode 2 (Manchester) and a filter slower than the step are refused; the reply names the largest OSR that keeps up. Up to eight inputs, float or double precision only. `mcu.sdfm` echoes each filter with its output rate, its settling time and its scale.

A fault line from the board, such as a gate driver's fault output or a desaturation detector, can turn the switches off in hardware with `tripIn`: `{"gpio": 40}` routes GPIO40 through Input X-BAR INPUT1 to TZ1, a one-shot trip of every ePWM module the code drives, so a low level on the pin forces EPWMxA and EPWMxB to their off level at once, without waiting for the step. `activeHigh: true` takes a line that is high on a fault (the pin's input is inverted, since TZ1 is active low), and `pullup: true` turns on the pin's pull-up for an open-drain line with none on the board. The pin is read asynchronously, so the trip needs no clock. The outputs stay off until the firmware calls `<prefix>_f28379d_trip_clear()` once the line is back to idle; `<prefix>_f28379d_tripped()` says whether the pin holds a trip, and `<prefix>_f28379d_trips()` counts them (ePWM1's trip interrupt, PIE INT2.1). The code's own stops (the supervisor, `startStop`, `pwmStart: firstDuty`) never release a trip from the pin. A pin the code already uses, cpu2 and other targets are refused; `mcu.tripIn` echoes it (SPRUHM8K 9.1, 15.2, 15.9.2).

The `f280049c` target takes `tripIn` too, with the same fields. The functions are `<prefix>_f280049c_trip_clear()`, `<prefix>_f280049c_tripped()` and `<prefix>_f280049c_trips()`, the outputs are forced low, and the supervisor's soft start waits for the clear. The pin must be one of the 100-pin PZ package's GPIOs: GPIO0 to GPIO17, GPIO22 to GPIO34, GPIO39, GPIO40 or GPIO56 to GPIO59, and not an ePWM output the code drives. GPIO18 and GPIO19 (the crystal) and GPIO35 and GPIO37 (TDI and TDO, the debugger's JTAG) are refused (SPRUI33H 9.1, 18.9; SPRS945H tables 5-1 and 5-3).

The `f280049c` target also takes `isrGpio`, the ISR timing pin: the pin is high while the ADC-A interrupt runs, so an oscilloscope on it shows how long the step takes and how often it runs. It can be any of the same PZ GPIOs, as long as it is not an ePWM output the code drives or the `tripIn` pin. `<prefix>_f280049c_init()` makes it a push-pull output, low, and `mcu.isrGpio` echoes it (SPRUI33H 8.2, 8.9.3).

The `f280049c` target reads `digitalIn` too, for pin levels: `{"field": "enable", "gpio": 40, "pullup": true, "activeLow": false}` reads `enable` from GPIO40 before each step instead of from the ADC, as on the `f28379d`. The pin can be any of the same PZ GPIOs that no driven ePWM output, `isrGpio`, `tripIn` or `digitalOut` entry uses. Each pin is synchronised to SYSCLKOUT unless it has a sampling window: `qualify` works as on the `f28379d`, with the samples counted at this device's SYSCLK of 100 MHz, so `samplePeriod` is 10 ns (QUALPRD 0) or 20 ns to 5.1 µs in steps of 20 ns, and pins in one group of 8 share one period. Edge counts (`edges`) are `f28379d` only and refused here. `mcu.digitalIn` echoes the pins and each window (SPRUI33H 8.2, 8.4, 8.5.2, 8.5.3, 8.9.2, 8.9.3).

The `f280049c` target also takes `pwmStart`, `startStop` and `initialDuty`, as the `f28379d` does. `"pwmStart": "firstDuty"` holds every driven ePWM's pins low by a one-shot trip from init until the first step's duty has loaded; `"startStop": true` adds `<prefix>_f280049c_pwm_stop()` and `<prefix>_f280049c_pwm_start()`, which hold the pins low and stop the step, then reset the controller and release the pins once its first duty has loaded; `initialDuty` is the duty whose CMPA init writes before the first step. With a `supervisor` the first two are refused, since it owns that trip; with `tripIn` the release waits until the fault pin's trip is cleared. The reply's `mcu` echoes `pwmStart`, `startStop`, `initialCmpa` and `initialDuty`.

The `f280049c` target also takes `syncInGpio` and `syncOut`, as the `f28379d` does. `syncInGpio` is a GPIO of the 100-pin package whose rising edge restarts ePWM1's period: Input X-BAR INPUT5 takes it as EXTSYNCIN1, which becomes ePWM1's sync input through SYNCSELECT, and the other modules follow ePWM1. `"syncOut": true` sends ePWM1's sync at the start of each period out on EXTSYNCOUT, GPIO6, for another board's sync input; GPIO6 is also EPWM4A, so it is refused with a fourth ePWM module. The second sync pin (`sync2InGpio`, Input X-BAR INPUT6 as EXTSYNCIN2) and `syncChain` (the sync input of ePWM4 and ePWM7, the heads of the second and third chains) work as on the `f28379d`, with the same choices: `epwm1`, `epwm4` (ePWM7 only), `extsyncin1` and `extsyncin2`. A chain on `extsyncin2` counts its phases from the second pin's rising edge. The reply's `mcu` echoes `syncIn`, `syncOut`, `syncIn2` and `syncChain`.

Values can go out on an SPI bus with `spi`, for an external SPI DAC that puts a controller's internal signals on a scope, a digital isolator to another board or a logic analyser: `{"module": "SPI-B", "baud": 10e6, "words": [{"field": "vout", "low": 0, "high": 3}, {"field": "duty", "low": 0, "high": 1, "codeBits": 12, "command": 3}]}` makes SPI-B the master (SPISIMO, SPICLK and SPISTE on GPIO24, GPIO26 and GPIO27) and sends, after each step, a frame of two 16-bit words: `vout` from 0 to 3 V as a code from 0 to 65535, then `duty` as a 12-bit code under the command 3 in the top four bits. The words go into the transmit FIFO back to back, so SPISTE stays active across the frame and goes inactive after it, and the receiving part sees one chip-select frame a step. Each word is `command` above a `codeBits`-bit code (by default the whole word less `shift`) above `shift` zero bits, the code being `low` at 0 and `high` at its largest value, rounded and clamped; set them from the receiving part's data sheet. `wordBits` (1 to 16) sets the word length, `clockPolarity` and `clockPhase` (0 or 1) are TI's CLKPOLARITY and CLK_PHASE bits (pick them from the timing diagram, since other makers number the four schemes differently), `simoGpio` picks another pin group, and `baud` is the fastest clock the receiving part takes: the code runs at the fastest LSPCLK / (SPIBRR + 1) not above it. A frame that would start while the last one is still in the FIFO is skipped and counted by `<prefix>_f28379d_spi_skipped()`, and `<prefix>_f28379d_spi_frame` keeps the last frame sent. A frame longer than the step, a pin the code already uses, a word that does not fit, more than 16 words, cpu2 and other targets are refused; `mcu.spi` echoes the pins, SPIBRR, the clock and the frame's length (SPRUHM8K 18.3, 18.4.2; SPRS880P table 5-3).

Measured inputs can come in on an SPI bus with `spiIn`, from an external or isolated SPI ADC instead of the on-chip ADC: `{"module": "SPI-A", "baud": 10e6, "words": [{"field": "vout", "low": 0, "high": 40.95, "codeBits": 12, "command": 6144}, {"field": "il", "low": -20.48, "high": 20.47, "codeBits": 12, "shift": 2, "command": 7168}]}` makes SPI-A the master (SPISIMO, SPISOMI, SPICLK and SPISTE on GPIO16 to GPIO19) and, before each step, sends a frame of two 16-bit words, 1800h then 1C00h, back to back under one SPISTE. Each reply is read from the receive FIFO: `vout` is the reply's bottom 12 bits, 0 V at code 0 and 40.95 V at 4095, and `il` the 12 bits two bits up. `command` is the word the code sends while it reads that reply, right-aligned in `wordBits`; for a part that answers a command in the next word, list its commands one word ahead and add a word for the last reply. The other fields are those of `spi`, with SPISOMI on the GPIO after SPISIMO, and `spiIn` must use another module than `spi`. The code waits for the replies at most twice the frame's length; a frame not back in time, or one that finds the transmit FIFO busy, keeps the last values and is counted by `<prefix>_f28379d_spi_in_missed()`, and `<prefix>_f28379d_spi_in_frame` keeps the last replies. A field that is not a measured input, a frame longer than the step, a pin the code already uses, cpu2 and other targets are refused; `mcu.spiIn` echoes the pins, SPIBRR, the clock, the frame's length and the wait (SPRUHM8K 18.3.2, 18.3.4, table 18-18; SPRS880P table 5-3).

An encoder's count can be homed on its index pulse with `encoderIndex`: `["eQEP1"]` makes eQEP1 reset its count on the encoder's first index pulse only (QEPCTL[PCRM] = 2h), to 0 turning forward and to −1 turning back, so from then on the count is the shaft's angle from the index and not from wherever the shaft stood at power-up. The count still runs the full 32 bits after that. A simulated encoder's `count` is 0 at its index, so once the board has seen the index its count differs from the simulated one by whole revolutions only, and an electrical angle taken from it matches the simulation. Each index pulse also latches the count into QPOSILAT and raises eQEP1's interrupt (PIE INT5.1; eQEP2's is INT5.2): `<prefix>_f28379d_eqep1_index_count()` counts the pulses (0 until the count is homed, held at 65535) and `<prefix>_f28379d_eqep1_index_position()` gives the count at the last one. A module that counts no encoder in the code, cpu2 and other targets are refused; `mcu.encoderIndex` echoes it (SPRUHM8K 17.5.1.3, 17.5.2.1, 17.9).

### What is generated

The code covers the blocks that run at one sample time: `constant`, `gain`, `sum`, `product`, `max`, `min`, `abs`, `not`, `limiter`, `comparator`, `affine`, the transforms (`clarke`, `invClarke`, `park`, `invPark`, `abc2dq`, `dq2abc`), `svpwm`, `adc`, `zoh`, `zDelay`, `ztf`, `fir`, `iir`, `dIntegrator`, `dpi`, `dpid` (all three methods, with back-calculation anti-windup), `sampleHold` and `delay`, and the tables `lookup` and `lookup2d` (up to 64 points per axis and 256 values).

Blocks that advance over the solver step, `rateLimiter`, `integrator`, `angle`, `smo`, `pll` and `srfPll`, are written at the code's sample time when they feed the duty cycle a PWM reads: each runs its own update once per call, with the sample time as its step, and the reply lists it in `discretized` with the method `blockUpdate`. The rate is the one the sampled blocks use, or the PWM period of a continuous controller. `angle`, `smo`, `pll` and `srfPll` need sine, cosine and a square root, so they are generated in `float` and `double` only. In `float`, an observer or a position loop with a large gain can drift a sample from the model; check it with `codegen.verify {"precision": "double"}` first.

Sampled blocks may run at more than one sample time when every slower one is a whole multiple N of the fastest (2 to 65535): the code runs at the fastest, and a slower block runs once every N calls, behind a call counter in the state structure, with its outputs held there between its runs. This works in `float`, `double` and fixed point. In fixed point the counter counts in the format's own steps, so it never widens the format `q15` or `q31` picks; N − 1 must fit the stored integer (up to 32767 in a 16-bit format), and a slower block whose count does not fit is left out with the reason. A C block at a slower rate is left out in every number type.

The blocks are evaluated in the same order as in the simulation. A signal that is read before its writer runs becomes a state field, so a loop that is closed through a delay behaves as it does in the simulator. An algebraic loop is an error that names the blocks.

### What is not generated

These are listed in the reply with the reason, and nothing is guessed:

- the PWM and carrier blocks (the timer of the microcontroller does that),
- continuous blocks (`pi`, `tf`, `pid`, filters) beside a sampled block, and the step-advancing blocks above anywhere but in a PWM's input,
- time sources (`sine`, `step`), logic blocks, `mcu`, plug-ins, `vco` and `phaseDetector`, and tables larger than the limits above,
- FIR and IIR filters of more than 32 taps,
- blocks whose sample time is not a whole multiple of the code's, and blocks with an offset.

A signal that crosses between a generated block and one of these becomes a field of the input or output structure. You feed it in, or read it out, yourself.

If the circuit has no control blocks, the menu item says so.

### How it was checked

The tests run the generated assignments in double precision against the simulator's own block evaluation, for a PI loop with each method and for a circuit with every supported block. They agree to 1e-9. The C text itself was not compiled in the tests. Compile it with your own toolchain and check it against your simulation before you rely on it. Chapter 10 explains why a digital loop needs the delay of the `mcu` block in the model first.

### Logging the controller over a UART

To see what the real controller computes, add `"log"` with the fields to send: `{"log": ["u", "PI_i", "y"]}`. A field can be an output (a duty cycle), an input (an ADC reading) or a state field (an integrator). Two more files come out, `<prefix>_log.h` and `<prefix>_log.c`, and the reply's `log.channels` gives each field its id.

- Build with `-D<PREFIX>_LOG` (for example `-DPC_CONTROL_LOG`). Without it every log function does nothing (`<prefix>_log_read` and `<prefix>_log_dropped` return 0), so the same source builds without the log.
- Call `<prefix>_log_init()` once and `<prefix>_log_sample(&st, &in, &out)` right after each `<prefix>_step()`. It puts one 13-byte frame per field into a ring buffer (1024 bytes; set `<PREFIX>_LOG_BUFFER_BYTES` to change it) and never waits for the UART. The `stm32g474` interrupt file does not call it yet: add the call after `<prefix>_step()` in `<prefix>_stm32g474_isr.c`.
- `<prefix>_init(&st)` sets the tunable parameters to their defaults and clears the states; `<prefix>_reset(&st)` clears the states and keeps `st->params`. The supervisor's restart (hiccup or a new start) calls `_reset`, so gains tuned at run time survive it. In the `stm32g474` interrupt the wait for ADC2 is bounded by `<PREFIX>_SUP_ADC2_WAIT_LOOPS` (default 4096, from RM0440: 653 ADC clocks at an ADC clock of core/6; define it first if your ADC clock is slower). On a timeout the supervisor goes to FAULT with `<PREFIX>_SUP_FAULT_ADC` (bit 8), the PWM stays off, and the trip is counted.
- Send the bytes that `<prefix>_log_read(buf, n)` returns over your UART, from the main loop or a transmit interrupt. When the buffer is full, a frame is dropped and `<prefix>_log_dropped()` counts it.
- On the `f28379d` target the generated code does both. The ADC-A interrupt calls `<prefix>_log_sample` after it writes the duty cycles, `main` calls `<prefix>_f28379d_log_start()` before it enables the interrupts, and its loop calls `<prefix>_f28379d_log_send()`, which fills SCI-A's 16-word transmit FIFO and returns without waiting. SCI-A sends 8 data bits, no parity and one stop bit at `logBaud` (default 115200) on `logTxGpio` (default GPIO84; SCITXDA can also go out on GPIO8, 29, 36, 42, 48, 65 or 135). The rate comes from LSPCLK, 50 MHz, so it is not always exact: `mcu.logSci` gives the BRR and the rate actually sent (115741 bit/s for 115200). The project file adds `<prefix>_log.c`; build with `-D<PREFIX>_LOG` to turn it on.
- A frame is `0xA5 0x5A`, the id, the step counter (uint32, little endian), the value (float32, little endian) and a CRC-16/CCITT-FALSE over the id, counter and value.

Read the capture back with `debug.serialLog`. A host with a read root (`powercraft-cli serve`) reads a capture file (`path`) or a serial port (`port`, `baud`, `seconds`), and the command takes the bytes as base64 (`bytes`) as well. Give `sampleTime` (the code's sample time) and pass `log.channels` as `channels`; `map` pairs simulated signals with channels:

`{"port": "/dev/ttyUSB0", "baud": 921600, "seconds": 2, "sampleTime": "100u", "channels": [...], "map": {"u": "u", "PI_i": "PI_i"}}`

Damaged frames fail their CRC and are dropped and counted, and the reader finds the next frame after noise or a lost byte. A value held between steps is compared as a staircase, like the simulated sampled block. Besides the `waveform.compare` figures, `divergence` lists where the hardware leaves the model: an error above `tolerance` (5 % of the signal's span) for a run of samples, and a variable outside the range the simulated one ever took, which is how an integrator winding up on the board shows.

To tune the controller on the board without building again, add `"tune": true`. Two more files come out, `<prefix>_tune.h` and `<prefix>_tune.c`, and the reply's `tune.params` gives each tunable coefficient (the rows of `<prefix>_params.csv`) its index. It needs at least one tunable coefficient (a gain, PI, PID or transfer-function block).

- Build with `-D<PREFIX>_TUNE`. Without it every tuning function does nothing.
- Call `<prefix>_tune_init()` once. In the main loop, pass every byte the UART receives to `<prefix>_tune_rx(&st, byte)` and send the bytes `<prefix>_tune_read()` returns. Never call them from the control interrupt. If a store of the number type takes more than one instruction on your MCU (a `double` on a C28x), define `<PREFIX>_TUNE_LOCK()` and `<PREFIX>_TUNE_UNLOCK()`, for example as `DINT` and `EINT`.
- A request is 10 bytes: `0x5A 0xA5`, `R` (read) or `W` (write), the index, the value (float32, little endian) and a CRC-16/CCITT-FALSE over the four bytes before it and the value. Each request gets a 10-byte reply in the same layout, with a status in place of the operation (0 done, 1 no such index, 2 written but saturated, 3 refused because the value is NaN or infinite, 4 unknown operation) and the value the code now holds, so you see how a `float` or fixed-point code rounded it. A request whose CRC fails is counted (`<prefix>_tune_errors()`) and never carried out.
- The generated `f28379d` and `stm32g474` interrupt and main files don't receive on the UART yet: connect your receive code to `<prefix>_tune_rx`.

## Real-time model

To test firmware against the power stage on a real-time rig, export the stage itself as C. `tools.realtimeModel` turns the active circuit into a fixed-step model: `<prefix>.h` and `<prefix>.c` (prefix `pc_plant` by default), C99 with no `malloc`. Call `<prefix>_init(&state)` once, then `<prefix>_step(&state, gates)` every step with the gate levels the firmware drives (a gate is on above 0.5), and read the node voltages and currents with `<prefix>_outputs(&state, out)`. The header lists the inputs and outputs by name. `file.exportRealtimeModel {dir}` takes the same params and writes the two files into the folder `dir` (`path` is its older name), within the folders you allow; nothing is written when the circuit has no real-time model.

| Param | What it does |
|---|---|
| `step` | The fixed step. The default is the circuit's maximum step. |
| `prefix` | A C identifier for the file names and functions. |
| `check` | Also run the reference solver at the same step, replay its gates through the model and report the largest error of every output (`tEnd` shortens the run). |
| `fpga` | `{clockHz, multipliers, latencyCycles}`: budget the slowest step against an FPGA clock (below). |

**How it works.** Every ideal switch, diode, MOSFET (with its body diode), IGBT and thyristor-family device (SCR, TRIAC, DIAC, GTO, IGCT) is a resistance that is either low (`ron`) or high (`roff`), with its forward drop as a source beside it. So for a fixed step there are only `2^n` different circuit matrices for `n` switches. The export inverts each one in advance, for the trapezoidal rule and for backward Euler. A step on the target then builds the right-hand side, multiplies by the matrix of the present switch states, and repeats that while a diode changes state. It never factors a matrix. The step follows the reference solver: backward Euler on the step after any switching, and the same switch rules.

**Reading the reply.**
- `worstCase` gives the multiply-adds of the slowest possible step: the solves (the switching-iteration limit) times the size of the matrix squared. Check that your target does that within one step.
- `dutyResolution` is the step times the fastest PWM frequency of the circuit. The model reads the gates once per step, so an edge takes effect up to one step late. Keep at least 100 steps per switching period for 1 %. The reply warns below that.
- `tableBytes` is the size of the stored matrices.
- With `check`, `check.outputs` gives the largest error of every output, `check.maxSolves` the most solves a step took, and `check.hostStepNs` the time per step measured on this computer. When PWM edges fall between steps (sine-triangle PWM), a switched voltage or switch current is up to one step late at each edge, so its largest error is close to its full swing; judge the model by the smooth signals (inductor currents, capacitor voltages) instead.
- With `check`, `timing.histogram` gives how many steps took each number of solves (1, 2, ...), ascending; the counts sum to `check.steps`. Most steps take one solve; only a step that changes switches takes more, up to `worstCase.solves`.
- With the `fpga` param, `timing.fpga` gives an estimate — not a measurement; no FPGA or HDL export (#4265) was built or run — of whether the slowest step fits that clock, from the multiply-add budget below ("Notes for FPGA and commercial real-time targets"): `cyclesPerStep` is `worstSolves · ⌈unknowns² ∕ multipliers⌉ + latencyCycles`, checked against the `stepCycles` a step of `step` has at `clockHz`. `fits` says whether it does, and `note` says what the count leaves out (the right-hand side, and for a machine its sine, cosine and divisions).

**Sources.** DC, sine, pulse, piecewise-linear (PWL, also repeating) and grid sources (with their harmonics and a sag or swell) are evaluated in the C at the end of every step with the same rules as the simulator, so a corner that falls on a step takes effect at that step.

**Coupled inductors.** A coupled inductor carries both winding currents from step to step, like a single inductor carries its current. Its companion conductances depend only on the step and the integration method, so they are part of the stored matrices; the outputs `i(K.1)` and `i(K.2)` are its winding currents.

**Saturating inductors.** An inductor with `isat` and `lsat` has two segments: `l` up to `isat` and `lsat` beyond. The simulator picks the segment of a step from the inductor's current at the last step, without iterating, so the model does the same: each saturating inductor is one more bit of the stored combinations, like a switch, and the reply lists them in `saturating`. A buck whose inductor crosses a 4 A knee dozens of times in 1 ms agrees with the reference solver within 4e-8 of each peak. An inductor on a linked catalogue core follows a continuous curve that no small set of stored matrices holds, so it has no real-time model.

**Single precision (`numbers: "f32"`).** For a target with a single-precision FPU (most microcontrollers) or float IP on an FPGA, `numbers: "f32"` writes the C in `float` throughout: each stored matrix entry and companion conductance is rounded once from the double-precision model, time is the integer step count, and a sine source's angle is a 32-bit phase that wraps at a full turn, so neither loses resolution in a long run. The sine is a fixed polynomial in the C rather than the platform's `sinf`, and no multiply-add is fused, so the C gives the same bits as the host's own `f32` emulator wherever `float` is binary32 (`FLT_EVAL_METHOD` 0). The tables take half the bytes. With `check`, `check.againstF64` gives each output's largest difference between the `f32` form and the double-precision model on the same gates: on the buck about 3e-4 of the inductor current's peak, on the three-phase inverter about 3e-6 of the phase currents' peak. A sine source's frequency is rounded to a whole number of phase units per step (at 1 µs, 1.2e-4 Hz at most), so its phase drifts slowly from the double-precision model's. A pulse or piecewise-linear source is a table of straight pieces, each starting at the first step its corner reaches: a one-shot pattern counts steps, a repeating one a 64-bit phase that wraps once a period, so it keeps its period over any run (on the step grid its corners and levels are the double-precision values, rounded once). A grid source's fundamental and each harmonic have a 32-bit phase of their own, and its sag is in force on the steps from the first that reaches its start up to the first that reaches its end. The `f32` form takes switches, capacitors and inductors (saturating too), coupled inductors, DC, sine, pulse, PWL and grid sources, and PM machines with the shaft and its sensors: a machine's and a position sensor's angle is a 32-bit phase too, advanced each step by its speed and rounded to a whole unit (2⁻³² of a turn). A speed that a step changes by a small fraction of its size keeps few bits of that change in `float`: on a PM generator at 300 rad/s the speed drifts about 7.5e-4 of its value in 10 ms and the phase currents about 3e-3 of their peak. A diode bridge whose bleeder resistors leave every stored matrix entry near the same value (all about 200 Ω, differing by 1e-3) loses that difference in `float` and its diodes chatter: export such a circuit in double precision.

**Block floating point (`numbers: "bfp24"`, `"bfp18"`).** For the multipliers of an FPGA's fabric, `bfp24` and `bfp18` are the `f32` form with the solve's stored matrices as block floating point: every entry is a 24- or 18-bit integer, and each row of each matrix shares one power of two. Each solve turns the right-hand side into 35-bit integers sharing one power of two, multiplies and sums in integers, in two slices of the right-hand side (its low 17 bits and the rest) so that each product fits a 25 × 18 DSP multiplier and its 48-bit accumulator (AMD UG479, DSP48E1), and rounds each row's exact sum once to `float`. The states and the rest of the step stay `float`, as do an interior machine's correction tables. The C gives the same bits as the host's emulator of the form. The tables take 4 bytes an entry and 2 a row. With `check`, `check.againstF64` gives the errors: on the buck `bfp24` keeps about 1.5e-4 of `v(out)`'s peak and 5.4e-4 of the inductor current's, the per-row 24-bit figures of the table below, and `bfp18` about 4e-3 and 1.5e-2. Holding the right-hand side at 18 bits instead of two slices makes the errors 30 to 160 times larger. `bfp18` can make a lightly damped circuit diverge (the half-bridge example does), which `check.againstF64` shows as an error larger than the peak: use `bfp24` or `f32` there.

**The solve in Verilog (`tools.realtimeHdl`).** `tools.realtimeHdl {rhsExponent, numbers, multipliers}` writes the model's solve, `x = A·b` with the table of one switch combination, as plain Verilog-2005 (`<prefix>_solve.v`, no vendor primitives) with the same `bfp24` or `bfp18` table words as the C. Each of the `multipliers` (`P`) reads its own block RAM, one word a cycle; a solve takes `N · ⌈N / P⌉` words plus 4 cycles of latency, which the reply gives as `cyclesPerSolve`. The right-hand side is `rhsBits` (default 18, the DSP48E1's narrow port, AMD UG479) integers, a word `β` standing for `β · 2^rhsExponent`: choose `rhsExponent` so the largest source and state of your circuit fit. Each output is `outputBits` (default 32) and saturates; `outputExponents` gives each unknown's scale. The core is checked bit for bit against its emulator in Verilator and Icarus. With the default `core: "solve"` the C model's step drives `table_sel` and `rhs`. `core: "step"` writes a whole step instead (`<prefix>_step.v` with its solve core `<prefix>_step_solve.v`): the gate and switch rules, the companions, the right-hand side, up to `S` solves and the state update, in fixed point. It needs `volts` and `amps`, the full scales (about twice the circuit's peaks: a value beyond them saturates and counts on the `saturated` port), and takes `bits` (default 24, 8 to 26) for every register. A step with `s` solves takes `fixed + s · perSolve` clock cycles, which `cyclesPerStep` gives for each method; `outputs` names each output's register and binary point, read through `rd_addr` and `rd_data`. The step core takes inductors, saturating inductors (`isat`, `lsat`: each is one more bit of the table selection after the switches', its segment picked at the start of each step from its current of the last step, as the model does; `saturating` lists them), coupled inductors (constant `l1`, `l2` and `k`; both winding currents are carried states, read as `i(K.1)` and `i(K.2)`), capacitors, sources of any waveform and the ideal switch, diode, MOSFET, IGBT, thyristor (SCR), IGCT, DIAC, TRIAC and GTO; any other part is an error that names it. A coupled inductor at a very short step (the flyback example's 20 ns) leaves the solve's entries small: raise `outputBits` if the reply asks for more. The `gates` port has one bit a model input (high above the gate threshold), then the gate terms that a TRIAC's and a GTO's rules read, which `gateTerms` lists with their bit, input, test and level: a GTO's turn-off bit is its input below minus the gate threshold, and a TRIAC's two firing bits are its input's magnitude above `igt` with a positive and with a negative sign (with the sign of its voltage they give the quadrant). Set each from its input's level, as you set the inputs' bits. A gate that is the circuit's own meter (the lamp dimmer's TRIAC and its gate ammeter) is no bit of the port: the core compares that meter's output register itself, which holds its value of the last step, as the simulator reads the meter, against the same gate threshold, `igt` or turn-off level, and `meterGates` lists each such bit with its output, register, test (`above` or `below`) and mantissa. There is nothing to set for it. In the lamp dimmer the TRIAC fires from its own meter in every half cycle; each firing comes within a few steps of the model's (11 steps in 10 000 at 1 µs and 400 V full scale), because the slow RC that times the DIAC sums the rounding of the 24-bit table words over thousands of steps. `numbers: "bfp28"` (core step and core solve) keeps the same rule with 28-bit table words, which no C model has: with `bits: 26` and `outputBits: 52` the dimmer's firings come within 2 steps of the model's. `numbers: "bfp32"` widens them to 32 bits: with `bits: 26` it needs `outputBits: 56`, and the firings come within 1 step. The step core takes solution words of up to 62 bits; a word wider than 52 bits is shifted down to its register with its own rounding (half up), and a core of at most 52 keeps the Verilog it had. The step core's registers (`bits`) go to 31, past the 26 of the machine core (a core with a PM machine keeps 26): with `numbers: "bfp32"`, `bits: 30` and `outputBits: 60` every firing of the dimmer lands on the model's step, and only the TRIAC's turn-off at its current's zero comes a step early, on 3 of 40 000 steps. With `fineCurrent: true` (core step) a switch with one terminal on ground, as the dimmer's TRIAC, reads its conducting current from its other terminal's solution word at a finer binary point instead of from its voltage register (one more operation a solve for each such switch, listed in `fineCurrentSwitches`), and those 3 turn-offs land on the model's step too. It is off by default: with `bits: 26` it moves the dimmer's second firing 2 steps late. Each product then takes more than one DSP slice. A DC source is a constant inside the core. A time-varying source (sine, pulse, PWL, grid) is a word of the `sources` input, source `k` at bits `k · bits`: before each `start`, set it to the source's value at the end of that step, at the binary point `sources` gives (the reply lists each one's register and point). `file.exportRealtimeHdl {dir}` writes the files into a folder.

**PM machines and the shaft.** A surface or interior PM synchronous machine (`spmsm`, `ipmsm`) is a fixed-step machine model with its own states (stator current and flux, electrical angle, speed and torque), stepped together with the circuit with the simulator's own machine equations. Its constant winding conductances are part of the stored matrices, and its back-EMF and the torque of the last step are currents on the right-hand side. An interior machine's saliency turns with the rotor, so it cannot be stored; the model solves it exactly every step as a small correction of the stored solution (about `2·n + 20` more multiply-adds per solve), at most one interior machine per model. The shaft's inertias, frictions, springs, gears and speed sources are part of the circuit; fan, constant-power, gear-loss and vehicle loads take their torque from the speed of the last step; speed and position sensors are outputs, so the firmware reads `w` and `th` as it would read a meter. Hall, encoder and resolver sensors integrate the shaft speed into their angle as the simulator does, and their signals are outputs too: the three Hall levels, the encoder's A, B, index and count, and the resolver's sine and cosine. A switch gated by a Hall level reads it from the last step, inside the model. The outputs add `i(M1.a)`, `i(M1.b)`, `i(M1.c)`, `Te(M1)`, `wm(M1)`, `theta(M1)` and the dq current `id(M1)`, `iq(M1)`; `check` compares the angles modulo 2π. The PM drive example (`pmsmFoc`) exports with its six gates as the inputs. Its PWM and dead-time edges fall between steps, so its `check` differs by the gate sampling: at 1 µs the phase currents stay within about 1.6 A of the 8 A limit and shrink about ten times at 0.25 µs.

**Gates driven by the circuit.** A gate that is the signal of the circuit's own meter (a TRIAC's gate ammeter, as in the lamp dimmer) is not an input: the model reads that meter from its last step, as the simulator does, and `switches[].meterGate` is true for it.

**Two rates (`slowStep`).** The shaft changes over milliseconds while the power stage needs a step of a microsecond or less. `slowStep`, a whole multiple of `step`, splits the model at each machine's shaft: the electrical part (switches, windings and the network around them) steps at `step`, and the shaft part (inertias, frictions, springs, gears, loads and sensors) at `slowStep`. Before each slow step the shaft takes the mean electromagnetic torque of the fast steps since the last one; the fast steps see the shaft speed interpolated between the last two slow steps. The files are then `<prefix>_fast.h/.c` and `<prefix>_slow.h/.c`, each part's model, and `<prefix>.h/.c`, the exchange that steps both with the same `<prefix>_init`, `<prefix>_step` and `<prefix>_outputs` calls; on a target whose fast part runs elsewhere, run the exchange beside the slow part. `split` in the reply gives each part's unknowns, table size and outputs. With `check`, `check.againstSingleRate` gives each output's largest difference between the split and the single-rate model on the same gates. The torque reaches the shaft one slow step late, so the difference grows with `slowStep`: on the PM drive at 1 µs, a 10 µs slow step moves the speed by under 0.08 % of its peak and the phase current by about 0.1 %, and a 100 µs one about ten times that. An element that joins the shaft to the windings' network, or a gate driven by a shaft sensor, would put both parts in one algebraic loop and is an error that names it. A split model is double precision and takes no faults yet.

**Limits.** At most 12 switches and saturating inductors together. Inductors on a linked catalogue core, nonlinear parts, machines other than PM synchronous ones (induction, dc, brushless dc, wound-field, reluctance, stepper) and reverse recovery have no real-time model; the error names the part. Losses and temperatures are not computed. The control blocks of the circuit are not part of the model: the firmware under test replaces them, and `tools.codeGeneration` writes them as C.

**On the target.** No target was run in the tests; these notes say what each kind of target needs.
- **A CPU real-time loop** (a real-time core, an RTOS task, Linux with PREEMPT_RT): call `<prefix>_step` from a periodic task or timer interrupt at the step, read the gates just before it and write the outputs just after. Measure the slowest step on the target itself: `check.hostStepNs` is measured on this computer only, and `worstCase.macs` counts the multiply-adds of the slowest possible step, which is the figure to compare with the target's speed.
- **An FPGA or a commercial real-time simulator:** the export is C in double precision; `tools.realtimeHdl` (above) writes the solve, or with `core: "step"` a whole step of a circuit of linear storage, sources and ideal switches, in Verilog. See "Notes for FPGA and commercial real-time targets" below for the table resolution, the multiply-add budget, the memory and the interface such a target needs; the `fpga` param budgets the slowest step against a clock from that same multiply-add formula (above, "Reading the reply").

**How it was checked.** The tests replay the reference solver's gates through the model. For the buck and the half-bridge, where every PWM edge falls on the step, every output agrees within 1e-6 of its peak; the measured difference is about 4e-8, the rounding of the stored waveforms. For the three-phase inverter, whose sine-triangle edges fall between steps, the phase currents agree within 1.1 % of their peak. The generated C, compiled with `cc -std=c99 -Wall -Wextra -Werror`, steps like the host model within 1e-9.


### As an FMU for co-simulation

`file.exportFmu {path: "plant.fmu"}` packs the same model as an FMU (FMI 2.0, co-simulation) for system tools that co-simulate FMUs. It takes `step`, `prefix` and `maxSolves` as above, and `outputs`, a list of output names to expose (all of them by default). The gates are the FMU's inputs (on above 0.5, held through each communication step) and the chosen outputs its outputs; 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. The FMU carries C sources, not a compiled library: the importing tool compiles `sources/` (`documentation/index.html` says how). A communication step that is not a whole number of model steps advances to the last whole step before it. Until the first communication step the outputs read the circuit's solution at the start time, fixed at export (`startValues` in the reply); from the first step on they follow the circuit. Each output whose quantity the model fixes carries its unit (`V`, `A`, `rad/s`, `rad` or `N.m`; `units` in the reply). `parameters`, a list of DC source names, makes each named source a tunable parameter of the FMU (unit `V` or `A`, start the source's value in the circuit) that the importing tool can set before the run and at any communication point; the source holds the new value from the next step on. The export is checked in FMPy, an open FMI importer: it validates the FMU, builds the sources and steps the buck example with its simulated gates, and every output follows Voltecx's own simulation within 1e-6 of its scale (`cargo xtask fmu`). With `fmiVersion: "3.0"` the same model comes out as an FMI 3.0 co-simulation FMU instead (FMI 2.0 stays the default): the archive adds `sources/buildDescription.xml`, the variables are `Float64`, value reference 0 is the independent variable `time`, the gates follow from 1 and the outputs after them, and `fixedInternalStepSize` is the model step; the FMU has no event mode and never returns early. Parameters and units work in both versions. FMU import is not in yet (#4402).

## Processor-in-the-loop

**Tools › Processor-in-the-Loop** (`codegen.pil`) runs the firmware that `tools.codeGeneration` writes for the `stm32g474` target against the circuit's real-time model, both compiled with this computer's C compiler into one program, and compares the result with the circuit's own closed-loop simulation. A host stand-in for ST's LL headers plays TIM1 and ADC1: every PWM period ADC1 samples the plant's measured outputs at TIM1's trigger and turns them into 12-bit codes, the ADC interrupt runs the control step and writes `TIM1_CCR1`, and the preloaded compare drives the plant's gate from the next period, one plant step at a time. Then the circuit itself is simulated for as long.

With `target` `f28379d` the same run uses the firmware written for the TI F28379D, against a host stand-in for C2000Ware's headers that plays ePWM1 and ADC-A: ePWM1 counts up, its SOCA at the counter's zero starts ADC-A, the ADC-A interrupt (reached through the PIE vector table the firmware's init fills) runs the control step and writes the shadowed CMPA, which drives EPWM1A from the next period. With a `deadtime` block, EPWM1A and EPWM1B carry the dead band, rounded up to TBCLK counts. On `buckClosedLoop` at a 10 ns step the output means are 11.9950 V with the F28379D firmware and 11.9932 V natively.

| Param | What it does |
|---|---|
| `target` | `stm32g474` (default) or `f28379d`. |
| `timerClock` | TIM1's clock (default 170 MHz) or, on the `f28379d`, EPWMCLK (default and at most 100 MHz). |
| `periods` | PWM periods to run (default: the circuit's end time times the PWM frequency; at most 20000). |
| `step` | The plant's fixed step (default: the circuit's maximum step; at least 10 steps per period). |
| `fullScale` | Every ADC input's value at the code 4095. The default is 1.5 times the native run's peak of that input. |
| `offset` | Every ADC input's value at the code 0, below `fullScale`. The default is minus the full scale for an input the native run takes below 0, such as a phase current, so it reads from mid-scale, and 0 for any other. The firmware reads it from `PC_CONTROL_OFFSET_k`, which defaults to 0 for your board. |
| `precision` | The firmware's numbers: `float`, `double` or a Q format. |
| `steadyPeriods` | The last periods the steady state is averaged over (default: a fifth). |
| `waveforms` | Also return the per-period means of both runs. |
| `supervisor` | The `supervisor` object of `tools.codeGeneration` (soft start, UVLO, OVP, OTP, restart). The firmware runs it: the run calls `pc_control_stm32g474_enable(1)` (or `pc_control_f28379d_enable(1)`) after the init. On the `stm32g474` ADC2's injected ranks convert its measurements after the control's, and outside SOFTSTART and RUN its `LL_TIM_DisableAllOutputs` (MOE clear, RM0440 29.6.20) holds every gate low. On the `f28379d` ADC-A's SOCs after the control's convert them, and a one-shot trip (TZFRC[OST], cleared by TZCLR[OST], SPRUHM8K 15.11) holds every ePWM output low. The native run has no supervisor, so compare the steady state after the soft start. On the `stm32g474` the cycle-by-cycle current limit runs too: give `iTrip`, `ocpThreshold` and `supervisorSignals.current`, the plant output (in A) the sense reads, such as `i(L1)`. COMP1 compares that current times `ocpThreshold / iTrip` with DAC3's threshold (the firmware's code for a 3.3 V reference, 10 mV of hysteresis), TIM1's channel 5 blanks it, and its output is TIM1's break input: the break clears MOE at once and sets BIF, and AOE sets MOE again at the next update event once the current is below the threshold (RM0440 29.3.18, 29.6.20). On the `f28379d` the same three parameters run it through CMPSS1: its high comparator compares the sense with its DAC, `(1 + DACHVALS) · 3.3 V / 4096` (SPRUHM8K equation 16), with the hysteresis the firmware sets, COMPHYSCTL[COMPHYS] = 1: the output rises above the DAC's level and falls 12 DAC LSB (about 9.7 mV) below it (TI SPRS880P 6.10.2.1.1 and figure 6-44), CTRIPH goes through the ePWM X-BAR's TRIP4 to every module's DCAEVT2 (held off during the digital compare's blanking window from CTR = ZERO when `blanking` is given), and DCAEVT2 sets the module's cycle-by-cycle trip: EPWMxA and EPWMxB stay low until a CTR = ZERO without the event, and TZFLG[CBC] tells the firmware the period was limited (SPRUHM8K 15.11). The reply's `supervisor.ocp` gives the comparator (`COMP1` or `CMPSS1`), the threshold, the trip current the DAC code gives, the comparator's hysteresis `hysteresisV`, and `limitedPeriods`, the periods in which the limit acted. |
| `supervisorSignals` | The plant output each measurement reads, for each one the supervisor has a threshold on: `{"vin": "v(VIN)", "vout": "v(VOUT)"}`, or `temp`. The scale is the supervisor's `vinFullScale`, `voutFullScale` or `tempFullScale` (with `tempOffset`), else 1.5 times the native run's peak from 0. |

**Reading the reply.** `steadyState` gives each measured signal's mean over the last periods in both runs and their difference, the mean of the PIL's ADC samples (`sampled`), and the commanded, effective and native duty. `transient` gives the largest and RMS difference of the per-period means over the whole run. Expect a small steady-state difference: the firmware regulates the sample at the start of each period rather than the average, the ADC rounds it to one LSB, and the plant reads the gate once per step. On `buckClosedLoop` at a 10 ns step the output means are 12.0031 V with the firmware and 11.9999 V natively, 3.1 mV apart.

**Limits.** One `pwm` block that drives every gate input of the plant, directly or through `deadtime` blocks (CH1 and CH1N, or EPWM1A and EPWM1B, with the timer's one dead time). Its carrier may be a sawtooth or a triangle, and a `pwm3` block drives three legs: TIM1's channels 1 to 3 on the `stm32g474` (CH1 to CH3N), or ePWM1 to ePWM3 in step with ePWM1 on the `f28379d` (EPWM1A to EPWM3B). On a triangle the counter counts up and down; TIM1 loads its compares at both ends (TIMx_RCR = 0), so a duty the interrupt writes drives the gates from the middle of the period, while the F28379D loads CMPA at the counter's zero only, so the new duty starts with the next period. The reply's duty is channel 1's. On the `f28379d` a second to eighth `pwm` block at the same frequency and carrier run on ePWM2 to ePWM8 (EPWM2A to EPWM8A), each counter starting at its carrier phase (TBPHS) when ePWM1 passes zero (ePWM4 and ePWM7 take ePWM1's sync through SYNCSELECT) and loading its own CMPA at its own zero. On the `stm32g474` a second `pwm` block at the same frequency and carrier runs on TIM8's channel 1 (TIM8_CH1 and TIM8_CH1N), its counter preset to its carrier phase and started by TIM1's (slave trigger mode), loading its own CCR1 at its own update events; a third is refused. On the `f28379d` the code must run every PWM period; no supervisor yet. On both targets the ADC scales a code from `offset` at 0 to `fullScale` at 4095, so a signal that goes negative, such as a phase current, reads from mid-scale. The `f28379d` header gives each SOC a `PC_CONTROL_OFFSET_k` beside its `PC_CONTROL_FULL_SCALE_k`, as the `stm32g474` header gives each rank, both 0 at the code 0 by default for your board. The STM32G474's ADC1 injected group converts four inputs; a fifth to eighth are ADC2's injected ranks 1 to 4, started by the same TIM1 trigger and read by the same interrupt (`PC_CONTROL_ADC_CHANNEL_5` to `_8` name their ADC2 channels), so at most eight. A supervisor whose UVLO, OVP or OTP measures on ADC2 then fits only with four control inputs or fewer, and is refused by name otherwise. The F28379D's ADC-A converts eight inputs; a ninth and later go on ADC-B's pins (ADCINB0 to B5), then ADC-C's and ADC-D's, each started by ePWM1's SOCA with ADC-A, and the ADC-A interrupt waits for their ADCINT1 flags before it reads them. The stand-in converts on all four ADCs, so at most 24. An input that is an `encoder` part's `count` takes no ADC rank: the firmware reads it from TIM2's 32-bit counter in quadrature encoder mode (four counts per line, read as a signed count; a second encoder uses TIM5), and the run writes the plant's count into that counter at the ADC's trigger. The reply's `counters` lists them (`field`, `signal`, `timer`). So a drive that reads three phase currents and turns the encoder count into its angle fits. An input that the controller's own `step` block writes, such as a speed reference, is a time source the code generator leaves to the target; the run drives its ADC pin as a signal generator on the bench would, with the step's `before` value until the first plant step that reaches `t0` and its `after` value from then on, and the reply's `adc` entry names the block in `reference`. Another source of simulation time (a `sine`, for example) is refused by name. So `pmsmFoc` itself runs on both targets, its six inputs (the speed reference, the speed, three phase currents and the rotor angle) on ADC-A of the `f28379d`, or on ADC1's four injected ranks and ADC2's first two on the `stm32g474`. Over 200 ms at a 200 ns step its speed settles at 189.79 rad/s on the `stm32g474` and 189.80 rad/s on the `f28379d`, against 189.76 rad/s natively. Its `pass` stays false because the phase currents average near 0 A over the window, where the relative error measures nothing; compare `w` instead. On the `f28379d` the count comes from eQEP1's 32-bit position counter (QPOSCNT) in quadrature-count mode, four counts per line and read as a signed count, and a second encoder uses eQEP2; the project's `main` muxes their pins with C2000Ware's `InitEQep1Gpio` and `InitEQep2Gpio` (GPIO20 to 23 and GPIO24 to 27), so the ISR timing pin can't be one of those, and `timer` names eQEP1 or eQEP2. An encoder count needs `float` or `double` firmware. The compiler, the FPU and the interrupt's timing are this computer's, not the MCU's, and the conversion is taken as instant. Without a C compiler (or in the browser) the command answers an error that says so.

## The board canvas

**Board > Open Board** opens the project's board (the `.vxpcb` a project gets from **Add Board**) in its own window. The layer panel on the left lists the copper layers top to bottom, each in its own colour: the check box shows or hides a layer, and a click on its name makes it the active layer, where new tracks go. Under the layers, **Non-active layers** sets how the copper layers other than the active one are drawn: **Normal** (each in its own colour), **Dim** (faint, so the active layer reads on top) or **Hidden** (only the active layer; items on the others cannot be picked by a click or a box). **Ctrl+H** over the board steps through the three; it is the Control key on macOS too. Further down, **Nets** lists every net on the board in its ratsnest colour: clear a net's box to leave its tracks, vias, zones, pads, fills and airwires undrawn and unpickable (a footprint stays, as it holds pads of other nets too), and **Show all nets** turns every net back on. The properties panel below it shows the selected item.

- **Select**: click an item to select it (Shift adds or removes one) and drag it to move it onto the grid. **R** turns the selection 90°, **F** flips it to the other face (its copper goes to the mirrored layer), **Delete** deletes it. A locked part is never moved.
- **Track**: click the points of a track on the active layer, then press Enter or double-click. **Via**: click to place a through via.
- **Width**, **Diameter** and **Drill** left at 0 take the sizes of the net's class in the board's rules; when the rules have none, the window says so and asks for one.

The **Board** menu, and the bar along the top of the board window, take the board from parts to fabrication files in order: **Add Footprints** (`board.addFootprints`), **Add Connectors** (`board.interfaceConnectors`, applied), **Add Test Points** (`design.debugAids` with only its test points, applied, then `board.addFootprints`: a test point on each switch node, gate, rail, current-sense end, ground, ADC input, feedback divider tap and PWM pin (every key net Place Test Points reviews), with a probe ground beside the ones that want a short one, put on the schematic first, then the footprints of them and of the connectors; a net that has a test point already gets none, so a second click adds nothing), **Auto Place** (`board.autoPlace`), **Place Test Points** (`board.testPoints`, applied), **Auto Route** (`board.autoRoute`), **Power Pours** (`board.groundPlan`, applied: the ground plan's copper pours for the power nets, each switching node's held to the pads of its switches, diodes and inductor, with the plan's ground checks measured on the routed board), **Fill Zones** (`board.fillZones`), **Place Labels** (`board.placeReferences`, then `board.addTitle`: each reference designator beside its part, and the board's name and revision), **Service Check** (`board.serviceCheck`, applied: each test point's net name, each pluggable connector pin's and each outer pour's on the silkscreen (a pour too small to hold its name gets it beside the pour, outside it and touching its edge), the ground net reading GND, each label's letters clear of every part's courtyard and never nearer another part than its own; the status bar counts the labels placed and the service findings, which **Check Board** lists), **Check Board** (the design rule check `board.drcRun` and the layout review `board.layoutReview`; each is also on the menu by itself), **3D View** (`board.view3d`, drawn live in a window) and **Export Fabrication Files** (`board.exportFab`, Gerber X2 and drill files in `fab/`). The steps take one row of their own, which a window 1440 px wide holds whole and a narrower one wraps between buttons; **Open as Tab** and the **Fab** picker are on the row under them. Each runs the engine command of the same name, opens the board window if it is closed and says on the status bar what it did. A greyed button needs an open circuit, or waits for a job in progress. After **Check Board** the side panel lists the design rule violations (with their markers on the board) and, below them, the layout review's findings; a click on a row selects the items it names and zooms to it. **3D View** opens a window with the board in 3D: drag to orbit, right-drag to pan and scroll to zoom; **Copper**, **Solder Mask**, **Silkscreen** and **Part Bodies** show or hide each layer (with the mask hidden, the copper and the laminate under it show bare), **Show Bottom** and **Show Top** look from the other side, **Reset View** frames the board again, and the lines under it name each part drawn without a body and why. **Board > Export STEP** (`board.exportStep`) writes the assembled board as a STEP file for mechanical CAD (chapter 22, section 8). **Board > Open Board as Tab** (or **Open as Tab** on the bar) puts the board in the editor area in place of the schematic, with a **Board · name** tab beside the circuits' tabs; a circuit's tab brings the schematic back, the board's tab brings the board back, its × closes the board and **Open in Window** floats it again.

When the board is a tab narrower than the thirteen buttons need (a 1280 or 1024 px window), the bar groups them into three menus by stage, beside **Open in Window** and the **Fab** picker: **Placement** (Add Footprints to Place Test Points), **Routing** (Auto Route, Power Pours, Fill Zones) and **Finishing** (Place Labels to Export Fabrication Files). Each item works as its button does, greyed with the same reason. In the same narrow tab **Board temperature**, **Current density** and **Near field** go into one **Overlays** menu, and the hint under the toolbar keeps to one line (hover it for the whole text), so the canvas keeps about three quarters of the tab. The side panel on the left scrolls with a bar that stays drawn whenever its rows run past the window.

The switch at the top right of the board canvas shows the board in **2D**, in **3D** or **2D + 3D** side by side (keys **2** and **3** while the board window has the focus). Both views are the same board: a part selected on either is selected on the other and on the schematic (a click on a part in 3D picks it, Shift adds or removes it, a click on nothing clears the selection), the parts selected on the schematic show dashed in both, and panning either view moves the other so both look at the same point; **Fit board** fits both. The 3D view needs the desktop app's GPU renderer: in the browser its choices are greyed and say why. If the board cannot be drawn in 3D (a stack-up layer with no thickness), the 3D view says why in its place.

With **View > Studio Layout (Preview)** on and the board as the document in front, the board window's rows of buttons give way to the menus and an icon tool strip, as in KiCad's and Altium's board editors. **Route** (after **Design**) holds **Route Tracks** and **Place Vias** (the canvas tools), then **Auto Route**, **Power Pours**, **Fill Zones** and **Stitching and Thieving**. **Design** starts with the board's steps (**Add Footprints**, **Auto Place**, **Place Test Points**, the outline, **Stack-up…**, **Rules…**, **Check Board**, **3D View** and the fabrication exports), then the circuit's design steps after a line. The strip over the top of the 2D canvas picks **Select**, **Route**, **Via** or **Measure**; each icon names its tool and key in its tooltip. While **Route** or **Via** is in use, the tool's settings sit at the top of the side panel instead of a row over the board, as in KiCad's and Altium's interactive router: the title names the track's net (**Routing · net VOUT**), then **Net**, **Mode** (**Walk around**, **Shove** or **Highlight**, which goes straight through and outlines what the track collides with), **Width (mm)**, the via's **Diameter (mm)** and **Drill (mm)**, the **Layer pair** that V moves between (the active layer and the next copper layer), and **Corners**. Each size shows what the tool uses: the net class's, marked **from the net class**, until you type one of your own (0 goes back to the class's); a size neither sets reads **—** with **Not set in the rules**, since the router needs one. Undo and Redo are on **Edit**, and Rotate, Flip, Delete, Fit and Find on their keys. The view options (grid, board temperature, current density, board look and the DRC markers) stay on one row above the board. With the studio off, or another document in front, the menus and the board window are as before.

In the studio, **Stack-up…** and **Rules…** (from **Design** or the side panel) open one **Board Setup** window instead of two dialogs beside the board, as KiCad's and Altium's board setup does. The list down its left picks the page: **Stack-up**, **Board finish**, then **Board limits**, **Net classes**, **Class patterns**, **Rule areas** and **Solder mask / paste**, **Pre-defined sizes**, **Violation severity**, and last **Fab preset**. Each rule page is the editor described below and makes the same edits; one page shows at a time, the one opened last. **Fab preset** picks the fab the board is made at, the same choice as the board's **Fab** box: **Board rules only**, or one of the built-in profiles (JLCPCB, PCBWay, OSH Park). Under the pick it lists that fab's published limits (track, clearance, drill, annular ring, aspect ratio, hole to hole, edge clearance, mask web, via plating, silk text height and stroke, and whether vias in pads are filled and capped), each **Not stated by the fab** where the fab's page gives none, and the page and date they were read from. The design rule check and **Auto Route** hold to the stricter of these limits and the board's own rules. **Board finish** keeps what the fab is asked for besides the images: the **Copper finish** (HASL SnPb, HASL lead-free, immersion tin, nickel or silver, ENIG, ENEPIG, hard gold, OSP, HT_OSP, or none, bare copper), and whether the board has a **Plated board edge**, an **Edge connector** and a **Bevelled edge connector**. Each starts **Not set** and is one undo step (`board.setFinish`), kept in the board file; **Export Fabrication Files** writes each value set into the Gerber job file (`Finish`, `EdgePlating`, `EdgeConnector`, `EdgeConnectorBevelled`, as the Gerber Job Format 2020.08 names them) and leaves out what is not set. No check reads them. **Pre-defined sizes** keeps the board's list of track widths and vias (diameter and drill, in mm) to pick from while routing: type a size and press **Add**, or **Remove** a row. Each change is one undo step (`board.setPredefinedSizes`) and is kept in the board file; none is filled in, so take them from the fab's capability sheet. The design rule check and the net classes keep their own values. **Violation severity** lists every rule of the design rule check with how its violations count: **Error** (the default) fails the check, **Warning** lists them among the check's warnings while the board still passes, and **Ignore** leaves them out and only counts them. A pick is one undo step (`board.setRuleSeverity`) and is kept in the board file; Auto Route and the checks an edit runs still see every violation. With the studio off the two dialogs open beside the board window as before.

**Board > Stack-up…** (or **Stack-up…** beside the layer panel's heading) opens the board's stack-up beside the board window: every layer top to bottom, as `board.stackup` reads it, with its name, type (signal, plane or mixed for copper; core or prepreg for a dielectric), thickness in µm, copper weight in oz, Dk, loss tangent and material. Enter applies a field as one `board.setLayer` (one undo step); an empty field clears the value, since Voltecx never assumes one. **Add Copper Layer** (`board.addLayer`) adds a signal layer with a prepreg under it above the bottom layer, and **Remove** on a copper row (`board.removeLayer`) takes it out with its dielectric, refused while an item is on it. The line under the table gives the copper count and the total thickness, or names the layers that have none; an odd copper count is a warning with a button that adds a layer, never an error.

**Board > Update from Schematic** (`board.updateFromSchematic`) brings the board up to date after you change the schematic, as KiCad's Update PCB from Schematic does. It lists every change first: a footprint whose part you deleted is removed (its tracks stay, for the design rule check to report), a renamed part's reference follows it, the do-not-populate mark follows the part, a pad whose pin moved to another net takes that net, and a net you renamed is renamed on its tracks, vias, zones and net class. Nothing is placed or moved and no copper is drawn. A part that has no footprint yet is listed too, for **Add Footprints**. The changes are one undo step; a board already in step is left as it is.

The menu item (and **F8** while the board is the document in front in the studio) opens the change list as a dialog: one row per change with a tick, the kind of change, the part or net, and what changes. Untick a row to leave it out; **Apply Changes** writes the ticked rows as one undo step and lists what is left, and **Check Again** reads the schematic afresh after you edit it. A part with no footprint has an arrow instead of a tick: **Add Footprints** places it.

Every edit is a command (`board.move`, `board.rotate`, `board.flip`, `board.addTrack`, `board.addVia`, `board.delete`), so the command line and the assistant can do the same. **Undo** and **Redo** in the window, or Edit > Undo while it has focus, step through the board's own history.

**Board look** (on by default, in the window's bar) draws the board as its picture (`board.picture`): a black background, top copper red, bottom copper blue, silkscreen yellow, the board edge and keep-outs magenta, vias as rings with their hole, pours tinted and hatched so the tracks over them stay visible, and each pad labelled inside with its number and net (`1 GND`, or `1` over `GND` on a small pad). **Theme** beside it switches to `kicadLike` colours or to `print` (dark ink on white paper, as the assembly drawing is printed); the colours and sizes live in a theme file (`crates/board/themes/board-picture.json`), never in the program. The window draws the board in its own plain colours while a layer is hidden, a part is dragged or the temperatures are shown. `board.picture {image: "board.png"}` (or `svg`) writes the same picture to a file. What the picture shows comes from the board itself, so a readable board has: part names (`board.serviceCheck {place: true, apply: true}`), part outlines (`board.addOutlines`), `+ IN -` polarity marks and pin-1 dots (`board.markPolarity`), a title (`board.addTitle`), its width and height on the fab layer (`board.addDimensions`) and each pad's number and net on the fab layer (`board.labelPads`). The silk sizes come from the command or from the silk the board already has; Voltecx never makes one up.

## Simulate from the command line

`powercraft-cli sim` opens a circuit file, runs it, prints measurements and checks them, all in one command. It is meant for scripts and for continuous integration, where the exit code says whether the design still meets its numbers.

```sh
powercraft-cli sim buck.voltecx --set Vin.v=24 --tend 5m \
  --measure 'mean(v(out))' --expect 'mean(v(out)) in 5.7..6.3' --png buck.png
```

FILE is a `.voltecx`, `.asc` (LTspice), `.plecs`, `.psimsch` (read only) or SPICE netlist (`.cir`, `.net`, `.sp`). It is imported by path, so `.include` and `.lib` lines are followed. The files it may read are those below the folder of FILE, or below the folder you give with `--root DIR`.

Options, each of which may be repeated where it makes sense:

- `--set PART.PARAM=VALUE` sets a parameter before the run, for example `R1.r=2k`. SI prefixes work. An unknown part or parameter is an error.
- `--tend TIME` sets the end time of the run, for example `5m`.
- `--measure 'FUNCTION(SIGNAL)'` prints a measurement, for example `mean(v(out))`. The functions are `mean`, `rms`, `min`, `max`, `pp` (peak to peak), `last` (the final value), `thd` (total harmonic distortion in percent) and `freq` (frequency in hertz). Add a time window with `mean(v(out), 2m, 5m)`. The signal names are the ones the scope shows.
- `--expect 'MEASUREMENT LIMIT'` checks a measurement. The limit is `in A..B`, `< X` or `> X` (`<=` and `>=` also work), for example `mean(v(out)) in 11.9..12.1` or `max(i(L1)) < 8`. Numbers take SI prefixes.
- `--csv OUT.csv` writes every signal to a CSV file, and `--png OUT.png` writes a picture of the waveforms. With `--measure` or `--expect` the picture shows only the signals you measured.
- `--json` prints one JSON object instead of text. It holds the measurements, the expectations (each with `pass`), the warnings and an `error` with a `code` and a `message`.
- `--strict` makes warnings a failure. The warnings come from the import (for example an ignored directive) and from the simulation.

Without `--measure` and `--expect` the command prints the signals the run recorded, which is a quick way to find their names. A line of the default output looks like `v(out) mean = 12.01 V`, and an expectation prints `PASS` or `FAIL` before it. Warnings go to the error output.

Exit codes:

| Code | Meaning |
|---|---|
| 0 | The run finished and every expectation held |
| 1 | FILE could not be read or imported, or an output file could not be written |
| 2 | Bad arguments, including a signal that does not exist or cannot be measured, or a time window that ends after the run (the message names the run's end time) |
| 3 | An expectation did not hold |
| 4 | The simulation failed: it did not converge, the circuit has a problem, or the run needs too many steps |
| 5 | There were warnings and `--strict` was given |

If several things go wrong, the code of the first one in this order is returned: a failed run (1, 2 or 4), then a failed expectation (3), then warnings (5).
