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, the run-hours total and the operator setpoints are all back to their initial values.
Three kinds of variable lifetime
IEC 61131-3 and the major vendors distinguish three lifetimes:
| 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: check that the variable is declared retentive
VAR RETAIN
ShiftCount : DINT;
RunHours : REAL;
END_VAR
A frequent error is a counter that is declared retentive but lives inside a function block instance 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: look for code that overwrites it at startup
Search the cyclic code and any startup OB for initialisation that writes ShiftCount := 0 unconditionally. Start-up logic should initialise only the values that are invalid (out of range) and leave the rest alone.
Step 3: retentive memory capacity and hardware
Retentive memory is limited, for example to a few hundred kilobytes on mid-range CPUs, and exceeding it gives a compile warning or error. Older PLCs keep retentive data in battery-backed RAM, so a dead battery loses everything at power off. Check the battery LED and replace the battery on schedule, with the PLC powered if the manual says so.
Step 4: downloads and resets
A reset to factory, a cold reset or a download with re-initialisation can clear retentive values by design. Before a major download, back up the live values (snapshot them to the project, or export the DB values) and restore them afterwards.
Where to keep values you cannot afford to lose
PERSISTENT where the platform supports it, for values that must survive downloads.You can 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.