Search code examples
timerarduinoesp32arduino-ideatmega

Is there a way to calculate -time interval- using Esp32 timers?


I want to calculate time interval with timers. I'm using arduino ide. Also i can not decide which library to useful.

I just tried something following code.

I'm using this library

    #include <ESP32Time.h>

    int a;
    int b;
    int ldrValue;
    #define LDR 0

/* create a hardware timer */
 
      hw_timer_t * timer = NULL;

     int timeThatPast;

 /* motor pin */

      int motor = 14;

/* motor state */

     volatile byte state = LOW;
    
      void IRAM_ATTR onTimer(){
        state = !state;
        digitalWrite(motor, state);
    }

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

      pinMode(motor, OUTPUT);

  /* Use 1st timer of 4 */
  /* 1 tick take 1/(80MHZ/80) = 1us so we set divider 80 and count up */
  
      timer = timerBegin(0, 80, false);

     /* Attach onTimer function to our timer */

      timerAttachInterrupt(timer, &onTimer, true);

//********************ALARM*******************
 

     /* Set alarm to call onTimer function every second 1 tick is 1us
      => 1 second is 1000000us */
      /* Repeat the alarm (third parameter) */
      timerAlarmWrite(timer, 7000000, false);

//********************************************
  /* Start an alarm */

      timerAlarmEnable(timer);
      Serial.println("start timer"); 

}

    void loop() {
      int ldrValue = analogRead(LDR);
      ldrValue = map(ldrValue, 0, 4095, 0, 10000);
        if(ldrValue > 8500){
           a = timerRead(timer);
          digitalWrite(motor,HIGH);
            while(1){
              int ldrValue = analogRead(LDR);
              ldrValue = map(ldrValue, 0, 4095, 0, 10000);
              
              if(ldrValue < 8500){
                
                b = timerRead(timer);
                digitalWrite(motor,LOW); 
                Serial.print("Entering Loop");
                Serial.println(a);
                Serial.println("**********");
                Serial.println("**********");
                Serial.print("Exiting loop");
                Serial.println(b);
                int difference = b - a;  
                Serial.println("Difference");       
                Serial.println(difference);
                break;     
              }

            }
          
          }
        
    }

Solution

  • Use millis or micros if you need more precise timing.

    Here is an example sketch:

    long lastDoTime = 0;
    
    void setup(){
        Serial.begin(115200);
        delay(1000);
        Serial.println("Hello! We will do something at every ms");
    }
    
    void doThisAtEvery(int ms){
        if( millis() - lastDoTime >= ms ){
            // Must save the lastDoTime
            lastDoTime  = millis();
    
            // Do some stuff at every ms
        }
    }
    
    void loop(){
        // It will do the thing in every 100 ms.
        doThisAtEvery(100);
    }
    

    If you want to toggle a pin let's say every 100 microsec

    long lastToggleTime = 0;
    int motorPin = 14;
    boolean lastPinState = LOW;
    
    void setup(){
        Serial.begin(115200);
    }
    
    void togglePinEvery(int micros){
        if( micros() - lastToggleTime >= micros ){
            lastToggleTime = micros();
            digitalWrite(motorPin,!lastPinState);
            lastPinState = !lastPinState;
        }
    }
    
    void loop(){
        togglePinEvery(100);
    }
    

    EDIT Since you wanted timers only.

    Here is a detailed explanation about timers: https://techtutorialsx.com/2017/10/07/esp32-arduino-timer-interrupts/

    Code example:

    volatile int interruptCounter;
    int totalInterruptCounter;
     
    hw_timer_t * timer = NULL;
    portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;
     
    void IRAM_ATTR onTimer() {
      portENTER_CRITICAL_ISR(&timerMux);
      interruptCounter++;
      portEXIT_CRITICAL_ISR(&timerMux);
     
    }
     
    void setup() {
     
      Serial.begin(115200);
     
      timer = timerBegin(0, 80, true);
      timerAttachInterrupt(timer, &onTimer, true);
      timerAlarmWrite(timer, 1000000, true);
      timerAlarmEnable(timer);
     
    }
     
    void loop() {
     
      if (interruptCounter > 0) {
     
        portENTER_CRITICAL(&timerMux);
        interruptCounter--;
        portEXIT_CRITICAL(&timerMux);
     
        totalInterruptCounter++;
     
        Serial.print("An interrupt as occurred. Total number: ");
        Serial.println(totalInterruptCounter);
     
      }
    }