Sorry about the title i wasn't sure how to describe this, i am using in a game i have made a PIR motion sensor that outputs a logic high when motion is detected to ensure the player i still there.
I have turned the time down to 0 on the pot to allow the software to be able to control that however i am having trouble with the timing aspects of it.
I am trying to create a function that outputs a 1 when motion is detected for a deadtime of 5 seconds where it ignores any change in state, next if no motion is detected for a period of 10 seconds it will output a 0.
This is proving more troublesome than i had imagined an im wondering if i have become code blind spending to much time in front of the screen but below is the code i came up with that i feel may be "Verbose" but i am finding bugs through my testing with a button instead of a motion sensor it will suddenly spam a cycle of "Dead Timer Started", "Dead Timer Expired!" at me.
int State; //0 For deadtimer, 1 for normal detection, 2 for off timer has expired
int dOnce; //Flag for getting previous millis for dead timer
int oOnce; //Flag for getting previous millis for off timer
int Init = 1;
int deadTimer = 5000;
int offTimer = 10000;
unsigned long prevMillis;
unsigned long offMillis;
void setup() {
Serial.begin(9600);
pinMode(19, INPUT);
pinMode(13, OUTPUT);
}
void loop() {
unsigned long currentMillis = millis();
if(dOnce == 0 && (digitalRead(19) == 1 || Init == 1)){
Serial.println("Dead Timer Started");
dOnce = 1;
Init = 0;
State = 0; //We are now running the deadtimer
oOnce = 0;
prevMillis = millis();
}
if(currentMillis - prevMillis > deadTimer && dOnce == 1){
Serial.println("Dead Timer Expired!");
dOnce = 0;
State = 1; //The deadtimer has finished
}
if(oOnce == 0 && digitalRead(19) == 0 && State == 1){
Serial.println("Off Timer Started");
dOnce = 0; //*
oOnce = 1;
offMillis = millis();
}
if(currentMillis - offMillis > offTimer && oOnce == 1 && State == 1){
Serial.println("Off Timer Expired!");
oOnce = 0;
State = 2;
}
}
Serial Monitor Output Below:
Dead Timer Started
Dead Timer Expired!
Off Timer Started
Off Timer Expired!
Dead Timer Started
Dead Timer Expired! } I hit the button as these 2 were displayed below is the result...
Off Timer Started } i am unable to recreate this bug every time
Off Timer Expired!
Dead Timer Started
Dead Timer Expired!
Dead Timer Started
Dead Timer Expired!
Dead Timer Started
Dead Timer Expired!
Dead Timer Started
Dead Timer Expired!
Dead Timer Started
Dead Timer Expired!
Dead Timer Started
Dead Timer Expired!
Dead Timer Started
Dead Timer Expired!
Dead Timer Started
Dead Timer Expired!
Off Timer Started
Off Timer Expired!
Dead Timer Started
Dead Timer Expired!
Off Timer Started
Off Timer Expired!
If anyone can help me improve this, fix this or suggest a different approach i will be forever grateful.