Go Down

Topic: timing loop control (Read 1 time) previous topic - next topic

batista1987

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

Code: [Select]

#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?

robtillaart


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

#define STD_LOOP_TIME 10000UL


Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

batista1987



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 :-(

Chagrin

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?

batista1987

yes 10000 microsecond, 10 millisecond

dxw00d

Code: [Select]
  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.

Chagrin


yes 10000 microsecond, 10 millisecond


You want something like:

Code: [Select]
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.

Go Up