Troubleshooting
PLC Loses Counters and Setpoints After Power Off: Retentive Memory Explained
Every Monday the shift totals and recipe setpoints are back to zero. Here is how retentive memory really works, and how to make values survive.
The symptom
After a weekend shutdown or a power failure, the production counter, run-hours total and operator setpoints are back to their initial values.
Three kinds of variable lifetime
IEC 61131-3 and the major vendors distinguish:
| Kind | Survives power cycle | Survives program download |
|---|---|---|
| Normal (non-retentive) | No | No |
VAR RETAIN | Yes | Usually reset on a cold reset or full download |
VAR PERSISTENT (CODESYS/TwinCAT) | Yes | Yes, in most download cases |
Step 1 — Is the variable declared retentive?
VAR RETAIN
ShiftCount : DINT;
RunHours : REAL;
END_VAR
A frequent error: the counter is retentive, but it is an instance of a function block whose instance data is not. In TIA Portal, check the retain setting of the instance DB or of the multi-instance inside the parent block.
Step 2 — Is your code overwriting it at startup?
Look for initialisation in the cyclic code or in a startup OB that writes ShiftCount := 0 unconditionally. Start-up logic should only initialise values that are invalid (out of range), not all values.
Step 3 — Retentive memory capacity and hardware
Retentive memory is limited (for example a few hundred kilobytes on mid-range CPUs). Exceeding it gives a compile warning or error. Older PLCs keep retentive data in battery-backed RAM: a dead battery loses everything on power off. Check the battery LED and replace on schedule, with the PLC powered if the manual says so.
Step 4 — Downloads and resets
A reset to factory, cold reset or download with re-initialisation can clear retentive values by design. Before a major download, back up live values (snapshot to project, or export the DB values) and restore them afterwards.
Better design for critical values
PERSISTENT where the platform supports it for values that must survive downloads.Practise variable declarations in the Structured Text reference.
Frequently asked questions
What is the difference between RETAIN and PERSISTENT?
RETAIN values survive a power cycle but are normally reset by a cold reset or full download. PERSISTENT values (CODESYS, TwinCAT) also survive most downloads.
Why does my retentive counter still reset?
Common causes are a non-retentive function block instance, startup code that writes the value unconditionally, a dead backup battery, or a download that re-initialises data.