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){

  if(distance > 150){

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
    use a "flag" variable to remember that the function has been called – jsotola Jan 13 '18 at 2:38

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){
    present = true;
} else if(present == true && distance > 150) {
    present = false;
static boolean didItAlready = false;

if(distance > 50 && !didItAlready){
     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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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