blinker.h
#ifndef blinker_h
#define blinker_h
// A simple blink class used to turn on and off blinking LEDs.
// Spawn a blinker for each pin you would like to blink an LED on.
// Its not ment to be the end all. Its just something to blink LEDs.
// It will probably crash and burn when the microsecond counter overruns.
//
// Written by : Jim Lee @ www.LeftCoast.biz
// Some defaults in case the user just doesn't care..
#define defPin 13
#define defOnMs 50
#define defPeriodMs 400
class blinker {
public:
blinker(int inPin=defPin,float inOnMs=defOnMs, float inPeriodMs=defPeriodMs);
void init(bool running=true); // Call this in the setup function perhaps?
void setBlink(bool onOff); // Start or stop the blinking..
void idle(void); // Call this in the loop function.
void setTimes(float inOnMs, float inPeriodMs); // Want to change the blink?
private:
unsigned long onTime;
unsigned long periodTime;
unsigned long startTime;
bool running;
bool pinHigh;
int pin;
};
#endif
blinker.cpp
#include "blinker.h"
#include <arduino.h>
blinker::blinker(int inPin,float inOnMs, float inPeriodMs) {
running = false;
pinHigh = false;
pin = inPin;
setTimes(inOnMs,inPeriodMs);
}
void blinker::init(bool running) {
pinMode(pin, OUTPUT);
setBlink(running);
}
void blinker::setBlink(bool onOff) {
if(onOff != running) { // ignore if no change
if (onOff) { // Start blinking..
startTime = micros(); // Starting NOW!
digitalWrite(pin,HIGH); // light on!
pinHigh = true; // set state.
running = true;
}
else { // Stop blinking..
digitalWrite(pin,LOW); // light off.
running = false; // set state.
pinHigh = false;
}
}
}
void blinker::idle(void) {
unsigned long now;
if (running) {
now = micros(); // Look at the time!
if (pinHigh) { // If the light is on..
if (now >= startTime+onTime) { // And its been on long enough!
digitalWrite(pin,LOW); // light off.
pinHigh = false; // set state
}
}
else { // Else the light is off..
if (now >= startTime+periodTime) { // And its been off long enough!
digitalWrite(pin,HIGH); // light on!
pinHigh = true; // set state
startTime = startTime + periodTime; // Set next iteration.
}
}
}
}
void blinker::setTimes(float inOnMs, float inPeriodMs) {
onTime = round(1000*inOnMs);
periodTime = round(1000*inPeriodMs);
}
I think that's all of it..
-jim lee