Simple counter class, non-volatile between resets and power on/off.

Simple Counter class, used to store count array in non-volatile flash memory between resets and power on/off.

Counter.cpp

Committer:
kpan
Date:
2018-11-12
Revision:
1:e8eeddee2959
Parent:
0:693f2f97c8c1
Child:
2:f02ac448ecd3

File content as of revision 1:e8eeddee2959:

#include "Counter.h"

#ifdef COUNTER_DEBUG
Serial debug_out(USBTX, USBRX);
#endif
Counter::Counter()
{
    new_count = flash_size() - SECTOR_SIZE;
    address = (int)((int*)(flash_size() - SECTOR_SIZE) + 1);
#ifdef COUNTER_DEBUG
    debug_out.printf("Constructing Object...\r\n");
#endif
    for(int i=0; i<MAX_LEN; i++)
        count[i] = 0;
    this->init();
}

#ifdef COUNTER_DEBUG
void Counter::print_memory()
{
    int *ptr = (int*) address;
    debug_out.printf("PartyID\tVoteCt\tMemCt\tAddress\r\n");
    for(int i=0; i<MAX_LEN; i++) {
        debug_out.printf("%dID\t%d\t%d\t%p\r\n", i, count[i], ptr[i], (ptr+i));
    }
}
#endif

void Counter::init()
{
#ifdef COUNTER_DEBUG
    debug_out.printf("Initializing...\r\n");
#endif
    if(*((int*)new_count) == -1) { // then we know it hasn't been initialized yet
        erase_sector(new_count);
        int zero = 0;
        program_flash(new_count, (char*)&zero, sizeof(int));
        memwrite();
    } else {
        memread();
    }
#ifdef COUNTER_DEBUG
    print_memory();
#endif
}

void Counter::memwrite()
{
#ifdef COUNTER_DEBUG
    debug_out.printf("Writing to Flash\r\n");
#endif
    erase_sector(address);
    int zero = 0;
    program_flash(new_count, (char*)&zero, sizeof(int));
    program_flash(address, (char*)&count, sizeof(int) * MAX_LEN);
#ifdef COUNTER_DEBUG
    print_memory();
#endif
}

void Counter::memread()
{
#ifdef COUNTER_DEBUG
    debug_out.printf("Reading from Flash\r\n");
#endif
    for(int i=0; i<MAX_LEN; i++) {
        count[i] = *((int*)address+i);
    }
}

void Counter::increment(int party_id)
{
#ifdef COUNTER_DEBUG
    debug_out.printf("Incrementing %d\r\n", party_id);
#endif
    count[party_id]++;
    memwrite();
}