runEvery library

Hi there,
I started developing on the arduino quite 3 months ago.
I used the delay() function to execute functions for a specific time, but I thought it wasn’t the best solution.
Because the delay() function is just wasting time, which you the micro controller could use to do some more useful things.
This is why I developed the runEvery library.
The library saves a start time and everytime it’s executed it checks if (the current time - time_start) equals or is higher then the given time.
Here is an example for blinking a LED every second.

const int myLedPin = 13;

boolean led_state = false;

unsigned long time_start, time_now;

void setup(void){
pinMode(myLedPin, OUTPUT);

//Start timer
time_start = millis();
}

void toggle_led(){
led_state = !led_state;
if(led_state){
digitalWrite(myLedPin, HIGH);
}else{
digitalWrite(myLedPin, LOW);
}
}

void loop(){
time_now = millis(){

if((time_now - time_start) >= 1000){
time_start = time_now;
toggle_led();
}
}

With the runEvery library it could look like this:

#include <runEvery.h>

const int myLedPin = 13;
boolean led_state = false;

//Define timer
runEvery run;

void setup(void){
pinMode(myLedPin, OUTPUT);

//Start timer
run.begin();
}

//Simple function to toggle led on/off
void toggle_led(){
led_state = !led_state;
if(led_state){
digitalWrite(myLedPin, HIGH);
}else{
digitalWrite(myLedPin, LOW);
}
}

void loop(){
if(run.s(1)) toggle_led();
}

Less code huh?

Tell me what you think about this.
Library is in the attachement in a zipped folder.

somsof62

runEvery.zip (2.5 KB)

I'm all for learning - but I am curious: Did you not find something here to help?

http://arduino.cc/playground/Main/LibraryList#Timing

Although libs with similar function exist, I think it is a good excercise in writing libraries! I have some remarks so you can improve the lib.

boolean runEvery::ms(int MS){
  unsigned long TIME_NOW = millis();
  if((TIME_NOW - _TIMER) >= MS){
    _TIMER = TIME_NOW;
   return true;
  }else{
    return false;
  }
}

boolean runEvery::s(int S){
  return runEvery::ms(S * 1000);
}

boolean runEvery::m(int M){
  return runEvery::s(M * 60);
}

1) the parameter of ms() s() and m() should be unsigned long !! Have you tested it with run.m(1) ? think it gives an overflow

2) the m() should call ms() directly to use less stack space!

boolean runEvery::m(unsigned long M)
{
  return runEvery::ms(M * 60000UL);
}

3) It should be better to use descriptive names, milliseconds(), seconds() and minute().

4) add microseconds, hours, days? or add a generic after(byte H, byte M, byte S, unsigned int MS, unsigned int US) ?

5) please include testcode / example(s) with the lib in the zip

Thank you for your suggestions. Yes you're right with the overflow. I'll fix that, add some more functions and examples.

somsof62

Here is the newest version of my library.

runEvery.zip (2.87 KB)