void loop(){
if (distance > 10) {
if (timerIsStarted == true){ // can be coded shorter as if (timerIsStarted)
if (millis() - startTime > 5000) { // check if more than 5000 milliseconds have passed by since distance was > 10
// if more than 5000 milliseconds HAVE passed by since distance > 10 has begone
// Do the stuff when timer > 5 seconds
}
}
else { // if distance is > 10 but timer was NOT yet started
// set flag-variable to true to avoid repeating startTime = millis();
// we want the BEGINNING of distance > 10
timerIsStarted = true;
startTime = millis(); // store snapshot of time in that moment WHEN distance STARTED to be > 10
}
}
else // if distance is LESS than 10
timerIsStarted = false; // set flag-variable to false to stop time-checking
}
static unsigned long LastTimeDistanceWasLE10 = 0;
if (distance <= 10)
{
LastTimeDistanceWasLE10 = millis();
}
if (millis() - LastTimeDistanceWasLE10 >= 5000)
{
// Distance has been > 10 for more than 5 seconds
Console.WriteLine("Distance is greater than 10");
}
They are intended to be global variables, so put them at the top of the code with the other global variables. (Not inside any function, and somewhere before/above where they are used)
for a beginner that sees this for the first time it might look odd to her/him if you code
if (timerIsStarted)
I wrote
if (timerIsStarted == true){ // can be coded shorter as if (timerIsStarted)
Your feedback made me think about it. So maybe places vice versa would be better
if (timerIsStarted ) { // a boolean variable does NOT need an explicit comparising if (timerIsStarted == true)
Anyway for a real expert the code could be much more "cluttered" she/he will be able to read and understand quickly just the same as a real expert is able to understand quickly the most compact code that has no comments at all.
Well me myself I'm not a real expert. And I'm not obsessed with my ego. I'm obsessed with writing code for beginners that is easy to understand. And as I'm no longer a beginner but a somehow to some extent advanced C++-user I started to get blind for beginners difficulties myself. It is an unavoidable effect that grows with the knowledge. Then you have to become an advanced user / expert in a second field: the beginners difficulties. And this is the reason why I almost always invite beginners to ask many questions. Because the beginners are the experts about beginners difficulties.
But I guess - for some users - writing such an answer will be seen as
you see he's obsessed with his ego.