Exit From Void Loop

Dunno why I can't write 5-10 lines of code to exit a VOID LOOP on a button push and call a function. I've tried WHILE, IFs, BREAK and more, but I just cant crack it.

It's gotta be simple. Help please.

My code snip below compiles OK and the sketch works, but the button push is ignored.

void loop(){
  while (pinSW=HIGH){
  if(oldEncPos != encoderPos) {
    Serial.println(encoderPos);
    oldEncPos = encoderPos;
    }}}
    AA();

if( ) while( true ) ; // blocks the loop() on button press

Making a few assumptions:

Perhaps because you never read that pin. Even you do in the code you failed to share, the while condition will always get the last value placed into pinSW.

Which, BTW, will happen to be HIGH, because you also erred in using = assignment instead of == test for equality.

You have to digitalRead(pinSW) any time you want to see if the value at the pin in changed.

a7

Do you want to completely exit the loop() function or do you want to call another function and return to the loop() function when done.?

What do the serial prints tell you about the state of your program?

while (pinSW=HIGH)

Show the code where/when/how does pinsSW get set to a high or low or in-between or negative high or positive low or what ever?

Also:

while (pinSW=HIGH){ . . .

Looks odd.

If pinSW is the name of the pin, you’d normally write something like this:

while ( digitalRead( pinSW ) == HIGH ) ) { . . .

Post your entire sketch.

ardocman:
Dunno why I can't write 5-10 lines of code to exit a VOID LOOP

The way to exit a function is with return;

But why would you want to exit from loop() - the way the Arduino code works it will be immediately called again. That's why it has the name loop()

...R

while (pinSW=HIGH){

All that succeeds in doing is to set the pinSW variable to HIGH

You need to do a digitalRead() of the pin state and to use == for comparison

Thanks UKHeliBob.

That's a big help.

Perhaps if you look in main.cpp in the hardware\arduino\avr\cores\arduino\ directory you can see how the GCC compiler sets things up (partial listing):

int main(void)
{	
   init();
   initVariant();
#if defined(USBCON)
   USBDevice.attach();
#endif
   setup();
   for (;;) {
      loop();
      if (serialEventRun) 
         serialEventRun();
   }
   return 0;
}

I have killed loops using inputs (buttons, sensors, etc.) with the interrupt features of Arduino. Not sure if this is applicable here but worth mentioning.

Interrupts are hardly ever needed for buttons.

@OP, it looks like AA() is a function call outside loop(). I suggest that you use tools -> autoformat to properly indent your code. If AA() is placed at the beginning of a line, it's outside loop().

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