For now our goal will be to have the motors move forward for 3 seconds. To accomplish this we need to edit our main While Loop so that it triggers when the OpMode is active AND the ElapsedTime timer is less than or equal to 3 seconds.
Let's take a look first at how our timer appears in OnBot Java when checking for less than or equal to 3 seconds:
When using our default template, our program will continue running until we press stop on the Driver Hub. However, in this situation we want our program to end when our timer is up. This means we need to modify our while loop to add a second condition!
Alongside our check for opModeIsActive()
we will add our check for if runtime is under 3 seconds:
&&
is a logical operator in Java. This symbol is the Java equivalent of "and."
Think back to in Part 1 we learned that ||
means OR in OnBot Java!
Now the While Loop will now activate when both conditions of the AND block are true.
Let's give our OpMode a try and test the following scenarios:
What happens when hitting play quickly after the initialization button is pressed?
What happens when hitting play 2 seconds after the initialization button is pressed?
What happens when hitting play 10 seconds after the initialization button is pressed?
Not being able to pause between initialization and pressing Play is probably not ideal in most situations. It certainly makes tracking how far the robot will travel more challenging, the opposite of what we'd like ElapsedTime to help us do.
To keep this from happening the timer should be reset once the OpMode is active. Let's add the line runtime.reset();
between the waitForStart();
command and the while loop.
Since this is before our loop our robot will complete it once when Play is pressed. Then will complete the check for our While Loop.
Test your program again with this change!
Now let's explore what happens when we change our time limit to different amounts. You can adjust your time limit by changing the 3 seconds within (runtime.seconds() <= 3.0)
to different numbers.
Consider marking different goals on the floor with tape to practice determining how much time the robot needs to reach it.
In previous parts, we've looked at adding telemetry as a way for the robot to communicate with us. In this situation, it would be helpful for the robot to be able to tell us how much time it has counted so we can make adjustments to our program!
For our key let's call it "Number of Seconds in Phase 1" for now. This will be useful for distinguishing where in our program our robot is during the next section.