Why do multiple consecutive calls to micros() not return consecutive values ?

This was asked in Nov '17 but no answer was given. So my code is

#include "Adafruit_VL53L0X.h"

Adafruit_VL53L0X lox = Adafruit_VL53L0X();
long timeLast = 0;
long timeNow = 0;
long timeGap = 0;
float timeN = 0;

void setup() {
  Serial.begin(115200);
  // wait until serial port opens for native USB devices
  while (! Serial) {
    delay(1);
  }

  Serial.println("Adafruit VL53L0X test.");
  if (!lox.begin()) {
    Serial.println(F("Failed to boot VL53L0X"));
    while(1);
  }
  // power
  Serial.println(F("VL53L0X API Continuous Ranging example\n\n"));

  // start continuous ranging
  lox.startRangeContinuous();
}

void loop() {
  
  if (lox.isRangeComplete()) {
    timeNow = micros();
    timeN = micros();
    timeGap = timeNow - timeLast;
    Serial.print(timeNow);
    Serial.print(",");
    Serial.print(lox.readRange());
    Serial.print(",");
    Serial.print(timeGap);
    Serial.print(",");
    Serial.println(timeN);
  }
  timeLast = timeNow;
}


I am running it on a Uno R3 board. When I check the output by subtracting timeNow from timeN, I find occasionaly I get a value of -4, that is time according to the two calls of the micros function has gone backwards. If I switch timeN to a data type long, I don't get negative values. Fortunately, I intend to put some code between the two micros calls which also ensures I don't get negative values.

So whilst I don't need a cure, I thought it might be worth flagging up the curious behaviour. Some one suggested it might be hardware related. I do have not only the VL53LOX sensor attached but also a shield with an SD card and clock.

The answer to your question is that it is working as designed.

From micros() - Arduino Reference

On the boards from the Arduino Portenta family this function has a resolution of one microsecond on all cores. On 16 MHz Arduino boards (e.g. Duemilanove and Nano), this function has a resolution of four microseconds (i.e. the value returned is always a multiple of four). On 8 MHz Arduino boards (e.g. the LilyPad), this function has a resolution of eight microseconds.

Like Delta_G explained. You get the wrong result occasionally. Every time there is a roll over....
So your occasional might be very regular...

Thank you. That gives me confidence to contnue my development at sub milli second time intervals, though perhaps i should upgrade my arduino to a faster speed like the Due.

Arduino speed check...

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