How to test millis() rollover on ESP32

I have a sketch that deals with time intervals and I and would like to test if I have coded everything correctly. So I'd like to test the behavior when the number of milliseconds rolls over (when it exceeds `4294967295 and restarts from 0, which happens after about 49 days since startup).
Is there a way to test without waiting 49 days ?
I have found that for Arduino boards the number of millis can be forced as follows:

extern unsigned long timer0_millis;
void setup() {
  timer0_millis = 4294901760;

However this code fails to compile on ESP32 with "undefined reference to `timer0_millis'"

How can I do on ESP32 ?

You could show the code, so we can check if millis() is used correctly.

You could use the ESP32's 64-bit timer capability. That will give you microsecond-resolution and you won't have to worry about rollover for more than 290,000 years.

You can use
unsigned long Mymillis = millis0;
in setup and periodically check that Mymillis is < millis() at the bottom of loop()

but, gfvalvo suggestion makes more sense.

If you use this calculation the roll-over of millis() is handled the right way automatically

define all variables that deal with millis() as unsigned long. Because the return-value of function millis() is of type unsigned long

unsigned long currentMillis;
unsigned long myInterval;
unsigned long startMillis;

if (currentMillis - startMillis >= myInterval) {
  // time for timed action

The integer-math of unsigned integers handles rollover automatically right.
you are doing the math in the if-conditions with variables of type unsigned long.

This means you can do the test with variables that you assign a value short before rollover

currentMillis = 200; // currentMillis short after rollover

startMillis = 4294967295 - 100; // snapshot of time short before rollover

serial.println(currentMillis - startMillis);

I did some research trying to find the library that defines the function millis() for ESP32 but had no success so far

best regards Stefan

Try this code.

RV mineirin

void setup() {
void loop() {
  int long abc = 0;
  abc = esp_timer_get_time();   // ESP32 Fuction similar to micros()
  Serial.println(abc);          // Some delay  add
  delay(1);                     // Delay 1000 uSeconds

In the file ...packages\arduino\hardware\mbed\1.1.6\cores\arduino\wiring.cpp

I found this

unsigned long millis()
  return t.read_ms();

best regards Stefan

Thank you for all your answers. At the end I decided to use the esp_timer_get_time() function and use micros. I also changed any variable used to store micros to the "long long" type.

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