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.

Revision:
1:e8eeddee2959
Parent:
0:693f2f97c8c1
Child:
2:f02ac448ecd3
--- a/Counter.cpp	Mon Nov 12 18:43:22 2018 +0000
+++ b/Counter.cpp	Mon Nov 12 19:01:53 2018 +0000
@@ -5,13 +5,13 @@
 #endif
 Counter::Counter()
 {
-    is_written = flash_size() - SECTOR_SIZE;
+    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<PARTY_LIMIT; i++)
-        vc[i] = 0;
+    for(int i=0; i<MAX_LEN; i++)
+        count[i] = 0;
     this->init();
 }
 
@@ -20,8 +20,8 @@
 {
     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));
+    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
@@ -31,40 +31,40 @@
 #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);
+    if(*((int*)new_count) == -1) { // then we know it hasn't been initialized yet
+        erase_sector(new_count);
         int zero = 0;
-        program_flash(is_written, (char*)&zero, sizeof(int));
-        write_vc();
+        program_flash(new_count, (char*)&zero, sizeof(int));
+        memwrite();
     } else {
-        read_vc();
+        memread();
     }
 #ifdef COUNTER_DEBUG
     print_memory();
 #endif
 }
 
-void Counter::write_vc()
+void Counter::memwrite()
 {
 #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);
+    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::read_vc()
+void Counter::memread()
 {
 #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);
+    for(int i=0; i<MAX_LEN; i++) {
+        count[i] = *((int*)address+i);
     }
 }
 
@@ -73,6 +73,6 @@
 #ifdef COUNTER_DEBUG
     debug_out.printf("Incrementing %d\r\n", party_id);
 #endif
-    vc[party_id]++;
-    write_vc();
+    count[party_id]++;
+    memwrite();
 }
\ No newline at end of file