Pages: [1]   Go Down
Author Topic: Run function only for a period of time  (Read 242 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 15
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi,

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

Code:
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:
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!
Logged

Finland
Offline Offline
Jr. Member
**
Karma: 1
Posts: 84
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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.
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 15
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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!
Logged

Pages: [1]   Go Up
Jump to: