Hardware timers in PlatformIO

Hi folks.

Seeed Studio XIAO ESP32-C3 dev board @ 160MHz in PlatformIO. Running associated Arduino core for everything non-critical like setting up pins, etc. I do have a few timing-critical routines where I was hoping to achieve sub-microsecond-level precision by using ESP32-C3 hardware timers: However, I am getting unexpeceted results. Can anyone please shed some light on it!
The “timing” part of my test code is as follows:

#include "driver/timer.h"
esp_err_t r1;

esp_err_t r2;

esp_err_t r3;

// TIMER0 initialization
void setupTimer(void) {

  timer_config_t config = {

    .alarm_en = TIMER_ALARM_DIS,

    .counter_en = TIMER_START,

    .counter_dir = TIMER_COUNT_UP,

    .auto_reload = TIMER_AUTORELOAD_EN,

    .divider = TIMER_DIVIDER

  };

  r1 = timer_init(TIMER_GROUP_0, TIMER_0, &config);

  r2 = timer_set_counter_value(TIMER_GROUP_0, TIMER_0, 0);

  r3 = timer_start(TIMER_GROUP_0, TIMER_0);

  ets_printf("timer_init: %d, timer_set_counter_value: %d, timer_start: %d\\n", r1, r2, r3);

}

// dummy test measurement routine, should print out \~1000us worth of ticks difference
uint64_t measure(void) {
  uint64_t t;
  timer_get_counter_value(TIMER_GROUP_0, TIMER_0, &t);  // timing start
  ets_printf("start: %lu, ", t);

  delay(1);                            // simple delay to simulate a sensor

  timer_get_counter_value(TIMER_GROUP_0, TIMER_0, &t);  // timing stop  
  ets_printf("stop: %lu\\n", t);

  return 0;                             // dummy return
}

setupTimer is called from setup() and prints all 0’s so I think TIMER0 is configured, initialized and started correctly. But the measure() function always prints 0’s, both for the start and stop values as if the timer wasn’t running at all??? Where did I go wrong?

Just to test my sanity, instead of the timer_get_counter_value() I tried using the esp_cpu_get_ccount() call.

uint64_t start = esp_cpu_get_ccount();
ets_printf("start: %lu, ", start);

This prints 0.

ets_printf("start: %lu, ", esp_cpu_get_ccount());

This prints a large value so I think it WORKS when called directly???

Again, can you please take a look. Appreciate pointers.

Thx,

Brian

Does it change when you print the value with Serial.println() instead of ets_printf()?

Also uint64_t migh be a unsigned long long, so %llu.

Hi Max. Thank you kindly for the time you took and the insight. I think I got it more or less working now. Forgot to mention, I had also tried Serial.println() and Serial.printf() with the same result. My %ul format specifier was the real problem. Thank you for pointing it out!

Thx,
Brian