Problems with mills(), micros() [Solved]

Hi! i’m trying to develop a code to call a function each 125microseconds on a Photon device … the code is the following:

void send(int delay) {
   unsigned long startedListening = millis();

   while ((millis() - startedListening) < delay) {
       unsigned long time = micros();

       if (lastRead > time) {
           lastRead = time;
       }

       if ((time - lastRead) > 125) {
           Serial.println("125 = " + String(time - lastRead));
           lastRead = time;
           function;
       }
   }
}

i expected that the printed value would be close to 125microseconds, but the printed output i get on the terminal is the following:

125 = 16926
125 = 5402
125 = 5302
125 = 5505

do you have any idea which is the problem?. thanks!!!

@fbt, your Serial.print() which includes a String conversion will take more than 125us most likely. Also, time is only initialized once I believe. The only real way to time such a short period is with logic analyzer or an oscilloscope.

You may want to consider using SparkIntervalTimer to create a timer interrupt/callback to your function. Since it uses a hardware timer, the interrupts are more reliable and accurate.

@bko, @Moors7, can you please check me on this?

3 Likes

Why don’t you try storing say 10 runs worth of times in a global array and then when they are all done, print them out later instead of immediately. That will take the time taken by Serial.println() out of the measurement.

2 Likes

Thanks @peekay123 and @bko for your help … it is already solved from your comments!

1 Like