How to break a While loop with no user input for a certain time?

Hi,

I am trying to break a while loop when there is no user input for a certain time passed. The exit condition is when the user press the D6 button. It will stay in the while loop if D6 is not pressed. How would I break the loop for a certain time passed when the user did not press D6 button?

    while (digitalRead(D6) != LOW)
  {
     -- do sometime
-- time passed no input break while loop
}

Thanks

I like to do it like this:

	unsigned long startTime = millis();
	while (digitalRead(D6) != LOW && millis() - startTime < 30000) {
		// Do something
	}

Change 30000 to the length of time in milliseconds.

1 Like

@rickkas7, thanks for your help. Is there any way to start the timer on the last user action in the while loop? I tested your suggestion code, the time starts from the beginning and if you take longer then the set time, it exit the loop and kick you out even if you are doing something in the loop. I been searching the forum there is a software timer maybe its a better solution. Going to give it a try in a little bit. Any other suggestion will be great. :smile:

Just reset startTime = millis() each time you see a user action.

@ScruffR, I used the software timers, Timer timer(3000, FunctionUpdateflag); and did a timer.reset() on user action. Which is preferred millis() or Timer? It seem both does almost the same thing.

For simple tasks like that I’d go for millis().

I would use timers “only” for tasks that actually are running asynchronous and “independent” to your main application while I drop in millis() wherever I need some timing there and then without having to create an object and keep track if I’ve got a free timer left or not, but that’s just my personal opinion.

1 Like