Add a function noLoop() to the standard functions

"I want my code to run only once! How to?!"

This question comes up every once in a while, including today. Solution:

#define noLoop() while(1)

Explain it in standard functions and have an example like other functions.

Processing has a noLoop() you can call too.

Or just put the code in setup()?

Iain

Yes, a different method is to put it in setup and the loop() is then only called once. Either way works. It's a simple fix that I proposed.

I'm not sure you understood my comment. Instead of putting your code in loop() put it into setup(). In this case loop() is empty and you don't care how often it's called.

people asking for such a function/define need to learn a bit more about programming, and spent more time on the tutorial and reference section. I think the question will still be asked even if it was part of the language. Its in the nature of tinkerers :slight_smile:

by the way I would call it STOP
#define STOP() while(true)

There are many more of this kind of #defines like

#define REPEAT do {
#define UNTIL(x) }while(!(x));

I once saw a set of defines to create a string switch

SWITCH(string)
{
CASE("monkey") : ...
BREAK;
CASE("fish") :...
BREAK;
DEFAULT ....
BREAK;
}
implementation left as an exercise for the reader .... :slight_smile:

Two things...

First, "noLoop()" versus "exit(0);". The former requires either defining the macro or an addition to the Arduino software. The latter is ready to use. The former leaves the interrupt flag alone which potentially allows the Sketch to limp along. The latter disables interrupts effectively shutting down all execution. They are the same number of characters to type. I think I'll go with the latter.

Second, if you're going to stop execution, you really should put the processor to sleep. (exit does not)

sixeyes:
I'm not sure you understood my comment. Instead of putting your code in loop() put it into setup(). In this case loop() is empty and you don't care how often it's called.

Now I get it. Right you can do that.

Quite technical, but I like it (good luck to the newbies). So what does exit(0) actually do and what command puts the processor to sleep?

So what does exit(0) actually do

This is from the documentation...

In a C++ context, global destructors will be called before halting execution.

I have not tested "in a C++ context" so I don't know if destructors are in fact called. In my test Sketch, this is essentially what was produced...

void exit( int ignored )
{
  cli();
  while ( true );
}

and what command puts the processor to sleep?

This should do the trick (untested)...

#include <avr/sleep.h>

void die( void )
{
  set_sleep_mode( SLEEP_MODE_PWR_DOWN );

  while ( true )
  {
    sleep_enable();
    cli();
    sleep_cpu();
  }
}

The "while ( true )" should not be necessary but I've dealt with enough "should nots" in my life to know that including it is worth the two (or four) bytes of Flash.

1 Like