Go Down

### Topic: Run function only for a period of time (Read 611 times)previous topic - next topic

#### aufruf

##### Feb 03, 2013, 04:48 pm
Hi,

I would like to run a function only for a specified period of time.

Code: [Select]
`int totalTime = 1; // in minutesint Interval = 2; // in secondsint counter = 0;unsigned long currentTime = 0;unsigned long previousTime = 0;void setup () { Serial.begin(9600); Serial.println("Start");}void loop() {  myCount();}void myCount(){   currentTime = millis();    if (currentTime - previousTime > (Interval*1000)){ previousTime = currentTime; counter = counter+1; Serial.println(counter);  }}`

In my code totalTime sets the overall period of time for which the function should run. My first attempt was to have a variable startTime and check this against the currentTime - totalTime. My problem is that when I put the code like below startTime gets overwritten each time.

Code: [Select]
`void myCount(){   currentTime = millis();  startTime = millis();    if (currentTime - previousTime > (Interval*1000) && startTime + totalTime < currentTime){ previousTime = currentTime; counter = counter+1; Serial.println(counter);  }}`

How would you implement this? Many thanks in advanve!

#### Chaul

#1
##### Feb 03, 2013, 05:14 pm
You mean for a specific amount of time from last reset or from a button press etc? As far as I know, millis() starts counting from zero after power on.

In any case, I would make the function define the action it should do and nothing more, and then have the running condition of that function in loop().
Code: [Select]
`if (millis() - startTime < totalTime*1000*60)  myCount();`
Where startTime has been initialized either to 0, or millis() at a specific event depending on what you want to trigger it. I assume you mean this variable to contain this info, so take it out of myCount(). It should be initialized somewhere else, not all the time. The function myCount would get called for totalTime [minutes] in a loop.

#### aufruf

#2
##### Feb 03, 2013, 05:24 pm
Hi,

Thanks a lot for that. Yes, I mean from a button press. The overall theme is to start the system (power on), do some adjustments in the preference menu and then from the menu start the system for a defined period of time. So I will need a startTime variable.

I will try to separate the two - thanks for the hint.

Cheers!

Go Up