Skip to content

Instantly share code, notes, and snippets.

@osfameron
Created May 12, 2012 16:22
Show Gist options
  • Save osfameron/2667424 to your computer and use it in GitHub Desktop.
Save osfameron/2667424 to your computer and use it in GitHub Desktop.
Arduino Multitasking sketch
class Task {
public:
Task (boolean on, int frequency) {
_on = on;
_frequency = frequency;
_nextTick = millis();
}
virtual void runTask () = 0;
void checkTask() {
int time = millis();
if (_on && (time >= _nextTick)) {
runTask();
_nextTick = time + _frequency;
}
}
void frequency(int frequency) {
_frequency = frequency;
}
void on() {
on(true);
}
void on(boolean b) {
_on = b;
}
void on(int f) {
frequency(f);
on(true);
}
void off() {
on(false);
}
private:
boolean _on;
int _frequency;
int _lastTick;
int _nextTick;
};
class BlinkLedTask : public Task {
public:
explicit BlinkLedTask (boolean on, int frequency, int pin)
: Task(on, frequency) {
_pin = pin;
pinMode(_pin, OUTPUT);
}
void runTask () {
doBlink();
}
void doBlink () {
setLed(!_led_state);
}
void setLed(boolean state) {
_led_state = state;
digitalWrite(_pin, state);
}
private:
boolean _pin;
protected:
boolean _led_state;
};
class SuperLedTask : public BlinkLedTask {
public:
SuperLedTask (boolean on, int frequency, int pin, BlinkLedTask* blt)
: BlinkLedTask(on, frequency, pin) {
_blt_ptr = blt;
}
void runTask () {
doBlink();
_blt_ptr->on(_led_state);
_blt_ptr->setLed(_led_state);
}
private:
BlinkLedTask *_blt_ptr;
};
BlinkLedTask blink1 = BlinkLedTask(true, 100, 11);
SuperLedTask blink2 = SuperLedTask(true, 1000, 13, &blink1);
Task* tasks [] = { &blink1, &blink2 };
void setup () {
Serial.begin(9600);
}
void loop () {
for (int i=0; i<2; i++) {
tasks[i]->checkTask();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment