timing loop control

Hi guys i've a questions, if a run this code

#define STD_LOOP_TIME 10000 // Fixed time loop of 10 milliseconds
unsigned long lastLoopUsefulTime = STD_LOOP_TIME;
unsigned long loopStartTime,timer;
void setup(){
    Serial.begin(9600);
    loopStartTime = micros();
  timer = loopStartTime;
}

void loop(){
 lastLoopUsefulTime = micros() - loopStartTime;
  if (lastLoopUsefulTime < STD_LOOP_TIME)
    delayMicroseconds(STD_LOOP_TIME - lastLoopUsefulTime);
  loopStartTime = micros();
  Serial.println(lastLoopUsefulTime,DEC);
  
}

why the output is 300? I think it should be 10. mistake?

not tried but my first guess is that you need to cast STD_LOOP_TIME to unsigned long

#define STD_LOOP_TIME 10000UL

robtillaart:
not tried but my first guess is that you need to cast STD_LOOP_TIME to unsigned long

#define STD_LOOP_TIME 10000UL

i've tried but the output is 300 :frowning:

I'm not sure why you think it should be "10". You're subtracting the micros() of the previous loop from the micros() of the current loop and printing the result. You do have a delay but that does not affect what is printed.

Is your intention to make sure the loop runs just once every 10000 microseconds?

yes 10000 microsecond, 10 millisecond

  loopStartTime = micros();
  Serial.println(lastLoopUsefulTime,DEC);

Surely these are the wrong way round. You are adding a delay (quite long, at 9600 baud), after you have taken a timestamp.

batista1987:
yes 10000 microsecond, 10 millisecond

You want something like:

void loop(){
 loopStartTime = micros();

  // do stuff
  Serial.println(micros(),DEC);

  if (micros() - loopStartTime < STD_LOOP_TIME)
    delayMicroseconds(STD_LOOP_TIME - (micros() - loopStartTime) - 200);
}

The Serial.println() is of course printing the micros() for each loop and in your serial monitor you should see the micros() incrementing by 10000 each time. You'll notice an arbitrary "200" in there; when testing the code I notice it was printing increments slightly over 10000 microseconds; that "200" is just a slight adjustment to get it closer to the desired 10000.