Loop Timing

I cant seem to figure out how to find the loop time in seconds. I noticed that if I move the prevMillis = millis() line after the Serial.prints it tells me prevMillis = 0 and never updates. Am I doing something wrong?? dt is increasing with the current time so it seems like prevMillis is never getting set even though it shows it increasing in the Serial.print

void setup() {
Serial.begin(9600);
}

void test() {
unsigned long prevMillis = 0;
float dt = (float(millis()) - float(prevMillis))/1000;
prevMillis = millis();
Serial.print("prevMillis: ");
Serial.print(prevMillis);
Serial.print(" dt:");
Serial.print(dt);
Serial.print("\n");

}

void loop() {
test();
}

What are you trying to time? As it is written, previousMillis is being set to zero as a local variable every time you call test(). If you want to preserve it's value, either declare it static or define it globally and get rid of the declaration inside test().

static unsigned long prevMillis = 0;

Why are you wasting processor cycles converting to float type? Just report dt in unsigned long milliseconds.

The problem is, that you define "unsigned long prevMillis = 0;" at the beginning of your loop. So everytime the loop is run, the value gets set to 0.

 float dt = (float(millis()) - float(prevMillis))/1000;

is efffectively

 float dt = (float(millis()) - 0)/1000;

thus it still changes over time.

Can't verify right now, but something along the lines of

unsigned long prevMillis = 0;

void setup() {
  Serial.begin(9600);
}

void test() {
  
  float dt = (float(millis()) - float(prevMillis))/1000;
  prevMillis = millis();
  Serial.print("prevMillis: ");
  Serial.print(prevMillis);
  Serial.print(" dt:");
  Serial.print(dt);
  Serial.print("\n");
  
}

void loop() {
  test();
}

should work.