Is there a way to make my program run only once?

I was wondering how I could make my code in Arduino run only once.

By that, I mean the void Loop() part. It is standard that the code runs over and over again.

But how can I make it run only once?
here is a example.

void setup() {
  

}

void loop() {
  // put your main code here, to run repeatedly:
pinMode(11,OUTPUT);

digitalWrite(11, HIGH);
delay(1000);
digitalWrite(11,LOW);
delay(1000);


}

In this code, the light turns on an off, over and over.
**Is there a way to make it turn on, then off, then stop completely? **

(I am using a Arduino Uno, and am running Arduino version 1.813)

Yes. Move all code from loop() to setup(). You can even remove the last line ("delay(1000);"). :wink:

Thanks! I was thinking that it was only for strictly setup needs, like pin modes.

The other way is to say 'while(1) {}'. Nothing happens after that.

1 Like

Ok

Or as the last line your program executes either

dead : goto dead;

or

for (; ; );

a7

Coolest way would be to put the processor to sleep.

@aarg figuratively and literally! Well played.

a7

Hook up an RC servo to pull out its own power cable.

-jim lee

@jimLee points deducted for involving hardware!

I do have a few devices that turn themselves off using a Polilio power control board. Push button or tilt switch on and one I/O line to reach over and turn the whole thing off. Boost regulator after the power board, things run good "forever" on 3 AAAs.

a7

siborg:
Thanks! I was thinking that it was only for strictly setup needs, like pin modes.

They are just conveniences.

The hidden main() function is like this:

void main()
{
  setup () ;
  while (true)
    loop () ;
}

That's pretty much all there is to it, you are free to do stuff how you want. Note that none of
this is meant to be hidden from you, in your Arduino installation all the source code for the
Arduino runtime is there for you to look at - that's how we learn.

[ You'll find there is a little more to main() than this, in fact, but this is the essence ]

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