Timing a loop

hi,
i want to let a servo sweep for a certain amound of seconds. so far i tried to use the StopWatch libary to do this:

Servo myservo;  // create servo object to control a servo 
                
 StopWatch MySW;  // create Stopwatch
int pos = 0;    // variable to store the servo position 
 

void loop() 
{ 
  
  MySW.start();
  if(MySW.value()<7000){

      for(pos = 90; pos < 100; pos += 1)  // goes from 0 degrees to 180 degrees 
      {                                  // in steps of 1 degree 
        myservo.write(pos);              // tell servo to go to position in variable 'pos' 
        delay(50);                       // waits 15ms for the servo to reach the position 
      } 
       
      for(pos = 100; pos>=90; pos-=1)     // goes from 180 degrees to 0 degrees 
      {                                
        myservo.write(pos);              // tell servo to go to position in variable 'pos' 
        delay(50);                       // waits 15ms for the servo to reach the position 
      } 
     
  }
  else{
    myservo.write(120);
    delay(5000);
  }

so it should sweep for 7000 ms and then move to 120°. My problem is that it does not stop at 7000ms. it always first finishes the sweep for loops and then stops. this gives a few more ms depending on where in the for loop it is.

is there a way to let it stop at exactly 7000ms? some kind of interrupt?

On each iteration of the loop, you need to test the time:

      for(pos = 90; pos < 100 [glow]&& MySW.value()<7000[/glow]; pos += 1)  // goes from 0 degrees to 180 degrees

Getting rid of the delays would allow the function to stop at exactly the specified time.

while(MwSW.value() < 7000)
{
// see if it's time to move a servo
// move to new position
// record time of this move
}

nice. thanx! seems to work perfectly. and i changed the delay to 15 ms because this is exact enough :smiley: