// This Timer.h library came from here: https://github.com/JChristensen/Timer
#include "Timer.h"
#define avoidPin 4
#define relayPin 5
#define delayMs 100
#define timeoutMs 1000 * 30
int lastValue;
bool isTimerRunning = false;
Timer mainTimer;
Timer workTimer;
void setup()
{
Serial.begin(115200);
pinMode(relayPin, OUTPUT);
pinMode(avoidPin, INPUT);
Serial.println("Set pins in setup mode, listening every ms: " + String(delayMs));
mainTimer.every(delayMs, mainCallback);
}
void mainCallback() {
int avoidVal = digitalRead(avoidPin);
// We only care if something changes (someone walks in front of the sensor)
if (avoidVal != lastValue) {
// It's different, is the timer running?
if (isTimerRunning) {
Serial.println("Don't need to do anything, timer is running");
}
else
{
// Timer not running, is somebody there?
if (avoidVal == LOW) {
digitalWrite(relayPin, HIGH);
// Start a timer to turn them off
workTimer.every(timeoutMs, workCallback, 1);
isTimerRunning = true;
Serial.println("LED is on, timer started, bool set");
} else {
Serial.println("Looks like nobody is there, not starting timer");
}
}
lastValue = avoidVal;
}
// If they are the same value who cares, we only care about things that change
}
void workCallback() {
isTimerRunning = false;
digitalWrite(relayPin, LOW);
Serial.println("LED off and bool = false");
}
void loop()
{
mainTimer.update();
workTimer.update();
}