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-16
Revision:
4:bb12605080d5
Parent:
3:c15c22484205

File content as of revision 4:bb12605080d5:

#include "Counter.h"

//#define COUNTER_DEBUG

#ifdef COUNTER_DEBUG
Serial debug_out(USBTX, USBRX);
#endif
Counter::Counter()
{
    is_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
    memset(&count, 0, MAX_LEN);
    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*)is_new_count) == -1) { // then we know it hasn't been initialized yet
        erase_sector(is_new_count);
        int zero = 0;
        program_flash(is_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(is_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();
}

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

void Counter::clear(){
    #ifdef COUNTER_DEBUG
        debug_out.printf("Clearing stored values\r\n");
    #endif
    memset(&count, 0, MAX_LEN);
}