Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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......");
}
share|improve this question
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 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 at 6:35

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.

share|improve this answer
    
Is there anyway to come out of while(1) loop inside void loop() – Uttam Nov 29 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 at 14:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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