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.h

Committer:
kpan
Date:
2018-11-16
Revision:
4:bb12605080d5
Parent:
3:c15c22484205

File content as of revision 4:bb12605080d5:

#ifndef COUNTER_H
#define COUNTER_H

#include "mbed.h"
#include "FreescaleIAP.h"

#ifndef MAX_LEN
#define MAX_LEN 8
#endif

/**
* Counter example
*
* @code
* #include "mbed.h"
* #include "Counter.h"
* 
* int main(void) {
*     
*     Counter ct;
*     while (true) {
*         ct.increment(rand()%MAX_LEN);
*         wait(0.5);
*     }
* }
* @endcode
*/

class Counter
{
private:
    int count[MAX_LEN];
    int is_new_count;
    int address;
    #ifdef COUNTER_DEBUG
    /** Simple print function
    *
    *   Prints all memory addresses in count array with values for debugging purposes.
    *
    */
    void print_memory(void);
    #endif
    /** Initialize count array
    *
    *   Either initializes count array to zeroes or existing count
    *   depending on whether it has been called before or not
    *
    */
    void init(void);
    /** Decrement count
    *
    *   Simply decrement value of index
    *   Private to disallow access for this specific purpose;
    *   @param index Index of count array to be decremented
    *
    */
    void decrement(int index);
    
public:

    /** Default Constructor
    *
    *   Sets read/write memory addresss of Flash memory
    *   Also calls init()
    *
    */
    Counter();
    
    /** Write to Memory
    *
    *   Writes current count array to Flash Memory
    *
    */
    void memwrite(void);
    
    /** Read from memory
    *
    *   Loads values of existiing count array from Flash Memory
    *
    */
    void memread(void);
    
    /** Increment count
    *
    *   Simply increments value of index
    *
    *   @param index Index of count array to be incremented
    *
    */
    void increment(int index);
    /** Clears Count
    *
    * RESETS count array
    *
    */
    void clear();
};

#endif