[esp32] How to disable, reset and again enable timer

I am trying to disable and again enable timer on my ESP32 but I have a problem resetting or restarting it. I don't have right words for that, but basically need him to start counting from 0 again. In arduino it is TCNT1 register. I was trying timerRestart(timer) function but without success. Code below should print out 2 zeros but it prints 0 and 30 because counter inside timer do not resets and it continues counting resulting in shorter ISR call. I don't want initialize whole timer all over again. What is the correct approach?

volatile int interruptCounter = 0;

hw_timer_t * timer = NULL;
void IRAM_ATTR onTimer() {
  interruptCounter++;
}

void setup() {
  Serial.begin(115200);
  timer = timerBegin(0, 80, true);
  timerAttachInterrupt(timer, &onTimer, true);
  timerAlarmWrite(timer, 1000, true);
  Serial.println("Starting test");
  Serial.println(interruptCounter);
  for (int i = 0; i < 100; i++) {
    timerRestart(timer);
    timerAlarmEnable(timer);
    delayMicroseconds(300);
    timerAlarmDisable(timer);
  }
  Serial.println(interruptCounter);
}

void loop() {}

I already found the answer. I had to use :

timerWrite(timer, 0)

to reset it.

1 Like

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