Timer

Hi everyone I want to run a function for 10 seconds .I have a button when I click to button I can call the function but I don't know how I will run the function for 10 seconds.when I click the button the function should work for 10 second.Can anybody help me please

When you call the function, record the time that the function was called, using millis(). While the function is running, periodically check the recorded time against the current time (millis()). When 10000 millisecnd has elapsed, return from the function. This is explained, with sample code, in the blink without delay example in the IDE (File Examples, Digital) and this post.

Ask yourself, how do I do this in real life.

.

Very similar to what you need: Timer function - #3 by sterretje - Project Guidance - Arduino Forum

@groundfungus I used millis() functıon but it couldn't work in the while loop.The time passed in the loop taken as 0 .I should make countment so I should use to run the functıon for some second

You can use the micros() function instead of millis(). Timing then in microseconds. The minimum, I believe, is 4 microseconds and 4 microsecond resolution. Check the Reference to be sure.

10 seconds is 10000 milliseconds. Store this value in a variable called timeout (or any name you want).

In your setup routine read the current milliseconds. Store them in a variable like oldtime.

In your main loop use an IF statement.

IF millis() minus oldtime geater than timeout (10 seconds) ........ do whatever you want and set oldtime=millis().

This is pseudo-code. I did not give you real code, because you should analyze the BlinkWithoutDelay routine that comes with the Arduino IDE.

For most codes it is best to use unsigned integer, if you do not negative numbers.