-2

I have been trying to exit from the while(1) loop by getting a value from the sensor and then run the code outside while(1).But the problem is that it does not exit. How may I fix this problem?

See Code Below.......

void setup() {
    pinMode(2,INPUT);
    Serial.begin(9600);
}

void loop() {
    int sensor;
    while(1)
    {
        sensor = digitalRead(2);
        if(sensor == 0)
        {
            Serial.println("inside while loop");
        }
        break;
    }
    Serial.println("Break......");
}
2
  • 1
    The while(1) loop executes once, every time loop() is called, printing or not, depending on the state of pin2. I would expect this code to print: either "inside while loop" (if pin 2 is false) or nothing, followed by "Break......"; over and over again. Is that what you're getting? Your question is incomplete. Please describe what you expected to see, and what you do see, on the terminal.
    – JRobert
    Nov 29 '16 at 3:20
  • The loop function loops (is called repeatedly). Why do you put an indefinite loop inside a function that is called indefinitely?
    – Nick Gammon
    Dec 15 '16 at 6:35
6

In the Arduino paradigm, unlike ordinary C programming where there is only 1 entry point called "main()", there are 2 entry points called "setup()" and "loop()". "setup()" is called only once after booting up. But "loop()" is called over and over again right after "setup()" is called. There is no need to create your own infinite loop (for example a "while(1)" statement) as in ordinary C programming.

2
  • Is there anyway to come out of while(1) loop inside void loop()
    – Uttam
    Nov 29 '16 at 0:54
  • Sorry for the delay, holidays. Yes, but most do not think this is good programming. You can execute a 'break" inside the loop and exit the loop. This Stackexchange question / answer goes into the details.
    – st2000
    Dec 1 '16 at 14:56
1

instead of while(1), one can use the variable name in while and change the value of the variable when you want to exit the loop. part of the code can be modified based on the following concept. bool condition= true; while(condition){ if (sensor==0) condition=false; This is my suggestion for the above problem.

1

Used like this

void setup() {
    pinMode(2,INPUT);
    Serial.begin(9600);
}

void loop() {
     bool cond = true;

int sensor;
while(cond)
{
    sensor = digitalRead(2);
    if(sensor == 0)
    {
        Serial.println("inside while loop");
    }
    cond = false;
}

  // like this you can used while inside the void loop()

}
1
  • Could you please add some explaination on how this solves the problem.
    – sa_leinad
    Nov 3 '20 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.