I'm trying to figure out if this is possible. I'm using ultrasonic sensor to detect when someone touches a portion of a wall. Say if obstacle(hand) is present between 30 and 40 cm away from the sensor.
What I want is, that if obstacle is present in that distance range for more than 2 seconds. Only then it should print.
And assume if the obstacle is present for 6 seconds, I don't want it to print three times. (i.e. it should print only once if time is greater than 2 seconds)
You need to detect when the event becomes true rather than when it is true (***) and at that time save the value of millis() and set a boolean to true to flag that timing is taking place
Then, later in loop(), if timing is taking place (ie the boolean is true) you can check whether the required period has elapsed by subtracting the current value of millis()
*** The StateChangeDetection example in the IDE will be of interest
If distance is greater than 40 and distance is greater than 40 do the thing, why not just do Distance > 30?
Perhaps you mean between 30 and 40?
if ( (distance >= 30) && (distance =< 40) )
millis() counts milliseconds since the mcu has been running. I can use millis() to count the time and when time equals the numbers do the thing.
unsigned long timePast = millis();
unsigned long TimOfTheThing = 2000;
void somefunction()
{
if ( millis() - timePast >= TimeOfTheThing )
{
//do the 2 second things here
//update the timePast
timePast = millis();
}
}
That's "if 40 is greater than distance and distance is greater than 30". Some people use that arrangement because it looks more like what they used in older languages: (40 > variable > 30)
Before writing code you should make sure your ideas are clear enough.
For instance, the following figure reflects my interpretation of your objective. Although it is not clear what should happen when an object has been successfully detected, my assumption is the red line: