Hello!
I have created a libary called Easy. It has 4 classes: schedule events using millis() (Routine), manipulate common cathode RGB LED (RGBled), manipulate LED (EasyLED), and play music on piezo (Song). I am having difficulties with the Routine class. In another thread, I posted the prototype code for the Routine class: http://arduino.cc/forum/index.php/topic,105742.msg793353.html. That code would not work as expected if the extra parameter is removed, because it uses 2 calls to the same function, and the static prev variable is being reset, so only the fading happens.
I then decide to use the new code here: http://arduino.cc/forum/index.php/topic,105742.msg793424.html#msg793424 using the Routine class of the Easy library. It should have blink the LED on pin 13 while fading the LED on pin 9 at the same time.
But, this is what happened: When I use that code LED on pin 13 blinks once, then never blinks again. LED on pin 9 continues to fade as expected, though. This can’t be a static variable resetting, because I used 2 instances of the class.
Easy.h (only showing the Routine class):
#ifndef Easy_h
#define Easy_h
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
class Routine{
public:
Routine();
void begin(unsigned long interval, void (*g)());
void begin(unsigned long interval, void (*g)(), word times);
void end();
void restart();
void begin_us(unsigned long interval, void (*g)());
void begin_us(unsigned long interval, void (*g)(), unsigned long times);
private:
boolean go;
};
#endif
Easy.cpp (only showing the Routine class):
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "Easy.h"
Routine::Routine(){
go = true;
}
void Routine::begin(unsigned long interval, void (*g)()){
static unsigned long prev = 0;
if (millis() - prev >= interval && go){
g();
prev = millis();
}
}
void Routine::begin(unsigned long interval, void (*g)(), word times){
static unsigned long prev = 0;
static word counter = 0;
if (millis() - prev >= interval && go && counter < times){
g();
prev = millis();
counter++;
}
}
void Routine::end(){
go = false;
}
void Routine::begin_us(unsigned long interval, void (*g)()){
static unsigned long prev = 0;
if (micros() - prev >= interval && go){
g();
prev = micros();
}
}
void Routine::begin_us(unsigned long interval, void (*g)(), unsigned long times){
static unsigned long prev = 0;
static unsigned long counter = 0;
if (micros() - prev >= interval && go && counter < times){
g();
prev = micros();
counter++;
}
}
void Routine::restart(){
go = true;
}
What might be the problem, and how can I improve the code, and fix it so that I can multitask? I am also looking for a way to make it easier to schedule events in the same manner as delay(), but without halting the code.