Preserving Data with Retain Variables
Retain variables preserve their values after a warm start. However, the degree of value retention for persistent variables is higher.
A special non-volatile memory area on the controller, for example as NVRAM or UPS, is required to extend the lifespan. Securing the retain variables in such a memory does not require any additional time, which is an advantage over data retention with the Persistence Manager. If the controller does not provide hardware support, then the data is usually stored in a file. Then the data will be retained if you shut down the controller correctly. In the event of a power failure or a "pulled plug", however, data will be lost.
Declaration
To declare a retain variable, add the RETAIN
keyword to a variable declaration.
Behavior
Restart of the controller
Uncontrolled abort (only available with hardware support like an NvRAM)
Call of the Reset Warm command
Repeated download of the application
Call of the Reset Cold command (in contrast to persistent variables)
Call of the Reset Origin command
When you restart an application, its variables are usually initialized with an explicitly preset initial value or with a default value. Variables marked with the RETAIN
keyword are managed in a separate memory area depending on the target system and retain their value. Then the variables are protected from power failure, for example. This means that you can apply retain variables to a parts counter in a production line so that you can continue counting even after a power failure.
Memory location of retain function block instances
Function block instances are stored as one block in memory. This is necessary so that the same code can work on different instances. If a variable is marked with RETAIN
in a function block, then each instance of the function block is protected with all variables. This is also true for the variables of the function block that are not marked this way. However, non-volatile memory is not available to the same extent as main memory.
A function block with a pointer to an instance in SRAM as a variable is not stored in the protected memory.
Importing of CoDeSys V2.3 projects
When you open a CoDeSys V2.3 project to import it into CODESYS V3, the declarations of retain variables are preserved and remain effective as before.
For more information, see: RETAIN
and Opening a V2.3 Project