Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Counter.cpp
00001 #include "Counter.h" 00002 00003 //#define COUNTER_DEBUG 00004 00005 #ifdef COUNTER_DEBUG 00006 Serial debug_out(USBTX, USBRX); 00007 #endif 00008 Counter::Counter() 00009 { 00010 is_new_count = flash_size() - SECTOR_SIZE; 00011 address = (int)((int*)(flash_size() - SECTOR_SIZE) + 1); 00012 #ifdef COUNTER_DEBUG 00013 debug_out.printf("Constructing Object...\r\n"); 00014 #endif 00015 memset(&count, 0, MAX_LEN); 00016 this->init(); 00017 } 00018 00019 #ifdef COUNTER_DEBUG 00020 void Counter::print_memory() 00021 { 00022 int *ptr = (int*) address; 00023 debug_out.printf("PartyID\tVoteCt\tMemCt\tAddress\r\n"); 00024 for(int i=0; i<MAX_LEN; i++) { 00025 debug_out.printf("%dID\t%d\t%d\t%p\r\n", i, count[i], ptr[i], (ptr+i)); 00026 } 00027 } 00028 #endif 00029 00030 void Counter::init() 00031 { 00032 #ifdef COUNTER_DEBUG 00033 debug_out.printf("Initializing...\r\n"); 00034 #endif 00035 if(*((int*)is_new_count) == -1) { // then we know it hasn't been initialized yet 00036 erase_sector(is_new_count); 00037 int zero = 0; 00038 program_flash(is_new_count, (char*)&zero, sizeof(int)); 00039 memwrite(); 00040 } else { 00041 memread(); 00042 } 00043 #ifdef COUNTER_DEBUG 00044 print_memory(); 00045 #endif 00046 } 00047 00048 void Counter::memwrite() 00049 { 00050 #ifdef COUNTER_DEBUG 00051 debug_out.printf("Writing to Flash\r\n"); 00052 #endif 00053 erase_sector(address); 00054 int zero = 0; 00055 program_flash(is_new_count, (char*)&zero, sizeof(int)); 00056 program_flash(address, (char*)&count, sizeof(int) * MAX_LEN); 00057 #ifdef COUNTER_DEBUG 00058 print_memory(); 00059 #endif 00060 } 00061 00062 void Counter::memread() 00063 { 00064 #ifdef COUNTER_DEBUG 00065 debug_out.printf("Reading from Flash\r\n"); 00066 #endif 00067 for(int i=0; i<MAX_LEN; i++) { 00068 count[i] = *((int*)address+i); 00069 } 00070 } 00071 00072 void Counter::increment(int party_id) 00073 { 00074 #ifdef COUNTER_DEBUG 00075 debug_out.printf("Incrementing %d\r\n", party_id); 00076 #endif 00077 count[party_id]++; 00078 memwrite(); 00079 } 00080 00081 void Counter::decrement(int party_id) 00082 { 00083 #ifdef COUNTER_DEBUG 00084 debug_out.printf("Decrementing %d\r\n", party_id); 00085 #endif 00086 count[party_id]--; 00087 memwrite(); 00088 } 00089 00090 void Counter::clear(){ 00091 #ifdef COUNTER_DEBUG 00092 debug_out.printf("Clearing stored values\r\n"); 00093 #endif 00094 memset(&count, 0, MAX_LEN); 00095 }
Generated on Mon Jul 25 2022 17:25:07 by
