Ultrasonic Sensor - If item is detected for certain amount of time

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.

    if (40 > distance && distance > 30)
      {
       Serial.println("obstacleIn3040"); 
       delay(250);   }

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)

Thank you.

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)

void loop()
{
  static unsigned long lastTimeAbsent = millis();

  int distance = GetDistance();

  if (distance > 30 && distance < 40)
  {
    // Present
    if (lastTimeAbsent != 0 
        && millis() - lastTimeAbsent > 2000)
    {
      Alarm = true;
      lastTimeAbsent = 0; 
    }
  {
  else
  {
    // Absent
    lastTimeAbsent = millis();
  }
}

Thanks for taking the time to explain. I appreciate it.

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:

BTW, this is a "state diagram" for a "digital state machine" (Google it!). The message should be printed upon entering the state "Detected"

This logic will detect an object coming into range and report only once, waiting for it to go out of range.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.