Go Down

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

aufruf

Hi,

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

Code: [Select]
int totalTime = 1; // in minutes
int Interval = 2; // in seconds
int 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

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

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