Hi everyone,
I have noticed a lot of posts lately of people who are confused on how to make a time delay using millis() (I have seen 3 threads in the past day and a half).
So, I decided to make a small class called "EventTimer" to simplify the process of adding timers to your program (it's also more organized).
Attached to this post are two files "EventTimerLib.h" and "EventTimerLib.cpp" add them to your project (if you're using the default Arduino IDE open your project and go to Sketch->Add File) and use #include "EventTimerLib.h" to start using it.
The class contains the following methods:
Start(length) //Starts the timer which runs for the specified length (in milliseconds)
GetStarted() //Returns true if the timer has been started and is not yet completed
GetCompleted() //Returns false if the timer is still running, otherwise true
SetTrigger(void (*trgFunc)(void)) //Sets the function to be triggered when the timer is completed
Update() //Updates the timer - Must called every loop() if using SetTrigger
You only need to use the Update() method if you are using SetTrigger() (which is optional).
Below is an example that blinks and LED every 500 milliseconds
#include "EventTimerLib.h"
int ledPin = 4;
byte ledState = B00000000;
//Create a timer object
EventTimer ledBlink;
// the setup function runs once when you press reset or power the board
void setup() {
pinMode(ledPin, OUTPUT);
}
// the loop function runs over and over again until power down or reset
void loop() {
//Start the timer if it hasn't been started yet
//The timer will restart everytime you use ledBlink.Start
//So make sure you check if it has been start first with ledBlink.GetStarted
if (ledBlink.GetStarted() == false) ledBlink.Start(500);
//Check if the time is up
if (ledBlink.GetComplete())
{
//Turn the led either on or off
ledState = ~ledState;
digitalWrite(ledPin, ledState);
//Restart the timer
ledBlink.Start(500);
}
}
Below is an example of the same thing but instead it uses SetTrigger() and Update():
#include "EventTimerLib.h"
int ledPin = 4;
byte ledState = B00000000;
//Create a timer object
EventTimer ledBlink;
void BlinkLED();
// the setup function runs once when you press reset or power the board
void setup() {
pinMode(ledPin, OUTPUT);
//Setup the callback
ledBlink.SetTrigger(BlinkLED);
}
// the loop function runs over and over again until power down or reset
void loop() {
//Start the timer if it hasn't been started yet
//The timer will restart everytime you use ledBlink.Start
//So make sure you check if it has been start first with ledBlink.GetStarted
if (ledBlink.GetStarted() == false) ledBlink.Start(500);
//Update the EventTimer
ledBlink.Update();
}
//Function turn turn the led on or off
void BlinkLED()
{
//Turn the led either on or off
ledState = ~ledState;
digitalWrite(ledPin, ledState);
//Restart the timer
ledBlink.Start(500);
}
Hopefully this helps people.
Also, I hope this is the proper board to post this in.
EventTimerLib.cpp (1.42 KB)
EventTimerLib.h (703 Bytes)