How to measure time since loop started, not setup

I'm confused as to how to accurately measure the time since loop() started, since millis() measures the total time since the code is being ran. In my case, these are not the same and never will be. I have a switch attached to A0 and ground, and I want the millis() function to initialize to 0 once the switch has been activated. The code I currently have is:

void loop() {

    float x, y, z, xa, ya, za;

if (digitalRead(switchPin) == LOW) {

    if (IMU.gyroscopeAvailable() && IMU.accelerationAvailable()) {

      IMU.readGyroscope(x, y, z);
      IMU.readAcceleration(xa, ya, za);

      //print these values with other stuff

      time1 = millis();
      Serial.println(time1);
    
    }
  }
}

This code still just returns the normal value of millis(), not the amount of time since the switch has been on. Any help is appreciated!

Save millis() as the start time when the switch becomes closed, not when it is closed

Then, at any time later, if you subtract the start time from the current value of millis() you will have the number of milliseconds since it became closed

See the StateChangeDetection example in the IDE

1 Like

Thanks!

I've tried using this code, and I cannot get the millis() value to actually save, and when I put Serial.println(time1 - time2) the value is the same, because both are still counting upwards, and the value is just the permanent difference between them. How can I save the value such that it stops counting upwards?

The code you showed looks like it is saving in millis() in time1. It doesn't show a time2. Do you have other code?

Maybe you mean something like "How do I save the value and not write over it until I need to?" In which case, you need to figure out the https://docs.arduino.cc/built-in-examples/digital/StateChangeDetection/ example as @UKHeliBob suggested.

It is unclear whether you want to record when loop() starts? Or when (digitalRead(switchPin) == LOW && lastSwitchState==HIGH).

Please post the code that you refer to

1 Like

capture a timestamp, T0, at the end of setup(). Measure time from that point

t = millis() - T0;

capture a separate timestamp when the switch closes

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