How do I run a while loop for a certain amount of time? (i.e. 5 seconds)

How do I run a while loop for a certain amount of time? (i.e. 5 seconds) Thanks!

To have a while loop run for a certain amount of time, use a timer!

vex::timer Timer = vex::timer();

You would place this near your motor/device identification section, and you call on the timer using this command.

Timer.clear();  // clears the current time stored in the timer
float currentTime = Timer.time(vex::timeUnits::sec);  // updates the timer

In the while loop, remember to update the value of the current time, so your while loop doesn’t become infinite!

while (currentTime < 5) {
 // loopy stuff

 // update timer!
 currentTime = Timer.time(vex::timeUnits::sec);
}
Device Identification Section Example
#include "Robot.h"

#include "vex.h"

vex::controller Controller = vex::controller();
vex::controller Controller2 = vex::controller(vex::controllerType::partner);

vex::timer Timer = vex::timer();
6 Likes

Holy thanks so much you literally just saved me (tournament tomorrow morning lol)!

1 Like