How to make functions which in loop run only once?

Submitted by jack on Thu, 08/08/2019 - 18:39

hey guys, i am doing a project on arduino. and i am using arduino UNO. i needed a help in coding. basically the arduino default loop runs forever. but i want some task to be run only once in the loop. 

so examle is like this, if my one push  button is pressed then it starts reading and if it high then it should print the "Pressed" once then if released then it should print "Not Pressed" only once

void loop(){

push = digitalRead(inPin); 

  if (push == HIGH) {         
    Serial.println("Pressed");
  } else {
       Serial.println("Not Pressed");
  }
}

But here it is printing continuosly.

How to do it for only once?

 

 

I am re-writing the code as

boolean execute = false;

void loop(){

push = digitalRead(inPin); 

  if (push == HIGH && execute == false) {         
    Serial.println("Pressed");

    execute = true;
  }

 if (push ==LOW && execute==true) {
       Serial.println("Not Pressed");

       execute = false;
  }

 

}

  Joined August 16, 2016      998
Tuesday at 12:29 AM