How do I measure time

Hello, I am here to ask how to make a action after time, for example how to make the robot turn after 14 seconds have past

//previous lines 
task::sleep(time in milliseconds, 1000 per second);
turn();

So you’d set task::sleep to 14000

I see what you are saying, however my question should be more clear, i’m asking about 14 seconds after the program initially started

In VEXcode V5 text, you can spin off a new thread at the start of the program that waits the desired amount of time, then does whatever you want:

#include "vex.h"

using namespace vex;

int wait_14sec(){
  this_thread::sleep_for(14000);

  //your code goes here!

  return(0);
}

int main(){
  thread myThread(wait_14sec);

  while (true){
    this_thread::sleep_for(10)
  }

}

On the off chance you’re using RobotMesh Studio Javascript, this becomes a fair bit easier to do - JS is designed to do these sorts of things more easily:

setTimeout(function(){
    //your code goes here!
}, 14000);

Note that with both of these approaches, your code is not guaranteed to run after exactly 14 seconds, only after at least 14 seconds - it may take longer if some other code takes up a lot of CPU time in such a way that it prevents the OS from switching back to the wait-14-seconds thread until more than 14 seconds have passed. That said, in most cases it will probably get close enough to 14 seconds for the precise time not to matter too much.

2 Likes

I think this would work:

#include "vex.h"

using namespace vex;

timer startTimer;

int main() {
  startTimer.reset();
  while(startTimer.time() <= 14000){
    // do things for the first 14 seconds
    wait(20, msec);
  }
  while(1){
    // do things forever after 14 seconds
    wait(20, msec);
  }
}
2 Likes

That’s all well and good but why don’t you just do

Int main(){
    task::sleep(14000);
    //other stuff
}
1 Like

You can pretty much do the same thing in VEXcode.
using threads/tasks that would be

  task t2( []()->int {
      this_thread::sleep_for(14000);
      printf("Done\n");
      return 0; 
  });

and even easier, using a timer

  timer::event( []()->void {
      printf("Timer fired\n");
      return; 
    }, 14000 );

(note, the lambda used cannot capture parameters)

6 Likes

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.