1

I am currently working in void loop() and have setup a distance meter that constantly checks the distance.

Once the distance threshold is met, a function is called. Now I only need this function to be called ONCE. But because the distance meter is constantly scanning (which I need), the function is also being repeatedly called. I tried making some sort of timer but I can't figure it out. Can someone please have a look at this?

if (distance <= 150){
    personPresent();
    }


  if(distance > 150){
    personAbsent();
      }

I need certain events within the if statement to occur only once. E.g., I want to register when there is a personPresent and have that event not fire repeatedly.

In this case, personPresent() is attached to a GPIO pin which triggers a buzzer sound. As it is now, the buzzer keeps on ringing as long as distance is less then 150. I need the buzzer to make a sound only ONCE and then not buzz for at least 5 minutes.

1
  • 3
    use a "flag" variable to remember that the function has been called
    – jsotola
    Jan 13, 2018 at 2:38

3 Answers 3

3

What you want is not to check the distance but to check that the distance condition changed.

static boolean present = false;

Inside loop:

if (present == false && distance <= 150){
    personPresent();
    present = true;
} else if(present == true && distance > 150) {
    personAbsent();
    present = false;
}
0
static boolean didItAlready = false;

if(distance > 50 && !didItAlready){
     doIt();
     didItAlready = true;
}

You simply need a variable to keep track of whether or not it has been done. If and when you want to do the action again then set your variable back to false.

0

You just need a global variable to track whether it is done or not like this...

//  other Codes

bool State=0;

void setup(){

// other Codes...

}

void loop(){

if(distance <= 150 && State==0){


personPresent(); // This function should get executed only once
State=1;


}else if(distance>150 && State==1){

personAbsent(); // This sould also get executed once
State=0;


}

}

The global boolean variable ''' State ''' will keep track of how and when the functions need to be executed once, whenever conditions are met. And the boolean variable changes everytime (distance AND Sate) the conditions are met triggering those functions once per bool update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.