Time tracking for downtime of a machine with esp32

hello everyone,
i wanted to ask if somebody can help me with calculating the duration of the time period. i wanted to code in a way that if the value of current (amps) goes above 2A the time tracker begins with counting the time and when it is below the 2A it stops with counting. in this way i wanted to have a clear understanding of when the machine is running and when it is stoped with production.

thanks a lot for ur help.

Note the time (millis) when the current exceeds the threshold.
Note the time when the current drops below the threshold.
Subtract the first timestamp from the second.

i have coded like this but i get 0 sec on my monitor. but i think i use the if statement in a wrong way.

 if(current>2){
  unsigned long startMillis = millis(); 
 
 if(current<2){
  unsigned long currentMillis = millis(); 
  unsigned long duration = ((currentMillis - startMillis)/1000); 
   Serial.print(duration);  Serial.println(" sec"); 
 }
 }

How can current be greater than two and less than two?

I'd not use millis() with an ESP32 but


unsigned long startMillis = millis();
bool GreaterThan2AmpsTriggered = false;
void setup() {
  // put your setup code here, to run once:

}



void loop() {
  // put your main code here, to run repeatedly:


if( (current>2) && (!GreaterThan2AmpsTriggered ))
{
   startMillis = millis();
   GreaterThan2AmpsTriggered = true;
}
 if(current<2 && GreaterThan2Amps ){
  unsigned long duration = (millis() - startMillis ); 
   Serial.print(duration);  
GreaterThan2Amps = false;
 }
 }






}

thank you very much it is working now.

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