C Language Development Kit/Snippets/Flash

From OptiWiki

Jump to: navigation, search

Since most terminals only contain a RAM-disk. There's always the risk of losing important settings when the main battery and back-up battery are both empty. This section explains how settings can be stored in non-volatile flash memory to be certain that important settings are never lost.

Important note: Do not attempt to store bar code data in non-volatile flash memory!


Sources of all menu functions

To be able to use the menu functions, include the following header file and source file and the input functions header and source file in your project.

Header file store.h (source)

Function to erase a Flash block

The following function can be used to erase a block from Flash.

Function to write a Flash block

The following function can be used to write a block to Flash.


Reading data out of flash memory

To read the stored data back from the memory, all that needs to be used is a address pointer, that's pointed to correct location. Besides that, it's recommended that a check is performed that the data in flash is valid.

Below you'll find a piece of source code that demonstrates the reading of data from flash memory.

int read_settings_from_flash(unsigned char *settings)
    int i;
    unsigned char *address;
    unsigned char *ptr;
    // Set pointer to start of Flash section
    address = (unsigned char *)FLASH_ADDRESS;
    // Verify that check string is found is flash
    for(i=0; i < strlen(CHECK_STRING); ++i)
        if (*address++ != CHECK_STRING[i] )
            return ERROR;           // Check failed, return ERROR
    ptr = settings;                 // Set pointer to settings (in RAM)
    // Copy settings to RAM till '\0' is found.
    while ((*ptr = *address) != 0)
    *ptr = '\0';
    return OK;

Example application

The best moment to read your stored settings from flash is at the start of your application. Also it is recommended to verify whether the reading from flash memory was successful to determine whether the settings must be reset to default or not.

Below you'll find a small application that demonstrates this.

#include "lib.h"
#include "store.h"
#include <stdio.h>
#include <string.h>
void main(void)
    unsigned char settings[20] = {0};
    if( read_settings_from_flash(settings) != OK )
        strcpy((char *)settings, DEFAULT_SETTING );
        printf("\fSettings are\nreset to\ndefault!");
        printf("\fSettings are\nrestored!");
    printf("\n(%s)", settings);
Personal tools