How to make functions which in loop run only once?

jack's picture

Offline

Joined: Sep 21, 2018

Replies: 2
How to make functions which in loop run only once?
August 8, 2019 - 6:39pm

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?

 

 

Aswinth Raj's picture

Offline

Joined: Aug 16, 2016

Replies: 910
you can use another variable as switch
August 10, 2019 - 1:42pm

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;
  }

 

}