Printing 5 times every loop instead of once

Hi,

I was experimenting with printing out the amount of time since the last boot. I wanted it to print it every 5 seconds. I am actually getting it printing the output 5 times every 5 seconds. At first I thought it was just running through the loop that fast, so I put in a boolean variable to stop it from printing it again until it had passed the next 5 second segment, but that didn't help. Here is the code:

bool printsec = true;
void setup() {
  Serial.begin(115200);
  Serial.println("Starting up.");
}

void loop() {
  // Print time since last boot
  if (millis() % 5000 == 0 && printsec)
  {
    printsec = false;
    Serial.print((millis()/1000));
    Serial.println(" seconds since last boot");
  }
  else {printsec = true;}
}

Here is the output

Starting up.
5 seconds since last boot
5 seconds since last boot
5 seconds since last boot
5 seconds since last boot
5 seconds since last boot
10 seconds since last boot
10 seconds since last boot
10 seconds since last boot
10 seconds since last boot
10 seconds since last boot

What am I doing wrong?

Never mind. I am an idiot. It's probably running through 10 times per millisecond. First time it prints, second time it resets printsec back to true, then it prints again. Solved by adding a 2 millisecond delay after the print.

Once uploading is done, the sketch is automatically started and a 32-bit millisCounter begins to count the elapse time, which is advanced by 1 ms time period. To print the accumulated elapsed time in evevry 5-sec interval, the following codes could be used: (Note that the millis() function can be used at any time to read the current value of millisCounter on the fly.)

unsigned long int prMillis = millis();
unsigned long int elapsedTime = 0;

void setup()
{
  Serial.begin(115200);
}

void loop()
{
  if (millis() - prMillis >= 5000)
  {
      prMillis = millis();
      elapsedTime += 5000;
      Serial.print("Elapsed Time since last Boot: ");
      Serial.print(elapsedTime/1000);
      Serial.println(" sec");
  }
  else
  {
    //do other tasks
  }
}
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.