# ACC PLC Simulator — How to Generate Programs with AI

**A complete guide for creating ladder logic (.json) and Structured Text (.st) files that load directly into the ACC PLC Simulator**

Simulator: https://accautomation.ca/simulator/ · Guide URL: https://accautomation.ca/simulator/acc-ai-guide.md · ACC Automation

Verified against `acc-plc-simulator.html` v1.128 and `acc-st.js` v1.020 by running both engines. The current simulator is v1.132: v1.129–v1.132 changed only the page's ad layout, with no change to the engine, programs or file formats, so everything in this guide still applies. v1.128 adds hover cards and one-click help for every instruction and an ST instruction list in the editor (no change to programs or file formats). v1.127 added **online editing** for ladder and Structured Text — a running program can be changed and the change swapped in between two scans (Section 10.4); the instruction set, the file formats and the validator are unchanged from v1.126. v1.126 added **sequencing and program flow** in ladder: the bit shift registers `BSL` and `BSR`, the drum sequencer `DRUM`, forward jumps to labels (`JMP`, `LBL`) and master control zones (`MCR`, `END MCR`) (Section 4.10). v1.125 added **indirect addressing**: a pointer operand `D[Dn]`, where the value in register Dn names the register actually used, accepted by MOV, the math and data blocks and the compares (Section 3.1.2). v1.124 added the data registers `D1`–`D4000` with data types (`INT`, `UINT`, `WORD`, `DINT`, `REAL`), the math instructions `ADD`, `SUB`, `MUL`, `DIV`, `MOD`, `INC`, `DEC`, `CPT` (expression) and `SCL` (scale), the data instructions `COP`, `FLL`, `PACK` and `UNPACK`, a typed `MOV` that can write D registers, compares that can test one register against another, and live error flags (`SB9`–`SB12`, `SW17`, `SW18`). Structured Text can read and write the same registers as `D[1]`–`D[4000]`. v1.123 added edge contacts (`P`, `N`), the retentive timer `RTO`, the up/down counter `CTUD`, the limit test `LIM`, and system bits and words (`SB1`–`SB18`, `SW1`–`SW19`). Programs written for v1.126, v1.125, v1.124, v1.123 and v1.122 still load and run unchanged.

---

## Instructions for AI assistants

If a user has asked you to convert, write or fix a PLC program for the ACC PLC Simulator, follow this guide exactly.

1. **Ask which language** the user wants if they have not said: ladder logic (delivered as a `.json` file) or Structured Text (delivered as a `.st` plain-text file). Never wrap ST in JSON.
2. **Map the I/O** to the simulator's addresses (Section 3.1). If the user names a scene, use its I/O table (Section 3.4). Remember that Stop and E-stop inputs are wired normally closed (Section 3.3). If the user has more than one scene connected, add each scene's address offset (Section 3.5).
3. **Convert the logic** using Section 5. The user's original program may be written for any PLC brand; convert its instructions to the equivalents listed in this guide, and tell the user about anything that has no equivalent (Section 5.1).
4. **Write the file** in the exact format of Section 4 (ladder) or Section 8 (ST). Copy the structure of the complete examples in Sections 6 to 8.
5. **Check it** against Section 10 before giving it to the user, then explain how to import it (Section 2) and how to test it (Section 10.3).

Reference files on this site:

| File | URL |
|---|---|
| This guide | https://accautomation.ca/simulator/acc-ai-guide.md |
| AI index (llms.txt) | https://accautomation.ca/simulator/llms.txt |
| Ladder example — conveyor | https://accautomation.ca/simulator/acc-example-conveyor-shuttle.json |
| ST example — conveyor | https://accautomation.ca/simulator/acc-example-conveyor-shuttle.st |
| Ladder example — analog | https://accautomation.ca/simulator/acc-example-analog-tank-level.json |
| ST example — analog | https://accautomation.ca/simulator/acc-example-analog-tank-level.st |
| Ladder example — v1.123 instructions | https://accautomation.ca/simulator/acc-example-buffer-runtime.json |
| Ladder example — v1.124 math and data | https://accautomation.ca/simulator/acc-example-batch-math.json |
| Ladder example — v1.125 pointers (recipe select) | https://accautomation.ca/simulator/acc-example-recipe-select.json |
| Ladder example — v1.126 bit shift register (bottle tracking) | https://accautomation.ca/simulator/acc-example-bottle-tracking.json |
| Ladder example — v1.126 drum sequencer (traffic light) | https://accautomation.ca/simulator/acc-example-traffic-drum.json |
| Ladder file validator (Python) | https://accautomation.ca/simulator/acc-validate-program.py |
| Simulator help | https://accautomation.ca/simulator/acc-plc-simulator-help.html |
| Scene guide | https://accautomation.ca/simulator/acc-scene-help.html |

---

## 1. What this guide is for

The ACC PLC Simulator is a free, browser-based PLC that runs ladder logic and IEC 61131-3 Structured Text against interactive 3D industrial scenes. Programs can be typed in by hand, but they can also be written by an AI assistant (Claude, ChatGPT, Gemini, Copilot and others) and imported as a file.

An AI can only produce a file that loads correctly if it knows the exact file format, the addresses the simulator accepts, and how the simulator scans a program. This guide supplies all three. Every ladder format rule in it was checked against the simulator's own import, export and scan code. It is written so that a person with no programming background can follow how it works, and so that the whole document can be pasted into an AI chat as its instructions.

**How to use it:**

The quickest way is to give the AI the link and your program:

> Read https://accautomation.ca/simulator/acc-ai-guide.md and convert my program below to ladder logic for the ACC PLC Simulator.

AI assistants that can browse the web will read the guide and follow it. If the AI cannot open links:

1. Open a new AI chat.
2. Paste this entire guide, or attach it as a file.
3. Describe the machine or process you want to control (see the prompt template in Section 11).
4. Ask for either a **ladder logic JSON file** or a **Structured Text .st file**.
5. Check the result with Section 10, then import it into the simulator.

---

## 2. The two file types — an important distinction

The simulator stores the two programming languages in **different file formats**.

| Language | File type | What it looks like | How to load it |
|---|---|---|---|
| Ladder logic | `.json` | Structured data describing rungs, contacts, coils and blocks | **📂 LOAD → ⬆ Import .json** (in the Save/Load dialog) |
| Structured Text | `.st` | Plain text source code, exactly as typed in the editor | Switch to **ST** mode, then use **Import .st** |

Structured Text is **not** stored as JSON. An ST program is simply the text you would type into the ST editor, saved in a plain text file ending in `.st`. When someone asks for "an ST file using JSON", the correct deliverable is a `.st` text file. Only ladder logic uses JSON.

A program is written in ladder **or** in ST. Both languages use the same I/O addresses, the same 100 ms scan, the same 3D scenes and the same Modbus bridge, so the same machine can be controlled either way.

---

## 3. Simulator facts every program must respect

### 3.1 Memory map (addresses)

| Prefix | Range | Type | Read by | Written by |
|---|---|---|---|---|
| `X` | X1–X16 | Digital input (pushbuttons, sensors) | Contacts, ST | The scene or the user |
| `Y` | Y1–Y16 | Digital output (motors, valves, lights) | Contacts, ST | OTE / OTL / OTU coils, BSL / BSR and DRUM (v1.126), ST |
| `C` | C1–C256 | Internal relay (program memory bit) | Contacts, ST | OTE / OTL / OTU coils, BSL / BSR and DRUM (v1.126), ST |
| `T` | T1–T256 | Ladder timer | Contacts (`T1`, `T1/DN`, `T1/EN`, `T1/TT`); compares, MOV and the math blocks (not CPT) read the elapsed time as `T1/ACC` (ms); ST reads the done bit only | TON / TOF / RTO blocks, RES |
| `CT` | CT1–CT256 | Ladder counter | Contacts (`CT1`, `CT1/DN`); compares, MOV and the math blocks (not CPT) read the count as `CT1/ACC`; ST reads the done bit only | CTU / CTD / CTUD blocks, RES |
| `AX` | AX1–AX8 | Analog input, integer 0–4095 | **Compare** elements, MOV, math and data blocks, CPT, ST | The scene or the AN-tab slider |
| `AY` | AY1–AY4 | Analog output, integer 0–4095 | Compare elements, MOV, math and data blocks, CPT, ST | **MOV** and the math blocks (rounded and limited to 0–4095), ST |
| `D` | D1–D4000 | **Data register**, a 16-bit word with no fixed type (Section 3.1.1) | Compare elements, MOV, math and data blocks, CPT — directly (`D10`) or through a pointer (`D[D5]`, Section 3.1.2) — and ST as `D[1]` | MOV, math and data blocks (directly or through a pointer), a DRUM's step register (v1.126), ST as `D[1]`, the **D** tab in STOP |
| `SB` | SB1–SB18 | System bit (status the simulator maintains) | Contacts, ST | The simulator only — read-only (Section 3.6) |
| `SW` | SW1–SW19 | System word, integer 0–65535 | Compare elements, MOV, math and data blocks, CPT, ST | The simulator only — read-only (Section 3.6) |

Notes:

- A bare `T1` means `T1/DN` (the done bit). A bare `CT1` means `CT1/DN`.
- **The `/DN` form is ladder-only.** In ladder, `T1`, `T1/DN`, `T1/EN` and `T1/TT` are all valid contact addresses. In Structured Text only the bare `T1` and `CT1` work — `T1/DN` there is a syntax error, because `/` is read as division.
- **Contacts read bits; compares read words.** `XIC AX1` is always false and `XIO AX1` is always true, and the editor refuses a contact on `AX`, `AY`, `SW`, `D`, a pointer `D[Dn]` or a `/ACC` address. Use a compare element (Section 4.6) instead.
- `C100` and up is the recommended convention for internal relays, so they are not confused with timer and counter numbers. Programs using C1 and up also work.
- Addresses must be inside these ranges. An out-of-range timer or counter number (such as `T0` or `T300`) causes a script error on every scan, so the program stops updating. An out-of-range `C` address (`C0`, `C300`) does not error at run time — it reads and writes silently but never appears on the I/O panel, so it looks like the program is doing nothing — and from v1.124 the import reports it as an element that fails the editor's checks. Keep to C1–C256.
- Analog values 0–4095 represent 0–100 % (0–10 V or 4–20 mA on real hardware). A percentage converts as `value = percent × 4095 ÷ 100`, rounded. For example 20 % = 819, 85 % = 3481, 95 % = 3890. From v1.124 a program can also do this conversion itself with `SCL` or `CPT` (Section 4.7).

#### 3.1.1 Data registers (D1–D4000) and data types

A D register is a plain 16-bit word. It has no type of its own: **each instruction that uses a D register says how to read and write it**, with its `dt` field (data type). When `dt` is left out it is `INT`.

| `dt` | Words | Range | Notes |
|---|---|---|---|
| `INT` | 1 (Dn) | −32,768 to 32,767 | The default. Whole numbers. |
| `UINT` | 1 (Dn) | 0 to 65,535 | Whole numbers. |
| `WORD` | 1 (Dn) | 0 to 65,535 | Same as `UINT`; use it for bit patterns. Blocks show it in hex (`0x00FF`). |
| `DINT` | 2 (Dn and Dn+1) | −2,147,483,648 to 2,147,483,647 | Whole numbers. Low word in Dn, high word in Dn+1. |
| `REAL` | 2 (Dn and Dn+1) | ±3.4 × 10³⁸ (32-bit float, about 7 significant digits) | Decimals. Low word in Dn, high word in Dn+1. |

Rules that follow from this:

- **A `DINT` or `REAL` in D10 also uses D11.** Give the next value D12, not D11. Writing anything to D11 corrupts the value in D10. The last start address for a two-word value is D3999; the editor refuses `D4000` as a `DINT` or `REAL`.
- **There is no automatic conversion.** An instruction reads every D register it names as its own `dt`. A `DINT` `ADD` that names `D1` reads D1 *and D2* as one 32-bit number, even if D1 was written as an `INT`. To change a value's type, `MOV` it (Section 4.7): MOV has a source type `st` and a destination type `dt`.
- `AX`, `AY`, `SW`, `T1/ACC` and `CT1/ACC` are always read as their natural value, whatever the instruction's `dt`.
- **D registers keep their values through STOP and RUN** and through undo. They are cleared by ladder **CLEAR**, and loading or importing a ladder program replaces them with the values saved in that program (all zero when the file has none — Section 4.1, `dregs`). Structured Text save, load, import and CLEAR do not touch them. Ladder CLEAR, load and import (and the automatic restore when the page opens) also reset the error flags SB9–SB12 and SW17/SW18; Structured Text CLEAR, load and import do not.
- Only the ladder math and data instructions (and, from v1.126, a `JMP` with no label below it) raise the error flags (Section 3.6). Structured Text reads and writes D as `INT` only (Section 8.2).
- The **D** tab on the right-hand panel lists the registers the program uses and has a **Go to** viewer that shows 16 registers at a time. Each register has a display format: `DEC` (signed), `UDEC`, `HEX`, `BIN`, `DINT` or `REAL`. A register the program writes as `DINT` or `REAL` shows in that format automatically, and one written as `WORD` shows in `HEX` (in a HEX field, type `0x1F40` or `FF` for hex; plain digits such as `255` are decimal). Values can be typed in while the PLC is in STOP.

#### 3.1.2 Indirect addressing — pointers `D[Dn]` (v1.125)

A **pointer** operand is written `D[Dn]`: the value in register `Dn` (the *pointer register*) is the **number** of the register actually used. If D5 holds 12, then `D[D5]` means D12; change D5 to 13 and the same instruction now uses D13. This is how one rung can work through a table — a recipe, a list of setpoints, a buffer — instead of one rung per entry.

```json
{"id":180,"kind":"block","type":"ADD","addr":"D2","a":"100","b":"D1","dt":"INT","pre":0}
{"id":181,"kind":"block","type":"MOV","addr":"D10","src":"D[D2]","pre":0}
```

These two blocks form the usual **base + index** pattern: D2 = 100 + D1, then D10 takes the value of D100, D101, D102 … as D1 is 0, 1, 2 … (Section 7.3 is a complete example).

- **Form.** Write it as a string, `"D[D5]"`: the letter D, square brackets, and a D register `D1`–`D4000` inside. The editor ignores case and spaces (`d[ d5 ]`, `D[D05]` are the same pointer), but write it in upper case without spaces. Only a D register may be the pointer: a constant (`D[5]` — just write `D5`), an analog or system word (`D[AX1]`), an expression (`D[D5 + 1]`) or a nested pointer (`D[D[D5]]`) is refused. To point at "base + offset", calculate the number into the pointer register first with `ADD` or `CPT`.
- **The pointer register is read as `INT`**, whatever the instruction's `dt`. It holds a register *number*, 1–4000 — not a value from the table.
- **The target is read and written as the instruction's type.** A `DINT` or `REAL` through `D[D5]` uses D*p* and D*p*+1, so the pointer must be 1–3999; `INT`, `UINT` and `WORD` may point up to 4000. A `COP` or `FLL` through a pointer must fit its whole run (`len` words, or `len` × 2 words for a two-word `FLL`) inside D1–D4000; `PACK` and `UNPACK` use one word.
- **It is resolved every time the instruction executes** — on every scan its rung is true, and for a compare on every scan. A rung that changes the pointer register affects every rung below it in the same scan.
- **An invalid pointer is a range fault, not a stop.** When the pointer register holds 0, a negative number, or a number that puts the access past D4000, the instruction writes **nothing** and sets SB11 and SB12, `SW17 = 4` and `SW18` = the rung (Section 3.6). A compare reads that operand as 0 (and faults). As with every fault, this happens only in RUN or STEP, never while the STOP display is redrawn.
- **Where a pointer is accepted** (Section 4.4): `MOV` source and destination; `ADD`, `SUB`, `MUL`, `DIV`, `MOD` operands `a`, `b` and the destination; `INC`/`DEC` destination; `SCL` input and destination; `CPT` destination and `D[Dn]` terms inside the expression; `COP` source start and destination start; `FLL` fill value and destination start; `PACK` destination word; `UNPACK` source word; compare A and B (`addr`, `cmp`); `LIM` A, `lo` and `hi`. **Nowhere else:** not on contacts, coils, timers, counters, `RES`, a CTUD's `cd`, the SCL limits, `len`, or the bit fields of `PACK`/`UNPACK`; `MOV` into `SW17` takes no pointer.
- **A pointer makes the instruction typed.** A compare or block that uses a pointer reads it as its `dt`, and its constants are checked against that `dt`, exactly as if it named a D register.
- **The editor cannot check the target** — it only knows the pointer register. A two-word pointer at 4000, or a `COP` that would run past D4000, is caught when it executes. The **D** tab lists the pointer register as used, not the registers it points to.
- **On the ladder** a block or compare shows the resolved address next to the pointer, for example `D[D5]→D12`, with the target's value; `D[D5]→?` means the pointer is currently invalid.

In Structured Text the same thing is an index expression: `D[D[5]]` or `D[100 + Recipe]` (Section 8.2).

### 3.2 How the scan works

Every 100 ms the simulator:

1. Reads inputs (X and AX) from the connected scene.
2. Updates the system bits and words (first scan, clocks, real-time clock, scan count) once, so every rung in the scan sees the same values.
3. Executes the program from **Rung 0000 down to the last rung**, left to right within each rung.
4. Writes outputs (Y and AY) to the scene.
5. Redraws the display.

These consequences matter when writing a program:

- **Memory updates immediately.** When a rung turns on `C1`, every rung *below* it sees `C1` on during the same scan. Rungs *above* it see the new value on the next scan. Rung order therefore changes behaviour.
- **OTE follows its rung every scan.** OTE writes ON when the rung is true and OFF when it is false. OTL and OTU only act when their rung is true, so the bit keeps its value otherwise.
- **MOV only writes when its rung is true.** The AY register keeps its last value when the rung goes false. If an output must return to a value, write a second MOV rung for that case.
- **Math and data blocks act on every scan their rung is true** — about ten times a second. `INC D5` behind a plain `XIC X1` adds 1 per scan for as long as X1 is held, not once per press. Put a `P` contact in front of any instruction that should act once per event (Section 4.7).
- **JMP and MCR change which rungs run** (v1.126, Section 4.10): a `JMP` skips the rungs down to its label, and an `MCR` zone whose rung is false runs its rungs with the power rail off.
- **STOP clears Y, C and AY, but not timers, counters or D registers.** Timer accumulators, counter counts and D registers keep their values through STOP. Loading or importing a program clears X, Y, C, T, CT, AX and AY, and sets the D registers to the values saved in the file. Programs should not rely on Y or C bits surviving a STOP (a shift register held in C or Y bits is empty after STOP → RUN; a drum's step register is a D register, so it keeps its step), and should reset counters and totals deliberately with RES or a MOV of 0 — or with an `XIC SB3` (first scan) rung when they must start from zero on every RUN.

### 3.3 Input wiring conventions used by the scenes

Stop pushbuttons and E-stops in the scenes are wired **normally closed (N.C.)** for fail-safe operation. The input is **ON when the button is not pressed** and turns OFF when pressed or if the wire breaks. So a Stop button is programmed with an **XIC** contact in series with the run logic. This surprises many beginners.

Always check the scene's I/O list (shown in the Connect dialog and the scene's About panel) before writing a program. For example, the Conveyor scene uses X1 Start (N.O.), X2 Stop (N.C.), X3 left sensor, X4 right sensor, Y1 motor run and Y2 direction.

### 3.4 Scene I/O reference

Current live scenes, from the simulator's scene registry (`acc-scenes.js`). The Connect dialog in the simulator always shows the current list.

**Control Panel** (`acc-panel-scene.html`)

| Address | Signal | Notes |
|---|---|---|
| X1 | Start PB | N.O. |
| X2 | Stop PB | **N.C.** — ON when not pressed |
| X3 | Jog PB | N.O. |
| Y1 | Motor run light | |

**Motor Starter** (`acc-motor-starter-scene.html`)

| Address | Signal | Notes |
|---|---|---|
| X1 | Start PB | N.O. |
| X2 | Stop PB | **N.C.** |
| X3 | Motor overload auxiliary contact | **N.C., maintained** — ON while healthy |
| Y1 | Motor contactor | |
| Y2 | Run light | |
| Y3 | Warning horn | Sounds 2 s before the contactor pulls in |

**Conveyor System** (`acc-conveyor-scene.html`)

| Address | Signal | Notes |
|---|---|---|
| X1 | Start PB | N.O. |
| X2 | Stop PB | **N.C.** |
| X3 | Left sensor | |
| X4 | Right sensor | |
| Y1 | Motor run | |
| Y2 | Direction | ON = reverse |

**Pick & Place Palletizer** (`acc-palletizer-scene.html`)

| Address | Signal | Address | Signal |
|---|---|---|---|
| X1 | Box present | Y1 | Arm move X |
| X2 | Arm home X | Y2 | Arm move Y (down) |
| X3 | Arm home Y (up) | Y3 | Grip close (vacuum) |
| X4 | Grip confirm (vacuum) | Y4 | Feed conveyor enable |
| X5 | At pick X | Y5 | Pallet eject |
| X6 | At place X1 (column 1) | | |
| X7 | At place X2 (column 2) | | |
| X8 | Arm down | | |
| X9 | Contact pressure | | |
| X10 | Skid present | | |

**Tank Fill Station** (`acc-tank-scene.html`)

| Address | Signal | Address | Signal |
|---|---|---|---|
| X1 | Low float (20 %) | Y1 | Inlet valve |
| X2 | High float (85 %) | Y2 | Drain pump |
| X3 | Start PB (N.O.) | Y3 | Overflow alarm (strobe) |
| X4 | Stop PB (**N.C.**) | Y4 | Mixer motor |
| X5 | E-stop (**N.C.**, latching) | | |
| X6 | Auto/Manual selector (maintained) | | |
| X7 | Inlet valve PB (manual) | | |
| X8 | Drain pump PB (manual) | | |
| X9 | Mixer PB (manual) | | |
| X10 | Overflow float (95 %) | | |

The tank level is published only as Modbus Input Register 30001 for external PLCs. It is **not** an AX address inside the simulator, so tank programs written for the simulator use the float switches.

**Traffic Light Intersection** (`acc-traffic-scene.html`)

| Address | Signal | Address | Signal |
|---|---|---|---|
| X1 | Ped PB N/S (cross E/W road) | Y1 | NS green |
| X2 | Ped PB E/W (cross N/S road) | Y2 | NS yellow |
| | | Y3 | NS red |
| | | Y4 | EW green |
| | | Y5 | EW yellow |
| | | Y6 | EW red |

**Analog inputs:** no live scene currently drives AX1–AX8. Programs that use analog values are tested with the AN-tab sliders, or with a gamepad (triggers and sticks drive AX1–AX5).

### 3.5 Running more than one scene at once (address offsets)

The addresses in Section 3.4 are what a scene uses **when it is the only scene connected**. That is the normal case, and unless the user tells you otherwise, write the program against those addresses exactly as listed.

From simulator v1.120 several scenes can be connected at the same time. Two scenes both using X1–X3 would fight over the same inputs, so the simulator gives each one its own block of PLC memory and translates. The scene still knows itself as X1–X3 internally; the **program** must use the shifted addresses.

| | Scene's own address | PLC address |
|---|---|---|
| Motor Starter, first connected (offset 0) | X1–X3 / Y1–Y3 | X1–X3 / Y1–Y3 |
| Control Panel, connected second (offset X+3 / Y+3) | X1–X3 / Y1 | **X4–X6 / Y4** |

The rule is one addition: **PLC address = scene address + that scene's offset**, applied separately to X and to Y. The offset never exceeds 15, and X and Y are offset independently.

**How to find the offsets.** They are shown in three places, and the user can read any of them to you:

- The CONNECT dialog lists each connected scene and its block, e.g. `Motor Starter X1–X3 · Y1–Y3`.
- The PLC memory strip at the top of that dialog colours the addresses each scene holds.
- The scene window itself relabels its I/O rows to the PLC address once it is offset, and its panel header reads `INPUTS X (scene X1–X3 → PLC X4–X6)`.

**What to do when writing a program:**

- If the user says nothing about offsets, assume every scene is at offset 0 and use the Section 3.4 addresses. This is correct for the single-scene case, which is most of the time.
- If the user names offsets, or pastes a block like `X4–X6 · Y4`, add the offset to every **discrete** address for that scene — X contacts and Y coils. Address comments should name the device, not the offset, since the offset can change.
- **Do not offset analog.** `AX` and `AY` addresses in a compare or a MOV stay exactly as Section 3.4 lists them. A scene that uses analog has to run at offset 0 anyway (see below), so its analog addresses are already correct.
- Never mix: a program written for one scene at offset 0 will drive the wrong machine if that scene is later given an offset. Say which offsets the program assumes.
- **Modbus addresses never shift.** Offsets exist only on the simulator-to-scene link. A scene in Modbus mode is never offset, so X5 is always Discrete Input 10005 regardless.

**Analog scenes run at offset 0.** The offset mechanism applies the digital offsets to the much smaller analog space (8 AX, 4 AY), so analog is dropped silently on an offset scene. Any scene using AX or AY must therefore be the only connected scene, or the first one launched. In practice this means: if a program uses analog, write it against the Section 3.4 addresses unchanged, and say in your notes that the analog scene must be connected first.

### 3.6 System bits and words

The simulator keeps these up to date by itself. A program reads them like any other address — `SB` with contacts, `SW` with compares, as a MOV source or as a math operand — but cannot set them.

| Address | Meaning |
|---|---|
| `SB1` / `SB2` | Always ON / always OFF |
| `SB3` | **First scan** — ON for one scan after STOP → RUN (and for the first STEP after STOP, an edit or a load). Use it to initialise. |
| `SB4` | Toggles every scan |
| `SB5` / `SB6` / `SB7` | 0.5 s / 1 s / 1 min clock pulses (half on, half off). There is deliberately no 100 ms clock: the scan itself is 100 ms, so it could not be seen reliably. |
| `SB9` / `SB10` / `SB11` | Error flags, set by the ladder math and data instructions (from v1.124): **SB9** math overflow, **SB10** divide by zero or invalid result, **SB11** address range fault. They are **sticky** — they stay on until the program clears them. An `OTU` on one of these clears it; no other coil may address an SB. |
| `SB12` | Any error flag on (`SB9` or `SB10` or `SB11`). It follows the other three, so clear those to clear it. |
| `SB17` / `SB18` | A 3D scene is linked / a gamepad is connected |
| `SW1`–`SW7` | Real-time clock: year, month (1–12), day, **weekday (1 = Monday … 7 = Sunday)**, hour (0–23), minute, second |
| `SW9` / `SW10` | Last / maximum scan execution time in microseconds |
| `SW11` | Actual time since the previous scan, ms (normally about 100) |
| `SW13` / `SW14` | Scan count, low / high word |
| `SW15` / `SW16` | Seconds in RUN, low / high word |
| `SW17` / `SW18` | **Last error code** / **rung number of the last error** (as displayed, e.g. 4 for Rung 0004). Codes: `1` overflow, `2` divide by zero (including `0 ** -1` in CPT), `3` invalid result (non-finite: `SQRT(-1)`, a REAL beyond ±3.4e38, or a CPT result too large to compute such as `10 ** 400`), `4` address range. Both are sticky. A `MOV` with `"src":"0"` into `SW17` clears the code; nothing else may write an SW, and SW18 keeps the rung number until the next fault. |
| `SW19` | Number of linked 3D scenes |

SB8, SB13–SB16, SW8 and SW12 are reserved and read 0. Addresses above SB18 or SW19 are invalid.

**Error flags and codes (v1.124).** Only the ladder word instructions (Section 4.7) and, from v1.126, a `JMP` with no label below it or a shift register or drum with invalid fields raise them, and only while scanning (RUN or STEP) — never while the STOP display is redrawn. Each fault sets its flag, `SB12`, `SW17` and `SW18`:

