I already found the answer. I had to use : timerWrite(timer, 0) to reset it. Answer from andz on forum.arduino.cc
🌐
Espressif Docs
espressif-docs.readthedocs-hosted.com › projects › arduino-esp32 › en › latest › api › timer.html
Timer — Arduino-ESP32 2.0.14 documentation
/* Repeat timer example This example shows how to use hardware timer in ESP32. The timer calls onTimer function every second. The timer can be stopped with button attached to PIN 0 (IO0). This example code is in the public domain.
🌐
Espressif
docs.espressif.com › projects › esp-idf › en › latest › esp32 › api-reference › system › esp_timer.html
ESP Timer (High Resolution Timer) - ESP32 - — ESP-IDF Programming Guide latest documentation
To start the timer in periodic ... invocation at a specific absolute time and then repeat at regular intervals; the timer will continue running until you explicitly stop it using esp_timer_stop()....
Discussions

Hardware timer, how to run once and restart again?
I had some trouble with timers and alarms on my esp32 doit devboard. Spent many hours trying to debug, end of the days its a silicon issue with the REV0 chips. Not sure if this applies to you but more information can be found here: https://github.com/espressif/arduino-esp32/issues/1313 More on reddit.com
🌐 r/esp32
8
5
April 12, 2021
How to delete and restart hw timer (for interrupts) on demand for esp32 arduino (stepper motor controller application) - Stack Overflow
I am having trouble figuring out ... timer from the esp-arduino library, here for a stepper motor controller application with my esp32 development board. It will count down and trigger the ISR as desired as many times as I want, but when I disable it (so that the ISR is not unnecessarily called), it will not start when I try ... More on stackoverflow.com
🌐 stackoverflow.com
Need Help Getting a Hardware Timer on an ESP32 to Start and Stop and Then Restart on a Trigger - Stack Overflow
I am trying to get a hardware timer in an ESP32 to start and stop based on states in a FSM.I have read quite a few ESP32 Timer Howtos, and I am still not getting it to work. The timer functions cor... More on stackoverflow.com
🌐 stackoverflow.com
Creating an LVGL timer crashes ESP32 with message - Guru Meditation Error: Core 1 panic'ed (LoadProhibited). Exception was unhandled.
SOLVED. So I am officially an idiot. I am OK to admit that and leave this post here. My error is obvious in hindsight - I should have created my timer AFTER initialising LVGL by calling lv_init(). Sometimes haste does indeed make waste... More on reddit.com
🌐 r/esp32
8
21
January 17, 2023
🌐
Arduino Forum
forum.arduino.cc › projects › programming
[esp32] How to disable, reset and again enable timer - Programming - Arduino Forum
January 26, 2021 - 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 …
🌐
Reddit
reddit.com › r/esp32 › hardware timer, how to run once and restart again?
r/esp32 on Reddit: Hardware timer, how to run once and restart again?
April 12, 2021 -

Guys

I have a DevKitC dev board, and I'm trying to set up a HW timer that I want to re-use under certain conditions. In other words, I don't want it to reload automatically, it should run once and then remain dormant until I enable it again. It seems to work the first time, but when I enable the timer a second time it fires immediately, without any delay. It seems I'm not resetting it properly, so that the counter starts from 0 again (?).

What I've tried is this:

initialize timer 0 in setup(), with a prescaler for 80MHz.

myTimer = timerBegin (0, 80, true);
timerAttachInterrupt (myTimer, &isrMyTimer, true);

then when I want to use the timer I enable it as follows (for a duration of 3 seconds):

timerAlarmWrite(myTimer, 3000000), false);
timerAlarmEnable(myTimer);

I am also trying to confirm the frequency to use for the timer, whether it is indeed 80MHz. I get the values as shown below for the different functions. Any thoughts on what they mean?

getCpuFrequencyMhz()		240	
getXtalFrequencyMhz()		40
getApbFrequency()		80000000
Top answer
1 of 4
2
I had some trouble with timers and alarms on my esp32 doit devboard. Spent many hours trying to debug, end of the days its a silicon issue with the REV0 chips. Not sure if this applies to you but more information can be found here: https://github.com/espressif/arduino-esp32/issues/1313
2 of 4
2
I managed to get it working. The trick that worked for me was to reset the timer (counter) before each use, with the following statement: timerRestart() Below is a little pseudo sketch, only showing the relevant statements, to give you or anyone finding this post later, an idea of what worked for me. #include // only needed to get ESP32 frequency detail hw_timer_t * tmrTEST = NULL; // timer used for TESTING unsigned long lngTimerStart = 0; // system micro-seconds at timer start int tmrDuration = 5; // run timer for 5 seconds // Interrupt Service Routine called when TEST timer fires. void IRAM_ATTR isrTimerTEST() { Serial.print(" >>>>> TEST TIMER ISR: "); Serial.print( micros() ); Serial.print(" diff="); Serial.println((micros()-lngTimerStart)/1000/1000); } void setup() { Serial.begin(115200); ... // Set up TEST timer.. tmrTEST = timerBegin (1, 80, true); // use ESP32 Timer 1, pre-scale 80 (for 80MHz freq), count up. timerAttachInterrupt (tmrTEST, &isrTimerTEST, true); // attach the function to call when timer interrupt fires. Edge. Serial.print(" >> CPU Freq: "); Serial.println(getCpuFrequencyMhz()); Serial.print(" >> XTL Freq: "); Serial.println(getXtalFrequencyMhz()); Serial.print(" >> APB Freq: "); Serial.println(getApbFrequency()); ... } void loop() { ... if (tmrDuration > 0) { // initiate TEST timer. duration in micro-seconds. False to run once. timerAlarmWrite(tmrTEST, (tmrDuration * 1000000), false); timerRestart(tmrTEST); // reset timer counter timerAlarmEnable(tmrTEST); // start the timer lngTimerStart = micros(); Serial.print(" >>>>> TimerTEST dur="); Serial.print(tmrDuration); Serial.print(" start: "); Serial.println( lngTimerStart ); } ... } Thanks for your replies and time !
🌐
Espressif
docs.espressif.com › projects › arduino-esp32 › en › latest › api › timer.html
Timer - - — Arduino ESP32 latest documentation
/* Repeat timer example This example shows how to use hardware timer in ESP32. The timer calls onTimer function every second. The timer can be stopped with button attached to PIN 0 (IO0). This example code is in the public domain.
Top answer
1 of 2
1

The word 'restart' had me thinking that it would just immediately start the timer again, but it turns out that is not the case. If the reload was set false previously, the timer has to be set again before it will actually execute - which works perfectly for my use case. Below is my new code (figured I would include the wifi and mqtt stuff to help anyone else as well):

#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include "VCDevices.h"

hw_timer_t * motorTimer = NULL;
Motor linMotor2 = Motor(pulsePin, directionPin);
int d = 0;
bool nextRun = false;

const char* ssid = "SSID";
const char* password = "PASSWORD_HERE";
const char* mqtt_server = "MQTT_SERVER_HERE";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char topArr[50];
char msgArr[100];

portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;

//Timer ISR
void IRAM_ATTR motorInterrupt(void) 
{
  portENTER_CRITICAL(&timerMux);
  noInterrupts();
  //check if the motor is in motion still
  if (!linMotor2.getMotorStatus())
  {
    d = linMotor2.Update();
    //give timer different delay, dependent on its current speed
    timerAlarmWrite(motorTimer, d, true);
    timerAlarmEnable(motorTimer);
  }
  //kill the timer and interrupt if not
  else
  {
    nextRun = true;
    //set the 'reload' boolean to false, to get it to only trigger one more time
    timerAlarmWrite(motorTimer, 10, false);
    // Serial.println("POSITION REACHED!");
  }

  interrupts();
  portEXIT_CRITICAL(&timerMux); 
}

void reconnect() 
{
  // Loop until we're reconnected
  while (!client.connected()) 
  {
    Serial.print("Attempting MQTT connection...");
    Serial.println(mqtt_server);
    // Attempt to connect
    if (client.connect("ESP8266Client"))
    {
      client.subscribe(motorControlTopic);
      Serial.println("connected");
    } 
    else 
    {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}


void setup_wifi() 
{
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* message, unsigned int length)
{
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;
  String response;
  
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }

  Serial.println();
  if (String(topic) == String(motorControlTopic))
  {
    if (messageTemp.toInt() > 0)
    {
      //check if motor is available to run
      if (linMotor2.getMotorStatus())
      {
        
        linMotor2.MoveTo(messageTemp.toInt());

        //set the motor timer and enable it
        timerAlarmWrite(motorTimer, 1, true);
        timerAlarmEnable(motorTimer);
        
        response = "moving to " + String(messageTemp.toInt()) + " mm position";
      }
      else
      {
        response = "motor is busy - wait for movement to end!";
      }
      Serial.println(response);
    }
  } 
}

void setup()
{ 
  //Start serial connection
  Serial.begin(115200);

  //Setup wifi and mqtt stuff
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  //Fix up motor settings
  pinMode(pulsePin, OUTPUT);
  linMotor2.SetSpeed(200);
  linMotor2.SetAcceleration(10);

  //Initialize timer here for later use!
  motorTimer = timerBegin(1, 80, true);
  timerAttachInterrupt(motorTimer, &motorInterrupt, true);
  Serial.println("TIMER SET!!");
  digitalWrite(pulsePin, LOW);

}

void loop()
{
  if (!client.connected()) reconnect();
  client.loop();  
  portENTER_CRITICAL(&timerMux);
  vTaskDelay(500);
  count = linMotor2.GetPosition();
  Serial.println("POSITION: " + String(count));
  if (nextRun)
  {
    noInterrupts();
    timerRestart(motorTimer);
    Serial.println("*********TIMER RESTARTED!******");
    nextRun = false;
    interrupts();
  }
  portEXIT_CRITICAL(&timerMux);
}
2 of 2
1

I found this question to be very similar to an issue I am experiencing, also in a stepper application I need to set a pin HIGH fo the stepper to run and then, after 2ms, need to set the pin back to LOW. To do that I am firing a second timer form inside the ISR of the first timer, but no matter what I try/set, the second timer always fires 23us later. To illustrate that I made the below barebone example so one can see that the interval between to two ISR is always 22/23us no matter what. This routine/strategy is part of the very popular TeensyStep library (ESP32 Fork) and the very short pulse length is not really appreciated by the large DRIVERS. What am I doing wrong?

hw_timer_t *timerA = NULL;
hw_timer_t *timerB = NULL;

void IRAM_ATTR onTimerA()
{
  digitalWrite(13, 1);  
  Serial.print("HI ");
  Serial.println(micros());
  timerAlarmEnable(timerB);
}

void IRAM_ATTR onTimerB()
{
  digitalWrite(13, 0);  
  Serial.print("LO ");
  Serial.println(micros());    
}

void setup()
{
  Serial.begin(115200);
  while (!Serial);

  timerA = timerBegin(0, 80, true);
  timerAttachInterrupt(timerA, &onTimerA, true);
  timerAlarmWrite(timerA, 1000000, true);  
  
  timerB = timerBegin(1, 80, true);
  timerAttachInterrupt(timerB, &onTimerB, true);
  timerAlarmWrite(timerB, 200000, false);

  timerAlarmEnable(timerA);
}

void loop(){}
🌐
Stack Overflow
stackoverflow.com › questions › 79526026 › need-help-getting-a-hardware-timer-on-an-esp32-to-start-and-stop-and-then-restar
Need Help Getting a Hardware Timer on an ESP32 to Start and Stop and Then Restart on a Trigger - Stack Overflow
Long story short, here is the working code for an ESP32 timer interrupt that can be restarted multiple times. // timer interrupt #include <esp_timer.h> hw_timer_t *launch_current_timer = NULL; portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED; int64_t start_time; int64_t end_time; int64_t duration; void IRAM_ATTR LaunchTimerEnd() { LROF(); portENTER_CRITICAL_ISR(&timerMux); input_values.LTE_value = true; portEXIT_CRITICAL_ISR(&timerMux); Serial.println("***LT OFF"); end_time = esp_timer_get_time(); // Get current time in microseconds duration = (end_time - start_time) / 1000; // elapsed tim
Find elsewhere
🌐
Espressif
docs.espressif.com › projects › esp-idf › en › latest › esp32 › api-reference › peripherals › gptimer.html
General Purpose Timer (GPTimer) - ESP32 - — ESP-IDF Programming Guide latest documentation
October 30, 2019 - The gptimer_start() function is used to start the timer. After starting, the timer will begin counting and will automatically overflow and restart from 0 when it reaches the maximum or minimum value (depending on the counting direction). The gptimer_stop() function is used to stop the timer.
🌐
ESP32 Forum
esp32.com › viewtopic.php
How do I stop a timer? - ESP32 Forum
November 2, 2021 - timer_config_t config; config.alarm_en = TIMER_ALARM_EN; //Alarm is the value that the timer will count to before rolling over config.counter_dir = TIMER_COUNT_UP; config.auto_reload = TIMER_AUTORELOAD_EN; config.counter_en = TIMER_PAUSE; //timer_set_counter_value config.intr_type = TIMER_INTR_LEVEL; config.divider = TIMER_DIVIDER; timer_init(TimerGroup, TimerIdx, &config); timer_set_counter_value(TimerGroup, TimerIdx, 0x00000000ULL); timer_set_alarm_value(TimerGroup, TimerIdx, TIMER_PERIODE); timer_enable_intr(TimerGroup, TimerIdx); timer_isr_register(TimerGroup, TimerIdx, timer_group0_isr, (void *) TimerIdx, Interrupt_Level, NULL); and when I want to stop the timer I do the following:
🌐
GitHub
github.com › khoih-prog › ESP32TimerInterrupt
GitHub - khoih-prog/ESP32TimerInterrupt: This library enables you to use Interrupt from Hardware Timers on an ESP32-based board. It now supports 16 ISR-based timers, while consuming only 1 hardware Timer. Timers' interval is very long (ulong millisecs). The most important feature is they're ISR-based timers. Therefore, their executions are not blocked by bad-behaving functions or tasks. This important feature is absolutely necessary for mission-critical tasks. · GitHub
January 29, 2023 - The following is the sample terminal output when running example Change_Interval on ESP32C3_DEV to demonstrate how to change Timer Interval on-the-fly · Starting Change_Interval on ESP32C3_DEV ESP32TimerInterrupt v2.3.0 CPU Frequency = 160 MHz Starting ITimer0 OK, millis() = 293 Starting ITimer1 OK, millis() = 303 Time = 10001, Timer0Count = 5, Timer1Count = 2 Time = 20002, Timer0Count = 10, Timer1Count = 4 Changing Interval, Timer0 = 4000, Timer1 = 10000 Time = 30003, Timer0Count = 12, Timer1Count = 5 Time = 40004, Timer0Count = 15, Timer1Count = 6 Changing Interval, Timer0 = 2000, Timer1 =
Starred by 202 users
Forked by 32 users
Languages   C++ 51.1% | C 48.5% | Shell 0.4%
🌐
ESP32 Forum
esp32.com › viewtopic.php
Using Timer Interrupt and Reload Timer - ESP32 Forum
August 18, 2019 - Serial.println("Reload Timer"); timerAlarmDisable(timer); // stop alarm timerDetachInterrupt(timer); // detach interrupt timerEnd(timer); // end timer timer = timerBegin(0, 80, true); // start time again timerAttachInterrupt(timer, &onTimer, true); // attach interrupt again timerAlarmWrite(timer, 5000000, true); // start alarm again timerAlarmEnable(timer); // enable alarm again ·
🌐
ESP-IDF Programming Guide
my-esp-idf.readthedocs.io › en › latest › api-reference › peripherals › timer.html
TIMER — ESP-IDF Programming Guide v3.0-dev-1395-gb9c6175 documentation
To do so, set the TIMERGN.int_clr_timers.tM structure defined in soc/esp32/include/soc/timer_group_struct.h, where N is the timer group number [0, 1] and M is the timer number [0, 1]. For example to clear an interrupt for the timer 1 in the timer group 0, call the following:
🌐
ESP32 Forum
esp32.com › viewtopic.php
How do i stop and restart timer? - ESP32 Forum
December 18, 2019 - I am new to ESP32. I want to start then stop and again restart(again start from 0) the timer how do i do that? I have reffered https://github.com/pcbreflux/espressif/ ... etimer.ino link. I have also gone through https://docs.espressif.com/projects/esp ... timer.html but i could not make it.
🌐
Espressif
docs.espressif.com › projects › esp-idf › en › stable › esp32s3 › api-reference › system › esp_timer.html
ESP Timer (High Resolution Timer) - ESP32-S3 - — ESP-IDF Programming Guide v6.0.1 documentation
To start the timer in periodic mode, call esp_timer_start_periodic(); the timer will continue running until you explicitly stop it using esp_timer_stop().
🌐
Espressif
docs.espressif.com › projects › esp-idf › en › v4.3 › esp32 › api-reference › peripherals › timer.html
General Purpose Timer - ESP32 - — ESP-IDF Programming Guide v4.3 documentation
Timer Control - describes how to read a timer’s value, pause or start a timer, and change how it operates. Alarms - shows how to set and use alarms. Interrupts- explains how to use interrupt callbacks. The two ESP32 timer groups, with two timers in each, provide the total of four individual ...
🌐
Espressif
docs.espressif.com › projects › esp-idf › en › stable › esp32s2 › api-reference › system › esp_timer.html
ESP Timer (High Resolution Timer) - ESP32-S2 - — ESP-IDF Programming Guide v6.0.1 documentation
To start the timer in periodic mode, call esp_timer_start_periodic(); the timer will continue running until you explicitly stop it using esp_timer_stop().
🌐
DeepBlue
deepbluembedded.com › home › blog › esp32 timers & timer interrupt tutorial (arduino ide)
ESP32 Timers & Timer Interrupt Tutorial (Arduino IDE) – DeepBlueMbedded
February 17, 2025 - You can disconnect it, reset the ESP32 board, Reconnect the input signal again, and it’s going to pick up the incoming signal and print its frequency on the LCD. Concluding Remarks: it’s not ideal in many aspects but it’s simple enough ...
🌐
Espressif
docs.espressif.com › projects › esp-idf › en › v4.2.2 › esp32 › api-reference › peripherals › timer.html
Timer - ESP32 - — ESP-IDF Programming Guide v4.2.2 documentation
Timer Control - describes how to read a timer’s value, pause or start a timer, and change how it operates. Alarms - shows how to set and use alarms. Interrupts- explains how to enable and use interrupts. The two ESP32 timer groups, with two timers in each, provide the total of four individual ...
🌐
Espressif
docs.espressif.com › projects › esp-idf › en › v4.4 › esp32 › api-reference › peripherals › timer.html
General Purpose Timer - ESP32 - — ESP-IDF Programming Guide v4.4 documentation
Timer Control - describes how to read a timer’s value, pause or start a timer, and change how it operates. Alarms - shows how to set and use alarms. Interrupts- explains how to use interrupt callbacks. The two ESP32 timer groups, with two timer(s) in each, provide the total of four individual ...
🌐
TechTutorialsX
techtutorialsx.com › 2017 › 10 › 07 › esp32-arduino-timer-interrupts
ESP32 Arduino: Timer interrupts
How to get started with pydantic, a data validation library for Python based on type annotations. ... In this post we are going to learn how to receive messages sent from the WebSerial UI, on the ESP32.