unsigned long to float problem

Hello,

I'am writing a program which includes an "elapsed time to seconds" step. I calculate the elapsed time by substracting two time variables (using two micros() at the two ends of the loop) and then dividing the result by 1000000.
For the division I have to convert the unsigned long to float.
At this step the numbers got mixed up.

Here is the code: (To present my problem more clearly I removed the division part )

  unsigned long t0 = 0;
  unsigned long t1 = 0;
  unsigned long dt = 0;

void setup()
{
   //Setup code...
}

void loop()
{
  
      t0 = micros();
      //
      //Doing a bunch of calculations
      //
      //
      //Setting t1---------------
      //Set t1
      t1 = micros();
      
      //Calculating elapsed time between two samples in milliseconds
      //1 sec is 1000000 microsec
      Serial.print("t1: ");
      Serial.println(t1, 5);
      Serial.print("t0: ");
      Serial.println(t0, 5);
      dt = t1-t0;
      Serial.print("dt: ");
      Serial.println(dt, 5);
      int dt2;
      dt2 = dt;
      Serial.print("dt2: ");
      Serial.println(dt2, 5);
      double dt3;
      dt3 = dt2;
      Serial.print("dt3: ");
      Serial.println(dt3, 5);
}

The output is:

t1: 2240444224
t0: 2240442033
dt: 2141
dt2: 2141
dt3: 296.00000
t1: 2300243244
t0: 2300241044
dt: 2200
dt2: 2200
dt3: 300.00000
t1: 2310042314
t0: 2310040123
dt: 2141
dt2: 2141
dt3: 296.00000

As you can see when I convert to floating point the number changes.

Please, please help me.

Thank you!

I calculate the elapsed time by substracting two time variables (using two micros() at the two ends of the loop) and then dividing the result by 1000000.

I don't see any division occurring.

      Serial.print("t1: ");
      Serial.println(t1, 5);
      Serial.print("t0: ");
      Serial.println(t0, 5);

Why are you printing the numbers using base 5?

Hmmm...I was thinking about giving myself a hard time by using base 5. :slight_smile:
I used 5 decimals, that's why I wrote the number 5 there. You have just showed me, that this was a mistake.
I corrected it, it works now.
Thank you very very much.