Serious bug in micros()

Here is the problem - in this program bgn is often larger than end.

void setup() {
  Serial.begin(9600);
  while(!Serial) {}
  Serial.println("bgn, end, bgn - end");
  for (uint32_t i = 0; i < 10000; i++) {
    uint32_t bgn = micros();
    uint32_t end = micros();
    if (bgn > end) {
      Serial.print(bgn);
      Serial. print(',');
      Serial.print(end);
      Serial.print(',');
      Serial.println(bgn - end);
    }
  }
}
void loop() {
}

Here is the print out for the first few cases with bgn > end.

bgn, end, bgn - end
25992,25000,992
43992,43000,992
65993,65001,992
83994,83002,992

I posted an issue about this on GitHub Arduino.

2 Likes

Link: https://github.com/arduino/ArduinoCore-renesas/issues/49

1 Like

A great fix for this has been posted as a pull request for the official R4 core here.