Metro SW timers as in Arduino

Metro SW timer as for Arduino. Almost unchanged. Please use with "Arduino" library.

Metro.cpp

Committer:
eduardoG26
Date:
2015-03-26
Revision:
0:1e3f8cf13bb8
Child:
1:33de962673fd

File content as of revision 0:1e3f8cf13bb8:

/*
The MIT License (MIT)

Copyright (c) 2013 thomasfredericks
Copyright (c) 2015 Eduardo de Mier

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include "Metro.h"
#include "millis.h"

Metro::Metro(unsigned long interval_millis)
{
    this->autoreset = 0;
    interval(interval_millis);
    reset();
}

// New creator so I can use either the original check behavior or benjamin.soelberg's
// suggested one (see below). 
// autoreset = 0 is benjamin.soelberg's check behavior
// autoreset != 0 is the original behavior

Metro::Metro(unsigned long interval_millis, uint8_t autoreset)
{   
    this->autoreset = autoreset; // Fix by Paul Bouchier
    interval(interval_millis);
    reset();
}

void Metro::interval(unsigned long interval_millis)
{
  this->interval_millis = interval_millis;
}

// Benjamin.soelberg's check behavior:
// When a check is true, add the interval to the internal counter.
// This should guarantee a better overall stability.

// Original check behavior:
// When a check is true, add the interval to the current millis() counter.
// This method can add a certain offset over time.

char Metro::check()
{
  if (millis() - this->previous_millis >= this->interval_millis) {
    // As suggested by benjamin.soelberg@gmail.com, the following line 
    // this->previous_millis = millis();
    // was changed to
    // this->previous_millis += this->interval_millis;
    
    // If the interval is set to 0 we revert to the original behavior
    if (this->interval_millis <= 0 || this->autoreset ) {
        this->previous_millis = millis();
    } else {
        this->previous_millis += this->interval_millis; 
    }
    
    return 1;
  }
  
  
  
  return 0;

}

void Metro::reset() 
{
 
  this->previous_millis = millis();

}