How serial port initialization delay works

I can't figure out how this feature works.

void setup() {
  /* Initialize serial and wait up to 5 seconds for port to open */
  Serial.begin(9600);
  for(unsigned long const serialBeginTime = millis(); !Serial && (millis() - serialBeginTime > 5000); ) { }

On the first pass, millis() - serialBeginTime will be less than 5000 and, therefore, the loop will exit because the truth condition will be violated.

If you want to wait 5 seconds after Serial.begin() before the code continues then why not simply use delay(5000); ?

This is an example from the ArduinoIoTCloud library, I wanted to understand how it works.

To me it only makes sense if the > is changed to a < sign since both !Serial and
millis()-serialBeginTime > 5000 need to be true for the loop to wait up to 5 seconds for
Serial to be TRUE

it's the same as

unsigned long const serialBeginTime = millis();
while (!Serial && (millis() - serialBeginTime > 5000)) {}

which will wait as long as the condition is true.
for a AND condition to be true, you need both to be true
so
➜ Serial needs to be uninitialized
AND
➜ waiting time needs to be more than 5s

ÉDIT: It will exit if one condition is false (which is guaranteed to be the second one immediately)

What about when Serial is not initialized, and it has been less than five seconds? How would you ever reach the five second point?

Yes it’s crappy code, the second condition is false right away and thus the AND is false and you exit the wait loop.

It was likely meant to be < indeed

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