Simple Question

Why does loop1 write data at full speed and loop2 writes data only once every 5 seconds?

void loop1() {
  unsigned long timestamp = millis();
  // Every 5 seconds write data
  while (millis() - timestamp < 5000) {
    Serial.print("loop1 time = "); Serial.println(millis());
    Serial.println();
  }
}

void loop2() {
  bool writedata = false;
  unsigned long timestamp = millis();
  // Every 5 seconds write data
  while (millis() - timestamp < 5000) {
    writedata = true;
  }
  if (writedata == true) {
    Serial.print("-------------------loop2 time = "); Serial.println(millis());
    Serial.println();
  }
}

I'd expect them both to run full speed. What am I missing?

"loop2" loops setting "writedata" to "true" for five seconds, then prints once and then gets called again, resetting the clock every five seconds.

Now I get this simple example. I was thinking loop2 would step right into the next if condition...

So if I modify loop1 as follows, I get the same result, only loop1 takes a hare over a millisecond where loop two takes a it over 2 milliseconds to complete...

void loop1() {
  unsigned long timestamp = millis();
  // Every 5 seconds write data
  while (millis() - timestamp < 999) {
  }
    Serial.print("loop1 time = "); Serial.println(millis());
    Serial.println();
}

thanks... :slight_smile:

I get the same result, only loop1 takes a hare over a millisecond where loop two takes a it over 2 milliseconds to complete

To print one character at 9600 bps takes just short of a millisecond - could that be your difference?
Without seeing the whole sketch, it is diifficult to judge, or see how you're timing this.

I was just reading millis() printed in the serial monitor.

The loops are basically the whole sketch, I just called them loop1, loop2 for discussion. Setup just sets the serial at full speed.

So the time printed in the first loop was:

loop1 time = 5001

loop1 time = 10002

loop1 time = 15003

loop1 time = 20004

...

and at some point it skipped a millisecond, indicated it was taking a bit longer.

The printed time for loop2 was:

-------------------loop2 time = 5003

-------------------loop2 time = 10005

-------------------loop2 time = 15007

-------------------loop2 time = 20010

...

Not exactly since I'm going from memory, but that was basically how I timed the loops. loop2 took longer, but I think you might be right, most of the time is printing the extra characters... :wink: