// Time interval can be in micro second, default is in milli second.

class STimer  {  // Super Simple Timer
  private:
    unsigned long lastTime;  // the latest time had doing Func( )
    void (*Func) (void);
    void (*backupFunc) (void);  // backup Func for start( )
    unsigned long T_int;   // interval in ms, can be set as in us (optional)

  public:
    STimer(void (*userFunc)(), unsigned long T, int isTinUs=0)
    {
      Func = backupFunc = userFunc;  // save the function pointer
      T_int = T * 1000;
      if(isTinUs !=0) T_int = T;   // T is in micro second as per unit
      lastTime = 0;  // initialization should be in constructor
      lastTime = -T_int; // compatible with Original version
    }

    void check() {
      if( Func == 0 ) return;  // no function pointer
      unsigned long _micros = micros( ); // Local variable could be in Register
      //  Note that ( _micros = micros() < Time)  means  ( _micros = ( micros()  < Time ) )
      // BTW, check roll over is actually NOT NECESSARY; by tsaiwn@cs.nctu.edu.tw
      if (_micros - lastTime >= T_int) {
        lastTime = _micros;  // latest time doing Func( )
        Func();
      }
    }// check(
    void start( ) {  // first run of doing Func( )
      if(Func == 0) Func = backupFunc;  // restore after .stop( )
      lastTime = micros( );  // latest time doing Func( )
      Func();   // First run
    } // start(
    void stop( ) {  // stop the scheduled Func  (userFunc)
      Func = 0;  // set as NULL
    } // stop(
}; // end of STimer

STimer T1(Blink1, 88000, 38); // 88000us (NOT ms) since 38 is NOT 0
STimer T2(Blink2, 1000);
STimer T3(Blink3, 2000);

void setup() 
{
  // put your setup code here, to run once:
  pinMode(13, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(9, OUTPUT);
  T1.start( );   // optional use the .start( ) function
  delay(2568); // Onpurpose  to compare T1 vs. T2 vs. T3
  T2.start( );  // do Blink2 right now
}

void loop() 
{
  // put your main code here, to run repeatedly:
  T1.check();
  T2.check();
  T3.check();
}

void Blink1() {
  digitalWrite(13, !digitalRead(13));
}
void Blink2() {  digitalWrite(9, !digitalRead(9)); }

void Blink3() {
  digitalWrite(11, !digitalRead(11));
}

Different to original Simple Timer:

(1)Can use micro second as the scheduled time unit:

   STimer T5(myJob5, 88000, 38);  // every 88000 micro seconds

(2)can use .start( ) to start the job scheduled immediately

(3)can use .stop( ) to stop the scheduled function

   to restart it, use .start( ) function

See the example above.

Share