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.
Diff: Counter.cpp
- Revision:
- 0:693f2f97c8c1
- Child:
- 1:e8eeddee2959
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Counter.cpp Mon Nov 12 18:43:22 2018 +0000 @@ -0,0 +1,78 @@ +#include "Counter.h" + +#ifdef COUNTER_DEBUG +Serial debug_out(USBTX, USBRX); +#endif +Counter::Counter() +{ + is_written = 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<PARTY_LIMIT; i++) + vc[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<PARTY_LIMIT; i++) { + debug_out.printf("%dID\t%d\t%d\t%p\r\n", i, vc[i], ptr[i], (ptr+i)); + } +} +#endif + +void Counter::init() +{ +#ifdef COUNTER_DEBUG + debug_out.printf("Initializing...\r\n"); +#endif + if(*((int*)is_written) == -1) { // then we know it hasn't been initialized yet + erase_sector(is_written); + int zero = 0; + program_flash(is_written, (char*)&zero, sizeof(int)); + write_vc(); + } else { + read_vc(); + } +#ifdef COUNTER_DEBUG + print_memory(); +#endif +} + +void Counter::write_vc() +{ +#ifdef COUNTER_DEBUG + debug_out.printf("Writing to Flash\r\n"); +#endif + erase_sector(address); + int zero = 0; + program_flash(is_written, (char*)&zero, sizeof(int)); + program_flash(address, (char*)&vc, sizeof(int) * PARTY_LIMIT); +#ifdef COUNTER_DEBUG + print_memory(); +#endif +} + +void Counter::read_vc() +{ +#ifdef COUNTER_DEBUG + debug_out.printf("Reading from Flash\r\n"); +#endif + for(int i=0; i<PARTY_LIMIT; i++) { + vc[i] = *((int*)address+i); + } +} + +void Counter::increment(int party_id) +{ +#ifdef COUNTER_DEBUG + debug_out.printf("Incrementing %d\r\n", party_id); +#endif + vc[party_id]++; + write_vc(); +} \ No newline at end of file