| Code (`SW17`) | Flag | Raised when | What is written |
|---|---|---|---|
| `1` overflow | `SB9` | An integer result (`INT`, `UINT`, `WORD`, `DINT`) does not fit its type | The result **wraps** (two's complement, like a real PLC) and is written |
| `2` divide by zero | `SB10` | `DIV`, `MOD` or a `CPT` divides by 0, or a `CPT` raises 0 to a negative power (`0 ** -1`, `EXPT(0, -1)`); an `SCL` with input min = input max | Nothing |
| `3` invalid result | `SB10` | A result is not a number or infinite, for any type (a REAL beyond ±3.4 × 10³⁸, `SQRT` of a negative number, or an integer `CPT` too large to compute such as `10 ** 400`); a `CPT` whose expression does not compile | Nothing |
| `4` range | `SB11` | A D address or a block (`COP`, `FLL`, `PACK`, `UNPACK`) runs past the end of its table, or a two-word value starts at D4000; or (v1.125) a pointer `D[Dn]` whose target is outside D1–D4000 for the access width — Dn holds 0 or a negative number, a `DINT`/`REAL` pointer holds 4000, or a `COP`/`FLL` run from it passes D4000; or (v1.126) a `JMP` with no `LBL` further down the program — including a backward jump — while its rung is true, or a shift register or drum with invalid fields (the editor refuses those) | Nothing. A compare reads the bad pointer operand as 0; the bad jump is ignored and the scan continues with the next rung |

Writing to `AY` never raises an overflow: the value is rounded and limited to 0–4095. Clearing is done by the program, typically on a reset button: `P X2 → OTU SB9 → OTU SB10 → OTU SB11 → MOV SW17 "0"` (Section 7.2). Structured Text arithmetic never sets these flags.

Typical uses: `XIC SB3 → RES CT1` (start every run from zero), `XIC SB6 → OTE Y1` (1 Hz flasher), `LIM SW5 lo 7 hi 17 → OTE Y4` (enable 07:00–17:59), `XIC SB12 → OTE Y8` (math fault lamp).

---

## 4. Ladder logic JSON format

### 4.1 Overall file structure

This is the **version 2** format that the simulator currently exports.

```json
{
  "version": 2,
  "name": "Program Name",
  "exported": "2026-09-16T00:00:00.000Z",
  "notes": "Optional documentation for people reading the file.",
  "program": [
    { "id": 1, "rn": 0, "comment": "…", "elements": [ … ] },
    { "id": 2, "rn": 1, "comment": "…", "elements": [ … ] }
  ],
  "comments": {
    "X1": "Start PB",
    "Y1": "Motor Run"
  },
  "dregs": { "D10": 0, "D11": 17096 },
  "dfmt": { "D10": "REAL" }
}
```

| Field | Required | What the simulator does with it |
|---|---|---|
| `version` | Recommended | Use `2`. Written on export; not checked on import. |
| `name` | Recommended | Written on export (always as "ACC PLC Program"); ignored on import. Useful for people. |
| `exported` | Recommended | ISO-8601 date/time string. Ignored on import. |
| `notes` | Optional | **Ignored** by the simulator and not kept on re-export. Use it only as documentation inside the file. |
| `program` | **Yes** | Array of rung objects, in execution order. |
| `comments` | Recommended | Address comments (Section 4.8). |
| `dregs` | Optional (v1.124) | Starting values of the D registers: an object of address → **raw 16-bit word, a whole number 0–65,535**. Only non-zero registers are written on export; every register not listed starts at 0. An `INT` of −1 is stored as `65535`. A `DINT` or `REAL` is two entries, low word first: `REAL` 100.0 in D10 is `"D10": 0, "D11": 17096`; `DINT` 100000 in D20 is `"D20": 34464, "D21": 1`. A file without `dregs` loads with every D register at 0. |
| `dfmt` | Optional (v1.124) | Display format chosen on the D tab for individual registers: address → `DEC`, `UDEC`, `HEX`, `BIN`, `DINT` or `REAL`. Display only — it never changes how the program reads a register. Registers written by the program as `DINT`, `REAL` or `WORD` show as `DINT`, `REAL` or `HEX` without an entry. |

Keys in `dregs` and `dfmt` are read without regard to case (`d1` loads as D1), but write them in upper case; keys that are not `D1`–`D4000`, `dregs` values that are not whole numbers 0–65,535, and `dfmt` values that are not one of the six formats, are ignored. The importer also accepts a bare array of rungs with no wrapper, but the wrapped form above is preferred. When writing a new program, `dregs` is usually unnecessary: set starting values with an `XIC SB3` first-scan rung (`MOV`, `FLL`) so they are visible in the ladder.

### 4.2 Rung object

| Field | Meaning |
|---|---|
| `id` | Integer, unique among rungs. Use 1, 2, 3 … |
| `rn` | Rung number starting at 0. The simulator renumbers rungs 0, 1, 2 … in array order on import, so the array order is what matters, but matching numbers keep the file readable. |
| `comment` | Rung comment shown in the rung header. Describe what the rung does. |
| `elements` | Array of elements, read **left to right**. |

**Rules for `elements`:**

- At least one **input** element (contact, compare, or parallel group), and at least one **output** element (coil or block). The **last** element must be an output or a block — a contact in last position drives nothing at all.
- **More than one output on a rung is allowed.** Coils and blocks in series all act, and power passes straight through them, so `XIC X1 → OTE Y1 → OTE Y2 → OTL C5` energises all three from the one condition. This is how the shipped Palletizer program sets and clears several step bits on a single rung. A contact placed *after* an output gates only the outputs that follow it, which is a compact way to write "do A always, and B only if…". One output per rung is still the clearer default; reach for several only when they genuinely share a condition.
- Input elements listed one after another are in **series** (Boolean AND).
- An OR is made with a `parallel` element (Section 4.5).
- A rung with only an output and no inputs is treated as always true, but the editor never creates one; use an always-true contact instead (Section 4.7, MOV). The one exception is the END MCR rung (v1.126), which holds the `MCRE` block alone (Section 4.10).
- **Do not create empty rungs.** A rung with `"elements": []` scans harmlessly, but the simulator does not draw its number or comment, so a "documentation rung" is invisible. Put documentation in rung comments, the `comments` map, or `notes`.

### 4.3 Element IDs

Every element has an integer `id`. IDs must be **unique across the whole file**, including elements inside parallel branches, because the editor finds elements by id. A simple method is to number elements 101, 102, 103 … in the order they are written. After import, the simulator gives new elements ids above the highest one in the file.

### 4.4 Complete element reference

| `kind` | `type` values | `addr` | Extra fields | Position |
|---|---|---|---|---|
| `contact` | `XIC`, `XIO`, `P`, `N` | X, Y, C, SB, T (/DN /EN /TT), CT (/DN) | — | Input area or inside a branch |
| `compare` | `GRT`, `LES`, `GEQ`, `LEQ`, `EQU`, `NEQ` | D1–D4000 or `D[Dn]`, AX1–AX8, AY1–AY4, SW1–SW19, T*n*/ACC, CT*n*/ACC | `cmp` (number, word address or `D[Dn]`), `dt` | Input area or inside a branch |
| `compare` | `LIM` | same as above | `lo`, `hi` (number, word address or `D[Dn]`), `cmp`: `0`, `dt` | Input area or inside a branch |
| `parallel` | — | — | `branches` | Input area |
| `output` | `OTE`, `OTL`, `OTU` | Y1–Y16, C1–C256 (and `OTU` on SB9–SB11 only) | — | Last element |
| `block` | `TON`, `TOF`, `RTO` | T1–T256 | `pre` (milliseconds) | Last element |
| `block` | `CTU`, `CTD` | CT1–CT256 | `pre` (count) | Last element |
| `block` | `CTUD` | CT1–CT256 | `pre` (count), `cd` (string, bit address) | Last element |
| `block` | `RES` | T1–T256 or CT1–CT256 | `pre`: `0` | Last element |
| `block` | `MOV` | D1–D4000, `D[Dn]` or AY1–AY4 (destination); `SW17` only with `"src":"0"` | `src` (string: constant, word or `D[Dn]`), `st`, `dt`, `pre`: `0` | Last element |
| `block` | `ADD`, `SUB`, `MUL`, `DIV`, `MOD` | D1–D4000, `D[Dn]` or AY1–AY4 (destination) | `a`, `b` (strings: constant, word or `D[Dn]`), `dt`, `pre`: `0` | Last element |
| `block` | `INC`, `DEC` | D1–D4000, `D[Dn]` or AY1–AY4 | `dt`, `pre`: `0` | Last element |
| `block` | `CPT` | D1–D4000, `D[Dn]` or AY1–AY4 | `expr` (string; may contain `D[Dn]` terms), `dt`, `pre`: `0` | Last element |
| `block` | `SCL` | D1–D4000, `D[Dn]` or AY1–AY4 | `src` (constant, word or `D[Dn]`), `inMin`, `inMax`, `outMin`, `outMax` (numbers), `dt`, `pre`: `0` | Last element |
| `block` | `COP` | D1–D4000 or `D[Dn]` (first destination word) | `src` (first source word: D, AX, AY, SW or `D[Dn]`), `len` (words), `pre`: `0` | Last element |
| `block` | `FLL` | D1–D4000 or `D[Dn]` (first destination) | `src` (fill value: constant, word or `D[Dn]`), `len` (elements), `dt`, `pre`: `0` | Last element |
| `block` | `PACK` | D1–D4000 or `D[Dn]` | `src` (first bit: X, Y or C), `len` (1–16 bits), `pre`: `0` | Last element |
| `block` | `UNPACK` | Y or C (first destination bit) | `src` (word: D, AX, AY, SW or `D[Dn]`), `len` (1–16 bits), `pre`: `0` | Last element |
| `block` | `BSL`, `BSR` | C1–C256 or Y1–Y16 (first bit of the register) | `len` (1–256 bits), `src` (data bit), `ul` (unload bit, Y or C, or `""`), `pre`: `0` | Last element, never in a branch (v1.126) |
| `block` | `DRUM` | D1–D4000 (step register) | `out` (first output, Y or C), `outs` (1–16), `steps` (1–16 × `{p, t, ev}`), `rst` (bit or `""`), `dn` (Y or C, or `""`), `pre`: `0` | Last element, never in a branch (v1.126) |
| `block` | `JMP` | L1–L256 (label) | `pre`: `0` | Last element, never in a branch (v1.126) |
| `contact` | `LBL` | L1–L256 (label) | — | Input area, top level, not last; normally first (v1.126) |
| `block` | `MCR`, `MCRE` (END MCR) | `"MCR"` | `pre`: `0` | Last element, never in a branch; `MCRE` alone on its rung (v1.126) |

`D[Dn]` is a pointer (v1.125, Section 3.1.2): it is accepted only in the places the table shows. `dt` is the data type, one of `"INT"` (the default when `dt` is missing), `"UINT"`, `"WORD"`, `"DINT"` or `"REAL"`, written exactly in upper case (Section 3.1.1). `st` is MOV's source type, same values. "Last element" means the output position: as with coils, several blocks may follow one another on a rung, and all of them act (Section 4.2).

The importer reads `id`, `kind`, `type`, `addr`, plus `pre`, `src`, `a`, `b`, `expr`, `inMin`, `inMax`, `outMin`, `outMax`, `len`, `dt`, `st`, `ul`, `out`, `outs`, `rst`, `dn` and `steps` for blocks, `cd` for CTUD, `cmp`, `lo`, `hi` and `dt` for compares, and `branches` for parallel groups. Anything else on an element is ignored, except a legacy `comment` (Section 4.8).

`pre` (timers and counters) and the constants in a compare that reads **no** D register should be **whole numbers from 0 to 99,999,999**. A compare that reads a D register — directly or through a pointer — instead takes constants that fit its `dt` (Section 4.6). From v1.124 the import checks every element with the editor's own rules: the program still loads, but the status bar reports how many elements fail and the first problem, and the editor refuses to save such an element unchanged. The validator in Section 10.2 applies the same rules before import.

### 4.5 Contacts and parallel branches

**Contacts**

```json
{"id":101,"kind":"contact","type":"XIC","addr":"X1"}
```

| `type` | Name | Passes power when… |
|---|---|---|
| `XIC` | Examine If Closed (normally open, `-| |-`) | the addressed bit is ON (1) |
| `XIO` | Examine If Open (normally closed, `-|/|-`) | the addressed bit is OFF (0) |
| `P` | Rising edge (`-|P|-`) | the bit went OFF → ON since the previous scan — true for **one scan only** |
| `N` | Falling edge (`-|N|-`) | the bit went ON → OFF since the previous scan — true for **one scan only** |

**Edge contacts (`P`, `N`).** An edge contact remembers its bit from the previous scan. It watches the bit every scan, even when contacts to its left are open. Use `P` wherever an action should happen once per press: counting, toggling, stepping a sequence. Each edge contact keeps its own memory, so two `P X1` contacts on different rungs both fire on the same press.

The memory starts OFF every time the PLC enters RUN. A bit that is already ON at that moment fires its rising edge once on the first scan, the same as an IEC `R_TRIG`.

```json
{"id":101,"kind":"contact","type":"P","addr":"X1"}
```

**Parallel branches (OR logic)**

A parallel group is one element holding two or more **branches**. Each branch is an array of contacts and/or compares in series. The group passes power if **any** branch passes power.

```json
{"id":121,"kind":"parallel","type":"XIC","addr":"","branches":[
  [ {"id":122,"kind":"contact","type":"XIC","addr":"X1"} ],
  [ {"id":123,"kind":"contact","type":"XIC","addr":"C1"},
    {"id":124,"kind":"contact","type":"XIO","addr":"C2"} ]
]}
```

This reads as: `X1 OR (C1 AND NOT C2)`.

Rules:

- A parallel element needs only `id`, `kind` and `branches`. Older files and the examples in this guide also carry `"type": "XIC"` and `"addr": ""` placeholders; they are ignored, so either form loads.
- A group needs **at least two** branches, and no branch may be empty.
- Branches contain **contacts and compares only**. Outputs and blocks never go inside a branch.
- Keep branches **flat** — never put a parallel group inside a branch. A nested group *evaluates* correctly, but the simulator sizes a rung from the branch count of its top-level groups only, so the nested rows are drawn over the rows below them and the rung becomes unreadable. If the logic is `(A OR B) AND C OR D`, expand it into branches such as `[A, C]`, `[B, C]`, `[D]`.
- A single-branch group loads and behaves as that one branch, but the editor's Parallel Branch Editor expects at least two. Use a plain series contact instead of a one-branch group.

### 4.6 Compare elements (thresholds and ranges)

```json
{"id":101,"kind":"compare","type":"LES","addr":"AX1","cmp":819}
```

A compare sits in the input area, like a contact, and passes power when the value at `addr` (A) meets the condition against `cmp` (B), or against the `lo`/`hi` limits for LIM. B and the limits can be fixed numbers or other registers.

| `type` | Passes power when… |
|---|---|
| `GRT` | A > B |
| `LES` | A < B |
| `GEQ` | A ≥ B |
| `LEQ` | A ≤ B |
| `EQU` | A = B (exact match) |
| `NEQ` | A ≠ B |
| `LIM` | `lo` ≤ A ≤ `hi` (both limits included). If `lo` is greater than `hi` the band wraps: it passes when A ≥ `lo` **or** A ≤ `hi`. |

```json
{"id":102,"kind":"compare","type":"LIM","addr":"AX1","lo":1000,"hi":3000,"cmp":0}
{"id":103,"kind":"compare","type":"GEQ","addr":"D20","cmp":"D22","dt":"DINT"}
{"id":104,"kind":"compare","type":"GRT","addr":"AX1","cmp":"AX2"}
{"id":105,"kind":"compare","type":"GEQ","addr":"AX1","cmp":"D[D2]","dt":"INT"}
```

- `addr` (A) can be:
  - a data register, `D1`–`D4000`, read as the compare's `dt`;
  - a pointer `D[Dn]` (v1.125, Section 3.1.2): the register whose number is in Dn, read as the compare's `dt`;
  - an analog input, `AX1`–`AX8`;
  - an analog output, `AY1`–`AY4`, for example to check a value the program has already moved;
  - a system word, `SW1`–`SW19`, for example `SW5` for the hour;
  - a timer's elapsed time `T1/ACC` (milliseconds), or a counter's count `CT1/ACC`.
- `cmp` (B), `lo` and `hi` are each either a **number** (`819`) or a **word address written as a string** (`"D22"`, `"AX2"`, `"T2/ACC"`, `"D[D2]"`), from the same list as A. So a compare can test one register against another: `GRT AX1 cmp "AX2"`, or against the table entry a pointer selects: `GEQ AX1 cmp "D[D2]"`.
- **`dt` matters only when the compare reads a D register** (as A, B, `lo` or `hi`), directly or through a pointer. Every D register in the compare is read as that type; `AX`, `AY`, `SW` and `/ACC` are read as their natural value. A `DINT` or `REAL` compare on `D4000` is refused (it would need D4001); through a pointer the same limit is checked on every scan.
- **A compare with a pointer is evaluated on every scan**, whether or not power reaches it. If the pointer is invalid (Section 3.1.2), that operand reads as 0 and the scan sets SB11 with code 4 and the compare's rung in SW18 — for example `GRT D[D5] cmp -1` with D5 = 0 is **true** and faults on every scan.
- **Constants follow two rules.** In a compare with no D register, constants must be whole numbers 0–99,999,999 (the v1.123 rule: 0–4095 is the useful range for AX/AY, the word's own range for SW). In a compare that reads a D register or a pointer, constants must fit `dt`: `INT` −32,768 to 32,767, `UINT`/`WORD` 0 to 65,535, `DINT` −2,147,483,648 to 2,147,483,647, `REAL` any number within ±3.4 × 10³⁸ (decimals only with `REAL`). Write constants as JSON numbers, not strings.
- **`EQU` on a `REAL` is rarely true after arithmetic** — a computed value such as 0.1 + 0.2 is not exactly 0.3. Use `LIM` or `GEQ`/`LEQ` around the target instead. REAL constants are rounded to 32-bit like the registers, so `MOV 0.1` into a REAL register followed by `EQU` with `0.1` is true.
- **One timer can stage several actions:** `GRT T1/ACC cmp 2000` and `GRT T1/ACC cmp 5000` on separate rungs act at 2 s and 5 s of the same TON.
- **LIM replaces two compares in series.** `LIM AX1 lo 1000 hi 3000` is the same as `GEQ AX1 1000` followed by `LEQ AX1 3000`.
- Analog signals rarely hit an exact value, so prefer `GRT`/`LES`/`GEQ`/`LEQ` over `EQU`.
- For on/off control with a dead band (hysteresis), use two rungs: one compare with `OTL` and a second compare with `OTU`, as in Section 7.
- Compares can be placed in series with contacts and inside parallel branches.

### 4.7 Output coils and blocks

**Coils**

```json
{"id":110,"kind":"output","type":"OTE","addr":"Y1"}
```

| `type` | Name | Behaviour |
|---|---|---|
| `OTE` | Output Energize `-( )-` | Bit ON while rung is true, OFF when false |
| `OTL` | Output Latch `-(L)-` | Sets the bit ON when rung is true; stays ON |
| `OTU` | Output Unlatch `-(U)-` | Sets the bit OFF when rung is true |

Coils write `Y1`–`Y16` or `C1`–`C256`. A coil addressed to an `X` input is not rejected — it does write the input bit — but a connected scene rewrites every X at the start of each scan, so the value is overwritten and the rung appears to do nothing. Never target X with a coil. A coil addressed to `AY` does nothing at all; use MOV. System bits are read-only: the one exception is `OTU` on `SB9`–`SB11`, which clears an error flag.

**Timers**

```json
{"id":128,"kind":"block","type":"TON","addr":"T1","pre":15000}
```

| `type` | Behaviour |
|---|---|
| `TON` | On-delay. While the rung is true, the accumulator counts up (to a maximum of `pre`) and DN turns on when it reaches `pre`. When the rung goes false, the timer resets to 0 and DN turns off. |
| `TOF` | Off-delay. While the rung is true, DN is on and the accumulator is 0. When the rung goes false, the accumulator counts; DN turns off once it reaches `pre`. |
| `RTO` | Retentive on-delay. Times while the rung is true, like TON, but **keeps** its accumulated time when the rung goes false, adding up across separate ON periods. DN turns on when the total reaches `pre`. Only a `RES` on the same address clears it; STOP does not. |

`pre` is in **milliseconds** (1000 = 1 second). A missing or zero `pre` makes the timer done immediately. The accumulator advances by the real elapsed time each scan (about 100 ms), at most 500 ms per scan. Read the result on another rung with a contact such as `XIC T1`, `XIC T1/TT` (timing) or `XIC T1/EN` (enabled), or compare the elapsed time with `T1/ACC`.

**Counters**

```json
{"id":140,"kind":"block","type":"CTU","addr":"CT1","pre":5}
```

| `type` | Behaviour |
|---|---|
| `CTU` | Adds 1 on each OFF→ON transition of its rung. DN turns on when the count reaches `pre`. The count keeps rising past `pre`. |
| `CTD` | Subtracts 1 on each OFF→ON transition, but never below 0. DN turns on when the count reaches 0. |
| `CTUD` | Up/down counter in one block. Adds 1 on each OFF→ON of its **rung**, and subtracts 1 on each OFF→ON of the bit named in `cd`. If both happen on the same scan they cancel. Never goes below 0. DN turns on when the count is at or above `pre`. |

```json
{"id":141,"kind":"block","type":"CTUD","addr":"CT2","pre":10,"cd":"X4"}
```

- Holding the rung true does not keep counting; the rung must go false and true again.
- **For an up/down count, use `CTUD`.** `cd` is a bit address written as a string (`"X4"`, `"C101"`), and it is read directly — it does not need its own rung. The older pattern of a `CTD` and a `CTU` on the same address still works, but needs both rungs and the same `pre` on each, because each block writes its preset every scan.
- Counts start at 0, so a `CTD` on its own never changes.
- Read the live count in a compare as `CT1/ACC`.
- Counts are cleared only by a `RES` rung or by loading a program. **STOP does not clear them.**

**Reset**

```json
{"id":150,"kind":"block","type":"RES","addr":"CT1","pre":0}
```

While its rung is true, `RES` clears the named timer or counter: the count or accumulated time goes to 0 and DN turns off (a timer's EN also turns off). `addr` is `T1`–`T256` or `CT1`–`CT256`, without `/DN`. Include `"pre": 0`.

A TON whose rung is still true starts timing again on the next scan after a reset.

**Move (MOV)**

```json
{"id":160,"kind":"block","type":"MOV","addr":"AY1","src":"4095","pre":0}
{"id":161,"kind":"block","type":"MOV","addr":"D20","src":"D1","st":"INT","dt":"DINT","pre":0}
```

While its rung is true, `MOV` writes the source value to the destination.

- `addr` is the destination: an analog output `AY1`–`AY4`, or (from v1.124) a data register `D1`–`D4000`, or (from v1.125) a pointer `"D[D5]"` (Section 3.1.2). The one other destination is `SW17` with `"src": "0"`, which clears the last error code.
- `src` is a **string**: either a constant such as `"2048"`, or a readable word: `"D1"`, `"AX1"`, `"AY2"`, `"SW6"`, `"T1/ACC"`, `"CT1/ACC"` or a pointer `"D[D2]"`. The editor refuses any other source.
- **Into AY** the value is rounded and limited to 0–4095, so a timer at 5000 ms moved to `AY1` gives 4095. This is exactly the v1.123 behaviour.
- **Into D** the value is written as the destination type `dt`. A constant must fit that type (whole numbers for the integer types).
- **`st` is the source type**, used only when `src` is a D register or a pointer; `dt` is the destination type, used only when `addr` is a D register or a pointer. Both default to `INT`. MOV is the instruction that **converts between types**: the example above reads D1 as an `INT` and writes it to D20–D21 as a `DINT`. A `REAL` moved into an integer type is rounded half away from zero (2.5 → 3, −2.5 → −3); a value that does not fit wraps and sets SB9 (Section 3.6).
- Include `"pre": 0`.
- The destination **keeps its value** when the rung goes false, so a two-state output needs two MOV rungs (one for each state).
- To copy an input straight through (for example a speed pot to a drive reference), use a rung that is always true in RUN, such as `XIC X2` for a Stop that is normally on, or `XIC SB1` (always ON), with `MOV AY1` and `"src": "AX1"`.

**Math and data blocks (v1.124)**

Every block in this group:

- writes to `addr`, its destination: a D register or a pointer `D[Dn]` (v1.125, Section 3.1.2), or for the math blocks also `AY1`–`AY4` (rounded and limited to 0–4095, never an overflow);
- reads and writes D registers as its `dt` (default `INT`, Section 3.1.1); constants must fit `dt`, and the integer types take whole numbers only;
- **acts on every scan its rung is true** and passes power through, so several blocks can follow one another on one rung and they act left to right;
- raises the error flags of Section 3.6 instead of stopping the PLC.

Operands (`a`, `b`, `src`) are written as strings, like MOV's `src`: a constant (`"100"`, `"-2.5"`), a word (`"D10"`, `"AX1"`, `"SW5"`, `"T1/ACC"`, `"CT1/ACC"`) or a pointer (`"D[D2]"`). The editor stores them that way; JSON numbers are accepted too.

**Once per event, not once per scan.** A block behind `XIC X1` acts about ten times a second while X1 is held. When it must act once per press or per change — counting with `INC`, adding a batch to a total, logging a value — put a rising-edge contact in front of it:

```json
{"id":170,"kind":"contact","type":"P","addr":"X1"},
{"id":171,"kind":"block","type":"INC","addr":"D5","pre":0}
```

| `type` | Fields | What it does |
|---|---|---|
| `ADD` | `a`, `b`, `dt` | `addr := a + b` |
| `SUB` | `a`, `b`, `dt` | `addr := a − b` |
| `MUL` | `a`, `b`, `dt` | `addr := a × b` (a `DINT` product wraps exactly) |
| `DIV` | `a`, `b`, `dt` | `addr := a ÷ b`. Integer types truncate toward zero (7 ÷ 2 = 3, −7 ÷ 2 = −3); `REAL` keeps decimals. |
| `MOD` | `a`, `b`, `dt` | `addr :=` remainder of `a ÷ b`; its sign follows `a` (−7 MOD 2 = −1) |
| `INC` / `DEC` | `dt` | `addr := addr + 1` / `addr − 1` |
| `CPT` | `expr`, `dt` | `addr :=` the expression (below) |
| `SCL` | `src`, `inMin`, `inMax`, `outMin`, `outMax`, `dt` | `addr := outMin + (src − inMin) × (outMax − outMin) ÷ (inMax − inMin)` |
| `COP` | `src`, `len` | Copies `len` raw 16-bit words starting at `src` (D, AX, AY, SW or a pointer) to D registers starting at `addr` (a D register or a pointer) |
| `FLL` | `src`, `len`, `dt` | Writes the value `src` into `len` elements of type `dt` starting at `addr` (a D register or a pointer) |
| `PACK` | `src`, `len` | Packs `len` bits (1–16) starting at `src` (X, Y or C) into the word `addr` (a D register or a pointer): the first bit is bit 0 |
| `UNPACK` | `src`, `len` | Writes bit 0, bit 1 … of the word `src` (D, AX, AY, SW or a pointer) to `len` bits (1–16) starting at `addr` (Y or C) |

```json
{"id":172,"kind":"block","type":"ADD","addr":"D10","a":"D10","b":"5","dt":"INT","pre":0}
{"id":173,"kind":"block","type":"DIV","addr":"D24","a":"D22","b":"D26","dt":"DINT","pre":0}
{"id":174,"kind":"block","type":"CPT","addr":"D30","expr":"AX1 * 100.0 / 4095","dt":"REAL","pre":0}
{"id":175,"kind":"block","type":"SCL","addr":"D1","src":"AX1","inMin":0,"inMax":4095,"outMin":0,"outMax":2000,"dt":"INT","pre":0}
{"id":176,"kind":"block","type":"COP","addr":"D100","src":"AX1","len":8,"pre":0}
{"id":177,"kind":"block","type":"FLL","addr":"D200","src":"0","len":10,"dt":"DINT","pre":0}
{"id":178,"kind":"block","type":"PACK","addr":"D50","src":"X1","len":8,"pre":0}
{"id":179,"kind":"block","type":"UNPACK","addr":"Y1","src":"D50","len":8,"pre":0}
```

Details:

- **Integer arithmetic** (`INT`, `UINT`, `WORD`, `DINT`): each operand is truncated toward zero first. A result that does not fit wraps around and sets SB9 — `ADD` of 1 to an `INT` 32767 gives −32768.
- **`DIV` and `MOD` by zero** write nothing and set SB10 with code 2. The editor refuses a constant `b` of 0; when `b` is a register that can be 0, guard the rung with a compare, such as `GRT D26 cmp 0`.
- **`SCL`** is not clamped: an input outside `inMin`…`inMax` gives an output outside `outMin`…`outMax`. The four limits are JSON numbers and may have decimals. Integer types round the result half away from zero; `REAL` keeps decimals. `inMin` equal to `inMax` is refused. Note that `src` is read as `dt` when it is a D register.
- **`COP`** copies raw words with no conversion, so a `DINT` or `REAL` is two words: `len` 2 copies one of them. The source and destination may overlap. `dt` is not used.
- **`FLL`** counts `len` in elements of `dt`: 10 `DINT`s fill D200–D219. Use it on a first-scan rung (`XIC SB3`) to clear a table.
- **`PACK`** writes the whole word: bits above `len` are 0. **`UNPACK`** sets each target bit ON or OFF while its rung is true and leaves them alone when it is false; it may not write X.
- `COP`, `FLL`, `PACK` and `UNPACK` must stay inside their tables (D1–D4000, AX1–AX8, AY1–AY4, SW1–SW19, X/Y1–16, C1–C256). The editor checks this for direct addresses; a start given by a pointer is checked each time the block executes, for the whole run. A run-time overrun writes nothing and sets SB11.
- **Through a pointer**, each operand is resolved every time the block executes (Section 3.1.2). One `MOV D10 src "D[D2]"` fetches whichever table entry D2 selects; one `P X1 → INC D[D3]` counts into whichever register D3 names.

**CPT expressions.** `expr` is a string using:

- numbers, and the words `D1`–`D4000`, `AX1`–`AX8`, `AY1`–`AY4`, `SW1`–`SW19`;
- pointer terms `D[Dn]` (v1.125), such as `D[D2] * 10 + D[D3]`;
- `+`, `-`, `*`, `/`, `MOD`, `**` (power), unary `-`, and brackets;
- the functions `ABS(x)`, `SQRT(x)`, `MIN(a, b, …)` and `MAX(a, b, …)` (two or more arguments), `LIMIT(min, in, max)`, `TRUNC(x)`, `ROUND(x)` and `EXPT(base, exponent)`.

Nothing else is accepted: no bits, no `T1/ACC` or `CT1/ACC` (MOV them into a D register first), no comparisons, `AND`/`OR`/`NOT`, `TRUE`/`FALSE`, no other indexing (`D[5]`, `D[AX1]`, `D[D5 + 1]` and `D[D[5]]` are refused — the index must be a single D register) and no other function names. Precedence is the Structured Text order (`**` first, then `*` `/` `MOD`, then `+` `-`); use brackets whenever in doubt.

- **Every D register in the expression is read as the CPT's `dt`**, and so is every pointer target. A `REAL` CPT that names D1 reads D1 and D2 as one float, even if D1 holds an `INT`. Read analog values straight from `AX`, or MOV a register into the right type first. A two-word type refuses `D4000`; a pointer term is checked when it executes, and an invalid one writes nothing and sets code 4.
- **`dt` `REAL`** works in floating point and writes a 32-bit float.
- **Integer `dt`** truncates every operand and every division, `**`, `SQRT` and `EXPT` result toward zero, and the editor refuses decimal constants: write `* 3 / 2` instead of `* 1.5`, or use `REAL`. `AX1 * 100 / 4095` with AX1 = 2048 gives 50. `ROUND()` rounds half away from zero. The arithmetic itself is done in double precision, so intermediate values beyond about 9 × 10¹⁵ lose precision before the result is wrapped to the type.
- Division or `MOD` by zero writes nothing and sets code 2; a result that is not a number (for example `SQRT` of a negative value) writes nothing and sets code 3.

### 4.8 Address comments

The simulator keeps **one comment per address**. Every contact, compare, coil or block that uses `X1` shows the same "Start PB" label.

In version 2 files, address comments live in a top-level `comments` object:

```json
"comments": {
  "X1": "Start PB",
  "X2": "Stop PB N.C.",
  "AX1": "Tank Level 0-4095",
  "C101": "Fill Request",
  "T1": "Mix Timer"
}
```

- Keys are addresses in **upper case**, exactly as written in the program (`X1`, `C101`, `T1`, `CT1`, `AX1`, `AY1`, `D10`, `SB3`, `SW5`). For a `DINT` or `REAL`, comment the first register (`D10`); naming the type in the comment (`"Total Litres (DINT)"`) helps the next reader. System addresses show a built-in description on the ladder when they have no comment, so a key is optional for them. A contact written as `T1/DN` or `T1/TT` looks up that exact key, so add a key for every form the program uses (for example both `T1` and `T1/TT`).
- Values are plain text.
- **Legacy format:** older files put a `"comment"` on each element. The importer still reads these, keeping the *first* comment it finds for each address and ignoring later different ones. If a `comments` map is present, it overrides them. New files should use the map only.

### 4.9 Reading and writing a rung — a worked translation

Boolean expression: `C1 := (X1 OR C1) AND X2`

Ladder:

```
    X1        X2
|---+----| |---+----| |------------------------(C1)---|
    |    C1    |
    +----| |---+
```

JSON:

```json
{"id": 1, "rn": 0,
 "comment": "RUN SEAL-IN — (Start X1 OR seal-in C1) AND Stop X2 (N.C.)",
 "elements": [
   {"id":101,"kind":"parallel","type":"XIC","addr":"","branches":[
     [ {"id":102,"kind":"contact","type":"XIC","addr":"X1"} ],
     [ {"id":103,"kind":"contact","type":"XIC","addr":"C1"} ]
   ]},
   {"id":104,"kind":"contact","type":"XIC","addr":"X2"},
   {"id":105,"kind":"output","type":"OTE","addr":"C1"}
 ]}
```

### 4.10 Shift registers, drum sequencer, jumps and master control (v1.126)

v1.126 adds seven ladder instructions for sequencing and program flow. They are **ladder-only**: Structured Text has no equivalent instructions (Section 5.1 shows how to write the same logic in ST). All of them except `LBL` are output-position blocks: each must be the **last element of its rung**, and none may sit inside a parallel branch. `LBL` is an input element.

The importer gives these types their kind whatever the file says (`LBL` becomes a contact, the others blocks), and stores a label as `L<n>`: `"l05 "` loads as `"L5"`. Write `kind` and the label that way.

**Bit shift registers — `BSL`, `BSR`**

```json
{"id":201,"kind":"block","type":"BSL","addr":"C1","len":8,"src":"X2","ul":"C9","pre":0}
{"id":202,"kind":"block","type":"BSR","addr":"Y1","len":4,"src":"C20","ul":"","pre":0}
```

| Field | Meaning |
|---|---|
| `addr` | First bit of the register: `C1`–`C256` or `Y1`–`Y16` |
| `len` | Number of bits, 1–256; `addr` + `len` − 1 must stay inside the table (`C250` with `len` 8 is refused) |
| `src` | Data bit: any bit address (`X2`, `C5`, `T1/DN`, `SB5` …) |
| `ul` | Unload bit, `Y` or `C`, or `""` for none |

- On each **rising edge** of the rung (false → true, like a counter) the register shifts one position. Holding the rung true does not shift again. A `P` contact in front is optional; it makes the intent plain.
- `BSL` moves every bit to the next higher address: `src` enters at `addr`, and the bit leaving the top (`addr` + `len` − 1) goes to `ul`. `BSR` moves every bit to the next lower address: `src` enters at the top, and the bit leaving `addr` goes to `ul`.
- `src` is read at the moment of the shift. `ul` is written only when a shift happens and keeps that value until the next one.
- The register bits are ordinary C or Y bits: contacts read them, `OTU` clears them (a reset rung empties a register with one `OTU` per bit), and STOP clears them like any C or Y bit. Do not drive a register bit with `OTE` — the coil rewrites it on every scan.
- The block passes power through. Its edge memory starts OFF on every STOP → RUN, so a rung that is already true shifts once on the first scan.

**Drum sequencer — `DRUM`**

```json
{"id":210,"kind":"block","type":"DRUM","addr":"D1","out":"Y1","outs":6,"rst":"X4","dn":"C1","pre":0,
 "steps":[{"p":33,"t":5000,"ev":""},{"p":34,"t":2000,"ev":""},{"p":12,"t":0,"ev":"X5"}]}
```

| Field | Meaning |
|---|---|
| `addr` | Step register, `D1`–`D4000`, read and written as `INT`: the current step, 1 … number of steps |
| `out` | First output bit, `Y` or `C` |
| `outs` | Number of outputs, 1–16; `out` + `outs` − 1 must stay inside the table |
| `steps` | 1–16 step objects, in order: `p` = output pattern, a whole number 0–65,535 (bit 0 drives `out`, bit 1 the next address …; `33` = binary 100001 = first and sixth outputs); `t` = step time in ms, 0–99,999,999; `ev` = event bit address, or `""` for none |
| `rst` | Reset bit (any bit address), or `""` |
| `dn` | Done bit, `Y` or `C`, or `""` |

- **While the rung is true** the current step's pattern is written to the outputs on every scan, and the step time adds the real elapsed time (at most 500 ms per scan, like a timer). The drum moves to the next step when **both** conditions hold: the step time has reached `t` (`t` = 0 means no time condition) **and** the event bit is ON (`ev` = `""` means no event condition). The new step's pattern is written on the same scan. A step with `t` = 0 and no event advances on the next scan, so it lasts one scan.
- After the last step the drum returns to step 1, and `dn` is ON for that one scan. It is written OFF on every other scan, so count cycles from it: `P C1 → INC D2`, or `XIC C1 → CTU CT1`.
- **While the rung is false** the drum pauses: the step and its time are held, and the outputs are not written, so they keep their last state.
- **Reset:** while `rst` is ON (checked every scan, rung true or false) the drum is at step 1 with step time 0 and does not advance. With the rung true, step 1's pattern is written.
- A step register holding a value outside 1 … number of steps (0 in a new program, or a value written by a `MOV`) is treated as step 1 and corrected to 1. No fault.
- The step time is not saved: it restarts from 0 on every STOP → RUN. The step register is a D register, so it keeps its value through STOP and is saved with the program (`dregs`); the drum resumes at the same step with a fresh step time.
- Bits in `p` at or above `outs` are ignored. The drum owns its output bits: do not drive them with `OTE` elsewhere. A `MOV` into the step register jumps the drum to that step, and that step's time starts from 0.

**Jumps — `JMP` and `LBL`**

```json
{"id":220,"kind":"block","type":"JMP","addr":"L1","pre":0}
{"id":221,"kind":"contact","type":"LBL","addr":"L1"}
```

- `LBL L1` marks the rung a `JMP L1` jumps to. It always passes power, so put it first on the rung, in front of the rung's own logic: `LBL L1 → XIC X4 → OTE Y2`. It must be at top level (not in a branch) and never the last element. Each label is used once.
- When a `JMP` executes with power, the scan skips every rung after the JMP's rung up to the rung that holds the matching `LBL`, then continues **with** that rung. Jumps go **forward only**: the `LBL` must be on a later rung. A `JMP` whose rung is false does nothing.
- Skipped rungs are not evaluated at all: coils keep their state (an `OTE` that was ON stays ON), timers neither time nor reset, counters and shift registers do not count or shift, word blocks and drums do not run, and edge memory is not updated — a `P` contact whose bit came ON during the skip fires on the first scan its rung runs again. Skipped rungs are drawn dimmed with `SKIPPED (JMP L1)`.
- A `JMP` with no `LBL` further down (missing, or above it) is reported on import. If it runs anyway, the jump is ignored and sets fault code 4 (Section 3.6) on every scan its rung is true.
- A jump may not go into or out of an MCR zone; it may jump over a whole zone.

**Master control zones — `MCR` and `END MCR`**

```json
{"id":230,"kind":"block","type":"MCR","addr":"MCR","pre":0}
{"id":231,"kind":"block","type":"MCRE","addr":"MCR","pre":0}
```

- `MCR` ends the rung that switches the zone. `MCRE` (shown as END MCR) stands alone on its own rung and closes the zone. Both have the fixed address `"MCR"`. The rungs between them are the zone.
- MCR rung **true**: the zone rungs run normally.
- MCR rung **false**: every zone rung runs with its power rail OFF, as if its conditions were false. `OTE` coils turn OFF; `OTL` and `OTU` hold; `TON` resets and `TOF` times out, as with a false rung; `RTO` holds its time; counters and shift registers see no rising edge (a `CTUD`'s `cd` input is read every scan and still counts down); MOV, math and data blocks do not run; drums pause with their outputs held. Zone rungs show `MCR OFF`.
- When the zone turns back on while a counter's or shift register's rung is true, that is a rising edge: it counts or shifts once.
- Zones cannot be nested, and an END MCR needs an open MCR above it. An MCR with no END MCR runs to the end of the program; the import reports it, but the program loads and runs (the validator gives a warning).
- An MCR zone is a program function, not a safety function: E-stops and safety interlocks belong in hardware.

**Program checks.** On import the simulator applies these rules (and the validator in Section 10.2 applies the same ones):

| Rule | Level |
|---|---|
| `BSL`, `BSR`, `DRUM`, `JMP`, `MCR`, `MCRE` are the last element of their rung and never inside a parallel branch | Error |
| `LBL` is at top level (not in a branch) and not the last element | Error |
| `END MCR` is alone on its rung | Error |
| Each label is used once | Error |
| Every `JMP` has its `LBL` on a later rung (no missing labels, no backward jumps) | Error |
| No MCR inside an open zone; no END MCR without an open MCR | Error |
| `JMP` and its `LBL` are in the same zone (or both outside any zone) | Error |
| Every MCR has an END MCR | Warning — the zone runs to the end of the program |

---

## 5. How to design ladder logic from a description or from ST

Follow these steps in order. They work whether you start from a written sequence of operation or from an existing Structured Text program.

**Step 1 — List the I/O.** Write down every input and output, its address, whether it is N.O. or N.C., and the scaling of any analog signal.

**Step 2 — Decide the states.** Break the sequence into steps (Idle, Forward, Reverse; or Fill, Mix, Drain). Give each active step its own internal relay (C bit). "Idle" is usually *all state bits off* and does not need its own bit.

**Step 3 — Replace integer state variables with bits.** Ladder has no `CASE` statement. An ST variable such as `State : INT` with values 0, 1, 2 becomes C bits, one per non-idle state. This keeps the ladder to plain contacts and coils. (From v1.124 a state number can also be kept in a D register, tested with `EQU D1 cmp 2` and changed with `MOV D1 src "3"`, but C bits remain the clearer default for a short sequence.) ST variables that hold **numbers** — totals, setpoints, scaled values — become D registers: one per `INT`, two per `DINT` or `REAL` (Section 3.1.1).

**Step 4 — Make one-shots for pushbuttons.** A start command that should act once per press needs a one-shot. Use a **rising-edge contact**:

```
Rung A:  P X1  → OTE C3     (C3 = pulse, true for one scan per press)
```

Or put `P X1` directly in the rung that must act once, with no pulse bit at all. Use `N` for "on release".

Files written for v1.122 and earlier use the two-rung equivalent, which still works (the conveyor example in Section 6 keeps it):

```
Rung A:  XIC X1  XIO C4  → OTE C3     (C3 = pulse, true for one scan)
Rung B:  XIC X1          → OTE C4     (C4 = X1 from last scan)
```

Rung A must come **before** Rung B, or the pulse never fires.

**Step 5 — Convert analog conditions to compares.** Each threshold becomes a compare element with its value converted to 0–4095. On/off control with a dead band becomes an OTL rung at one threshold and an OTU rung at the other. When the program also needs the value in engineering units (litres, °C, %), scale it once with `SCL` into a D register on an always-true rung, and compare the D register instead (Section 7.2).

**Step 5a — Arithmetic.** Each ST assignment that calculates becomes a math block (`ADD`, `SUB`, `MUL`, `DIV`, `MOD`, `SCL`) or, for a longer formula, one `CPT`. Choose `dt` for every D register before writing the rungs, and keep two-word values on their own pairs of registers. Ask of every math rung: *should this happen once per event, or continuously?* Continuous calculations (scaling, averages) sit on an always-true rung; anything that accumulates (`INC`, `x := x + …`) needs a `P` contact.

**Step 6 — Write each state rung.** For a state held with seal-in (OTE style):

```
[Stop OK] AND ([enter condition] OR [this state bit AND NOT exit condition]) → OTE state bit
```

Or use an OTL rung to enter and a separate OTU rung to leave. Both styles are correct; seal-in is easier to read, and latch/unlatch is easier when a state has many entry or exit paths. With latches, remember to unlatch every state bit when Stop is pressed.

**Step 7 — Order the rungs for same-scan transitions.** Because memory updates immediately, place the rung that sets the *next* state before the rung that clears the *current* state. The next-state rung still sees the current bit on, and the current-state rung can then drop out using the next-state bit as an interlock.

**Step 8 — Add interlocks.** Two states that must never be on together should each include an XIO contact of the other. This replaces ST's `ELSE State := 0` safety net.

**Step 9 — Drive the outputs last.** Write one rung per physical output, driven from the state bits (for example `C1 OR C2 → Y1`). For analog outputs, write one MOV rung per value the output can take, or calculate the value into a D register and MOV it to the AY on an always-true rung. Keeping outputs separate from state logic makes troubleshooting much easier. Where a single transition really does set and clear several bits at once, putting those coils on one rung (section 4.2) keeps the step logic in one place instead of repeating the same condition on three rungs.

**Step 10 — Document.** Give every rung a comment, add every used address to the `comments` map, and describe the program in `notes`.

### 5.1 ST-to-ladder translation table

| Structured Text | Ladder equivalent |
|---|---|
| `Y1 := X1;` | `XIC X1 → OTE Y1` |
| `Y1 := NOT X1;` | `XIO X1 → OTE Y1` |
| `Y1 := X1 AND X2;` | `XIC X1, XIC X2 → OTE Y1` (series) |
| `Y1 := X1 OR X2;` | parallel `[X1]`,`[X2]` → `OTE Y1` |
| `IF X1 THEN C1 := TRUE; END_IF;` | `XIC X1 → OTL C1` |
| `IF X2 THEN C1 := FALSE; END_IF;` | `XIC X2 → OTU C1` |
| `Y3 := AX1 > 3890;` | `GRT AX1 cmp 3890 → OTE Y3` |
| `IF AX1 < 819 THEN C101 := TRUE; END_IF;` | `LES AX1 cmp 819 → OTL C101` |
| `IF C101 THEN AY1 := 4095; ELSE AY1 := 0; END_IF;` | `XIC C101 → MOV AY1 src "4095"` and `XIO C101 → MOV AY1 src "0"` |
| `AY1 := AX1;` | always-true rung → `MOV AY1 src "AX1"` |
| `State : INT` with `CASE` | one C bit per non-idle state (Steps 2–3) |
| `R_TRIG` / `NOT Last` pattern | `P` contact (Step 4) |
| `F_TRIG` | `N` contact |
| `tmr(IN := X1, PT := T#5s); Y1 := tmr.Q;` | `XIC X1 → TON T1 pre 5000`, then `XIC T1 → OTE Y1` |
| `IF tmr.ET > 2000 THEN …` | `GRT T1/ACC cmp 2000` |
| `cnt(CU := X1, R := X3, PV := 5); Y4 := cnt.Q;` | `XIC X1 → CTU CT1 pre 5`, `XIC CT1 → OTE Y4`, `XIC X3 → RES CT1` |
| `c(CU := X1, CD := X2, R := X3, PV := 10); Y1 := c.QU;` | `XIC X1 → CTUD CT1 pre 10 cd "X2"`, `XIC CT1 → OTE Y1`, `XIC X3 → RES CT1` |
| `Y1 := (AX1 >= 1000) AND (AX1 <= 3000);` | `LIM AX1 lo 1000 hi 3000 → OTE Y1` |
| `IF SB3 THEN … END_IF;` (first scan) | `XIC SB3 → …` |
| `Level : INT;` (a numeric variable) | a D register, e.g. `D1` with `"dt":"INT"`; `DINT`/`REAL` variables take two registers (`D10`–`D11`) |
| `Level := (AX1 * 2000) / 4095;` | always-true rung → `CPT D1 expr "AX1 * 2000 / 4095"` (truncates, like the ST `INT`), or `SCL D1 src "AX1" inMin 0 inMax 4095 outMin 0 outMax 2000` (rounds to the nearest whole number) |
| `Pct := AX1 * 100.0 / 4095;` (`Pct : REAL`) | always-true rung → `CPT D10 expr "AX1 * 100.0 / 4095"` with `"dt":"REAL"` |
| `Total := Total + Level;` | `ADD D22 a "D22" b "D1"` — behind a `P` contact if it should add once per event |
| `IF StartEdge.Q THEN Count := Count + 1; END_IF;` | `P X1 → INC D5` |
| `Diff := A - B;` / `Prod := A * B;` | `SUB D3 a "D1" b "D2"` / `MUL D3 a "D1" b "D2"` |
| `Avg := Total / Count;` | `GRT D26 cmp 0 → DIV D24 a "D22" b "D26"` (guard against 0: ST returns 0 for a division by zero, ladder writes nothing and sets SB10) |
| `Out := LIMIT(0, x, 4095);` | `CPT D12 expr "LIMIT(0, D3, 4095)"` |
| `Y1 := Level > Setpoint;` | `GRT D1 cmp "D2" → OTE Y1` (a compare can test two registers) |
| `IF Level < 200 THEN …` | `LES D1 cmp 200 → …` |
| `Big := Level;` (`Big : DINT`, `Level : INT`) | `MOV D20 src "D1"` with `"st":"INT"`, `"dt":"DINT"` |
| `D[5] := 0;` | `MOV D5 src "0"` |
| `x := D[i];` (`i` kept in D1, `x` in D10) | `MOV D10 src "D[D1]"` — a pointer: D1 holds the register number (3.1.2) |
| `D[i] := x;` | `MOV D[D1] src "D10"` |
| `Sp := D[100 + Recipe];` (`Recipe` in D1) | `ADD D2 a "100" b "D1"`, then `MOV D10 src "D[D2]"` (Section 7.3) |
| `Table : ARRAY[0..2] OF INT;` with `Table[Recipe]` | a block of D registers (D100–D102) plus a pointer register, as in the row above |
| `Bits := …` / testing single bits of a word | `PACK` / `UNPACK` (Section 4.7) |
| Shifting a `BOOL` array one place on each pulse (`IF Pulse.Q THEN FOR i := 8 TO 2 BY -1 DO Trk[i] := Trk[i-1]; END_FOR; Trk[1] := X2; END_IF;`) | `P X1 → BSL C1 len 8 src "X2"` (4.10) |
| `CASE Step OF` with a timer per step, driving outputs from the step | `DRUM` with one step per case (4.10), or one C bit per state (Steps 2–3) |
| `IF NOT Skip THEN … END_IF;` around a block of statements | `XIC Skip → JMP L1` above the block's rungs, `LBL L1` first on the rung after them (4.10) — the jump skips while its rung is true |
| `IF Enable THEN … ELSE (set the same outputs FALSE) END_IF;` | `XIC Enable → MCR`, the rungs, then an `END MCR` rung (4.10) |

Not supported in ladder: loops (`FOR`/`NEXT`), subroutines and user functions (`Call`/`Return`), and `Search`, `End` and message (`Send`/`Receive`) instructions. Keep a program that needs a loop or a function in ST, or unroll a short loop into rungs. From v1.125 an array indexed by a variable **does** have a ladder form: keep the array in consecutive D registers, calculate the register number (base + index) into a pointer register with `ADD` or `CPT`, and use `D[Dn]` (Section 3.1.2). Two differences from ST: the pointer register holds the full register number, not an offset, and an out-of-range pointer sets SB11 and writes nothing, where an out-of-range ST index stops the PLC. `COP` and `FLL` cover the common table cases (copy a block of registers, clear a table).

In the other direction, these ladder instructions have no ST equivalent: `RTO` (ST has no standard retentive timer block), and the v1.126 `BSL`, `BSR`, `DRUM`, `JMP`/`LBL` and `MCR`/`END MCR`. For the v1.126 ones there is no direct ST instruction; write the same behaviour with `IF`/`CASE` logic, as in the rows above: a shift as array assignments under an `R_TRIG`, a drum as `CASE Step OF` with a `TON`, a jump as `IF … END_IF` around the skipped code, and an MCR zone as `IF … ELSE` that sets the zone's `OTE` outputs FALSE. Keep a program that needs `RTO` in ladder.

---

## 6. Complete ladder example — Conveyor Shuttle Control

**Sequence:** Press Start (X1) and the conveyor runs forward until the right sensor (X4), then reverses until the left sensor (X3), then stops. Stop (X2, N.C.) stops everything at any time.

**Bit map:** C1 = Forward, C2 = Reverse, C3 = Start pulse, C4 = Start last scan, C5 = Start request from Idle.

**Ladder:**

```
Rung 0 – Start one-shot
    X1        C4
|----| |-------|/|------------------------------------------(C3)---|

Rung 1 – Start memory
    X1
|----| |----------------------------------------------------(C4)---|

Rung 2 – Start request from Idle
    X2        C3        C1        C2
|----| |-------| |-------|/|-------|/|-----------------------(C5)---|

Rung 3 – Reverse state
    X2        C1        X4
|----| |---+----| |-------| |---+---------------------------(C2)---|
           |    C5        X4    |
           +----| |-------| |---+
           |    C2        X3    |
           +----| |-------|/|---+

Rung 4 – Forward state
    X2        C1        X4        C2
|----| |---+----| |---+----|/|-------|/|--------------------(C1)---|
           |    C5    |
           +----| |---+

Rung 5 – Conveyor run
    C1
|---+----| |---+--------------------------------------------(Y1)---|
    |    C2    |
    +----| |---+

Rung 6 – Reverse direction
    C2
|----| |----------------------------------------------------(Y2)---|
```

**JSON file** (https://accautomation.ca/simulator/acc-example-conveyor-shuttle.json):

```json
{
  "version": 2,
  "name": "Conveyor Shuttle Control",
  "exported": "2026-09-16T00:00:00.000Z",
  "notes": "Conveyor scene. Press Start to travel right to X4, reverse back to X3, then stop. Stop (N.C.) drops everything. Idle = C1 and C2 both OFF.",
  "program": [
    {"id": 1, "rn": 0,
     "comment": "START ONE-SHOT — C3 ON for one scan when X1 goes true (X1 AND NOT C4)",
     "elements": [
       {"id":101,"kind":"contact","type":"XIC","addr":"X1"},
       {"id":102,"kind":"contact","type":"XIO","addr":"C4"},
       {"id":103,"kind":"output","type":"OTE","addr":"C3"}
     ]},
    {"id": 2, "rn": 1,
     "comment": "START MEMORY — C4 follows X1; must be after Rung 0 so the one-shot works",
     "elements": [
       {"id":104,"kind":"contact","type":"XIC","addr":"X1"},
       {"id":105,"kind":"output","type":"OTE","addr":"C4"}
     ]},
    {"id": 3, "rn": 2,
     "comment": "START REQUEST — Stop OK, Start pulse, and Idle (not Forward, not Reverse)",
     "elements": [
       {"id":106,"kind":"contact","type":"XIC","addr":"X2"},
       {"id":107,"kind":"contact","type":"XIC","addr":"C3"},
       {"id":108,"kind":"contact","type":"XIO","addr":"C1"},
       {"id":109,"kind":"contact","type":"XIO","addr":"C2"},
       {"id":110,"kind":"output","type":"OTE","addr":"C5"}
     ]},
    {"id": 4, "rn": 3,
     "comment": "REVERSE STATE — enter at right limit X4 from Forward or Start request; hold until left limit X3; Stop drops it",
     "elements": [
       {"id":111,"kind":"contact","type":"XIC","addr":"X2"},
       {"id":118,"kind":"parallel","type":"XIC","addr":"","branches":[
         [
           {"id":112,"kind":"contact","type":"XIC","addr":"C1"},
           {"id":113,"kind":"contact","type":"XIC","addr":"X4"}
         ],
         [
           {"id":114,"kind":"contact","type":"XIC","addr":"C5"},
           {"id":115,"kind":"contact","type":"XIC","addr":"X4"}
         ],
         [
           {"id":116,"kind":"contact","type":"XIC","addr":"C2"},
           {"id":117,"kind":"contact","type":"XIO","addr":"X3"}
         ]
       ]},
       {"id":119,"kind":"output","type":"OTE","addr":"C2"}
     ]},
    {"id": 5, "rn": 4,
     "comment": "FORWARD STATE — Start request or seal-in; drops at right limit X4, when Reverse is on, or on Stop",
     "elements": [
       {"id":120,"kind":"contact","type":"XIC","addr":"X2"},
       {"id":123,"kind":"parallel","type":"XIC","addr":"","branches":[
         [
           {"id":121,"kind":"contact","type":"XIC","addr":"C1"}
         ],
         [
           {"id":122,"kind":"contact","type":"XIC","addr":"C5"}
         ]
       ]},
       {"id":124,"kind":"contact","type":"XIO","addr":"X4"},
       {"id":125,"kind":"contact","type":"XIO","addr":"C2"},
       {"id":126,"kind":"output","type":"OTE","addr":"C1"}
     ]},
    {"id": 6, "rn": 5,
     "comment": "Y1 CONVEYOR RUN — Forward OR Reverse",
     "elements": [
       {"id":129,"kind":"parallel","type":"XIC","addr":"","branches":[
         [
           {"id":127,"kind":"contact","type":"XIC","addr":"C1"}
         ],
         [
           {"id":128,"kind":"contact","type":"XIC","addr":"C2"}
         ]
       ]},
       {"id":130,"kind":"output","type":"OTE","addr":"Y1"}
     ]},
    {"id": 7, "rn": 6,
     "comment": "Y2 REVERSE — ON only in Reverse state",
     "elements": [
       {"id":131,"kind":"contact","type":"XIC","addr":"C2"},
       {"id":132,"kind":"output","type":"OTE","addr":"Y2"}
     ]}
  ],
  "comments": {
    "X1": "Start PB",
    "X2": "Stop PB N.C.",
    "X3": "Left Sensor",
    "X4": "Right Sensor",
    "Y1": "Conveyor Run",
    "Y2": "Reverse",
    "C1": "Forward State",
    "C2": "Reverse State",
    "C3": "Start Pulse",
    "C4": "Start Last Scan",
    "C5": "Start Request"
  }
}
```

---

## 7. Complete ladder example — Analog Tank Level Control

This example uses the compare, latch, MOV, counter and reset instructions. It is not tied to a scene: test it by dragging the AX1 slider on the AN tab and toggling X2 and X3.

**Sequence:** AX1 is the tank level (0–4095 = 0–100 %). When the level drops below 20 %, the inlet valve opens fully (Y1 on, AY1 = 4095). It closes when the level rises above 85 % or when Stop (X2, N.C.) is pressed. A high-level alarm (Y3) turns on at 95 %. Counter CT1 counts fill cycles; after 5 fills, Service Due (Y4) turns on until the Service Reset button (X3) is pressed.

**Ladder:**

```
Rung 0 – Fill request on
   [LES AX1 < 819]     X2
|-----[ LES ]---------| |---------------------------------(L C101)---|

Rung 1 – Fill request off
   [GRT AX1 > 3481]
|---+---[ GRT ]---+---------------------------------------(U C101)---|
    |      X2     |
    +-----|/|-----+

Rung 2 – Inlet valve
    C101
|----| |----------------------------------------------------(Y1)-----|

Rung 3 – Valve fully open
    C101
|----| |-----------------------------------------[MOV 4095 → AY1]----|

Rung 4 – Valve closed
    C101
|----|/|-----------------------------------------[MOV 0 → AY1]-------|

Rung 5 – High level alarm
   [GEQ AX1 ≥ 3890]
|-----[ GEQ ]-----------------------------------------------(Y3)-----|

Rung 6 – Fill cycle counter
    C101
|----| |-----------------------------------------[CTU CT1 pre 5]-----|

Rung 7 – Service due
    CT1
|----| |----------------------------------------------------(Y4)-----|

Rung 8 – Counter reset
    X3
|----| |-----------------------------------------[RES CT1]-----------|
```

Points to notice: Rung 1 shows a compare inside a parallel branch. Rungs 3 and 4 are both needed because MOV keeps its last value. The counter only counts when C101 turns on, not while it stays on. After a reset, Y4 turns off one scan later, because Rung 7 runs before Rung 8.

**JSON file** (https://accautomation.ca/simulator/acc-example-analog-tank-level.json):

```json
{
  "version": 2,
  "name": "Analog Tank Level Control",
  "exported": "2026-09-16T00:00:00.000Z",
  "notes": "Generic example (not tied to one scene). AX1 = tank level 0-4095 (0-100%). Fill starts below 20% (819) and stops above 85% (3481). AY1 = inlet valve position. Y3 = high-level alarm above 95% (3890). CT1 counts fill cycles; Y4 = service due after 5 fills; X3 resets the count.",
  "program": [
    {"id": 1, "rn": 0,
     "comment": "FILL REQUEST ON — level below 20% (819) and Stop OK",
     "elements": [
       {"id":101,"kind":"compare","type":"LES","addr":"AX1","cmp":819},
       {"id":102,"kind":"contact","type":"XIC","addr":"X2"},
       {"id":103,"kind":"output","type":"OTL","addr":"C101"}
     ]},
    {"id": 2, "rn": 1,
     "comment": "FILL REQUEST OFF — level above 85% (3481) OR Stop pressed (compare inside a branch)",
     "elements": [
       {"id":106,"kind":"parallel","type":"XIC","addr":"","branches":[
         [
           {"id":104,"kind":"compare","type":"GRT","addr":"AX1","cmp":3481}
         ],
         [
           {"id":105,"kind":"contact","type":"XIO","addr":"X2"}
         ]
       ]},
       {"id":107,"kind":"output","type":"OTU","addr":"C101"}
     ]},
    {"id": 3, "rn": 2,
     "comment": "Y1 INLET VALVE — open while filling",
     "elements": [
       {"id":108,"kind":"contact","type":"XIC","addr":"C101"},
       {"id":109,"kind":"output","type":"OTE","addr":"Y1"}
     ]},
    {"id": 4, "rn": 3,
     "comment": "AY1 VALVE FULL OPEN — MOV constant 4095 while filling",
     "elements": [
       {"id":110,"kind":"contact","type":"XIC","addr":"C101"},
       {"id":111,"kind":"block","type":"MOV","addr":"AY1","src":"4095","pre":0}
     ]},
    {"id": 5, "rn": 4,
     "comment": "AY1 VALVE CLOSED — MOV constant 0 when not filling (MOV holds its last value, so both states need a rung)",
     "elements": [
       {"id":112,"kind":"contact","type":"XIO","addr":"C101"},
       {"id":113,"kind":"block","type":"MOV","addr":"AY1","src":"0","pre":0}
     ]},
    {"id": 6, "rn": 5,
     "comment": "Y3 HIGH LEVEL ALARM — level at or above 95% (3890)",
     "elements": [
       {"id":114,"kind":"compare","type":"GEQ","addr":"AX1","cmp":3890},
       {"id":115,"kind":"output","type":"OTE","addr":"Y3"}
     ]},
    {"id": 7, "rn": 6,
     "comment": "FILL CYCLE COUNTER — counts each OFF-to-ON of the fill request",
     "elements": [
       {"id":116,"kind":"contact","type":"XIC","addr":"C101"},
       {"id":117,"kind":"block","type":"CTU","addr":"CT1","pre":5}
     ]},
    {"id": 8, "rn": 7,
     "comment": "Y4 SERVICE DUE — counter done (5 fills)",
     "elements": [
       {"id":118,"kind":"contact","type":"XIC","addr":"CT1"},
       {"id":119,"kind":"output","type":"OTE","addr":"Y4"}
     ]},
    {"id": 9, "rn": 8,
     "comment": "COUNTER RESET — Service Reset PB clears CT1",
     "elements": [
       {"id":120,"kind":"contact","type":"XIC","addr":"X3"},
       {"id":121,"kind":"block","type":"RES","addr":"CT1","pre":0}
     ]}
  ],
  "comments": {
    "X2": "Stop PB N.C.",
    "X3": "Service Reset PB",
    "AX1": "Tank Level 0-4095",
    "AY1": "Inlet Valve Position",
    "Y1": "Inlet Valve Open",
    "Y3": "High Level Alarm",
    "Y4": "Service Due",
    "C101": "Fill Request",
    "CT1": "Fill Cycle Count"
  }
}
```

Both example files were run through the simulator's own import and scan code: the conveyor completes forward → reverse → stop and refuses to start while Stop is pressed, and the tank example fills, closes, alarms, counts to 5 and resets as described. The Structured Text versions in Section 8 were compiled and run on the real `acc-st.js` engine and produce the same output sequences.

### 7.1 Complete ladder example — Parts Buffer and Run-Time Service (v1.123 instructions)

This example uses the instructions added in v1.123: a first-scan bit, an up/down counter, a limit test on a counter value, a retentive timer, a clock bit and a rising-edge contact. It is not tied to a scene. To test it, toggle X1–X4 on the X tab.

**Sequence:** X1 (part in) and X2 (part out) keep a running count of parts in a buffer. Y1 means the buffer is full (10 parts), and Y2 means it holds some parts but is not full. The count starts at zero every time the PLC enters RUN. X3 is a "conveyor running" feedback. The program totals its running time across every stop, and after 10 s of running Y3 flashes at 1 Hz until the service reset X4 is pressed.

**Ladder:**

```
Rung 0 – First scan clears the count
    SB3
|----| |-------------------------------------------------[RES CT1]------|

Rung 1 – Buffer count (up on X1, down on X2)
    X1
|----| |------------------------------------[CTUD CT1 pre 10 cd X2]-----|

Rung 2 – Buffer full
    CT1
|----| |------------------------------------------------------(Y1)-----|

Rung 3 – Parts waiting
   [LIM 1 ≤ CT1/ACC ≤ 9]
|-----[ LIM ]-------------------------------------------------(Y2)-----|

Rung 4 – Run-time total
    X3
|----| |------------------------------------------[RTO T1 pre 10000]---|

Rung 5 – Service due, flashing
    T1        SB6
|----| |-------| |--------------------------------------------(Y3)-----|

Rung 6 – Service reset (one press)
    X4
|----|P|-------------------------------------------------[RES T1]------|
```

Points to notice:
- **Rung 0** relies on SB3 being on for exactly one scan, so the count is cleared once per RUN rather than held at zero.
- **Rung 1** needs no separate rung for X2: the CTUD reads its `cd` bit directly.
- **Rung 3** tests the counter's value with LIM. Two compares in series would do the same job.
- **Rung 4** is retentive: stopping the conveyor, or the PLC, does not lose the accumulated time.
- **Rung 6** acts once per press because of the rising-edge contact.

**JSON file** (https://accautomation.ca/simulator/acc-example-buffer-runtime.json):

```json
{
  "version": 2,
  "name": "Parts Buffer and Run-Time Service",
  "exported": "2026-10-13T00:00:00.000Z",
  "notes": "Generic v1.123 example (not tied to one scene). X1 = part in, X2 = part out, X3 = conveyor running feedback, X4 = service reset PB. CT1 counts parts in the buffer (CTUD). Y1 = buffer full (10), Y2 = buffer has parts but is not full. T1 (RTO) totals conveyor running time; Y3 flashes at 1 Hz once 10 s of running has accumulated, until X4 is pressed.",
  "program": [
    {"id": 1, "rn": 0,
     "comment": "FIRST SCAN — empty the buffer count every time the PLC enters RUN",
     "elements": [
       {"id":101,"kind":"contact","type":"XIC","addr":"SB3"},
       {"id":102,"kind":"block","type":"RES","addr":"CT1","pre":0}
     ]},
    {"id": 2, "rn": 1,
     "comment": "BUFFER COUNT — part in (X1) counts up, part out (X2) counts down, never below 0",
     "elements": [
       {"id":103,"kind":"contact","type":"XIC","addr":"X1"},
       {"id":104,"kind":"block","type":"CTUD","addr":"CT1","pre":10,"cd":"X2"}
     ]},
    {"id": 3, "rn": 2,
     "comment": "Y1 BUFFER FULL — count at or above 10",
     "elements": [
       {"id":105,"kind":"contact","type":"XIC","addr":"CT1"},
       {"id":106,"kind":"output","type":"OTE","addr":"Y1"}
     ]},
    {"id": 4, "rn": 3,
     "comment": "Y2 PARTS WAITING — count between 1 and 9",
     "elements": [
       {"id":107,"kind":"compare","type":"LIM","addr":"CT1/ACC","lo":1,"hi":9,"cmp":0},
       {"id":108,"kind":"output","type":"OTE","addr":"Y2"}
     ]},
    {"id": 5, "rn": 4,
     "comment": "RUN-TIME TOTAL — RTO keeps adding up conveyor running time across every stop",
     "elements": [
       {"id":109,"kind":"contact","type":"XIC","addr":"X3"},
       {"id":110,"kind":"block","type":"RTO","addr":"T1","pre":10000}
     ]},
    {"id": 6, "rn": 5,
     "comment": "Y3 SERVICE DUE — flashes at 1 Hz (SB6) once 10 s of running is reached",
     "elements": [
       {"id":111,"kind":"contact","type":"XIC","addr":"T1"},
       {"id":112,"kind":"contact","type":"XIC","addr":"SB6"},
       {"id":113,"kind":"output","type":"OTE","addr":"Y3"}
     ]},
    {"id": 7, "rn": 6,
     "comment": "SERVICE RESET — one press (rising edge of X4) clears the run-time total",
     "elements": [
       {"id":114,"kind":"contact","type":"P","addr":"X4"},
       {"id":115,"kind":"block","type":"RES","addr":"T1","pre":0}
     ]}
  ],
  "comments": {
    "X1": "Part In",
    "X2": "Part Out",
    "X3": "Conveyor Running",
    "X4": "Service Reset PB",
    "Y1": "Buffer Full",
    "Y2": "Parts Waiting",
    "Y3": "Service Due",
    "CT1": "Buffer Count",
    "CT1/ACC": "Buffer Count",
    "T1": "Run-Time Total"
  }
}
```

This example was imported and run on `acc-plc-simulator.html` v1.123, and imports on v1.124 with no warnings. The count clears on entering RUN, counts up and down, floors at 0, and switches Y1/Y2 at the right counts. The RTO keeps a partial total, reaches DN after 10 s in total, Y3 flashes, and one press of X4 clears it. There is no Structured Text version: ST has no standard retentive timer block (Section 8.3).

### 7.2 Complete ladder example — Batch Tank Totaliser (v1.124 math and data instructions)

This example uses the instructions added in v1.124: scaling with `SCL`, expressions with `CPT` (one `REAL`, one `INT`), a typed compare on a D register, a `MOV` that converts `INT` to `DINT`, `INC` and `ADD` made one-shot by a `P` contact, a guarded `DIV`, `MOV` to an analog output, and error-flag handling. It is not tied to a scene. To test it, drag AX1 on the **AN** tab, toggle X1 and X2 on the **X** tab, and watch the registers on the **D** tab.

**Sequence:** AX1 is a tank level transmitter, 0–4095 = 0–2000 litres. The program keeps the level in litres (D1) and in percent (D10, a `REAL`), turns on a low-level warning Y1 below 200 L, and drives a refill valve AY1 in proportion to the empty space. Each press of Batch Complete (X1) logs one batch: the batch count, the total litres and the average litres per batch. Y3 lights when any math error flag is on, and Fault Reset (X2) clears the flags.

**Register map:** D1 level L (`INT`) · D10–D11 level % (`REAL`) · D12 valve demand (`INT`) · D20–D21 this batch, L (`DINT`) · D22–D23 total L (`DINT`) · D24–D25 average L per batch (`DINT`) · D26–D27 batch count (`DINT`).

**Ladder:**

```
Rung 0 – Level in litres
    SB1
|----| |------------------------------[SCL AX1 0–4095 → 0–2000 → D1 INT]---|

Rung 1 – Level in percent
    SB1
|----| |---------------------------[CPT D10 REAL := AX1 * 100.0 / 4095]----|

Rung 2 – Low level
   [LES D1 < 200 INT]
|-----[ LES ]---------------------------------------------------(Y1)-------|

Rung 3 – Refill valve
    SB1
|----| |--[CPT D12 INT := LIMIT(0,(2000-D1)*4095/2000,4095)]--[MOV D12 → AY1]--|

Rung 4 – Batch log (once per press)
    X1
|----|P|--[INC D26 DINT]--[MOV D1 INT → D20 DINT]--[ADD D22 := D22 + D20 DINT]--|

Rung 5 – Average per batch
   [GRT D26 > 0 DINT]
|-----[ GRT ]---------------------------------[DIV D24 := D22 / D26 DINT]-|

Rung 6 – Math fault lamp
    SB12
|----| |--------------------------------------------------------(Y3)-------|

Rung 7 – Fault reset (once per press)
    X2
|----|P|------(U SB9)----(U SB10)----(U SB11)----[MOV 0 → SW17]-----------|
```

Points to notice:
- **Rungs 0, 1 and 3** run on every scan (`XIC SB1`, always ON), which is what a continuous calculation needs.
- **Rung 1** reads `AX1`, not `D1`. A `REAL` CPT reads every D register it names as a `REAL`, so `D1 * 100.0 / 2000` would read D1 and D2 as one float and give nonsense.
- **Rung 2** is a typed compare: because it reads D1, its constant is checked against `INT`.
- **Rung 3** shows two blocks in series: the CPT runs first, then the MOV copies its result to the analog output. The `INT` CPT truncates at each step and `LIMIT` keeps the result inside 0–4095.
- **Rung 4** acts once per press because of the `P` contact. Without it, holding X1 for one second would log about ten batches. The `MOV` converts the `INT` level into a `DINT` so the `DINT` `ADD` reads it correctly; adding `D1` directly would read D1 and D2 together as one `DINT`.
- **Rung 5** is guarded by `GRT D26 > 0`, so the `DIV` never divides by zero before the first batch (that would set SB10 and SW17 = 2 on every scan).
- **Rungs 6 and 7** handle errors. The flags are sticky: Y3 stays on after a fault until X2 is pressed. SW18 keeps the rung number of the last fault.

**JSON file** (https://accautomation.ca/simulator/acc-example-batch-math.json):

```json
{
  "version": 2,
  "name": "Batch Tank Totaliser",
  "exported": "2026-10-13T00:00:00.000Z",
  "notes": "Generic v1.124 example (not tied to one scene). AX1 = tank level transmitter 0-4095 = 0-2000 L. X1 = Batch Complete PB (N.O.), X2 = Fault Reset PB (N.O.). D1 = level in litres (INT), D10 = level in % (REAL, D10-D11), D12 = refill valve demand (INT) copied to AY1. Each press of X1 logs one batch: D26 = batch count (DINT, D26-D27), D22 = total litres (DINT, D22-D23), D24 = average litres per batch (DINT, D24-D25). Y1 = low level below 200 L. Y3 = math fault lamp (SB12); X2 clears the fault flags and SW17.",
  "program": [
    {"id": 1, "rn": 0,
     "comment": "LEVEL IN LITRES — SCL scales AX1 0-4095 to D1 = 0-2000 L (INT, rounded)",
     "elements": [
       {"id":101,"kind":"contact","type":"XIC","addr":"SB1"},
       {"id":102,"kind":"block","type":"SCL","addr":"D1","src":"AX1","inMin":0,"inMax":4095,"outMin":0,"outMax":2000,"dt":"INT","pre":0}
     ]},
    {"id": 2, "rn": 1,
     "comment": "LEVEL IN PERCENT — CPT as REAL keeps the decimals (D10-D11). Reads AX1, not D1: a REAL CPT would read D1 as a REAL",
     "elements": [
       {"id":103,"kind":"contact","type":"XIC","addr":"SB1"},
       {"id":104,"kind":"block","type":"CPT","addr":"D10","expr":"AX1 * 100.0 / 4095","dt":"REAL","pre":0}
     ]},
    {"id": 3, "rn": 2,
     "comment": "Y1 LOW LEVEL — typed compare on a D register: D1 below 200 L",
     "elements": [
       {"id":105,"kind":"compare","type":"LES","addr":"D1","cmp":200,"dt":"INT"},
       {"id":106,"kind":"output","type":"OTE","addr":"Y1"}
     ]},
    {"id": 4, "rn": 3,
     "comment": "REFILL VALVE — CPT works out the demand from the empty space (0-4095), then MOV copies it to AY1",
     "elements": [
       {"id":107,"kind":"contact","type":"XIC","addr":"SB1"},
       {"id":108,"kind":"block","type":"CPT","addr":"D12","expr":"LIMIT(0, (2000 - D1) * 4095 / 2000, 4095)","dt":"INT","pre":0},
       {"id":109,"kind":"block","type":"MOV","addr":"AY1","src":"D12","st":"INT","pre":0}
     ]},
    {"id": 5, "rn": 4,
     "comment": "BATCH LOG — once per press of X1 (P contact): count the batch, convert the level to DINT, add it to the total",
     "elements": [
       {"id":110,"kind":"contact","type":"P","addr":"X1"},
       {"id":111,"kind":"block","type":"INC","addr":"D26","dt":"DINT","pre":0},
       {"id":112,"kind":"block","type":"MOV","addr":"D20","src":"D1","st":"INT","dt":"DINT","pre":0},
       {"id":113,"kind":"block","type":"ADD","addr":"D22","a":"D22","b":"D20","dt":"DINT","pre":0}
     ]},
    {"id": 6, "rn": 5,
     "comment": "AVERAGE PER BATCH — only when at least one batch is logged, so DIV never divides by zero",
     "elements": [
       {"id":114,"kind":"compare","type":"GRT","addr":"D26","cmp":0,"dt":"DINT"},
       {"id":115,"kind":"block","type":"DIV","addr":"D24","a":"D22","b":"D26","dt":"DINT","pre":0}
     ]},
    {"id": 7, "rn": 6,
     "comment": "Y3 MATH FAULT — SB12 is on while any error flag (SB9 overflow, SB10 divide/invalid, SB11 range) is set",
     "elements": [
       {"id":116,"kind":"contact","type":"XIC","addr":"SB12"},
       {"id":117,"kind":"output","type":"OTE","addr":"Y3"}
     ]},
    {"id": 8, "rn": 7,
     "comment": "FAULT RESET — one press of X2 clears the sticky flags and the error code",
     "elements": [
       {"id":118,"kind":"contact","type":"P","addr":"X2"},
       {"id":119,"kind":"output","type":"OTU","addr":"SB9"},
       {"id":120,"kind":"output","type":"OTU","addr":"SB10"},
       {"id":121,"kind":"output","type":"OTU","addr":"SB11"},
       {"id":122,"kind":"block","type":"MOV","addr":"SW17","src":"0","pre":0}
     ]}
  ],
  "comments": {
    "X1": "Batch Complete PB",
    "X2": "Fault Reset PB",
    "AX1": "Tank Level 0-4095",
    "AY1": "Refill Valve Demand",
    "Y1": "Low Level",
    "Y3": "Math Fault",
    "D1": "Level L",
    "D10": "Level % (REAL)",
    "D12": "Valve Demand",
    "D20": "Batch Litres (DINT)",
    "D22": "Total Litres (DINT)",
    "D24": "Average L/Batch (DINT)",
    "D26": "Batch Count (DINT)"
  },
  "dregs": {},
  "dfmt": {}
}
```

This example was imported and run on `acc-plc-simulator.html` v1.124 with no import warnings and no page errors. Results, each after a STEP:

| AX1 | D1 (L) | D10 (%) | D12 = AY1 | Y1 |
|---|---|---|---|---|
| 4095 | 2000 | 100 | 0 | OFF |
| 1024 | 500 | 25.0061 | 3071 | OFF |
| 300 | 147 (146.5 rounded) | 7.326 | 3794 | ON |

Pressing X1 once at each of those three levels, in that order, gives D26 = 1, 2, 3; D22 = 2000, 2500, 2647; D24 = 2000, 1250, 882 (2647 ÷ 3, truncated). Holding X1 for several scans logs only one batch. To see the fault handling, stop the PLC, type 2147483647 into D26 on the D tab (it shows in `DINT` format) and press X1 again: the `INC` wraps D26 to −2147483648, and SB9, SB12 and Y3 turn on with SW17 = 1 and SW18 = 4 (Rung 0004). Because D26 is now negative, Rung 5 stops updating the average. A press of X2 clears SB9, SB12 and SW17 on that scan, Y3 goes off on the next scan, and SW18 still reads 4.

There is no Structured Text version: ST reads and writes D registers only as `INT` (Section 8.2), so an ST program would keep the `DINT` and `REAL` values in its own declared variables instead of D10–D27.

### 7.3 Complete ladder example — Recipe Select with Pointers (v1.125 indirect addressing)

This example uses the pointer operand added in v1.125 (Section 3.1.2): a recipe number chosen by push buttons, a pointer calculated with `ADD` (base + recipe), `MOV` through the pointer into working registers, a typed compare against the analog input, and the fault lamp that shows a pointer out of range. It also shows both ways to give a table its starting values: an `XIC SB3` first-scan rung, and `dregs`. It is not tied to a scene. To test it, toggle X1–X4 on the **X** tab, drag AX1 on the **AN** tab, and watch the registers on the **D** tab.

**Sequence:** Three recipes, A, B and C, each have a setpoint and an output demand. Recipe A, B or C (X1, X2, X3) selects recipe number 0, 1 or 2. The program fetches that recipe's setpoint and demand into working registers. While the process value AX1 is below the setpoint, the demand goes to AY1; at or above the setpoint, Y1 turns on and AY1 goes to 0. Y8 lights when any math error flag is on, and Fault Reset (X4) clears the flags.

**Register map:** D1 recipe number 0–2 · D2 setpoint pointer (100 + D1) · D3 demand pointer (110 + D1) · D10 working setpoint · D11 working demand · D100–D102 setpoint table (loaded on the first scan) · D110–D112 demand table (from `dregs`). Every register is `INT`.

| Recipe | D1 | Setpoint (D100 + D1) | Demand (D110 + D1) |
|---|---|---|---|
| A (X1) | 0 | D100 = 1000 | D110 = 1500 |
| B (X2) | 1 | D101 = 2000 | D111 = 2500 |
| C (X3) | 2 | D102 = 3000 | D112 = 4095 |

**Ladder:**

```
Rung 0 – Load setpoint table (first scan)
    SB3
|----| |--[MOV 1000 → D100]--[MOV 2000 → D101]--[MOV 3000 → D102]---------|

Rung 1 – Recipe A          Rung 2 – Recipe B          Rung 3 – Recipe C
    X1                         X2                         X3
|----|P|--[MOV 0 → D1]--|  |----|P|--[MOV 1 → D1]--|  |----|P|--[MOV 2 → D1]--|

Rung 4 – Fetch recipe through pointers
    SB1
|----| |--[ADD D2 := 100 + D1]--[ADD D3 := 110 + D1]--[MOV D[D2] → D10]--[MOV D[D3] → D11]--|

Rung 5 – At setpoint
   [GEQ AX1 >= D10 INT]
|-----[ GEQ ]---------------------------------------------------(Y1)-------|

Rung 6 – Demand while below setpoint
    Y1
|----|/|-----------------------------------------------[MOV D11 → AY1]-----|

Rung 7 – No demand at setpoint
    Y1
|----| |-----------------------------------------------[MOV 0 → AY1]-------|

Rung 8 – Math fault lamp
    SB12
|----| |--------------------------------------------------------(Y8)-------|

Rung 9 – Fault reset (once per press)
    X4
|----|P|------(U SB9)----(U SB10)----(U SB11)----[MOV 0 → SW17]-----------|
```

Points to notice:
- **Rung 4** is the base + index pattern. The pointer registers D2 and D3 hold register **numbers** (100–102 and 110–112), not table values and not offsets. They are calculated on the same rung, just before the `MOV`s that use them, so the fetch always uses the recipe selected this scan.
- **One rung serves every recipe.** Without pointers, each recipe would need its own pair of `MOV` rungs. Adding a fourth recipe needs only a fourth table entry and a fourth select rung.
- **Rung 5** is a typed compare: it reads D10, so its `dt` (`INT`) applies. `GEQ AX1 cmp "D[D2]"` would give the same result without the working copy; the copy makes the selected setpoint easy to see on the D tab.
- **Rungs 1–3** use `P` contacts for a clean once-per-press selection. A `MOV` of a constant writes the same value on every scan, so holding a button changes nothing more.
- **Rungs 0 and the `dregs` entries** show the two ways to load a table. The first-scan rung reloads D100–D102 every time the PLC enters RUN, so values typed on the D tab do not survive; the `dregs` values (D110–D112) load with the file and can be changed on the D tab and exported. Use one method per table.
- **Rungs 8 and 9** catch a bad pointer. If D1 ever held a number outside the table, the fetch would point at the wrong registers — and past D4000 it writes nothing and sets SB11 (Section 3.6). In a real program, put `LIM D1 lo 0 hi 2` in front of the fetch so only valid recipe numbers are used.

**JSON file** (https://accautomation.ca/simulator/acc-example-recipe-select.json):

```json
{
  "version": 2,
  "name": "Recipe Select with Pointers",
  "exported": "2026-10-14T00:00:00.000Z",
  "notes": "Generic v1.125 example (not tied to one scene). X1/X2/X3 = Recipe A/B/C select PBs (N.O.), X4 = Fault Reset PB (N.O.). AX1 = process value 0-4095. D1 = recipe number 0-2 (INT). Setpoint table D100-D102 is loaded on the first scan; demand table D110-D112 starts from dregs. D2 = pointer to the setpoint (100 + D1), D3 = pointer to the demand (110 + D1). D10 = working setpoint, D11 = working demand. Y1 = at setpoint (AX1 >= D10). AY1 = demand while below setpoint, 0 at setpoint. Y8 = math fault lamp (SB12); X4 clears the fault flags and SW17.",
  "program": [
    {"id": 1, "rn": 0,
     "comment": "LOAD SETPOINT TABLE — first scan only: recipe A, B, C setpoints into D100-D102",
     "elements": [
       {"id":101,"kind":"contact","type":"XIC","addr":"SB3"},
       {"id":102,"kind":"block","type":"MOV","addr":"D100","src":"1000","dt":"INT","pre":0},
       {"id":103,"kind":"block","type":"MOV","addr":"D101","src":"2000","dt":"INT","pre":0},
       {"id":104,"kind":"block","type":"MOV","addr":"D102","src":"3000","dt":"INT","pre":0}
     ]},
    {"id": 2, "rn": 1,
     "comment": "SELECT RECIPE A — one press of X1 sets recipe number 0",
     "elements": [
       {"id":105,"kind":"contact","type":"P","addr":"X1"},
       {"id":106,"kind":"block","type":"MOV","addr":"D1","src":"0","dt":"INT","pre":0}
     ]},
    {"id": 3, "rn": 2,
     "comment": "SELECT RECIPE B — one press of X2 sets recipe number 1",
     "elements": [
       {"id":107,"kind":"contact","type":"P","addr":"X2"},
       {"id":108,"kind":"block","type":"MOV","addr":"D1","src":"1","dt":"INT","pre":0}
     ]},
    {"id": 4, "rn": 3,
     "comment": "SELECT RECIPE C — one press of X3 sets recipe number 2",
     "elements": [
       {"id":109,"kind":"contact","type":"P","addr":"X3"},
       {"id":110,"kind":"block","type":"MOV","addr":"D1","src":"2","dt":"INT","pre":0}
     ]},
    {"id": 5, "rn": 4,
     "comment": "FETCH RECIPE — pointers D2 = 100 + recipe and D3 = 110 + recipe, then MOV through them into the working registers",
     "elements": [
       {"id":111,"kind":"contact","type":"XIC","addr":"SB1"},
       {"id":112,"kind":"block","type":"ADD","addr":"D2","a":"100","b":"D1","dt":"INT","pre":0},
       {"id":113,"kind":"block","type":"ADD","addr":"D3","a":"110","b":"D1","dt":"INT","pre":0},
       {"id":114,"kind":"block","type":"MOV","addr":"D10","src":"D[D2]","st":"INT","dt":"INT","pre":0},
       {"id":115,"kind":"block","type":"MOV","addr":"D11","src":"D[D3]","st":"INT","dt":"INT","pre":0}
     ]},
    {"id": 6, "rn": 5,
     "comment": "Y1 AT SETPOINT — typed compare: AX1 at or above the working setpoint D10",
     "elements": [
       {"id":116,"kind":"compare","type":"GEQ","addr":"AX1","cmp":"D10","dt":"INT"},
       {"id":117,"kind":"output","type":"OTE","addr":"Y1"}
     ]},
    {"id": 7, "rn": 6,
     "comment": "DEMAND — below setpoint, AY1 gets the recipe's demand D11",
     "elements": [
       {"id":118,"kind":"contact","type":"XIO","addr":"Y1"},
       {"id":119,"kind":"block","type":"MOV","addr":"AY1","src":"D11","st":"INT","pre":0}
     ]},
    {"id": 8, "rn": 7,
     "comment": "DEMAND OFF — at setpoint, AY1 = 0",
     "elements": [
       {"id":120,"kind":"contact","type":"XIC","addr":"Y1"},
       {"id":121,"kind":"block","type":"MOV","addr":"AY1","src":"0","pre":0}
     ]},
    {"id": 9, "rn": 8,
     "comment": "Y8 MATH FAULT — SB12 is on while any error flag is set (a pointer outside D1-D4000 sets SB11)",
     "elements": [
       {"id":122,"kind":"contact","type":"XIC","addr":"SB12"},
       {"id":123,"kind":"output","type":"OTE","addr":"Y8"}
     ]},
    {"id": 10, "rn": 9,
     "comment": "FAULT RESET — one press of X4 clears the sticky flags and the error code",
     "elements": [
       {"id":124,"kind":"contact","type":"P","addr":"X4"},
       {"id":125,"kind":"output","type":"OTU","addr":"SB9"},
       {"id":126,"kind":"output","type":"OTU","addr":"SB10"},
       {"id":127,"kind":"output","type":"OTU","addr":"SB11"},
       {"id":128,"kind":"block","type":"MOV","addr":"SW17","src":"0","pre":0}
     ]}
  ],
  "comments": {
    "X1": "Recipe A PB",
    "X2": "Recipe B PB",
    "X3": "Recipe C PB",
    "X4": "Fault Reset PB",
    "AX1": "Process Value 0-4095",
    "AY1": "Demand Output",
    "Y1": "At Setpoint",
    "Y8": "Math Fault",
    "D1": "Recipe Number 0-2",
    "D2": "Setpoint Pointer",
    "D3": "Demand Pointer",
    "D10": "Working Setpoint",
    "D11": "Working Demand",
    "D100": "Setpoint Recipe A",
    "D101": "Setpoint Recipe B",
    "D102": "Setpoint Recipe C",
    "D110": "Demand Recipe A",
    "D111": "Demand Recipe B",
    "D112": "Demand Recipe C"
  },
  "dregs": {"D110": 1500, "D111": 2500, "D112": 4095},
  "dfmt": {}
}
```

This example was imported and run on `acc-plc-simulator.html` v1.125 with no import warnings and no page errors. Results, each after a STEP:

| Step | D1 | D2 / D3 | D10 | D11 | Y1 | AY1 |
|---|---|---|---|---|---|---|
| First STEP after import, AX1 = 0 | 0 | 100 / 110 | 1000 | 1500 | OFF | 1500 |
| AX1 = 1200 | 0 | 100 / 110 | 1000 | 1500 | ON | 0 |
| Press X2 (recipe B) | 1 | 101 / 111 | 2000 | 2500 | OFF | 2500 |
| Press X3 (recipe C) | 2 | 102 / 112 | 3000 | 4095 | OFF | 4095 |
| AX1 = 3000 | 2 | 102 / 112 | 3000 | 4095 | ON | 0 |
| AX1 = 2999 | 2 | 102 / 112 | 3000 | 4095 | OFF | 4095 |

The first STEP also loads D100–D102 = 1000, 2000, 3000, and the MOV blocks show `D[D2]→D100` and `D[D3]→D110` (then `→D101`, `→D102` as the recipe changes). Holding X2 for several scans selects recipe B once and leaves D1 = 1.

To see the fault handling, set AX1 to 3000, stop the PLC, type 3950 into D1 on the D tab and press STEP. The `ADD`s make D2 = 4050 and D3 = 4060, past D4000: both MOV blocks show `D[D2]→?` and `D[D3]→?`, D10 stays 3000 and D11 stays 4095 (nothing is written), and SB11, SB12 and Y8 turn on with SW17 = 4 and SW18 = 4 (Rung 0004). A press of X1 puts D1 back to 0 and the fetch works again (D10 = 1000, D11 = 1500), but Y8 stays on — the flags are sticky. A press of X4 clears SB11, SB12 and SW17 on that scan, Y8 goes off on the next scan, and SW18 still reads 4.

The Structured Text equivalent of the fetch is `D[10] := D[100 + D[1]]; D[11] := D[110 + D[1]];` (Section 8.2). There is no separate `.st` file: in ST, an index outside 1–4000 stops the PLC instead of setting SB11.

### 7.4 Complete ladder example — Bottle Reject Tracking (v1.126 bit shift register)

This example uses `BSL` (Section 4.10) to carry an inspection result along a conveyor to a reject station, with the unload bit catching a bad bottle that was never rejected. It uses X, Y and C addresses only and is not tied to a scene. To test it, toggle X1–X4 on the **X** tab and watch C1–C9 and Y1–Y2.

**Sequence:** Bottles pass an inspection sensor (X2, ON = bad) and then eight bottle positions of conveyor. The infeed photo-eye X1 turns on once per bottle; each time, the register moves one position and the inspection result enters position 1. Position 6 is the reject station: a bad-bottle bit there fires the reject solenoid Y1. The reject confirm eye X4 sees the bad bottle leave the line and clears its bit. A bad-bottle bit that reaches the end of the register was not rejected, so it latches the missed-reject alarm Y2. Reset (X3) clears the register and the alarm.

**Bit map:** C1–C8 tracking register (C1 = the bottle just inspected, C6 = reject station) · C9 unload bit (the bit leaving C8).

**Ladder:**

```
Rung 0 – Tracking shift (once per bottle)
    X1
|----|P|----------------------[BSL C1 len 8, data X2, unload C9]-----------|

Rung 1 – Reject
    C6
|----| |--------------------------------------------------------(Y1)-------|

Rung 2 – Reject confirmed
    C6        X4
|----| |-------| |----------------------------------------------(U C6)-----|

Rung 3 – Missed reject
    C9
|----| |--------------------------------------------------------(L Y2)-----|

Rung 4 – Reset
    X3
|----| |----(U C1)--(U C2)-- … --(U C8)--(U C9)--(U Y2)-------------------|
```

Points to notice:
- **Rung 0** shifts once per bottle. The `P` contact and the BSL's own rising-edge detection both make holding X1 shift only once.
- **Rung 1** reads one position of the register. Any position can be tested the same way; the register bits are ordinary C bits.
- **Rung 2** removes the bad bottle from tracking once the reject is confirmed, so its bit never reaches the unload bit. Removing a bit is an `OTU` — never an `OTE` on a register bit, which would rewrite it every scan.
- **Rung 3** uses the unload bit: C9 holds the bit that left C8 on the last shift, so a 1 there is a bad bottle that left the tracked zone. The alarm is latched because C9 changes again on the next shift.
- **Rung 4** empties the register with one `OTU` per bit. STOP also clears C bits, so tracking restarts empty after STOP → RUN.

**JSON file** (https://accautomation.ca/simulator/acc-example-bottle-tracking.json):

```json
{
  "version": 2,
  "name": "Bottle Reject Tracking with BSL",
  "exported": "2026-10-14T00:00:00.000Z",
  "notes": "Generic v1.126 example (not tied to one scene). A conveyor carries bottles from an inspection sensor through eight tracked positions; the reject station is at position 6. X1 = infeed photo-eye, ON once per bottle (the shift pulse). X2 = inspection reject sensor, ON = bad bottle. X3 = Reset PB (N.O.). X4 = reject confirm photo-eye at the reject station. C1-C8 = BSL tracking register, one bit per bottle position (C1 = the bottle just inspected). C9 = unload bit: the bit leaving position 8. Y1 = reject solenoid (on while a bad-bottle bit is at position 6). Y2 = missed-reject alarm (latched when a bad-bottle bit leaves the tracked zone).",
  "program": [
    {"id": 1, "rn": 0,
     "comment": "TRACKING SHIFT — once per bottle (P X1) the register moves one position: the inspection result X2 enters C1, every bit moves up, the bit leaving C8 goes to C9",
     "elements": [
       {"id":101,"kind":"contact","type":"P","addr":"X1"},
       {"id":102,"kind":"block","type":"BSL","addr":"C1","len":8,"src":"X2","ul":"C9","pre":0}
     ]},
    {"id": 2, "rn": 1,
     "comment": "REJECT — a bad-bottle bit at position 6 (C6) fires the reject solenoid Y1",
     "elements": [
       {"id":103,"kind":"contact","type":"XIC","addr":"C6"},
       {"id":104,"kind":"output","type":"OTE","addr":"Y1"}
     ]},
    {"id": 3, "rn": 2,
     "comment": "REJECT CONFIRMED — the confirm eye X4 sees the bad bottle leave the line: clear its tracking bit",
     "elements": [
       {"id":105,"kind":"contact","type":"XIC","addr":"C6"},
       {"id":106,"kind":"contact","type":"XIC","addr":"X4"},
       {"id":107,"kind":"output","type":"OTU","addr":"C6"}
     ]},
    {"id": 4, "rn": 3,
     "comment": "MISSED REJECT — a bad-bottle bit shifted out of the register (C9) was never rejected: latch alarm Y2",
     "elements": [
       {"id":108,"kind":"contact","type":"XIC","addr":"C9"},
       {"id":109,"kind":"output","type":"OTL","addr":"Y2"}
     ]},
    {"id": 5, "rn": 4,
     "comment": "RESET — X3 clears every tracking bit, the unload bit and the alarm",
     "elements": [
       {"id":110,"kind":"contact","type":"XIC","addr":"X3"},
       {"id":111,"kind":"output","type":"OTU","addr":"C1"},
       {"id":112,"kind":"output","type":"OTU","addr":"C2"},
       {"id":113,"kind":"output","type":"OTU","addr":"C3"},
       {"id":114,"kind":"output","type":"OTU","addr":"C4"},
       {"id":115,"kind":"output","type":"OTU","addr":"C5"},
       {"id":116,"kind":"output","type":"OTU","addr":"C6"},
       {"id":117,"kind":"output","type":"OTU","addr":"C7"},
       {"id":118,"kind":"output","type":"OTU","addr":"C8"},
       {"id":119,"kind":"output","type":"OTU","addr":"C9"},
       {"id":120,"kind":"output","type":"OTU","addr":"Y2"}
     ]}
  ],
  "comments": {
    "X1": "Infeed Photo-eye (shift)",
    "X2": "Inspection Reject Sensor",
    "X3": "Reset PB",
    "X4": "Reject Confirm Eye",
    "Y1": "Reject Solenoid",
    "Y2": "Missed Reject Alarm",
    "C1": "Track Pos 1 (inspected)",
    "C2": "Track Pos 2",
    "C3": "Track Pos 3",
    "C4": "Track Pos 4",
    "C5": "Track Pos 5",
    "C6": "Track Pos 6 (reject station)",
    "C7": "Track Pos 7",
    "C8": "Track Pos 8",
    "C9": "Bit Leaving Tracking"
  },
  "dregs": {},
  "dfmt": {}
}
```

This example was imported and run on `acc-plc-simulator.html` v1.126 with no import warnings and no page errors. A bad bottle (X2 ON during one X1 pulse) followed by good bottles sets C1, then moves one position per pulse; holding X1 ON for several scans shifts once. At the sixth pulse the bit is at C6 and Y1 turns on; X4 then clears C6 and Y1 turns off, and nothing reaches C9. A second bad bottle with no X4 confirm fires Y1 at C6, moves on to C8, and on the next pulse leaves into C9: Y2 latches and stays on after C9 drops on the following pulse. X3 clears C1–C9 and Y2.

### 7.5 Complete ladder example — Traffic Light Drum (v1.126 drum sequencer)

This example drives a two-way traffic light from one `DRUM` (Section 4.10). Y1–Y6 are the Traffic Light Intersection scene's outputs (Section 3.4), so it can run that scene; the run switch X3 and reset X4 are toggled on the **X** tab. Watch D1 (step) and D2 (cycles) on the **D** tab.

**Sequence:** While Run (X3) is ON the lights cycle: NS green 5 s, NS yellow 2 s, all red 1 s, EW green 5 s, EW yellow 2 s, all red 1 s (16 s per cycle). With X3 OFF the sequence pauses and the lights hold. Reset (X4) returns to step 1 and clears the cycle count; the lights show NS green once X3 is ON. Each completed cycle adds 1 to D2.

**Step table:** outputs Y1 NS green, Y2 NS yellow, Y3 NS red, Y4 EW green, Y5 EW yellow, Y6 EW red (pattern bit 0 = Y1 … bit 5 = Y6).

| Step | Lights ON | `p` (binary Y6…Y1) | `t` (ms) |
|---|---|---|---|
| 1 | NS green, EW red | 33 (100001) | 5000 |
| 2 | NS yellow, EW red | 34 (100010) | 2000 |
| 3 | NS red, EW red | 36 (100100) | 1000 |
| 4 | EW green, NS red | 12 (001100) | 5000 |
| 5 | EW yellow, NS red | 20 (010100) | 2000 |
| 6 | NS red, EW red | 36 (100100) | 1000 |

**Ladder:**

```
Rung 0 – Traffic sequence
    X3
|----| |-----[DRUM D1: out Y1 ×6, 6 timed steps, reset X4, done C1]------|

Rung 1 – Cycle count (once per cycle)
    C1
|----|P|----------------------------------------------[INC D2 INT]-------|

Rung 2 – Reset count
    X4
|----| |-------------------------------------------[MOV 0 → D2 INT]------|
```

Points to notice:
- **One block replaces a state machine.** Without the drum this needs six step bits, six timers and an output rung per light.
- **Rung 0**'s condition is the run enable: with X3 OFF the drum holds its step and step time, and the lights stay as they are. To blank the lights instead, use a separate output stage rather than an `OTE` on Y1–Y6 (the drum owns those bits).
- **The reset bit** works with the rung true or false, and holds step 1 while it is ON.
- **Rung 1** counts with the done bit, which is ON for the one scan in which the drum wraps from step 6 to step 1.
- No `dregs` are needed: D1 starts at 0, which the drum treats as step 1 and corrects.

**JSON file** (https://accautomation.ca/simulator/acc-example-traffic-drum.json):

```json
{
  "version": 2,
  "name": "Traffic Light Drum Sequencer",
  "exported": "2026-10-14T00:00:00.000Z",
  "notes": "v1.126 example for the Traffic Light Intersection scene (Y1-Y6 as that scene uses them). X3 = Run enable switch (maintained, ON = run). X4 = Reset PB (N.O.). One DRUM drives all six lights: D1 = step register (1-6), Y1 NS green, Y2 NS yellow, Y3 NS red, Y4 EW green, Y5 EW yellow, Y6 EW red. Steps: 1 NS green 5 s, 2 NS yellow 2 s, 3 all red 1 s, 4 EW green 5 s, 5 EW yellow 2 s, 6 all red 1 s (16 s cycle). With X3 OFF the drum pauses and the lights hold. X4 returns the drum to step 1 and clears the cycle count. C1 = done bit, ON for one scan each time step 6 ends; D2 = completed cycles (INT).",
  "program": [
    {"id": 1, "rn": 0,
     "comment": "TRAFFIC SEQUENCE — while X3 is ON the drum steps through six timed patterns on Y1-Y6; X4 resets it to step 1; C1 pulses once per cycle",
     "elements": [
       {"id":101,"kind":"contact","type":"XIC","addr":"X3"},
       {"id":102,"kind":"block","type":"DRUM","addr":"D1","out":"Y1","outs":6,"rst":"X4","dn":"C1","pre":0,
        "steps":[
          {"p":33,"t":5000,"ev":""},
          {"p":34,"t":2000,"ev":""},
          {"p":36,"t":1000,"ev":""},
          {"p":12,"t":5000,"ev":""},
          {"p":20,"t":2000,"ev":""},
          {"p":36,"t":1000,"ev":""}
        ]}
     ]},
    {"id": 2, "rn": 1,
     "comment": "CYCLE COUNT — once per completed cycle (P on the done bit C1) add 1 to D2",
     "elements": [
       {"id":103,"kind":"contact","type":"P","addr":"C1"},
       {"id":104,"kind":"block","type":"INC","addr":"D2","dt":"INT","pre":0}
     ]},
    {"id": 3, "rn": 2,
     "comment": "RESET COUNT — X4 clears the cycle count",
     "elements": [
       {"id":105,"kind":"contact","type":"XIC","addr":"X4"},
       {"id":106,"kind":"block","type":"MOV","addr":"D2","src":"0","dt":"INT","pre":0}
     ]}
  ],
  "comments": {
    "X3": "Run Enable Switch",
    "X4": "Reset PB",
    "Y1": "NS Green",
    "Y2": "NS Yellow",
    "Y3": "NS Red",
    "Y4": "EW Green",
    "Y5": "EW Yellow",
    "Y6": "EW Red",
    "C1": "Drum Cycle Done",
    "D1": "Drum Step",
    "D2": "Cycle Count"
  },
  "dregs": {},
  "dfmt": {}
}
```

This example was imported and run on `acc-plc-simulator.html` v1.126 with no import warnings and no page errors, scanning every 100 ms with X3 ON from the first scan. D1 = 1 with Y1 and Y6 on; D1 = 2 (NS yellow) at 5.0 s, 3 (all red) at 7.0 s, 4 (EW green) at 8.0 s, 5 (EW yellow) at 13.0 s, 6 (all red) at 15.0 s, and back to 1 at 16.0 s, with C1 on for that one scan and D2 = 1; after the second cycle D2 = 2. Turning X3 off 3 s into step 1 holds D1 = 1 and the lights; after X3 is turned back on, step 2 starts 2 s later. With X3 ON, X4 sets D1 = 1, NS green and D2 = 0 at once and holds step 1 while it is ON; with X3 OFF it sets D1 = 1 and D2 = 0 and the lights hold until X3 is turned on.

---

## 8. Structured Text (.st) files

### 8.1 Format

A `.st` file is plain UTF-8 text containing the program exactly as it would appear in the simulator's ST editor. There is no JSON wrapper, no header, and no special encoding.

### 8.2 Rules

- **Do not declare I/O addresses.** X1–X16, Y1–Y16, C1–C256, AX1–AX8, AY1–AY4, T1–T256, CT1–CT256, SB1–SB18, SW1–SW19 and the data registers `D[1]`–`D[4000]` are built in. Use them directly. Declaring an X/Y/C/AX/AY/T/CT address anyway (`VAR X1 : BOOL; END_VAR`) raises no error: the declaration is silently ignored, the real input still wins, and a phantom entry appears in the variables watch — which makes the program hard to debug. Declaring a variable named like a system address (`SW1`, `SB3`) is a compile error.
- **Declare your own variables** in one or more `VAR … END_VAR` blocks at the top.
- **Assignment is `:=`.** A single `=` is a comparison. The editor flags `=` used as assignment.
- **Every statement ends with `;`**, including `END_IF;`, `END_CASE;`, `END_FOR;` and `END_WHILE;`.
- **The whole program runs every scan.** Never use a `WHILE` loop to wait for something. Use a timer function block. All loops share a per-scan iteration budget; exceeding it stops the program with "Execution budget exceeded — possible infinite loop (check WHILE/REPEAT/FOR)".
- **STOP resets ST state.** Unlike ladder timers and counters, ST variables and function-block instances are reset when the PLC goes to STOP, and variables declared with `:= value` start from that value again. One consequence to watch: if an input is still on when RUN resumes, an edge block (`R_TRIG`, or a `CTU` counting an input) sees a fresh rising edge on the first scan and fires once.
- Comments use `(* … *)`, `/* … */` or `//`.
- Names are not case-sensitive.
- `T1` and `CT1` are read-only done bits owned by the ladder timer table. Assigning to one is refused at compile time: "Cannot assign to timer/counter bit T1 directly — use a TON/CTU function block". Write the bare name only — `T1/DN` is a syntax error in ST. ST timing and counting use IEC function blocks instead.
- ST can write to `X` addresses, exactly like a ladder coil, and with the same caveat: a connected scene overwrites every X each scan.
- **System bits and words (Section 3.6) are read-only in ST too.** Read them freely, for example `IF SB3 THEN count := 0; END_IF;` or `Y1 := (SW5 >= 7) AND (SW5 < 18);`. Assigning to one is a compile error, in the main program and inside your own `FUNCTION` and `FUNCTION_BLOCK` bodies (from `acc-st.js` v1.017; on v1.016 a write inside a function block was only caught at run time, where it stopped the PLC). The exceptions are `SB9`, `SB10` and `SB11 := FALSE` and `SW17 := 0`, which clear an error; any other constant on those is also a compile error. Addresses above SB18 or SW19 are compile errors.
- A `FOR` loop variable must be your own variable, not an I/O or system address.
- **Data registers are written `D[n]` in ST** (from `acc-st.js` v1.018), with `n` from 1 to 4000: `D[10] := D[10] + 1;`, `Y1 := D[1] < 200;`, or with a computed index, `FOR i := 1 TO 10 DO D[100 + i] := 0; END_FOR;`. A computed index is the ST form of a ladder pointer: ladder `D[D5]` is `D[D[5]]` in ST (Section 3.1.2). ST always reads and writes them as **`INT`**: a value is rounded half away from zero (2.5 → 3) and wraps silently outside −32,768 … 32,767 — no error flag is set. To share a `DINT` or `REAL` with ladder, keep it in ST variables, or split it into whole-number `INT` parts yourself. The ladder form `D10` (no brackets) is an undeclared identifier in ST, and a bare `D` is a compile error.
- A constant index outside 1–4000 (`D[0]`, `D[4001]`) or with decimals (`D[1.5]`) is a compile error. A computed index is rounded, and one outside 1–4000 is a run-time error that **stops the PLC**.
- D registers belong to the simulator, not to the ST program, so they keep their values when ST goes to STOP, and through ST CLEAR, ST load and `.st` import (Section 3.1.1), unlike ST variables.
- A variable you declare named `D` takes precedence over the register table; a function-block instance named `D` makes `D[n]` a compile error. In the main program it hides `D[n]` everywhere; inside a `FUNCTION` or `FUNCTION_BLOCK` it hides the table only within that function or block. Avoid the name `D`.
- Operator precedence, from loosest to tightest: `OR`, `XOR`, `AND`, `=` `<>`, `<` `>` `<=` `>=`, `+` `-`, `*` `/` `MOD`, `**`. Comparisons bind tighter than `AND`/`OR`, so `AX1 < 819 AND X2` means `(AX1 < 819) AND X2`. Use brackets whenever in doubt.
- Function blocks accept named parameters (recommended) or positional ones.

### 8.3 Supported language

| Area | Supported |
|---|---|
| Declarations | `name : TYPE;` or `name : TYPE := initial;`, several names per line allowed (`a, b : INT;`). Optional `PROGRAM … END_PROGRAM` wrapper. |
| Data types | `BOOL`; `INT`, `DINT`, `SINT`, `UINT`, `LINT`, `WORD`, `DWORD`, `BYTE` (all integers; decimals are dropped on assignment); `REAL`, `LREAL`; `TIME` (`T#500ms`, `T#2s`, `T#1m30s`); `ARRAY[lo..hi] OF type` |
| Boolean | `AND` (or `&`), `OR`, `XOR`, `NOT` |
| Compare | `=`, `<>`, `<`, `>`, `<=`, `>=` |
| Arithmetic | `+`, `-`, `*`, `/`, `MOD`, `**` (divide by zero returns 0; ST never sets the SB9–SB11 error flags) |
| Data registers | `D[1]` … `D[4000]`, read and written as `INT` (v1.018) |
| Control | `IF / ELSIF / ELSE`, `CASE … OF` (single values, lists `1, 2:`, ranges `3..5:`, `ELSE`), `FOR … TO … BY`, `WHILE`, `REPEAT … UNTIL … END_REPEAT`, `EXIT`, `CONTINUE`, `RETURN` |
| Function blocks | `TON`, `TOF`, `TP` (IN, PT → Q, ET); `CTU` (CU, R, PV → Q, CV); `CTD` (CD, LD, PV → Q, CV); `CTUD` (CU, CD, R, LD, PV → QU, QD, CV — never below 0, needs `acc-st.js` v1.016); `R_TRIG`, `F_TRIG` (CLK → Q). There is no retentive timer block. |
| Functions | `ABS`, `SQRT`, `MIN`, `MAX`, `LIMIT(min, in, max)`, `TRUNC`, `ROUND`, `EXPT(base, exp)`, `SEL(g, in0, in1)`, `SHL`, `SHR`, `REAL_TO_INT`, `INT_TO_REAL`, `BOOL_TO_INT`, `INT_TO_BOOL`, plus user `FUNCTION` and `FUNCTION_BLOCK` (nesting function blocks needs `acc-st.js` v1.015 or later — see 8.4) |
| Time literals | `T#500ms`, `T#2s`, `T#1m30s`, `T#1h`, `T#1d`, and combinations |
| Not in ST | The ladder-only instructions `RTO`, `BSL`, `BSR`, `DRUM`, `JMP`/`LBL` and `MCR`/`END MCR` (v1.126) — use `IF`/`CASE` logic instead (Section 5.1) |

### 8.4 Function block usage

Declare the instance in `VAR`, call it **once every scan** with named parameters, then read its outputs:

```
VAR
    onDelay : TON;
END_VAR

onDelay(IN := X1, PT := T#2s);
Y1  := onDelay.Q;      (* TRUE 2 s after X1 turns on *)
AY1 := onDelay.ET;     (* elapsed time in ms *)
```

Calling a timer inside an `IF` that is sometimes skipped is a common mistake. The timer only updates on scans where it is called.

**Function blocks may be declared inside your own `FUNCTION_BLOCK` (fixed in `acc-st.js` v1.015).** A `TON`, `CTU`, `R_TRIG` or another user block declared in a user-defined `FUNCTION_BLOCK` now works, and so does nesting user blocks several levels deep. Each instance owns its own state, so two instances of the same block type keep separate timers and counts.

```
(* Works on v1.015 and later *)
FUNCTION_BLOCK Deb
  VAR_INPUT inp : BOOL; END_VAR
  VAR_OUTPUT outp : BOOL; END_VAR
  VAR t : TON; END_VAR
  t(IN := inp, PT := T#50ms);
  outp := t.Q;
END_FUNCTION_BLOCK

VAR
    dStart : Deb;   (* each instance keeps its own timer *)
    dStop  : Deb;
END_VAR

dStart(inp := X1);
dStop(inp := X2);
Y1 := dStart.outp AND NOT dStop.outp;
```

Declaring timers at the top level of the program also works and is often clearer for a short program — use whichever suits.

> **On `acc-st.js` v1.014 and earlier this failed.** A block instance declared inside a user `FUNCTION_BLOCK` compiled without complaint and then threw `"<name>" is not a function-block instance` on **every** scan, which stops the PLC rather than just the rung. If a program has to run on an older copy of the engine, keep every timer and counter at the top level. Check the version in the `acc-st.js` header or via `AccST.version`.

A user `FUNCTION_BLOCK` holding only plain variables and logic works normally, and so does a user `FUNCTION`.

### 8.5 Template

```
(* PROGRAM TITLE - Structured Text *)
(* ACC PLC Simulator - <Scene name> Scene *)
(* I/O: X1 = ..., X2 = ... (N.C.), Y1 = ... *)

VAR
    State     : INT := 0;   (* describe each value *)
    StartEdge : R_TRIG;     (* one-shot on Start *)
END_VAR

(* 1. Edge detection and inputs *)
StartEdge(CLK := X1);

(* 2. Stops and faults first - they have priority *)
IF NOT X2 THEN
    State := 0;
END_IF;

(* 3. State transitions *)
CASE State OF
    0: IF StartEdge.Q AND X2 THEN State := 1; END_IF;
    1: (* ... *)
ELSE
    State := 0;
END_CASE;

(* 4. Outputs driven from state - always assign every output *)
Y1 := (State = 1);
```

### 8.6 Complete ST example — Conveyor Shuttle Control

Download: https://accautomation.ca/simulator/acc-example-conveyor-shuttle.st

```
(* CONVEYOR SHUTTLE CONTROL - Structured Text *)
(* ACC PLC Simulator - Conveyor Scene *)
(* X1 Start PB (N.O.)  X2 Stop PB (N.C.)  X3 Left sensor  X4 Right sensor *)
(* Y1 Conveyor run     Y2 Reverse                                         *)

VAR
    State      : INT  := 0;      (* 0 = Idle, 1 = Forward, 2 = Reverse *)
    StartLast  : BOOL := FALSE;  (* Start button state, previous scan  *)
    StartPulse : BOOL := FALSE;  (* One-shot on the Start press        *)
END_VAR

(* One-shot the Start button *)
StartPulse := X1 AND NOT StartLast;
StartLast  := X1;

(* Stop has priority over everything *)
IF NOT X2 THEN
    State := 0;
ELSIF StartPulse AND State = 0 THEN
    State := 1;
END_IF;

(* State transitions *)
CASE State OF
    1:  (* Forward - travelling right *)
        IF X4 THEN
            State := 2;
        END_IF;
    2:  (* Reverse - travelling left *)
        IF X3 THEN
            State := 0;
        END_IF;
    ELSE
        State := 0;
END_CASE;

(* Outputs driven from state *)
Y1 := (State = 1) OR (State = 2);
Y2 := (State = 2);
```

### 8.7 Complete ST example — Analog Tank Level Control

The same program as Section 7. Download: https://accautomation.ca/simulator/acc-example-analog-tank-level.st

```
(* ANALOG TANK LEVEL CONTROL - Structured Text *)
(* AX1 Tank level 0-4095  X2 Stop PB (N.C.)  X3 Service reset *)
(* Y1 Inlet valve  Y3 High alarm  Y4 Service due  AY1 Valve position *)

VAR
    FillCount : CTU;
END_VAR

(* Fill request with 20 % / 85 % dead band; Stop closes the valve *)
IF AX1 < 819 AND X2 THEN
    C101 := TRUE;
END_IF;
IF AX1 > 3481 OR NOT X2 THEN
    C101 := FALSE;
END_IF;

(* Outputs *)
Y1 := C101;
IF C101 THEN
    AY1 := 4095;
ELSE
    AY1 := 0;
END_IF;
Y3 := AX1 >= 3890;

(* Count fill cycles; service due after 5 *)
FillCount(CU := C101, R := X3, PV := 5);
Y4 := FillCount.Q;
```

---

## 9. What the simulator does when a JSON file is imported

This is useful when a file loads but does not behave as expected.

1. The file is parsed. The importer uses the `program` array, or the whole file if it is a bare array. Anything else fails with "Invalid format".
2. The user confirms the import; the current program is replaced.
3. Address comments are cleared, then rebuilt: legacy element `comment` values first (first one per address wins), then the `comments` map on top.
4. Each element is rebuilt from `id`, `kind`, `type` (default `XIC`), `addr` (default empty), each kept exactly as written in the file (except that a pointer written with spaces or leading zeros, such as `"d[ d05 ]"`, is stored as `"D[D5]"`), plus `pre`/`src`/`cd`/`a`/`b`/`expr`/`inMin`/`inMax`/`outMin`/`outMax`/`len`/`dt`/`st`/`ul`/`out`/`outs`/`rst`/`dn`/`steps` for blocks, `cmp`/`lo`/`hi`/`dt` for compares and `branches` for parallel groups. From v1.126 a `LBL` is always rebuilt as a contact and `BSL`, `BSR`, `DRUM`, `JMP`, `MCR` and `MCRE` as blocks, whatever their `kind`; a label is stored as `L<n>` (`"l05 "` → `"L5"`); drum steps keep the values written in the file (only their shape is fixed), so a bad step value is reported rather than hidden.
5. Rungs are renumbered 0, 1, 2 … in array order.
6. All memory (X, Y, C, T, CT, AX, AY) and the error flags (SB9–SB12, SW17, SW18) are cleared, every D register is set to 0 and then to the values in `dregs`, the D-tab formats are taken from `dfmt`, and the undo history is reset (the imported program is the first undo point).
7. **From v1.124 every element is checked with the editor's own rules.** The program loads either way, but when elements fail, the status bar shows how many and the first problem, for example `Imported "tank.json" — 12 rungs · ⚠ 2 problems found by the editor's checks — rung 0004: B is 0 — DIV by zero would fault on every scan.` From v1.126 the count also includes the program checks of Section 4.10 (instruction positions, labels, jumps and MCR zones); an MCR zone with no END MCR is counted there too, although the program still runs.

An address with a space inside — `"X 1"`, `"D 5"` — is not an address: the import check reports it and it reads as 0 or OFF, or writes nothing, when the program runs. A pointer is the one exception: spaces inside the brackets are ignored (`"D[ D5 ]"` is stored as `"D[D5]"`). Write every address without spaces; the validator in Section 10.2 refuses them (a pointer with spaces gets a warning).

If a rung has no `elements` array, the import fails without a message on screen (the error appears only in the browser's developer console), and the existing address comments are lost.

Because missing fields get quiet defaults (an element with no `type` becomes `XIC`; a compare with no `cmp` compares against 0; a LIM with no `lo`/`hi` tests 0 to 0; a CTUD with no `cd` never counts down; a timer with no `pre` is done immediately; a MOV with no `src` moves 0; a math block with no `a` or `b` reads 0; a `CPT` with no `expr` sets fault 3 on every scan; a `COP`, `FLL`, `PACK` or `UNPACK` with no `len` sets fault 4 on every scan; a missing `dt` means `INT`), a file can import without an error message and still be wrong. The import check catches bad addresses and values, but not missing fields or logic mistakes. The validator in Section 10.2 catches both, before the file is imported.

---

## 10. Checking the result before importing

### 10.1 Checklist

**Ladder JSON**

- [ ] The file is valid JSON (no trailing commas, no comments inside the JSON).
- [ ] Top level has `"version": 2`, `program`, and a `comments` map.
- [ ] Every rung has at least one input and at least one output, and its last element is an output or block (an END MCR rung holds only its `MCRE` block).
- [ ] No empty rungs.
- [ ] Every rung and element has an integer `id`; rung ids are unique, and element ids are unique across the file.
- [ ] Coils only write Y or C (the one exception: OTU on SB9–SB11); timers use T, counters use CT; MOV and the math blocks write D or AY.
- [ ] Timer `pre` values are in milliseconds; `pre` is a whole number 0–99,999,999.
- [ ] Compares use D, AX, AY, SW, `T*n*/ACC` or `CT*n*/ACC`, with `cmp` (LIM: `lo` and `hi`) as a number or a word address string. Without a D register, constants are whole numbers 0–99,999,999; with one, they fit the compare's `dt`.
- [ ] MOV has a string `src` (a constant or a readable word) and `"pre": 0`; RES and every math and data block have `"pre": 0`.
- [ ] Every `dt` and `st` is `INT`, `UINT`, `WORD`, `DINT` or `REAL` (upper case), and every constant fits it — whole numbers for the integer types.
- [ ] Each D register is used as one type throughout. `DINT` and `REAL` values take two registers (D10 and D11) and nothing else writes the second one; none starts at D4000.
- [ ] Math blocks that accumulate (`INC`, `DEC`, `ADD` into its own operand) have a `P` contact unless they are meant to act on every scan.
- [ ] No `DIV`/`MOD` by a constant 0; a register divisor that can be 0 is guarded by a compare.
- [ ] `CPT` expressions use only numbers, D/AX/AY/SW words, `+ - * / MOD **`, brackets and ABS, SQRT, MIN, MAX, LIMIT, TRUNC, ROUND, EXPT; no decimals unless `dt` is `REAL`; every D register named in them is meant to be read as the CPT's `dt`.
- [ ] `COP`, `FLL`, `PACK`, `UNPACK` have a `len` that keeps them inside their tables; `UNPACK` writes Y or C.
- [ ] Pointers are written `"D[Dn]"` (upper case, no spaces, Dn in D1–D4000) and used only in the fields that accept them (Section 3.1.2): never on contacts, coils, timers, counters, `RES`, `cd`, `len`, the SCL limits or the PACK/UNPACK bits.
- [ ] Every pointer register holds a register **number** (1–4000, or 1–3999 for a `DINT`/`REAL` access, and low enough that a `COP`/`FLL` run ends by D4000), is set before the rungs that use it in the same scan, and is written only as `INT` — never by a `DINT` or `REAL` instruction.
- [ ] If the program can raise a math error, something shows it (`XIC SB12 → OTE …`) and something clears it (`OTU SB9`–`SB11`, `MOV SW17 "0"`).
- [ ] `dregs` (if present) holds whole numbers 0–65,535 keyed `D1`–`D4000`; `dfmt` values are DEC, UDEC, HEX, BIN, DINT or REAL.
- [ ] Every CTUD has a `cd` string naming a bit address.
- [ ] `BSL`/`BSR`: `addr` C or Y, `len` 1–256 inside the table, `src` a bit address, `ul` a C or Y bit or `""`; nothing else writes the register bits with `OTE`.
- [ ] `DRUM`: `addr` a D register used only as the step register (`INT`), `out` + `outs` (1–16) inside the Y or C table, 1–16 `steps` each with whole-number `p` 0–65,535 and `t` 0–99,999,999 ms and `ev` a bit address or `""`, `rst`/`dn` valid or `""`; no `OTE` on the drum's outputs.
- [ ] `BSL`, `BSR`, `DRUM`, `JMP`, `MCR` and `MCRE` are the last element of their rung and not in a branch; `MCRE` is alone on its rung; `LBL` is at top level and not last.
- [ ] Labels are written `L1`–`L256`, each used once; every `JMP` has its `LBL` on a later rung, in the same MCR zone.
- [ ] MCR zones are not nested, and every MCR has an END MCR below it.
- [ ] No contacts on D, AX, AY, SW or `/ACC` addresses; nothing writes SB or SW (except the clear-only cases).
- [ ] One-shots use a `P` contact, or the two-rung pattern in the right order.
- [ ] Every MOV output that must change back has a second MOV rung.
- [ ] Every CTD has a matching CTU on the same address (or use CTUD instead).
- [ ] Every parallel group has at least two non-empty branches of contacts and compares only.
- [ ] N.C. field devices (Stop, E-stop) use XIC contacts.
- [ ] Rungs that set a bit are above the rungs that must see it in the same scan.
- [ ] Every address matches the scene's I/O list and is in the `comments` map, and no address has a space inside it.

**Structured Text**

- [ ] Saved as plain text with a `.st` extension.
- [ ] No I/O or system addresses declared in `VAR`; nothing assigned to SB or SW except the clear-only cases.
- [ ] Data registers written `D[n]` with `n` 1–4000, used only for `INT` values; no variable named `D`.
- [ ] Every assignment uses `:=`, every statement ends with `;`.
- [ ] No waiting loops; timing uses TON/TOF/TP.
- [ ] Every function block instance is called unconditionally each scan.
- [ ] Every output is assigned on every scan (avoid outputs that are only set inside an `IF`, unless latching is intended).

### 10.2 Automatic validator (ladder JSON)

Download https://accautomation.ca/simulator/acc-validate-program.py (or copy the code below) and run `python3 acc-validate-program.py my-program.json` (Python 3, no extra packages). It prints `OK` or a list of problems, with the rung and element where each was found. Warnings point out things that load but are probably not what was intended — for example a math block that changes its own value on every scan, two `DINT`/`REAL` values that overlap, a pointer register that a `DINT` or `REAL` instruction writes, an `OTE` on a shift-register or drum bit, a drum step with no time and no event, or an MCR zone that is never closed. It applies every check the v1.126 editor applies on import (including the pointer `D[Dn]` rules, the `CPT` expression rules, which it parses itself, and the v1.126 program checks for instruction positions, labels, jumps and MCR zones), plus stricter checks for mistakes that load but misbehave, such as a coil on an X input or an address with a space inside it. Like the editor, it cannot know where a pointer will point when the program runs; a pointer outside D1–D4000 shows up as code 4 in `SW17`.

```python
#!/usr/bin/env python3
"""Validate an ACC PLC Simulator ladder program (.json) before importing it.
Checks the rules used by the simulator's own import, edit-dialog and scan code
(acc-plc-simulator.html v1.126, CPT expressions as parsed by acc-st.js v1.018),
verified by running that engine.
Usage:  python3 acc-validate-program.py my-program.json
"""
import json, math, re, sys

N256 = r'([1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-6])'
N16  = r'([1-9]|1[0-6])'
N18  = r'([1-9]|1[0-8])'
N19  = r'([1-9]|1[0-9])'
N4000 = r'([1-9][0-9]{0,2}|[1-3][0-9]{3}|4000)'
BIT_ADDR = re.compile(rf'^(X{N16}|Y{N16}|C{N256}|SB{N18}|T{N256}(/(DN|EN|TT))?|CT{N256}(/DN)?)$')
OUT_ADDR = re.compile(rf'^(Y{N16}|C{N256})$')
TIMER    = re.compile(rf'^T{N256}$')
COUNTER  = re.compile(rf'^CT{N256}$')
ANALOG   = re.compile(r'^(AX[1-8]|AY[1-4])$')
# Words a compare, a MOV source or a math operand may read (v1.124 adds D1-D4000)
WORD     = re.compile(rf'^(D{N4000}|AX[1-8]|AY[1-4]|SW{N19}|T{N256}/ACC|CT{N256}/ACC)$')
D_ADDR   = re.compile(rf'^D{N4000}$')
PTR      = re.compile(rf'^D\[D{N4000}\]$')    # v1.125 pointer D[Dn], written in upper case
AY_REG   = re.compile(r'^AY[1-4]$')
SB_CLEAR = re.compile(r'^SB(9|10|11)$')
ANY_ADDR = re.compile(rf'^(X{N16}|Y{N16}|C{N256}|SB{N18}|SW{N19}|T{N256}(/(DN|EN|TT|ACC))?|CT{N256}(/(DN|ACC))?|AX[1-8]|AY[1-4]|D{N4000})$')
NUM_MAX  = 99_999_999          # editor limit for presets, and for constants in compares without a D register
D_MAX    = 4000
SB_MAX, SW_MAX = 18, 19

CONTACTS = ("XIC", "XIO", "P", "N")
COMPARES = ("GRT", "LES", "GEQ", "LEQ", "EQU", "NEQ", "LIM")
TIMERS   = ("TON", "TOF", "RTO")
COUNTERS = ("CTU", "CTD", "CTUD")
MATH2    = ("ADD", "SUB", "MUL", "DIV", "MOD")
INCDEC   = ("INC", "DEC")
DATA     = ("COP", "FLL", "PACK", "UNPACK")
WORD_BLOCKS = MATH2 + INCDEC + ("CPT", "SCL") + DATA
TYPED    = ("MOV",) + MATH2 + INCDEC + ("CPT", "SCL", "FLL") + COMPARES   # instructions with a 'dt' field
SHIFT    = ("BSL", "BSR")                  # v1.126 bit shift registers
FLOW     = ("JMP", "MCR", "MCRE")           # v1.126 program control (output position)
SEQ      = SHIFT + ("DRUM",)
PHASE3_OUT = SEQ + FLOW                     # output-position instructions with position rules
BLOCKS   = TIMERS + COUNTERS + ("RES", "MOV") + WORD_BLOCKS + SEQ + FLOW
# Data types: words used, smallest value, largest value, whole numbers only
TYPES = {"INT": (1, -32768, 32767, True), "UINT": (1, 0, 65535, True), "WORD": (1, 0, 65535, True),
         "DINT": (2, -2147483648, 2147483647, True),
         "REAL": (2, -3.4028234663852886e38, 3.4028234663852886e38, False)}
D_FORMATS = ("DEC", "UDEC", "HEX", "BIN", "DINT", "REAL")
# Optional fields each instruction keeps (the editor drops the others)
FIELDS = {**{t: ("cmp", "dt") for t in COMPARES[:6]}, "LIM": ("lo", "hi", "cmp", "dt"),
          "MOV": ("src", "dt", "st"), **{t: ("a", "b", "dt") for t in MATH2},
          "INC": ("dt",), "DEC": ("dt",), "CPT": ("expr", "dt"),
          "SCL": ("src", "inMin", "inMax", "outMin", "outMax", "dt"),
          "COP": ("src", "len"), "PACK": ("src", "len"), "UNPACK": ("src", "len"), "FLL": ("src", "len", "dt")}
PHASE2_FIELDS = ("src", "dt", "st", "a", "b", "expr", "inMin", "inMax", "outMin", "outMax", "len")
_C_NUM = re.compile(r'^C([0-9]+)$')


def out_of_range_c(a):
    """C0 and C257+ read and write at run time, but never show on the I/O panel."""
    m = _C_NUM.match(a.upper())
    return bool(m) and not (1 <= int(m.group(1)) <= 256)

errors, warnings, ids, rung_ids = [], [], [], []
ctu, ctd = set(), set()
bit_writes = []        # (bits, instruction, where) for OTE coils and the v1.126 shift registers and drums
d_dest = []            # (first word, last word, type, where) of every typed D destination
ptr_regs = {}          # pointer register number -> where it is first used as D[Dn]

def err(w, m):  errors.append(f"{w}: {m}")
def warn(w, m): warnings.append(f"{w}: {m}")
def is_num(v):  return isinstance(v, (int, float)) and not isinstance(v, bool)

# ── JavaScript value semantics (the simulator is JavaScript) ──────────────
_NUMLIT = re.compile(r'^\s*[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?\s*$')
_PFLOAT = re.compile(r'^[-+]?(Infinity|([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?)')

def js_str(v):
    """String(v) as JavaScript writes it."""
    if v is None: return "null"
    if v is True: return "true"
    if v is False: return "false"
    if isinstance(v, int): return str(v)
    if isinstance(v, float):
        if math.isnan(v): return "NaN"
        if math.isinf(v): return "Infinity" if v > 0 else "-Infinity"
        if v.is_integer() and abs(v) < 1e21: return str(int(v))
        return re.sub(r'e([+-])0*([0-9])', r'e\1\2', repr(v))
    if isinstance(v, list): return ",".join("" if x is None else js_str(x) for x in v)
    if isinstance(v, dict): return "[object Object]"
    return str(v)

def js_truthy(v):
    if v is None or v is False: return False
    if isinstance(v, str): return v != ""
    if is_num(v): return v != 0 and not (isinstance(v, float) and math.isnan(v))
    return True

_WSC = '[\t\n\v\f\r \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]'

def js_trim(s):
    """String.prototype.trim(): JavaScript white space only."""
    return re.sub('^' + _WSC + '+|' + _WSC + '+$', '', s)

def js_number(s):
    """Number(string) - '' is 0, hex/binary/octal prefixes allowed, otherwise NaN."""
    s = js_trim(s)
    if s == "": return 0.0
    if re.fullmatch(r'[-+]?(Infinity|([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?)', s):
        return float(s.replace("Infinity", "inf"))
    m = re.fullmatch(r'0([xX][0-9a-fA-F]+|[bB][01]+|[oO][0-7]+)', s)
    if m: return float(int(s, 0))
    return math.nan

def js_parse_float(v):
    if is_num(v): return float(v)
    m = _PFLOAT.match(js_str(v).lstrip())
    return float(m.group(0).replace("Infinity", "inf")) if m else math.nan

def is_num_lit(v):
    return is_num(v) or bool(_NUMLIT.match(js_str(v)))

_JS_WS = re.compile('[\t\n\v\f\r \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+')

_PTR_FORM = re.compile('^D' + _WSC + '*\\[' + _WSC + '*D' + _WSC + '*([0-9]+)' + _WSC + '*\\]$')

def norm(v):
    """_normAddr: String(v||'') trimmed (JS trim), upper case; a pointer typed with spaces or
    leading zeros (d[ d05 ]) becomes D[D5]. Other addresses keep their inner characters."""
    a = js_trim(js_str(v)).upper() if js_truthy(v) else ""
    m = _PTR_FORM.match(a)
    return f"D[D{int(m.group(1))}]" if m else a

def whole_in(s, lo, hi):
    n = js_number(s)
    return s != "" and not math.isnan(n) and not math.isinf(n) and n == int(n) and lo <= n <= hi

def dt_of(t):
    return t if isinstance(t, str) and t in TYPES else "INT"

def d_num(a):
    m = re.match(r'^D([0-9]+)$', norm(a))
    return int(m.group(1)) if m else 0

def is_d(a):  return 1 <= d_num(a) <= D_MAX

def ptr_num(a):
    """Pointer D[Dn]: the number n of the pointer register, or 0 when a is not a pointer."""
    m = re.match(r'^D\[D([0-9]+)\]$', norm(a))
    return int(m.group(1)) if m else 0

def is_ptr(a):  return 1 <= ptr_num(a) <= D_MAX
def is_d_op(a): return is_d(a) or is_ptr(a)        # a D register, direct or through a pointer
def d_fits(a, t): n = d_num(a); return n >= 1 and n + TYPES[dt_of(t)][0] - 1 <= D_MAX

def in_range(s, pfx, top):
    m = re.match('^' + pfx + r'([0-9]+)$', s)
    return bool(m) and 1 <= int(m.group(1)) <= top

def is_bit_addr(a):
    s = norm(a)
    if in_range(s, 'X', 16) or in_range(s, 'Y', 16) or in_range(s, 'C', 256) or in_range(s, 'SB', SB_MAX): return True
    m = re.match(r'^(T|CT)([0-9]+)(/(DN|EN|TT))?$', s)
    return bool(m) and 1 <= int(m.group(2)) <= 256 and (m.group(1) == 'T' or m.group(4) in (None, 'DN'))

def is_word_addr(a):
    s = norm(a)
    if in_range(s, 'AX', 8) or in_range(s, 'AY', 4) or in_range(s, 'SW', SW_MAX) or in_range(s, 'D', D_MAX): return True
    m = re.match(r'^(T|CT)([0-9]+)/ACC$', s)
    return bool(m) and 1 <= int(m.group(2)) <= 256

def word_table(start, n):
    """wordRange(): `n` words from a D/AX/AY/SW start stay inside that table."""
    m = re.match(r'^(D|AX|AY|SW)([0-9]+)$', norm(start))
    if not m: return False
    top = {"D": D_MAX, "AX": 8, "AY": 4, "SW": SW_MAX}[m.group(1)]
    return int(m.group(2)) >= 1 and int(m.group(2)) + n - 1 <= top

def bit_table(start, n):
    """bitRange(): `n` bits from an X/Y/C start stay inside that table."""
    m = re.match(r'^(X|Y|C)([0-9]+)$', norm(start))
    if not m: return False
    top = 256 if m.group(1) == "C" else 16
    return int(m.group(2)) >= 1 and int(m.group(2)) + n - 1 <= top

def range_text(t):
    _, lo, hi, whole = TYPES[dt_of(t)]
    return f"{lo:,} to {hi:,}" if whole else "+/-3.4e38 (float32)"

# ── CPT expressions: the acc-st.js expression parser and the editor's CPT rules ──
KEYWORDS = set("""PROGRAM END_PROGRAM VAR VAR_INPUT VAR_OUTPUT VAR_GLOBAL VAR_TEMP END_VAR IF THEN ELSIF ELSE
END_IF CASE OF END_CASE FOR TO BY DO END_FOR WHILE END_WHILE REPEAT UNTIL END_REPEAT EXIT RETURN CONTINUE
FUNCTION END_FUNCTION FUNCTION_BLOCK END_FUNCTION_BLOCK TRUE FALSE AND OR XOR NOT MOD BOOL INT DINT SINT LINT
UINT REAL LREAL TIME WORD DWORD BYTE ARRAY""".split())
BINPREC = {'OR': 1, 'XOR': 2, 'AND': 3, 'AND_OP': 3, '=': 4, '<>': 4, '<': 5, '>': 5, '<=': 5, '>=': 5,
           '+': 6, '-': 6, '*': 7, '/': 7, 'MOD': 7, '**': 8}
CPT_FUNCS = {"ABS": 1, "SQRT": 1, "MIN": 2, "MAX": 2, "LIMIT": 3, "TRUNC": 1, "ROUND": 1, "EXPT": 2}
CPT_OPS = ('+', '-', '*', '/', 'MOD', '**')

DIGITS = "0123456789"

class CptError(Exception):
    pass

def _time_ms(s):
    s = s.replace("_", "")
    total, found = 0.0, False
    for m in re.finditer(r'([0-9]*\.?[0-9]+)\s*(ms|s|m|h|d)', s, re.I):
        found = True
        total += float(m.group(1)) * {"d": 86400000, "h": 3600000, "m": 60000, "s": 1000, "ms": 1}[m.group(2).lower()]
    return total if found else (0.0 if math.isnan(js_parse_float(s)) else js_parse_float(s))

def cpt_tokens(src):
    toks, i, n = [], 0, len(src)
    while i < n:
        c = src[i]
        if c in " \t\r\n": i += 1; continue
        if src.startswith("//", i):
            while i < n and src[i] != "\n": i += 1
            continue
        if src.startswith("(*", i) or src.startswith("/*", i):
            close = "*)" if c == "(" else "*/"
            j = src.find(close, i + 2)
            i = n + 1 if j < 0 else j + 2
            continue
        if c in "Tt" and (src[i + 1:i + 2] == "#" or re.match(r'ime#', src[i + 1:i + 5], re.I)):
            j = i + 2 if src[i + 1:i + 2] == "#" else i + 5
            k = j
            while k < n and re.match(r'[0-9smhd_.]', src[k], re.I): k += 1
            toks.append(("num", _time_ms(src[j:k]), False)); i = k; continue
        if c in DIGITS or (c == "." and src[i + 1:i + 2] in DIGITS and i + 1 < n):
            num, real = "", False
            while i < n and (src[i] in "0123456789_"): num += src[i]; i += 1
            if i < n and src[i] == "." and src[i + 1:i + 2] != ".":
                real = True; num += "."; i += 1
                while i < n and src[i] in "0123456789_": num += src[i]; i += 1
            if i < n and src[i] in "eE":
                real = True; num += "e"; i += 1
                if i < n and src[i] in "+-": num += src[i]; i += 1
                while i < n and src[i] in "0123456789": num += src[i]; i += 1
            toks.append(("num", js_parse_float(num.replace("_", "")), real)); continue
        if re.match(r'[A-Za-z_]', c):
            j = i
            while j < n and re.match(r'[A-Za-z0-9_]', src[j]): j += 1
            word = src[i:j]; i = j
            toks.append(("kw", word.upper(), None) if word.upper() in KEYWORDS else ("id", word, word.upper()))
            continue
        if src[i:i + 2] in (":=", "<>", "<=", ">=", "**", ".."):
            toks.append(("op", src[i:i + 2], None)); i += 2; continue
        if c in "+-*/()[].,;:<>=&":
            toks.append(("op", "AND_OP" if c == "&" else c, None)); i += 1; continue
        raise CptError(f"Unexpected character '{c}'")
    toks.append(("eof", None, None))
    return toks

class CptParser:
    def __init__(self, toks): self.t, self.p = toks, 0
    def peek(self, k=0): return self.t[self.p + k]
    def next(self): tok = self.t[self.p]; self.p += 1; return tok
    def is_op(self, v): return self.peek()[0] == "op" and self.peek()[1] == v
    def expect_op(self, v):
        if self.is_op(v): return self.next()
        tok = self.peek()
        raise CptError(f"Expected {v} but found '{'end of program' if tok[1] is None else tok[1]}'")
    def expr(self, min_prec):
        left = self.unary()
        while True:
            kind, val, _ = self.peek()
            if kind not in ("kw", "op") or val not in BINPREC or BINPREC[val] < min_prec: break
            self.next()
            right = self.expr(BINPREC[val] if val == "**" else BINPREC[val] + 1)
            left = {"k": "bin", "op": val, "a": left, "b": right}
        return left
    def unary(self):
        kind, val, _ = self.peek()
        if (kind == "kw" and val == "NOT") or (kind == "op" and val in ("-", "+")):
            self.next()
            return {"k": "un", "op": val, "a": self.unary()}
        return self.postfix()
    def postfix(self):
        node = self.primary()
        while True:
            if self.is_op("."):
                self.next()
                if self.peek()[0] != "id":
                    tok = self.peek()
                    raise CptError(f"Expected id but found '{'end of program' if tok[1] is None else tok[1]}'")
                node = {"k": "member", "obj": node, "field": self.next()[2]}
            elif self.is_op("["):
                self.next(); idx = self.expr(0); self.expect_op("]")
                node = {"k": "index", "obj": node, "index": idx}
            elif self.is_op("("):
                args = self.call_args()
                if node["k"] != "var": raise CptError("Cannot call this expression")
                named = any(a[0] for a in args)
                node = {"k": "fbcall" if named else "call", "name": node["name"], "up": node["up"], "args": args}
            else:
                return node
    def call_args(self):
        self.expect_op("(")
        args = []
        if not self.is_op(")"):
            while True:
                if self.peek()[0] == "id" and self.peek(1)[0] == "op" and self.peek(1)[1] == ":=":
                    name = self.next()[2]; self.next()
                    args.append((name, self.expr(0)))
                else:
                    args.append((None, self.expr(0)))
                if self.is_op(","): self.next()
                else: break
        self.expect_op(")")
        return args
    def primary(self):
        kind, val, extra = self.peek()
        if kind == "num": self.next(); return {"k": "num", "value": val, "real": extra}
        if kind == "kw" and val in ("TRUE", "FALSE"): self.next(); return {"k": "bool"}
        if kind == "id": self.next(); return {"k": "var", "name": val, "up": extra}
        if kind == "op" and val == "(":
            self.next(); e = self.expr(0); self.expect_op(")"); return e
        raise CptError(f"Unexpected token '{'end of program' if val is None else val}'")

def cpt_check(expr):
    """cptCompile(): returns (error text, ast)."""
    try:
        p = CptParser(cpt_tokens(js_str(expr)))
        if p.peek()[0] == "eof": return "Expression error: empty expression", None
        ast = p.expr(0)
        if p.peek()[0] != "eof": return f"Expression error: unexpected '{p.peek()[1]}'", None
    except CptError as x:
        return f"Expression error: {x}", None
    def walk(nd):
        k = nd["k"]
        if k == "num": return ""
        if k == "var":
            u = nd["up"]
            for pfx, top in (("D", D_MAX), ("AX", 8), ("AY", 4), ("SW", SW_MAX)):
                m = re.match('^' + pfx + r'([0-9]+)$', u)
                if m:
                    if 1 <= int(m.group(1)) <= top: return ""
                    return f"{u} is outside D1-D{D_MAX}" if pfx == "D" else f"{u} does not exist"
            return (f'"{nd["name"]}" is not allowed - use numbers and D, AX, AY or SW words '
                    f'(move T1/ACC or CT1/ACC into a D register first)')
        if k == "un":
            return "NOT is not allowed in CPT" if nd["op"] == "NOT" else walk(nd["a"])
        if k == "bin":
            if nd["op"] not in CPT_OPS: return f"Operator {nd['op']} is not allowed in CPT - arithmetic only"
            return walk(nd["a"]) or walk(nd["b"])
        if k == "call":
            want = CPT_FUNCS.get(nd["up"])
            if not want:
                return f"Function {nd['name']} is not available in CPT (ABS, SQRT, MIN, MAX, LIMIT, TRUNC, ROUND, EXPT)"
            minmax = nd["up"] in ("MIN", "MAX")
            if (len(nd["args"]) < 2) if minmax else (len(nd["args"]) != want):
                return f"{nd['name']} takes {'2 or more' if minmax else want} argument{'s' if want > 1 else ''}"
            for _, a in nd["args"]:
                r = walk(a)
                if r: return r
            return ""
        if k == "bool": return "TRUE/FALSE are not allowed in CPT"
        if k == "index":
            # Only a pointer: D[Dn] with Dn a D register.
            ob, ix = nd["obj"], nd["index"]
            if not (ob["k"] == "var" and ob["up"] == "D" and ix["k"] == "var" and re.match(r'^D[0-9]+$', ix["up"])):
                return "In CPT an indexed address must be a pointer, D[Dn] - the index is a D register, e.g. D[D5]."
            return "" if is_d(ix["up"]) else f"{ix['up']} is outside D1-D{D_MAX}."
        return "This expression form is not allowed in CPT"
    bad = walk(ast)
    return bad, (None if bad else ast)

def cpt_has_decimal(nd):
    if nd["k"] == "num" and (nd["real"] or not (math.isfinite(nd["value"]) and nd["value"] == int(nd["value"]))):
        return True
    kids = [nd[x] for x in ("a", "b") if x in nd] + [a for _, a in nd.get("args", [])]
    return any(cpt_has_decimal(c) for c in kids)

# ── The editor's own element check (validateFull), applied to the element as
#    the importer rebuilds it (jsonToProgram). Returns '' or the editor's reason.
def canon_lbl(v):
    """_canonLbl: a label is stored L<n> ("l05 " -> "L5"); anything else is kept as written."""
    m = re.fullmatch(r'L0*([0-9]+)', js_trim(js_str("" if v is None else v)).upper())
    return "L" + m.group(1) if m else v

def forced_kind(e):
    """v1.126 types have one kind each, whatever the file says (LBL a contact, the rest blocks)."""
    k = e.get("kind")
    if k == "parallel": return k
    t = e.get("type")
    if t == "LBL": return "contact"
    if t in PHASE3_OUT: return "block"
    return k

def with_kind(e):
    """The element as the importer sees it: kind forced, branches rebuilt the same way."""
    if not isinstance(e, dict): return e
    if e.get("kind") == "parallel" and isinstance(e.get("branches"), list):
        return dict(e, branches=[[with_kind(x) for x in br] if isinstance(br, list) else br for br in e["branches"]])
    k = forced_kind(e)
    return e if k == e.get("kind") else dict(e, kind=k)

def restore_steps(v):
    """DRUM steps as the importer keeps them: values as written, only the shape fixed."""
    if not isinstance(v, list): return []
    out = []
    for x in v[:64]:
        if isinstance(x, dict):
            out.append({"p": x["p"] if "p" in x else 0, "t": x["t"] if "t" in x else 0,
                        "ev": x["ev"] if isinstance(x.get("ev"), str) else ""})
        elif isinstance(x, list):
            out.append({"p": 0, "t": 0, "ev": ""})
        else:
            out.append({"p": "?", "t": 0, "ev": ""})
    return out

def restore(e):
    kind, t = forced_kind(e), e.get("type")
    f = {"type": t if js_truthy(t) else "XIC", "addr": e.get("addr") if js_truthy(e.get("addr")) else ""}
    if f["type"] in ("LBL", "JMP"):
        f["addr"] = canon_lbl(f["addr"])
    if kind == "block":
        f["pre"] = e["pre"] if js_truthy(e.get("pre")) else 0
        if f["type"] == "MOV":
            f["src"] = "0" if ("src" not in e or e["src"] == "") else e["src"]
        if f["type"] == "CTUD":
            f["cd"] = e["cd"] if js_truthy(e.get("cd")) else ""
        for k in ("a", "b", "expr", "inMin", "inMax", "outMin", "outMax", "len", "dt", "st"):
            if k in e: f[k] = e[k]
        if f["type"] != "MOV" and "src" in e: f["src"] = e["src"]
        for k in ("ul", "out", "outs", "rst", "dn"):
            if k in e: f[k] = e[k]
        if f["type"] == "DRUM": f["steps"] = restore_steps(e.get("steps"))
    if kind == "compare":
        f["cmp"] = 0 if e.get("cmp") in (None, "") else e["cmp"]
        if f["type"] == "LIM":
            for k in ("lo", "hi"):
                f[k] = 0 if (k not in e or e[k] == "") else e[k]
        if "dt" in e: f["dt"] = e["dt"]
    return f

def operand_err(op, t, label, rule):
    v = "" if op is None else js_str(op).strip()
    if v == "": return f"{label} is empty - enter a constant or a word such as D1 or AX1."
    if is_num_lit(v):
        n = js_parse_float(v); _, lo, hi, whole = TYPES[dt_of(t)]
        if not math.isfinite(n): return f"{label} is not a number."
        if rule == "phase1":
            return "" if whole_in(v, 0, NUM_MAX) else \
                f"{label} must be a whole number from 0 to {NUM_MAX:,} (or use a D register with a Type)."
        if whole and n != int(n): return f"{label} {v} has decimals - {dt_of(t)} holds whole numbers; use REAL for decimals."
        if n < lo or n > hi: return f"{label} {v} does not fit {dt_of(t)} ({range_text(t)})."
        return ""
    a = norm(v)
    if a.startswith("D[") or a.endswith("]"):
        if not re.match(r'^D\[D[0-9]+\]$', a):
            return f'{label} "{v}" - a pointer is written D[Dn], with a D register inside the brackets (e.g. D[D5]).'
        return "" if is_ptr(a) else f"The pointer register in {a} must be D1-D{D_MAX}."
    if re.match(r'^D[0-9]+$', a):
        if not is_d(a): return f"{a} is outside D1-D{D_MAX}."
        if not d_fits(a, t): return f"{a} is too high for {dt_of(t)} - it needs two words, so the last start address is D{D_MAX - 1}."
        return ""
    if is_word_addr(a): return ""
    return (f'{label} "{v}" must be a constant or a word: D1-D{D_MAX}, AX1-AX8, AY1-AY4, '
            f'SW1-SW{SW_MAX}, T1/ACC or CT1/ACC.')

def dest_err(addr, t, label="Destination"):
    a = norm(addr)
    if a.startswith("D[") or a.endswith("]"):
        if not re.match(r'^D\[D[0-9]+\]$', a):
            return f'{label} "{a}" - a pointer is written D[Dn], with a D register inside the brackets (e.g. D[D5]).'
        return "" if is_ptr(a) else f"The pointer register in {a} must be D1-D{D_MAX}."
    if re.match(r'^D[0-9]+$', a):
        if not is_d(a): return f"{a} is outside D1-D{D_MAX}."
        if not d_fits(a, t): return f"{a} is too high for {dt_of(t)} - it needs two words, so the last start address is D{D_MAX - 1}."
        return ""
    if in_range(a, "AY", 4): return ""
    return f"{label} must be a D register (D1-D{D_MAX} or a pointer D[Dn]) or an analog output (AY1-AY4)."

def d_start_err(a, msg):
    """_dStartErr: a D-start field (COP/FLL/PACK destination, COP/UNPACK source) is D1-D4000 or a pointer D[Dn]."""
    if a.startswith("D["): return "" if is_ptr(a) else f"{a} - a pointer is written D[Dn] with Dn in D1-D{D_MAX}."
    return "" if re.match(r'^D[0-9]+$', a) and is_d(a) else msg

def len_err(v, top, what):
    return "" if whole_in("" if v is None else js_trim(js_str(v)), 1, top) else f"{what} must be a whole number from 1 to {top}."

def editor_check(f):
    typ, s = f["type"], norm(f["addr"])
    t = dt_of(f.get("dt"))
    if not s: return "Enter an address."
    if "dt" in f and typ in TYPED and not (isinstance(f["dt"], str) and f["dt"] in TYPES):
        return f'Unknown data type "{js_str(f["dt"])}".'
    has = f.__contains__
    blank = lambda k: js_trim(js_str(f[k])) == ""
    is_cy = lambda a: in_range(a, "C", 256) or in_range(a, "Y", 16)
    # ── v1.126 shift registers, drum, jumps and master control (validateFull with strict=true) ──
    if typ in ("LBL", "JMP"):
        m = re.fullmatch(r'L([0-9]+)', s)
        return "" if m and 1 <= int(m.group(1)) <= 256 else \
            f"{'A label' if typ == 'LBL' else 'JMP'} uses a label number L1-L256 (e.g. L1)."
    if typ in ("MCR", "MCRE"):
        return "" if s == "MCR" else "MCR and END MCR have no address."
    if typ in SHIFT:
        if not is_cy(s): return f"The register starts at a C or Y bit (C1-C256, Y1-Y16), not {s}."
        if not has("len"): return "Enter the number of bits."
        if not has("src") or blank("src"): return "Enter the data bit."
        x = len_err(f["len"], 256, "Number of bits")
        if x: return x
        n = int(js_number(js_str(f["len"])))
        if not bit_table(s, n): return f"{js_str(f['len'])} bits from {s} run past the end of the {'C (C256)' if s[0] == 'C' else 'Y (Y16)'} table."
        if not is_bit_addr(f["src"]): return f'Data bit must be a bit address (X1, C5, T1/DN ...), not "{js_str(f["src"])}".'
        if has("ul") and not blank("ul") and not is_cy(norm(f["ul"])):
            return f'Unload bit must be a C or Y bit (or left empty), not "{js_str(f["ul"])}".'
        return ""
    if typ == "DRUM":
        if not (re.fullmatch(r'D[0-9]+', s) and is_d(s)): return f"The step register must be a D register (D1-D{D_MAX})."
        if not has("out") or blank("out"): return "Enter the first output bit."
        if not has("outs"): return "Enter the number of outputs."
        if not has("steps"): return "A drum needs 1 to 16 steps."
        x = len_err(f["outs"], 16, "Number of outputs")
        if x: return x
        o = norm(f["out"])
        if not is_cy(o): return f'First output must be a Y or C bit, not "{js_str(f["out"])}".'
        if not bit_table(o, int(js_number(js_str(f["outs"])))):
            return f"{js_str(f['outs'])} outputs from {o} run past the end of the {'C' if o[0] == 'C' else 'Y'} table."
        if has("rst") and not blank("rst") and not is_bit_addr(f["rst"]): return "Reset must be a bit address (X1, C5 ...) or left empty."
        if has("dn") and not blank("dn") and not is_cy(norm(f["dn"])): return "Done bit must be a Y or C bit, or left empty."
        st = f["steps"]
        if not 1 <= len(st) <= 16: return "A drum needs 1 to 16 steps."
        for i, x in enumerate(st, 1):
            if not whole_in(js_str(x["p"]), 0, 65535): return f"Step {i}: output pattern must be a whole number 0-65535."
            if not whole_in(js_str(x["t"]), 0, NUM_MAX): return f"Step {i}: time must be whole milliseconds 0-{NUM_MAX:,}."
            if js_trim(x["ev"]) != "" and not is_bit_addr(x["ev"]): return f"Step {i}: event must be a bit address (X1, C5 ...) or left empty."
        return ""
    if typ in CONTACTS:
        if re.match(r'^(SW|AX|AY|D)[0-9]+$', s) or s.endswith("/ACC") or s.startswith("D["): return f"{s} is a word, not a bit - use a compare."
        return "" if is_bit_addr(s) else f"{s} is not a bit address (X, Y, C, SB, T, T/DN, CT, ...)."
    if typ in COMPARES:
        if s.startswith("D["):
            x = operand_err(s, t, "A", "typed")
            if x: return x
        elif not is_word_addr(s):
            return f"Compare reads a word: D1-D{D_MAX} (or a pointer D[Dn]), AX1-AX8, AY1-AY4, SW1-SW{SW_MAX}, T1/ACC or CT1/ACC."
        if is_d(s) and not d_fits(s, t): return f"{s} is too high for {t} - it needs two words."
        typed = any(isinstance(o, str) and is_d_op(o) for o in (s, f.get("cmp"), f.get("lo"), f.get("hi")))
        rule = "typed" if typed else "phase1"
        if typ == "LIM":
            for k, label in (("lo", "Low"), ("hi", "High")):
                if has(k):
                    x = operand_err(f[k], t, label, rule)
                    if x: return x
        elif has("cmp"):
            return operand_err(f["cmp"], t, "B (comparand)", rule)
        return ""
    if typ in ("OTE", "OTL", "OTU"):
        if re.match(r'^SB[0-9]+$', s):
            return "" if typ == "OTU" and int(s[2:]) in (9, 10, 11) else "System bits are read-only (only OTU on SB9-SB11)."
        if re.match(r'^SW[0-9]+$', s): return "System words cannot be driven by a coil."
        return "" if in_range(s, "Y", 16) or in_range(s, "C", 256) or in_range(s, "X", 16) else \
            f"{s} cannot be driven by a coil - use Y1-Y16 or C1-C256."
    pre_err = (f"Preset must be a whole number from 0 to {NUM_MAX:,}."
               if has("pre") and not whole_in(js_str(f["pre"]).strip(), 0, NUM_MAX) else "")
    if typ in TIMERS: return pre_err if in_range(s, "T", 256) else "Timers use T1-T256."
    if typ in COUNTERS:
        if not in_range(s, "CT", 256): return "Counters use CT1-CT256."
        if typ == "CTUD" and not is_bit_addr(f.get("cd") or ""): return "CTUD needs a bit address for its count-down input (e.g. X2)."
        return pre_err
    if typ == "RES":
        return "" if in_range(s, "T", 256) or in_range(s, "CT", 256) else "RES targets a timer (T1-T256) or counter (CT1-CT256)."
    if typ == "MOV":
        st = dt_of(f.get("st"))
        if re.match(r'^SW[0-9]+$', s):
            if s != "SW17": return "System words are read-only. Only SW17 can be cleared, by moving 0."
            src = "0" if f.get("src") is None else js_str(f["src"]).strip()
            return "" if is_num_lit(src) and js_number(src) == 0 else f"{s} can only be cleared - set the MOV source to 0."
        x = dest_err(s, t, "MOV destination")
        if x: return x
        if has("src"):
            src = js_str(f["src"]).strip()
            if is_num_lit(src):
                if is_d_op(s): return operand_err(src, t, "Source", "typed")
                if not math.isfinite(js_parse_float(src)): return "Source is not a number."
            else:
                return operand_err(src, st, "Source", "typed")
        return ""
    if typ in MATH2:
        x = dest_err(s, t)
        for k in ("a", "b"):
            if not x and has(k): x = operand_err(f[k], t, k.upper(), "typed")
        if not x and typ in ("DIV", "MOD") and has("b") and is_num_lit(f["b"]) and js_parse_float(f["b"]) == 0:
            x = f"B is 0 - {typ} by zero would fault on every scan."
        return x
    if typ in INCDEC: return dest_err(s, t)
    if typ == "CPT":
        x = dest_err(s, t)
        if x or not has("expr"): return x
        if not js_str(f["expr"]).strip(): return "Enter an expression, e.g. AX1 * 100 / 4095."
        bad, ast = cpt_check(f["expr"])
        if bad: return bad
        plain = re.sub(r'D\s*\[\s*D[0-9]+\s*\]', '', js_str(f["expr"]), flags=re.I)   # pointer terms are checked at run time
        for m in re.finditer(r'\bD[0-9]+\b', plain, re.I | re.A):
            if not d_fits(m.group(0), t):
                return f"{m.group(0).upper()} is the last register - a {t} needs two words ({m.group(0).upper()} and the next)."
        if t != "REAL" and cpt_has_decimal(ast):
            return f"The expression has a decimal number - {t} works in whole numbers. Use REAL, or scale by whole numbers."
        return ""
    if typ == "SCL":
        x = dest_err(s, t)
        if x: return x
        if has("src"):
            x = operand_err(f["src"], t, "Input", "typed")
            if x: return x
        for k in ("inMin", "inMax", "outMin", "outMax"):
            if has(k):
                v = js_str(f[k]).strip()
                if not is_num_lit(v) or not math.isfinite(js_parse_float(v)): return f'Scale limits must be numbers ({k} is "{v}").'
        if has("inMin") and has("inMax") and js_parse_float(f["inMin"]) == js_parse_float(f["inMax"]):
            return "Input min and max are equal - the scale would divide by zero."
        return ""
    if typ == "COP":
        x = d_start_err(s, f"COP copies into D registers - the destination start must be D1-D{D_MAX} or a pointer D[Dn].")
        if x: return x
        if has("src"):
            sa = norm(f["src"])
            if sa.startswith("D["):
                x = d_start_err(sa, "")
                if x: return x
            elif not re.match(r'^(D|AX|AY|SW)[0-9]+$', sa): return "COP source start must be a D, AX, AY or SW address, or a pointer D[Dn]."
        if has("len"):
            x = len_err(f["len"], D_MAX, "Length")
            if x: return x
            n = int(js_number(js_str(f["len"])))
            if not is_ptr(s) and not word_table(s, n): return f"{s} + {n} words runs past D{D_MAX}."
            if has("src"):
                sa = norm(f["src"])
                if not is_ptr(sa) and not word_table(sa, n): return f"{n} words from {sa} runs past the end of that table."
        return ""
    if typ == "FLL":
        x = d_start_err(s, f"FLL fills D registers - the destination start must be D1-D{D_MAX} or a pointer D[Dn].")
        if x: return x
        if has("len"):
            x = len_err(f["len"], D_MAX, "Length")
            if x: return x
            if not is_ptr(s) and d_num(s) + js_number(js_str(f["len"])) * TYPES[t][0] - 1 > D_MAX: return f"{js_str(f['len'])} x {t} from {s} runs past D{D_MAX}."
        if has("src"): return operand_err(f["src"], t, "Fill value", "typed")
        return ""
    if typ == "PACK":
        x = d_start_err(s, f"PACK writes one D register - the destination must be D1-D{D_MAX} or a pointer D[Dn].")
        if x: return x
        if has("len"):
            x = len_err(f["len"], 16, "Number of bits")
            if x: return x
            if has("src") and not bit_table(f["src"], int(js_number(js_str(f["len"])))):
                return "First bit must be X, Y or C, and the bits from it must stay inside the table (X/Y 1-16, C 1-256)."
        return ""
    if typ == "UNPACK":
        if has("len"):
            x = len_err(f["len"], 16, "Number of bits")
            if x: return x
            if not bit_table(s, int(js_number(js_str(f["len"])))) or s.startswith("X"):
                return "First destination bit must be Y or C, and the bits from it must stay inside the table (Y 1-16, C 1-256)."
        elif not re.match(r'^(Y|C)[0-9]+$', s):
            return "First destination bit must be a Y or C address."
        if has("src"):
            sa = norm(f["src"])
            if sa.startswith("D["):
                x = d_start_err(sa, "")
                if x: return x
            elif not (is_d(sa) or word_table(sa, 1)): return "Source word must be D, AX, AY or SW, or a pointer D[Dn]."
        return ""
    return ""

def good_id(v):
    """Ids must be positive whole numbers: the editor replaces anything else on import."""
    return isinstance(v, int) and not isinstance(v, bool) and v > 0

# ── This validator's own checks (stricter than the editor where a mistake would load but misbehave) ──
def common(e, w):
    if not good_id(e.get("id")):
        err(w, "every element needs a positive whole-number 'id'")
    else:
        ids.append(e["id"])
    if e.get("comment"):
        warn(w, "element 'comment' is the legacy format; put address comments in the top-level 'comments' map")

def word_range(a):
    """Largest value the word at address a can hold, for out-of-range warnings."""
    a = a.upper()
    if ANALOG.match(a): return 4095
    if a.startswith("SW"): return 65535
    return NUM_MAX                       # T/ACC (ms) and CT/ACC (count)

def check_dt(e, w, t):
    if "dt" in e and t in TYPED and not (isinstance(e["dt"], str) and e["dt"] in TYPES):
        err(w, f"'dt' must be one of INT, UINT, WORD, DINT, REAL (got {e['dt']!r})")
    if t == "MOV" and "st" in e and not (isinstance(e["st"], str) and e["st"] in TYPES):
        warn(w, f"'st' {e['st']!r} is not a data type; it is read as INT")

def check_upper(e, w):
    for k in ("addr", "src", "a", "b", "ul", "out", "rst", "dn"):
        v = e.get(k)
        if isinstance(v, str) and not is_num_lit(v) and v != v.strip().upper():
            warn(w, f"write the address in '{k}' in upper case ({(norm(v) if is_ptr(v) else v.strip().upper())!r})")
        elif isinstance(v, str) and is_ptr(v) and v != norm(v):
            warn(w, f"write the pointer in '{k}' as {norm(v)!r} (no spaces or leading zeros)")

def check_spaces(e, w):
    """An address with a space inside ('X 1', 'D 5') is refused by the editor and never works.
    Pointers are the exception - D[ D5 ] is read as D[D5]."""
    for k in ("addr", "src", "a", "b", "cmp", "lo", "hi", "cd", "ul", "out", "rst", "dn"):
        v = e.get(k)
        if isinstance(v, str) and not is_num_lit(v) and not is_ptr(v) and _JS_WS.search(js_trim(v)):
            err(w, f"'{k}' {v!r} has a space inside the address; write {_JS_WS.sub('', v).upper()!r}")

def note_ptrs(e, w):
    """Remember every pointer register, to warn when a two-word value is written over one."""
    for k in ("addr", "src", "a", "b", "cmp", "lo", "hi"):
        v = e.get(k)
        if isinstance(v, str) and is_ptr(v):
            ptr_regs.setdefault(ptr_num(v), w)
    if isinstance(e.get("expr"), str):
        for m in re.finditer(r'D\s*\[\s*D([0-9]+)\s*\]', e["expr"], re.I):
            if 1 <= int(m.group(1)) <= D_MAX: ptr_regs.setdefault(int(m.group(1)), w)

def check_compare_operand(e, w, field, a, typed):
    v = e.get(field)
    if field not in e or v is None or v == "":
        err(w, f"needs '{field}': a number, or a word address such as \"D20\"" +
               (" (a missing limit is treated as 0)" if field in ("lo", "hi") else ""))
        return
    if isinstance(v, str) and is_num_lit(v):
        warn(w, f"'{field}' {v!r} is a numeric string; write constants as JSON numbers")
    if not typed and is_num(v) and v == int(v) and 0 <= v <= NUM_MAX and v > word_range(a):
        if field == "cmp":
            warn(w, f"'cmp' {v} is above the largest value {a} can hold ({word_range(a)}), so the result never changes")
        elif field == "lo":
            warn(w, f"LIM lo {v} is above the largest value {a} can hold ({word_range(a)}), so the test is never true")

def check_input(e, w):
    """Contacts and compares may sit before the output or inside branches."""
    common(e, w)
    k, t, a = e.get("kind"), e.get("type"), str(e.get("addr", ""))
    if k == "contact" and t == "LBL":
        label_style(e, w)                 # address checked by the editor rule, position by check_structure()
        return
    if k == "contact":
        if t not in CONTACTS:
            err(w, f"contact type must be XIC, XIO, P (rising edge) or N (falling edge), not {t!r}")
        if a.upper().startswith(("AX", "AY", "SW")) or a.upper().endswith("/ACC") or D_ADDR.match(a.upper()) or norm(a).startswith("D["):
            err(w, f"contacts read bits; {a} is a word, so use a compare element")
        elif out_of_range_c(a):
            err(w, f"{a} is outside C1-C256: the editor refuses it (it would read and write, but never "
                   f"appear on the I/O panel)")
        elif not BIT_ADDR.match(a):
            err(w, f"invalid contact address {a!r}")
    elif k == "compare":
        if t not in COMPARES:
            err(w, f"compare type must be GRT/LES/GEQ/LEQ/EQU/NEQ/LIM, not {t!r}")
        check_dt(e, w, t)
        if not (WORD.match(a) or is_ptr(a)):
            err(w, f"compare address must be D1-D4000, a pointer D[Dn], AX1-AX8, AY1-AY4, SW1-SW19, T1/ACC or CT1/ACC (got {a!r})")
        fields = ("lo", "hi") if t == "LIM" else ("cmp",)
        typed = any(isinstance(o, str) and is_d_op(o) for o in [a] + [e.get(f) for f in fields])
        for f in fields:
            check_compare_operand(e, w, f, a, typed)
        if "dt" in e and not typed and isinstance(e["dt"], str) and e["dt"] in TYPES:
            warn(w, "'dt' only matters when the compare reads a D register; it is ignored here")
        if t == "LIM":
            lo, hi = e.get("lo"), e.get("hi")
            if is_num(lo) and is_num(hi) and lo > hi:
                warn(w, f"LIM lo {lo} > hi {hi}: the test is true OUTSIDE {hi}..{lo} - "
                        f"intended for a wrap-around band, otherwise swap them")
    elif k == "parallel":
        err(w, "parallel group nested inside a branch: it evaluates correctly but the rung is sized from "
               "top-level groups only, so the nested rows draw over the rungs below. Flatten it into more branches")
    else:
        err(w, f"only contacts and compares may be used as inputs (found kind={k!r})")

def note_d_dest(e, w):
    t = e.get("type")
    dt = dt_of(e.get("dt"))
    a = norm(e.get("addr"))
    if not is_d(a) or t not in TYPED or t in COMPARES: return
    width = TYPES[dt][0]
    if t == "FLL":
        n = js_number(js_str(e.get("len", 1)))
        width *= int(n) if math.isfinite(n) and n == int(n) and n >= 1 else 1
    d_dest.append((d_num(a), d_num(a) + width - 1, dt, w, t))

def check_word_block(e, w, t, a, edge):
    """Phase 2a word instructions: hints the editor does not give."""
    def missing(field, effect):
        if field not in e:
            warn(w, f"{t} has no '{field}': {effect}")
    if t in MATH2:
        missing("a", "it is read as 0"); missing("b", "it is read as 0" + (", so it faults on every scan" if t in ("DIV", "MOD") else ""))
    elif t == "CPT":
        missing("expr", "the expression is empty, so it raises fault 3 on every scan")
    elif t == "SCL":
        missing("src", "the input is read as 0")
        for f in ("inMin", "inMax", "outMin", "outMax"):
            missing(f, "the result is invalid, so it raises fault 3 on every scan")
    elif t in DATA:
        missing("len", "the length is 0, so it raises range fault 4 on every scan")
        missing("src", "the source is " + ("read as 0" if t == "FLL" else "missing, so it raises range fault 4 on every scan"))
    for f in PHASE2_FIELDS:
        if f in e and f not in FIELDS.get(t, ()):
            warn(w, f"'{f}' is not used by {t}; the editor drops it")
    # Accumulating instructions run on every scan their rung is true.
    reads_self = t in INCDEC or (t in MATH2 and norm(a) in (norm(e.get("a")), norm(e.get("b")))) or \
        (t == "CPT" and is_d(a) and re.search(rf'\b{norm(a)}\b', js_str(e.get("expr", "")), re.I | re.A))
    if reads_self and not edge:
        warn(w, f"{t} {a} changes its own value on EVERY scan the rung is true (10 times a second); "
                f"put a P contact on the rung for one step per event")

def check_output(e, w, edge=False):
    common(e, w)
    k, t, a = e.get("kind"), e.get("type"), str(e.get("addr", ""))
    if k == "output":
        if t not in ("OTE", "OTL", "OTU"):
            err(w, f"output type must be OTE/OTL/OTU, not {t!r}")
        if a.upper().startswith("X"):
            err(w, f"coil writes input {a} — a connected scene overwrites every X each scan, so the rung does nothing; write a Y or C instead")
        elif a.upper().startswith("SB"):
            if not (t == "OTU" and SB_CLEAR.match(a.upper())):
                err(w, f"system bits are read-only; only OTU on SB9-SB11 is allowed (it clears an error flag), got {t} {a}")
        elif a.upper().startswith(("AX", "AY", "SW")) or D_ADDR.match(a.upper()):
            err(w, f"coils cannot write word {a}; use a MOV block")
        elif out_of_range_c(a):
            err(w, f"{a} is outside C1-C256: the editor refuses it (it would read and write, but never "
                   f"appear on the I/O panel)")
        elif not OUT_ADDR.match(a):
            err(w, f"coils may only write Y1-Y16 or C1-C256 (got {a!r})")
        elif t == "OTE":
            bit_writes.append((set(bit_list(a, 1)), "OTE", w))
    elif k == "block" and t in SEQ + FLOW:
        check_phase3(e, w, t, a)
    elif k == "block":
        if t in TIMERS:
            if not TIMER.match(a): err(w, f"timer address must be T1-T256 (got {a!r})")
            if not isinstance(e.get("pre"), int) or e["pre"] <= 0:
                err(w, "timer needs a positive integer 'pre' in milliseconds")
            elif e["pre"] > NUM_MAX:
                err(w, f"timer 'pre' above {NUM_MAX:,} ms; the editor refuses it")
        elif t in COUNTERS:
            if not COUNTER.match(a): err(w, f"counter address must be CT1-CT256 (got {a!r})")
            if not isinstance(e.get("pre"), int) or e["pre"] < 0:
                err(w, "counter needs a non-negative integer 'pre' (the target count)")
            elif e["pre"] > NUM_MAX:
                err(w, f"counter 'pre' above {NUM_MAX:,}; the editor refuses it")
            if t == "CTUD":
                cd = str(e.get("cd", ""))
                if not cd:
                    err(w, "CTUD needs a 'cd' string: the bit address whose OFF->ON counts down, e.g. \"X2\"")
                elif not BIT_ADDR.match(cd.upper()):
                    err(w, f"CTUD 'cd' must be a bit address such as X2 or C101 (got {cd!r})")
            if t in ("CTU", "CTUD"):
                ctu.add(a)                # CTUD also counts up, so a CTD on its address is not orphaned
            elif t == "CTD":
                ctd.add(a)
        elif t == "RES":
            if not (TIMER.match(a) or COUNTER.match(a)):
                err(w, f"RES address must be a timer (T1) or counter (CT1), got {a!r}")
        elif t == "MOV":
            check_dt(e, w, t)
            src = "0" if e.get("src") is None else js_str(e.get("src")).strip()
            if "src" in e and src == "":
                warn(w, "empty MOV 'src' is loaded as \"0\"; write \"0\" explicitly")
                src = "0"
            if a.upper() == "SW17":
                # The only system word a program may write: clearing the last error code.
                if not (is_num_lit(src) and js_number(src) == 0):
                    err(w, "MOV into SW17 only clears the error code; 'src' must be \"0\"")
            elif not (AY_REG.match(a.upper()) or D_ADDR.match(a.upper()) or is_ptr(a)):
                err(w, f"MOV destination must be D1-D4000, a pointer D[Dn] or AY1-AY4 (got {a!r})")
            if "src" not in e:
                warn(w, "MOV has no 'src', so it loads as \"0\"; give a constant such as \"2048\" or a word such as \"AX1\" or \"D10\"")
            elif not (WORD.match(src.upper()) or is_ptr(src)):
                if is_num_lit(src):
                    v = js_parse_float(src)
                    if AY_REG.match(a.upper()) and math.isfinite(v) and not 0 <= v <= 4095:
                        warn(w, f"MOV source {src} is clamped to 0-4095")
                else:
                    err(w, f"MOV src {src!r} is not a number or a readable word (D, D[Dn], AX, AY, SW, T1/ACC, CT1/ACC)")
            if "st" in e and not (D_ADDR.match(src.upper()) or is_ptr(src)):
                warn(w, "'st' (source type) only matters when 'src' is a D register; it is ignored here")
            note_d_dest(e, w)
        elif t in WORD_BLOCKS:
            check_dt(e, w, t)
            if "dt" in e and t in ("COP", "PACK", "UNPACK"):
                warn(w, f"{t} copies raw 16-bit words or bits; 'dt' is ignored")
            check_word_block(e, w, t, a, edge)
            note_d_dest(e, w)
        else:
            err(w, f"block type must be TON/TOF/RTO/CTU/CTD/CTUD/RES/MOV, a math/data block "
                   f"({'/'.join(WORD_BLOCKS)}) or {'/'.join(SEQ + FLOW)}, not {t!r}")
    else:
        err(w, f"the last element must be an output coil or a block (found kind={k!r})")

def bit_list(start, n):
    """bitRange(): the bit addresses from start, or [] when they leave the table."""
    m = re.match(r'^(X|Y|C)([0-9]+)$', norm(start))
    if not m or not isinstance(n, int) or n < 1 or not bit_table(start, n): return []
    return [f"{m.group(1)}{int(m.group(2)) + i}" for i in range(n)]

def whole(v):
    """A whole number field as the editor reads it (+v), or None."""
    n = js_number(js_str(v)) if v is not None else math.nan
    return int(n) if math.isfinite(n) and n == int(n) else None

def label_style(e, w):
    a = e.get("addr")
    c = canon_lbl(a)
    if isinstance(a, str) and isinstance(c, str) and js_trim(a).upper() != c:
        warn(w, f"write the label as {c!r} (it is stored that way on import)")

def check_phase3(e, w, t, a):
    """v1.126 hints the editor does not give. The editor's own rules run in editor_agrees()."""
    if t == "JMP":
        label_style(e, w)
    if t in SHIFT:
        bits = bit_list(a, whole(e.get("len")))
        if bits:
            bit_writes.append((set(bits), f"{t} {norm(a)} ({len(bits)} bits)", w))
        ul = bit_list(e.get("ul"), 1) if OUT_ADDR.match(norm(e.get("ul"))) else []
        if ul:
            ul = ul[0]
            bit_writes.append(({ul}, f"{t} unload bit", w))
            if ul in bits:
                warn(w, f"unload bit {ul} is inside the register {bits[0]}-{bits[-1]}; the shift overwrites it")
    elif t == "DRUM":
        if is_d(a):
            d_dest.append((d_num(a), d_num(a), "INT", w, "DRUM"))
        n = whole(e.get("outs"))
        bits = bit_list(e.get("out"), n)
        if bits:
            bit_writes.append((set(bits), f"DRUM outputs {bits[0]}-{bits[-1]}", w))
        dn = bit_list(e.get("dn"), 1) if OUT_ADDR.match(norm(e.get("dn"))) else []
        if dn:
            dn = dn[0]
            bit_writes.append(({dn}, "DRUM done bit", w))
            if dn in bits:
                warn(w, f"done bit {dn} is also one of the drum outputs {bits[0]}-{bits[-1]}")
        steps = e.get("steps")
        if isinstance(steps, list) and bits:
            for i, x in enumerate(steps, 1):
                if not isinstance(x, dict): continue
                p = whole(x.get("p", 0))
                if p is not None and 0 <= p <= 65535 and p >> len(bits):
                    warn(w, f"step {i} pattern {p} has bits above output {len(bits)}; they are ignored")
                tm, ev = whole(x.get("t", 0)), x.get("ev", "")
                if tm == 0 and not (isinstance(ev, str) and ev.strip()):
                    warn(w, f"step {i} has no time and no event, so it lasts one scan")

def check_bit_writes():
    """A bit written by a shift register or drum and also by an OTE (or a second register or drum)."""
    for i, (b1, n1, w1) in enumerate(bit_writes):
        for b2, n2, w2 in bit_writes[i + 1:]:
            if (n1 == "OTE" and n2 == "OTE") or w1 == w2: continue      # same element: warned already
            both = sorted(b1 & b2, key=lambda x: (x[0], int(x[1:])))
            if both:
                what = "an OTE writes it on every scan" if "OTE" in (n1, n2) else "the last one scanned wins"
                warn("file", f"{', '.join(both[:4])}{' ...' if len(both) > 4 else ''} written by {n1} ({w1}) "
                             f"and by {n2} ({w2}); {what}")

def check_structure(prog):
    """programStructure(): positions, labels, jumps and MCR zones (v1.126)."""
    rungs = []
    for r in prog:
        els = r.get("elements") if isinstance(r, dict) else None
        rungs.append([with_kind(e) for e in els if isinstance(e, dict)] if isinstance(els, list) else [])
    def typ(e):
        if e.get("kind") == "parallel": return None
        return e["type"] if js_truthy(e.get("type")) else "XIC"
    def name(t): return "END MCR" if t == "MCRE" else t
    def key(e):
        a = e.get("addr") if js_truthy(e.get("addr")) else ""
        if isinstance(a, str) and is_ptr(a): a = norm(a)
        return js_trim(js_str(canon_lbl(a))).upper()
    def branches(e):
        return [br for br in e.get("branches", []) if isinstance(br, list)] if isinstance(e.get("branches"), list) else []
    rw = lambda i: f"rung {i:04d}"
    for i, els in enumerate(rungs):
        for k, e in enumerate(els):
            last, t = k == len(els) - 1, typ(e)
            if t in PHASE3_OUT and not last:
                err(rw(i), f"{name(t)} must be the last instruction of its rung (output position)")
            if t == "LBL" and last:
                err(rw(i), "a rung cannot end with a LBL - it needs an output after it")
            if e.get("kind") == "parallel":
                def walk(be):
                    if not isinstance(be, dict): return
                    if be.get("kind") == "parallel":
                        for b2 in branches(be):
                            for x in b2: walk(x)
                        return
                    if typ(be) in PHASE3_OUT:
                        err(rw(i), f"{name(typ(be))} cannot sit inside a parallel branch")
                for br in branches(e):
                    for be in br: walk(be)
        if any(typ(e) == "MCRE" for e in els) and len(els) > 1:
            err(rw(i), "END MCR goes on a rung of its own, with no contacts")
    label_at, zone_of, zone, open_ = {}, [], 0, None
    for i, els in enumerate(rungs):
        if any(isinstance(be, dict) and typ(be) == "LBL"
               for e in els if e.get("kind") == "parallel" for br in branches(e) for be in br):
            err(rw(i), "a LBL cannot sit inside a parallel branch - put it at the start of the rung")
        for e in els:
            if typ(e) == "LBL":
                L = key(e)
                if L in label_at:
                    err(rw(i), f"label {L} is used twice (rungs {label_at[L]:04d} and {i:04d})")
                else:
                    label_at[L] = i
        has_m, has_e = any(typ(e) == "MCR" for e in els), any(typ(e) == "MCRE" for e in els)
        zone_of.append(open_ if open_ is not None else 0)
        if has_m:
            if open_ is not None:
                err(rw(i), "MCR zones cannot be nested - close the zone above with END MCR first")
            zone += 1; open_ = zone
        if has_e:
            if open_ is None:
                err(rw(i), "END MCR has no MCR above it")
            else:
                zone_of[i] = open_
            open_ = None
    if open_ is not None:
        warn(rw(len(rungs) - 1 if rungs else 0), "an MCR zone is never closed - add an END MCR rung "
             "(until then the zone runs to the end of the program)")
    for i, els in enumerate(rungs):
        for e in els:
            if typ(e) != "JMP": continue
            L = key(e)
            j = label_at.get(L)
            if j is None:
                err(rw(i), f"JMP {L} has no matching LBL {L} (at run time it is ignored and sets fault code 4)")
            elif j <= i:
                err(rw(i), f"JMP {L} jumps backwards (LBL {L} is on rung {j:04d}) - jumps only go forward")
            elif zone_of[i] != zone_of[j]:
                err(rw(i), f"JMP {L} jumps into or out of an MCR zone - keep the jump and its label in the same zone")

def editor_agrees(e, w, before):
    """Anything the editor's own check refuses is an error, even if no rule above caught it."""
    if e.get("kind") == "parallel": return
    check_upper(e, w)
    check_spaces(e, w)
    note_ptrs(e, w)
    if len(errors) > before: return
    msg = editor_check(restore(e))
    if msg:
        err(w, f"the editor refuses this element: {msg}")

def check_rung(r, n, w):
    if not good_id(r.get("id")):
        err(w, "rung needs a positive whole-number 'id'")
    else:
        rung_ids.append(r["id"])
    if r.get("rn") != n:
        warn(w, f"'rn' is {r.get('rn')!r}; the simulator renumbers on import, but {n} keeps the file readable")
    els = r.get("elements")
    if not isinstance(els, list):
        err(w, "missing 'elements' array (the import would fail silently)"); return
    els = [with_kind(e) if isinstance(e, dict) else e for e in els]
    if not els:
        warn(w, "empty rung: it scans harmlessly, but its comment is NOT displayed; remove it or add logic")
        return
    kinds = [e.get("kind") for e in els]
    if not any(k in ("output", "block") for k in kinds):
        err(w, "rung has no output: it needs at least one coil or block")
    if kinds[-1] not in ("output", "block"):
        err(w, "rung ends with a contact or compare, which drives nothing; "
               "the last element must be a coil or block")
    edge = False                          # a P/N contact to the left makes a block act once per event
    for j, e in enumerate(els[:-1]):
        ew = f"{w} element[{j}]"
        before = len(errors)
        if e.get("kind") in ("output", "block"):
            # Legal and used by the shipped example programs: coils in series all fire,
            # and any contact after one gates only the outputs that follow it.
            check_output(e, ew, edge)
            editor_agrees(e, ew, before)
            continue
        if e.get("kind") == "parallel":
            common(e, ew)
            br = e.get("branches", [])
            if len(br) == 1:
                warn(ew, "single-branch parallel group: it loads and behaves as that branch, but the editor "
                         "expects 2+. Use a plain series contact instead")
            elif not br:
                err(ew, "parallel group has no branches")
            for b, branch in enumerate(br):
                if not branch: err(ew, f"branch {b} is empty")
                for c, be in enumerate(branch):
                    bw, bb = f"{ew} branch{b}[{c}]", len(errors)
                    check_input(be, bw)
                    editor_agrees(be, bw, bb)
                    edge = edge or be.get("type") in ("P", "N")
        else:
            check_input(e, ew)
            editor_agrees(e, ew, before)
            edge = edge or e.get("type") in ("P", "N")
    before = len(errors)
    check_output(els[-1], f"{w} element[{len(els)-1}]", edge)
    editor_agrees(els[-1], f"{w} element[{len(els)-1}]", before)

def check_d_overlap():
    """DINT and REAL use two words (Dn and Dn+1): warn when typed destinations overlap."""
    seen = sorted(d_dest)
    for i, (a0, a1, at, aw, aty) in enumerate(seen):
        for b0, b1, bt, bw, bty in seen[i + 1:]:
            if b0 > a1: break
            if a0 == b0 and a1 == b1 and at == bt: continue
            warn("file", f"D{a0}..D{a1} ({aty} {at}, {aw}) overlaps D{b0}..D{b1} ({bty} {bt}, {bw}); "
                         f"DINT and REAL take two words, so give each value its own registers")
    for p, pw in sorted(ptr_regs.items()):
        for a0, a1, at, aw, aty in seen:
            if a0 <= p <= a1 and TYPES[at][0] == 2:
                warn("file", f"D{p} is a pointer register (D[D{p}], {pw}) but {aw} writes {at} into D{a0}..D{a1}; "
                             f"a pointer is read as INT, so it would point somewhere unexpected")

def check_dregs(d):
    reg, fmt = d.get("dregs"), d.get("dfmt")
    if reg is not None:
        if not isinstance(reg, dict):
            err("dregs", "'dregs' must be an object of D address -> raw word 0-65535")
        else:
            for k, v in reg.items():
                if not D_ADDR.match(k):
                    err("dregs", f"key {k!r} must be written as an upper-case D address D1-D4000 (keys that are not D1-D4000 are ignored)")
                elif not (is_num(v) and v == int(v) and 0 <= v <= 65535):
                    err("dregs", f"{k} = {v!r}: values are raw unsigned 16-bit words, whole numbers 0-65535 "
                                 f"(INT -1 is 65535; DINT and REAL take two words, low word first)")
    if fmt is not None:
        if not isinstance(fmt, dict):
            err("dfmt", "'dfmt' must be an object of D address -> display format")
        else:
            for k, v in fmt.items():
                if not D_ADDR.match(k):
                    err("dfmt", f"key {k!r} must be written as an upper-case D address D1-D4000 (keys that are not D1-D4000 are ignored)")
                elif v not in D_FORMATS:
                    err("dfmt", f"{k} format {v!r} must be one of {', '.join(D_FORMATS)} (others are ignored)")

def main(path):
    with open(path, encoding="utf-8") as f:
        d = json.load(f)
    if isinstance(d, list):
        warn("file", "bare rung array accepted by the importer; the wrapped v2 object is preferred")
        prog, d = d, {"program": d}
    else:
        prog = d.get("program")
        if not isinstance(prog, list):
            err("file", "missing top-level 'program' array"); prog = []
        if d.get("version") != 2:
            warn("file", "use \"version\": 2 (current export format)")
    for n, r in enumerate(prog):
        check_rung(r, n, f"rung {n:04d}")
    check_structure(prog)
    cm = d.get("comments")
    if cm is None:
        warn("file", "no top-level 'comments' map; addresses will show no comments")
    elif not isinstance(cm, dict):
        err("file", "'comments' must be an object of address -> text")
    else:
        for k, v in cm.items():
            if k != k.upper():
                err("comments", f"key {k!r} must be upper case")
            elif re.fullmatch(rf'L{N256}', k):
                warn("comments", f"key {k!r}: labels show no address comment on the ladder; describe the jump in the rung comment")
            elif not ANY_ADDR.match(k) and not out_of_range_c(k):
                err("comments", f"key {k!r} must be an address such as X1, C101, T1, T1/DN, AX1, SB3, SW5, D10")
            if not isinstance(v, str):
                err("comments", f"comment for {k} must be a string")
    check_dregs(d)
    check_d_overlap()
    check_bit_writes()
    for a in sorted(ctd - ctu):
        warn("file", f"{a} has CTD but no CTU; CTD cannot count below 0, so it will never change")
    rdup = sorted({i for i in rung_ids if rung_ids.count(i) > 1})
    if rdup:
        err("file", f"duplicate rung ids: {rdup}")
    dup = sorted({i for i in ids if ids.count(i) > 1})
    if dup:
        err("file", f"duplicate element ids: {dup}")
    for m in warnings: print("  warning -", m)
    if errors:
        print(f"FAILED - {len(errors)} problem(s):")
        for m in errors: print("  -", m)
        sys.exit(1)
    print(f"OK - {len(prog)} rungs, {len(ids)} elements, ids unique"
          + (f", {len(warnings)} warning(s)" if warnings else ""))

if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit("Usage: python3 acc-validate-program.py <program.json>")
    main(sys.argv[1])
```

### 10.3 Testing in the simulator

1. Import the file (ladder: **📂 LOAD → ⬆ Import .json**; ST: **ST** mode → **Import .st**).
2. For ST, fix any red-highlighted lines. RUN is refused until the program compiles.
3. In STOP mode with no scene connected, toggle inputs on the **X** tab, drag analog inputs on the **AN** tab, and press **⏭ STEP** to execute one scan at a time.
4. Press **F5** to run. Watch power flow (ladder) or the **Live Values** column (ST). Check timers and counters on the **T** and **CT** tabs, data registers on the **D** tab (pick `DINT` or `REAL` format for two-word values), and system bits and words on the **SYS** tab — `SB12` and `SW17`/`SW18` show any math error and the rung that caused it.
5. After an import, read the status bar: v1.124 and later report any element that fails the editor's checks, with its rung (v1.126 adds the jump, label and MCR checks). For a pointer, the block shows where it points (`D[D2]→D101`); `→?` means it is invalid right now. A skipped rung shows `SKIPPED (JMP L1)`, a zone rung with its MCR off shows `MCR OFF`, and a drum shows `STEP 2` and `2/6` and its time in step.
6. Click **CONNECT**, launch the matching scene, and run the full sequence. Test Stop and E-stop at every step.

### 10.4 Online editing while testing (v1.127)

Online editing changes nothing about the programs an AI writes: the ladder JSON and `.st` formats, the instruction set and the validator are the same as in v1.126. It only affects how a change is tried on a running scene.

- **To try a small change without stopping the scene,** edit in RUN (or press **✎ EDIT**; in ST, just type). The running program keeps scanning until **ACCEPT**, which checks the edit (ladder element and program checks; ST compile) and swaps it in between two scans. **CANCEL** discards it.
- **Memory is not reset by an accept.** Bits, timers, counters, D registers and system flags keep their values, and the first-scan bit `SB3` does not come on again — an `XIC SB3` initialisation rung does not re-run. Ladder edge memory and drum step time carry over for an element that keeps its type.
- **A removed or readdressed coil leaves its output ON.** If the running program wrote `Y1` and the new one never writes it, `Y1` stays in its last state. The accept dialog lists these outputs. This is real controller behaviour, not a fault in the program.
- **ST variables keep their values,** matched by name and type, and so do function-block instances. Initializers in `VAR` (`count : INT := 10;`) are **not** re-applied; only a new variable, or one whose type changed, starts from its initial value.
- **For a clean test of a revised file, import it** (Section 9) rather than pasting the change in as an online edit: the import resets memory and starts from a first scan. LOAD, Import and CLEAR are refused while an online edit is pending, and SAVE or export stores the running program, not the pending edit — accept or cancel first.

---

## 11. Prompt template to give an AI

Copy this, fill in the brackets, and send it together with this guide:

```
Read https://accautomation.ca/simulator/acc-ai-guide.md (or the attached copy) and follow it exactly.
Using that guide,
create a [ladder logic JSON file / Structured Text .st file] for the ACC PLC Simulator.

Scene: [Conveyor / Tank Fill Station / Traffic Light / other]
Scene address offset: [none / X+n Y+n — only if several scenes are connected at once]

I/O:
- X1 = [description] (N.O. or N.C.)
- X2 = [description] (N.O. or N.C.)
- Y1 = [description]
- AX1 = [description, what 0 and 4095 mean] (if analog)
- AY1 = [description, what 0 and 4095 mean] (if analog)
- Values to calculate or keep: [e.g. level in litres, batch total, setpoint] (if any — these become D registers)

Sequence of operation:
1. [what happens first]
2. [what happens next]
3. [what stops the machine, and what happens on Stop / E-stop]

Requirements:
- Follow the file format, address ranges and scan rules in the guide exactly.
- Use the version 2 JSON format with a top-level "comments" map.
- Comment every rung and every address used.
- Explain the rung order and any interlocks after the file.
- Check the result against the Section 10 checklist before giving it to me.
```

---

## 12. Common mistakes and how to avoid them

| Mistake | Result | Fix |
|---|---|---|
| Stop button programmed with XIO | Machine never starts (the N.C. input is normally ON) | Use XIC for N.C. field devices |
| One-shot rungs in the wrong order | Start press does nothing | Pulse rung above the "last state" rung |
| Rung ends with a contact | The trailing contact drives nothing | End every rung with a coil or block |
| Rung has no coil or block at all | Nothing is written | Add an output |
| Duplicate element or rung `id` values | Editing one element or rung changes another | Keep ids unique |
| Output or block inside a parallel branch | Invalid structure | Branches hold contacts and compares only |
| Parallel group nested inside a branch | Evaluates right but draws over the rungs below it | Flatten into more branches (4.5) |
| Coil addressed to an X input | Silently overwritten if a connected scene owns that address; holds its value if none does, which is worse — it works until a scene is connected | Coils write Y or C only |
| `C0` or `C300` used as an internal relay | Works invisibly — never shows on the I/O panel; v1.124 reports it on import | Keep to C1–C256 |
| Timer preset entered in seconds | Timer finishes 1000× too fast | `pre` is milliseconds |
| `XIC AX1` used as an analog check | Always false | Use a compare element |
| Section 3.4 addresses used while the scene is offset | Program drives the wrong block, or nothing | Add the scene's offset (3.5) |
| `cmp` missing | Compares against 0 | Always include `cmp` |
| `cmp` written as a numeric string (`"819"`) | Works from v1.124 (on v1.123 EQU and NEQ never matched), but differs from the export format | Write constants in `cmp`, `lo` and `hi` as numbers; use a string only for an address (`"D20"`) |
| Timer `pre` missing or 0 | Timer is done immediately | Always include `pre` in milliseconds |
| `src` written as a number | Works, but differs from the export format | Write `src` as a string, e.g. `"2048"` |
| Only one MOV rung for an on/off analog output | Output stays at the last value | One MOV rung per value |
| CTD used without CTU | Count never changes | Pair with CTU on the same address |
| Empty "documentation" rung | Its comment is invisible | Use rung comments, `comments` or `notes` |
| Address comments only on elements | Only the first comment per address is kept | Use the top-level `comments` map |
| Relying on `notes` or `name` inside the simulator | Not shown, lost on re-export | Keep them as file documentation only |
| ST program declares `X1 : BOOL` | Conflicts with built-in I/O | Never declare addresses |
| ST uses `=` for assignment | Compile error | Use `:=` |
| ST uses `T1/DN` | Syntax error — `/` is read as division | Use bare `T1` in ST |
| ST declares a timer inside a user `FUNCTION_BLOCK` on `acc-st.js` v1.014 or earlier | Runtime error every scan; program does nothing | Works on v1.015 and later; on older engines declare timers at the top level (8.4) |
| ST waits with `WHILE NOT X3 DO` | Loop budget error | Use state logic and timers |
| `XIC SW5` or `XIC T1/ACC` | Always false — contacts read bits, not words | Use a compare or LIM |
| Coil or MOV writing an SB or SW | Refused by the editor; at run time any write is ignored except one that clears SB9–SB11 or SW17 | System addresses are read-only (3.6) |
| `SB3` used to *hold* a state | It is on for one scan only | Use it as a contact on the first scan: `XIC SB3 → OTL C…` or `XIC SB3 → RES …` |
| A clock bit expected faster than SB5 | There is none — SB5 (0.5 s) is the fastest | Use SB4 (toggles every scan) or a TON |
| CTUD without `cd` | Never counts down | Add `"cd": "X2"` (a bit address) |
| LIM written with `cmp` instead of `lo`/`hi` | Tests 0 to 0 | Use `lo` and `hi` |
| `RTO` expected to reset when its rung goes false | It keeps its time | Add a `RES` rung |
| Ladder `RTO` converted to ST | No such block in ST | Keep the program in ladder, or accumulate time in a user `FUNCTION_BLOCK` |
| `INC`, `ADD` or another accumulating block behind `XIC X1` | Adds on every scan — about 10 per second while X1 is held | Use a `P` contact for once per press (4.7) |
| A calculation expected to run only when its rung turns on | Math blocks act on every scan their rung is true | Put a `P` contact in front, or accept continuous calculation on an always-true rung |
| `INT` total or count that grows past 32,767 | Wraps to −32,768 and sets SB9 | Use `DINT` (or `UINT` for 0–65,535) |
| A `DINT` or `REAL` in D1 and another value in D2 | They share D2, so each write corrupts the other | Two-word values take Dn and Dn+1; give the next value D3 (3.1.1) |
| `DINT` or `REAL` starting at `D4000` | Refused — it needs D4001 | Last start address is D3999 |
| A `DINT` `ADD` (or `REAL` `CPT`) that names a register holding an `INT` | Reads that register and the next as one 32-bit value — wrong result | `MOV` it into the right type first (`st` → `dt`), or read AX directly |
| Decimal constant (`1.5`, `0.5`) in an `INT`/`DINT` instruction or CPT | Refused by the editor | Use `REAL`, or scale with whole numbers (`* 3 / 2`) |
| Expecting `INT` division to round | `7 / 2` gives 3, and `CPT` truncates every step | Use `REAL`, `ROUND()` in a REAL CPT, or `SCL` (which rounds) |
| `REAL` constant beyond ±3.4 × 10³⁸, or a `REAL` result that overflows | Constant refused; result writes nothing and sets SB10, code 3 | Keep values in range |
| `DIV` or `MOD` by a register that can be 0 | Writes nothing, sets SB10 and code 2 on every scan | Guard with `GRT Dn cmp 0` (7.2) |
| `T1/ACC` or a bit used in a `CPT` expression | Refused | `MOV` the value into a D register first; CPT reads D, AX, AY and SW only |
| `dt` written in lower case (`"int"`) or misspelt | Refused by the editor | `INT`, `UINT`, `WORD`, `DINT`, `REAL` in upper case |
| Error flags never cleared | SB9–SB12 and SW17 stay on after the cause is gone (they are sticky) | `OTU SB9`/`SB10`/`SB11` and `MOV SW17 "0"` on a reset rung (7.2) |
| Values typed into the D tab expected to be in the file | Only an export or a save stores them (`dregs`) | Export after setting values, or set them on an `XIC SB3` rung |
| ST writes `D10` instead of `D[10]` | Undeclared identifier | Use `D[10]`; ST reads and writes D as `INT` only (8.2) |
| Pointer register loaded with the table **value** or an **offset** (`MOV D2 src "1"` to mean "entry 1") | `D[D2]` uses D1 — the wrong register, or 0 and a range fault | The pointer holds the register **number**: base + index, e.g. `ADD D2 a "100" b "D1"` (3.1.2) |
| Pointer written `D[5]`, `D[AX1]`, `D[D5+1]` or `D[D[5]]` | Refused by the editor | Only `D[Dn]`: calculate the number into Dn first with `ADD` or `CPT` |
| Pointer used on a contact, coil, timer, counter, `RES`, `len` or a PACK/UNPACK bit field | Refused by the editor | Pointers work only in MOV, the math and data blocks' word fields and the compares (3.1.2) |
| Pointer register that can be 0, negative, above 4000, or 4000 for a `DINT`/`REAL` | Nothing is written; SB11, SB12, `SW17 = 4` on every scan; a compare reads 0 | Keep the index in range (`LIM D1 lo 0 hi 2` in front of the rungs), and show SB12 |
| A `REAL` or `DINT` instruction writes the pointer register | It is read as `INT`, so it points somewhere unexpected — a `REAL` 1.5 leaves 0 in Dn (a range fault), a `DINT` also overwrites Dn+1 | Write pointer registers as `INT` only (`ADD`, `MOV` with `dt` `INT`) |
| Pointer register changed below the rungs that use it | Those rungs use the old target until the next scan | Calculate the pointer on a rung above its users (3.2) |
| Address with a space inside (`"X 1"`, `"D 5"`) | The import check reports it; the scan reads 0 / OFF or writes nothing | Write addresses without spaces (Section 9) |
| `BSL` expected to shift on every scan its rung is true | It shifts once per rising edge of the rung | Pulse the rung once per product (`P X1`) (4.10) |
| `OTE` on a shift-register bit or a drum output | The coil rewrites the bit every scan, so the register or drum seems to do nothing | Read those bits with contacts; clear register bits with `OTU` |
| Drum step `p` written as a list of outputs (`[1, 6]`) | Refused by the editor — `p` is one whole number, bit 0 = `out` | Add the bit values: Y1 + Y6 = 1 + 32 = 33 (4.10) |
| Drum step with `t` 0 and no `ev` | It lasts one scan | Give it a time or an event |
| Drum outputs expected to turn off when the rung goes false | The drum pauses and the outputs hold | Drive the drum's outputs on C bits and gate the real outputs in a separate rung, or give step 1 an all-off pattern and reset with the rung true |
| `JMP` to a label above it (a loop) | Reported on import; at run time the jump is ignored and sets fault code 4 | Jumps go forward only; ladder has no loops |
| Label used twice, or `LBL` in a branch or at the end of a rung | Reported on import | One `LBL` per label, first on its rung |
| `JMP` used to skip a rung that must turn its outputs off | Skipped rungs hold their outputs and timers | Use an MCR zone, or interlock the rung itself |
| `END MCR` with contacts in front, or MCR zones nested | Reported on import | `END MCR` alone on its rung; close a zone before opening the next |
| BSL, BSR, DRUM, JMP or MCR asked for in ST | No such instructions in ST | Write the logic with `IF`/`CASE` (5.1), or use ladder |

---

*ACC Automation · accautomation.ca · Free PLC training in your browser*
