// What happens to interval code when micros()/millis() wrap around.
// JUMP_TO_US = 0  -> honest run from boot (wrap of micros() at ~71.6 min)
// JUMP_TO_US > 0  -> esp_timer is set to this value in setup() (fast repeats)
#define JUMP_TO_US 0ULL
#include "esp_timer.h"
#include "esp_private/esp_timer_private.h"

const unsigned long INTERVAL_US = 1000000;  // 1 s
const unsigned long INTERVAL_MS = 1000;     // 1 s

unsigned long lastBadUs = 0, lastGoodUs = 0, lastBadMs = 0, lastGoodMs = 0;
uint32_t badUs = 0, goodUs = 0, badMs = 0, goodMs = 0, loops = 0;
int64_t nextReport = 0;

void setup() {
  Serial.begin(115200);
  delay(500);
  if (JUMP_TO_US) esp_timer_private_set(JUMP_TO_US);
  Serial.printf("# sizeof(unsigned long)=%u jump=%llu\n", (unsigned)sizeof(unsigned long), JUMP_TO_US);
  lastBadUs = lastGoodUs = micros();
  lastBadMs = lastGoodMs = millis();
  nextReport = esp_timer_get_time() + 1000000;
  Serial.println("# t64_us,micros,millis,loops,bad_us,good_us,bad_ms,good_ms");
}

void loop() {
  unsigned long now = micros();
  // BAD: compare against a future timestamp
  if (now >= lastBadUs + INTERVAL_US) { lastBadUs = now; badUs++; }
  // GOOD: subtract, then compare
  if (now - lastGoodUs >= INTERVAL_US) { lastGoodUs = now; goodUs++; }

  unsigned long nowMs = millis();
  if (nowMs >= lastBadMs + INTERVAL_MS) { lastBadMs = nowMs; badMs++; }
  if (nowMs - lastGoodMs >= INTERVAL_MS) { lastGoodMs = nowMs; goodMs++; }
  loops++;

  int64_t t = esp_timer_get_time();
  if (t >= nextReport) {
    nextReport += 1000000;
    Serial.printf("%lld,%lu,%lu,%lu,%lu,%lu,%lu,%lu\n", t, micros(), millis(),
                  (unsigned long)loops, (unsigned long)badUs, (unsigned long)goodUs,
                  (unsigned long)badMs, (unsigned long)goodMs);
    loops = badUs = goodUs = badMs = goodMs = 0;
  }
}
