简体   繁体   中英

Can the PIR sensor work without loop?

void setManual(){
//do something like turn on and off the light
}
void setAuto(){
  for(;;){
     digitalRead(pirPin); //read data from PIR
     digitalWrite(ledPin, pirValue); // turn on and of the light follow the PIR's data
  }
}

My problem is when I call the setAuto() , then I cannot go to another method.
I have no idea about this. So, can the PIR sensor work without loop? Or how can I break this loop for go to another method?

You cannot go into another method because

for(;;)

is an infinite loop.

You can read from a sensor using a timer, elapsed millis, in in the main loop() statement with perhaps a delay in between. Lots of ways to do it. But entering an infinite loop in a separate will probably not do what you want as your program matures to completion. The main loop() in Arduino code is already an infinite loop and the one you should usually use.

You have created an infinite loop using for(;;). You could try this instead:

void setManual(){
    //do something like turn on and off the light
    }
    void setAuto(){
      bool flag=true;
      int data;
      while flag {
         data = digitalRead(pirPin); //read data from PIR
         if(data == 0) { //Specify a condition that can if triggered would change your flag to false and exit the loop
           flag = false;
           //break;     //<-- You can also use this statement to break out of the loop.
         }
         digitalWrite(ledPin, pirValue); // turn on and of the light follow the PIR's data
      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM