I'm going to assume you're using IterativeRobot, since SampleRobot (or implementations of RobotBase) should really only be used if you're 100% certain you know what you're doing.
You'll notice IterativeRobot has both Init and Periodic functions for Robot, Autonomous, Teleop, Test and Disabled (e.g. AutonomousPeriodic, TeleopPeriodic, RobotInit, etc). The Init functions are called when you enter that mode, and the Periodic functions are called on a regular basis. You can think of the Periodic functions as being inside of the loop, and the Init functions above the loop.
The robot main loop follows a process to ensure you don't end up 'locking up' the program in the loop. It goes like this:
Check state (from driverstation) -> If different from the last, call <state>Init -> Call <state>Periodic -> Repeat
During each iteration, the state is checked, and the appropriate periodic function is called. Because of this, it's important not to lock up the Periodic functions (e.g. don't put in your own loops unless they have a set number of iterations, such as iterating over motors).
"But how can I do motor.set(val); sleep(3); motor.set(0)?"
This is fairly simple. Instead of putting a sleep in the periodic function, check if that time has elapsed. Something like this:
Code:
void AutonomousInit() {
start_time = now();
}
void AutonomousPeriodic() {
if (now() - start_time < 3) {
motor.Set(val);
} else {
motor.Set(0);
}
}
This allows you to do time-based functions using the periodic functions. I wouldn't recommend coding these time checks yourself, though. WPILib provides the Command-Based programming system that abstracts this for you, and allows you to code Commands for a discrete action (e.g. DriveForward, LiftArm, etc). I suggest doing some reading on that if you're looking to do autonomous.