Skip to main content

Device Data Persistence

Recommended Code Flow For Device Data Persistence

When a device enters a deep sleep state to conserve power, it is essentially shut down: execution of the application code stops. When the device awakes, the code will be executed afresh and its variables reset. However, the device can preserve essential data in a small bank of memory — just under 4KB — which remains powered during deep sleep.

This preserved space is utilized by creating a table called nv as a global variable using Squirrel’s <- operator. This table, which must be named ‘nv’, is not created automatically; this is the job of your code. However, once it has been instantiated it will remain available for as long as the device is powered.

While all Squirrel data types and entities may be stored in a table, only those which can be serialized may be preserved in the nv table. For more information on what Squirrel data can be serialized, see the Developer Guide Squirrel Data Serialization.

Note This approach is not currently recommended for imp004m-based designs as this imp does not yet provide nv support (see Design Hardware With The imp004m.

Sample Code

The following code shows how nv table is used to preserve a single value across periodic deep sleeps. When the device starts, the code checks for the presence of the nv table in Squirrel’s root table and, if necessary, instantiates it. The table can now be written to and read just as you would with any Squirrel table.

By establishing the nv table at the top of your device code, you can easily ensure that your application’s essential data will be preserved whenever the device goes into deep sleep to conserve power.

It is important to remember that the nv table is not preserved when the device loses power. Data that needs to persist across cold starts should be passed to the device’s agent and placed in persistent storage there. To see how this is done, look at our recipe Agent Data Persistence.

API Properties Used

Further Reading