0

I have used a switch case in my Arduino project and also I have used a for loop on my second case, but the function is not getting out of the for loop. I want to run my second case only for 5sec then wants to break it. Help me with that.

int cmd;
void loop(){                     // run over and over again
  if(Serial.available()){
    Serial.println("enter 1 or 2");
    cmd=Serial.read();

    switch (cmd){
      case '1':
        function1() ;
        break ;

      case '2':
        int i=0;
        for(i=0;i<100;i++){
          function2();
          delay(50);
        }
        break;    
    }  
  }    
}      
H. Puc
  • 77
  • 1
  • 8
Ravi
  • 189
  • 1
  • 15

1 Answers1

2

Your loop will always take more then 5 seconds to complete as your total delay is 5 seconds plus the execution time of function2. If it is not exiting the loop, my bet would be that your function2 is responsible for that. Anyway, if you need timing, you should use the millis() funcion, the result would be something like this:

long startTime = millis();
long delay = 50000;

while(millis() < startTime + delay){
    functionw();
}

This implementation would be much more closer to your 5 second time limit.

MustSeeMelons
  • 737
  • 1
  • 10
  • 24
  • actually I am using the adafruit fingerprint example files case 1 for enroll and case 2 for fingerprint which can be found on this website ( https://github.com/adafruit/Adafruit-Fingerprint-Sensor-Library/tree/master/examples) – Ravi Mar 23 '17 at 13:00
  • and wants to run the case 2 till the finger is not placed on the sensor – Ravi Mar 23 '17 at 13:03
  • Not really sure what you are trying to accomplish, but if you want to do X while something hasn't happened - use Interrupts. – MustSeeMelons Mar 23 '17 at 14:03