Breaking out of loop()

I tried looking at a way of breaking out of the loop() function, the comments state that you return out of a function to stop the function but the posts I have seen all say that loop() still runs.

If I were to read two button states or three, like a CTRL+ALT+DEL state and then call the main(); function from within loop() and main does nothing, will that end the program or do I have to do something like while(1){}; to keep the processor doing something?

bool running = true;

void loop() {
  if (running) {
     // set running to false to 'exit' loop forever
  }
}

'break' will exit the loop function, wherever it is placed. So if it's not at the top, all the lines between it and the beginning, will still run.

This will also work:

bool running = true;

void loop() {
  // nothing can be in here
  if (not running) {
     break;
  }
... // other code
}

But it's more confusing than the simple way above.

No, a break will only exit the current conditional block (if/switch) and for/while loop construct.
Depending on how the code is structured, this may not exit the loop function.
Did you mean "return"?

I think this is easiest. Returning from main() (which would cause an exit to the OS on a computer that had an OS) in an embedded system is ambiguous at best, and you can’t do it from and arduino sketch, anyway.

Just write a stop function:

void stop() {
   noInterrupts();    //optional.   Shouldn’t matter.
   while(1) { /* spin and do nothing */ }
}

I'm looking to build a state machine that when a certain condition is met, the program stops and won't do anything until it is reset.

The reset has to perform some housekeeping functions as modules connected to it retain information after power off, so before that happens, I have to "Listen" for a reset sequence being initiated as the information needs to be retained until the reset has occurred but only after the condition has been met by the listening for a stop request.

So imagine this situation, three buttons, when pressed at once and held for 3 seconds causes the "Stop" and I need to leave loop() and wait on another function to listen for the same three buttons pressed again simultaneously to reset the modules attached.

Then return to loop() to await start again by pressing of any of the three buttons.

I'm talking at beginner level. The OP said "exit" and I'm just sticking with their terminology for the time being.

In a state machine, all you need to do this, is an IDLE state (that does nothing).

But, this talk of "returning to loop" makes zero sense in the context of a state machine. Please show us your state machine.

You should have mentioned your state machine in the first post. It obviously affects what you are trying to do.

The thing you are calling a "reset" sounds more like a "shutdown".

Good luck with your project.

I have yet to fully write it, what I have is a roughing out and won't make any sense because the way I program is to write in a manner that makes sense to me despite the functionality not being correct, I add in what I need when I work it out.

I have seen examples of state machines that are a list of functions, eg...

Blockquote
void loop(){
getButtonState();
checkButtonPressed();
sendSignalsToOutputs();
if( someStateReached ){ // we end it
while(1){};
}
}

When I get to if( someStateReached ) I intend on jumping out of loop() to do things to wait for the restart as I don't want the state to change at that point because I am using external modules that keep a count of whats happened, even when power is turned off, it returns, so I need to have some housekeeping done, such as store a copy of that information in the flash memory so I can check it to see if the external mods were cleared or not, of not, to reset the external mods.

THB the more I explain the more confusing it will become which is why I ask simple questions first.

I tried using OpenAI chatGPT to generate possible examples I could use but even with an AI its understanding of what I was trying to attempt didn't generate anything close to what I am building.

Sure it generated a couple of state machines but they were nothing like I need, the examples helped a little but not that much as its not complete in terms of what question I asked, almost like it was just spitting out previously stored examples and then some advice on one about the fact I used a non digital pin to generate something that would use PWM, which was helpful to know.

For example, I asked it how you would use a state machine to pulse a pin (7) when one of two buttons are pressed without using delay() and it used delay within a state machine... It got confused with the "Reset" and treated the reset as an input when its going to be an output signal to the external modules...

I'm pretty sure by now you're completely lost and confused.

To give you some idea... I shall try and give you a rundown of the states involved.

The system listens for one of 3 buttons to be pressed to start that count, when another button is pressed, that count stops and another counter starts and so on until all three buttons are pressed and held for 3 seconds, all active counters cease to count and an audible beep is made. The machine then sits and waits for three buttons to be pressed again for 3 seconds AFTER the first check on three buttons being pressed and held has had a "Release" state detected if so, beeps are output in that process, the internal reference is reset and external references are reset and the system returns back to waiting for one of three buttons to be pressed. (back in to loop() )

If power is lost, the external references will when powered back on indicate their last state automatically as they are not part of the Arduino, which is why the internal count needs to be checked from flash and if it has counts in them, to pulse the reset pin allocated to clear those counts on external modules then enter a listener state as described above.

Confused much? I know I am as the code I have does need to be completed before I can test it, I am still waiting on parts to arrive to build the external components and check if I need to build a debouncer module as I can't be doing with making it in software for reliability reasons and peace of mind and simplifying code to negate needing to illuminate an LED to confirm button pressed.

break does not exit an if block. Consider:

while (true) {
    bool done = is_it_done();
    if (done) {
        break;
    }
}

If break exited only the if block, it would be effectively the same as leaving out the if block completely (and the loop would never end). But break does not exit only an if block, so the loop can end (if/when is_it_done() returns true).

I'm slowly giving up on Arduino, fed up of being able to upload simple sketches and then when I try something bigger thats within the size constraints, suddenly Arduino IDE reckons there is no Arduino attached or the port is not avilable.

I even tried downloading the IDE version 2.x and that doesn't run at all and this is a 64bit dual core PC.

Thanks to everyone thats tried to help but I think the guys at Arduino need to pull their heads out for a while and sort their IDE's out.

What? I've never had this happen to me. Have you tried getting help to troubleshoot that issue?

Hi,
Have you got more than one Arduino controller?
Have you changed the USB cable?

Tom.. :smiley: :+1: :coffee: :australia:

Its the nano without the USB and has external FTDI.

I have had similar issues with the UNO board.

The IDE sees the attached board (at the time) but doesn't reckon the USB is attached.

IDK what the problem is. I downloaded the IDE2 and the software doesn't run says to me that the issue is within the IDE and not the hardware.

The IDE needs the USB to be attached to see the board, so USB must be attached.
How do you know the IDE can see the attached board?

Thanks.. Tom.. :smiley: :+1: :coffee: :australia:

Because I can see it on the connection information at the bottom of the IDE.

It is only when the time comes to upload to the Arduino that the IDE then decides that it is not connected.

I regressed in terms of IDE version to be able to successfully connect without issues and upload, so this is a problem in the IDE later version, a bug introduced by the dev team.

Hi, @MarkG

That is telling you what the IDE is expecting.
This what my IDE shows and I don't have a controller connected.

The IDE looks there when it starts to upload, it is not what has been found.

You need to look here to see what ports the IDE can see.

port

Tom... :grinning: :+1: :coffee: :australia:

Why the fascination with whatever you're doing not being in the loop function? For what you describe, put that code that you want to be out of loop in that while 1 block. When you're ready to "go back to loop" then break out of the while loop.

It seems you may have a misunderstanding of how a state machine works. It isn't one function after another where the execution stays in the one function until that state is over. In a state machine the loop function repeats very fast and acts almost like a checklist to locate simple actions to take.

void loop(){
   switch (state) {
       case WAITING_ON_BUTTON:
              // Code to check the button
             //if button pressed change state to RUNNING_MOTOR
             break;
       case RUNNING_MOTOR:
              // code to take a single step with the motor
             // if limit switch activate change state to BLINKING_LIGHTS
             break;
        case BLINKING_LIGHTS:
            //  code to calculate if it's time to blink and blink if so
            //  check three buttons
            //  if three buttons pressed change state to IDLE
            break;
        case IDLE:
            //  Don't do nuffin
           //  Check for the exit signal
           //  If exit signal then go to SHUTDOWN state.
           break;
        case SHUTDOWN:
           // do your shutdown code
           break;
   }
}

The thing about a state machine is that the loop function will be called thousands of times a second. It will check that button thousands of times a second. Or check if it's time to blink thousands of times a second. Don't ever think you're wasting the processors effort. The states just decide what's going to happen. And if one of them is nothing then it is. You don't have to exit the loop function to stop things from happening.

2 Likes

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