One way to create an autonomous code is to use a timer to define which actions should occur when. Within the SDK actions can be set to a timer by using ElapsedTime.
Timers consist of two main categories: count up and count down. In most applications a timer is considered to be a device that counts down from a specified time interval. For instance, the timer on a phone or a microwave. However, some timers, like stopwatches, count upwards from zero. These types of timers measure the amount of time that has elapsed.
ElapsedTime is a count up timer. Registering the amount of time elapsed from the start of a set event, like the starting of a stopwatch. In this case, it is the amount of time elapsed from when the timer is instantiated or reset within the code.
The ElapsedTime timer starts counting the amount of time elapsed from the point of its creation within a code. For instance, in this section ElapsedTime will be created (or instantiated) in the section of code that occurs when the op mode is initialized. There is no option to stop the ElapsedTime timer. Instead, the reset() function can be used within your code to reset the timer at various intervals.
One the timer has been reset, the amount of time that has elapsed can be queried by calling methods like time(), seconds(), or milliseconds(). The time given by the queried methods can be used in loops to dictate how long a specific action should take place.
For more information on the ElapsedTime object check out the Java Docs.
Start by creating a new op mode called HelloWorld_ElapsedTime
using the BasicOpMode_Linear
sample. There are other feature you can select that may make things easier as you begin to develop your autonomous op modes. For instance, as you may recall, selecting Setup Code for Configured Hardware creates the necessary references to the hardware map. Another selection you can make is for the code to be setup as an autonomous op mode. This adds the @Autonomous
annotation that distinguishes the code as an autonomous op mode in the Driver Station Application.
When creating an op mode a decision needs to be made on whether or not to set it to autonomous mode. For applications under 30 seconds, typically required for competitive game play changing the op mode type to autonomous is recommended. For applications over 30 seconds, setting the code to the autonomous op mode type will limit your autonomous code to 30 seconds of run time. If you plan on exceeding the 30 seconds built into the SDK, keeping the code as a teleoperated op mode type is recommended.
For information on how op modes work please visit the Introduction to Programming section.
Selecting the features discussed above will allow you to start with the following code.
Since the focus of this section is Elapsed Time, a variable of ElapsedTime
and an instance of ElapsedTime
needs to be created. To do this the following line is needed
The above line performs two actions. A private ElapsedTime
variable called runtime
is created. Once runtime
is created and defined as an ElapsedTime
variable, it can hold the relevant time information and data. The other part of the line runtime = new ElapsedTime();
creates an instance of the ElapsedTime
timer object and assigns it to the runtime variable.
Add this line to the op mode with the other private variables.
The goal for this example is to have a series of actions performed on timed intervals, like driving forward for three seconds. Another way to think about it is that the robot drives forward while the ElapsedTime
timer is less than or equal to three seconds or runtime.seconds() <= 3.0
. For this particular example the best way to achieve this goal is to use a while loop. Replace the default op mode while loop with the following loop.
It is important to know that, within a linear op mode, a while loop must always have the opModeIsActive()
Boolean as a condition. This condition ensures that the while loop will terminate when the stop button is pressed.
While loops run when the condition is true and stop when the condition is false. In this case, the while loop should only start if both conditions (opModeIsActive()
and runtime.seconds() <= 3.0
) are true. The while loop should terminate when theruntime.seconds() > 3
is greater than three seconds or the stop button on the driver station is pressed. To accomplish this the logical operator &&
needs to be used.
&&
is a logical operator in Java. This symbol is the Java equivalent of "and." Using this in a conditional statement requires that both statements need to be true in order for the overall condition to be true.
Recall that the ElapsedTime
timer starts when it is instantiated or reset. Since the timer is being instantiated when the runtime variable is being created, and the variable creations are happening before the waitForStart();
command is written; the timer will start when the op mode is initialized rather than when the op mode is started. This can cause issues on consistency in the robots performance, depending on the delay between initialization and start.
Consider the following scenario:
In a competition setting, teams are often required to initialize their robot prior to the start of a match. This means that a robot can sit in initialization anywhere from a few seconds to a few minutes. If an autonomous code is centered around using an ElapsedTime
timer that begins upon instantiation, the longer a robot is sitting in initialization the less likely it is to run as expected.
In order to avoid issues from a time delay between initialization and start, a timer reset can be added to the code. Add the line runtime.reset()
; between the waitForStart();
command and the while loop.
Now the timer is reset , lets go ahead and add the motor related code. If you recall from Programming Drivetrain Motors article; the motors on the drivetrain mirror each other. The mirrored nature of the motor mounting causes the motors to rotate in opposing directions. In order to remedy this discrepancy the direction of the right motor needs to be reversed. Add the following lines of code to the op mode above the waitForStart();
command.
Now, within the while loop add the linesleftmotor.setPower(1);
and rightmotor.setPower(1);
to set both motors to run at full speed in the forward direction.
You now have the basic code you need to have your robot drive forward for three seconds. This should give you a basic sense of coding with ElapsedTime
. Other actions like opening and closing a claw, or lifting an arm can be coded into your autonomous program.
As advised in previous sections, it is beneficial to add telemetry to certain code to get the feedback data you want or need. For this example, the telemetry will display how many seconds have elapsed for each leg of the robots journey.
For this particular guide, the end goal is to test the accuracy of a robot driving forward from point a to point b and then driving backwards back to point a. In order to do that another section of code based off the timer needs to be written. One way to do this is to to copy the while loop that you already made and make the necessary edits like switching the direction of power to the motors.
Notice that an additional runtime.reset();
was added to the code above. The other option for a second while loop would have involved adding an additional condition to the while loop. Such as:
while(opModeIsActive() && (runtime.seconds() > 3.0) && runtime.seconds() <=6.0)
The choice to reset the timer before starting a new leg of the robots journey was made to reduce the amount of code changes that may need to be made while testing the code.
Sections
Goals of Section
Learning the logic needed to use elapsed time for autonomous control.
As alluded to in the Hello Robot - Robot Control section, robot control comes in many different forms. One of the control types to consider for robots with drivetrains, is robot navigation.
Robot navigation as a concept is dependent on the type of drivetrain and the type of operation mode. For instance, the code to control a mecanum drivetrain differs from the code used to control a differential drivetrain. There is also a difference between coding for teleoperated driving, with a gamepad, or coding for autonomous, where each movement of the robot must be defined within code.
The following section goes through some of the basics of programming for a differential drivetrain, as well as how to set up a teleoperated arcade style drivetrain code. The concepts and logic highlighted in this section will be applicable the autonomous control section Elapsed Time.
Start by creating a basic op mode called DualDrive
.
Visit the Test Bed - OnBot Java section for more information on creating an op mode. The op mode below focuses on hardware mapping only the relevant drivetrain motors.
Since the focus of this section is creating a functional drivetrain in code, lets started by adding rightmotor.setPower(1);
and leftmotor.setPower(1);
to the op more while loop.
Before moving on try running the code as is and consider the following questions:
What behavior is the robot exhibiting?
What direction is the robot spinning in?
When motors run at different speeds they spin along their center pivot point. But the motors are both set to a power (or duty cycle) of 1?
DC Motors are capable of spinning in two different directions depending on the current flow: clockwise and counter clockwise. When using a positive power value the Control Hub sends current to the motor for it to spin in a clockwise direction.
With the Class Bot and current code, both motors are currently set to run in the clockwise direction. If you set the robot on blocks and run the code again though, you can see that the motors run in opposing directions. With the mirrored way the motors mount to the drivetrain, one motor is naturally the inverse of the other.
Why would the inverse motor cause the robot to spin in a circle? Both speed and direction of rotation of the wheels impact the overall direction the robot moves in. In this case, both motors were assigned to have the same power and direction but how the motors transfer motion to the wheels, causes the robot to spin instead of moving forward.
Check the Introduction to Motion section for more information on the mechanics of transferring motion and power.
In the info block above you were asked to determine which direction the robot spun in. The robot pivots in the direction of the inversed motor. For instance, when the right motor is the inversed motor the robot will pivot to the right. If the left motor is the inversed motor the robot will pivot to the left.
For the Class Bot, the robot pivots to the right, so the right motor will be reversed. Add the line rightmotor.setDirection(DcMotorSimple.Direction.REVERSE);
to the op mode under the variable declarations.
Adding the rightmotor.setDirection(DcMotorSimple.Direction.REVERSE);
code line reverses (or inverses) the direction of the right motor. Both motors now consider the same direction forward an
Recall that when the motors were running in opposing directions the robot spun in circles. This same logic will be used to control the robot using the arcade style of control mentioned in the Hello Robot - Autonomous Robot section.
Remember positive/negative values inputted by the gamepad's y-axis are inverse of the positive/negative values of the motor.
To better understand consider the following table. The table shows the expected value generated from moving the joystick all the way in one direction, along the axis. For instance, when the joystick is pushed all the way in the upwards direction the coordinate values are (0,1).
Now that you have a better understanding of how the physical movement of the gamepad affects the numerical inputs given to your Control System; its time to consider how to control the drivetrain using the joystick.
Recall, from the Programming Drivetrain Motors section, that the speed and direction of a motor plays a large part in how the drivetrain moves.
The numerical outputs for setPower
determine the speed and direction of the motors. For instance, when both motors are set to 1 they move in the forward direction at full speed (or 100% of duty cycle). Much like the gamepads, the numerical value for setPower
is in a range of -1 to 1. The absolute value of the assigned number determines percentage of duty cycle. As an example, 0.3 and -0.3 both indicate that the motor is operating at a duty cycle of 30%. The sign of the number indicates the direction the motor is rotating in. To better understand, consider the following graphic.
When a motor is assigned a setPower
value between -1 and 0, the motor will rotate in the direction it considers to be reverse. When a motor is assigned a value between 0 and 1, it will rotate forward.
In the Programming Drivetrain Motors section, it was discussed that a robot rotates when the motors are moving in opposing directions. However, this has more to do with both speed and direction. To think of it numerically, a differential drivetrain will turn to the right when the setPower
value for the right motor is less than that of the left motor. This is exhibited in the following example.
When both motors are rightmotor.setPower(1); leftmotor.setPower(1);
the robot will run at full speed in a mostly straight line. However, when the rightmotor is running in the same direction but at a lower speed, such as rightmotor.setPower(0.3); leftmotor.setPower(1);
the robot will turn or rotate to the right. This is likely to be an arching movement that is not as sharp as a full pivot. In contrast when the rightmotor
is set to full speed but in the opposite direction of the leftmotor
, the robot pivots to the right. So, mathematically the following is considered to be true:
As previously implied, gamepad1.right_stick_y
and gamepad1.right_stick_x
send values to the Control System from the game pad joystick. In contrast, the setPower
function interprets numerical information set in the code and sends the appropriate current to the motors to dictate how the motors behave.
In an arcade drive, the following joy stick inputs (directions) need to correspond with the following outputs (motor power values).
To get the outputs expressed in the table above, the gamepad values must be assigned to each motor in a meaningful way, where. Algebraic principles can be used to determine the two formulas needed to get the values. However, the formulas are provided below.
Rather than setPower(1);
both the motors can be set to the above formulas. For instance, the right motor can be set as rightmotor.setPower(y-x);
.
With this you now have a functional teleoperated arcade drive. From here you can start adding hardware mapping for the other pieces of robot hardware. Below is an outline of the expected code for the Class Bot with full hardware mapping.
In the previous section you learned about how to use Elapsed Time to allow your robot to navigate the world around it autonomously. When starting out many of the robot actions can be accomplished by turning on a motor for a specific amount of time. Eventually, these time-based actions may not be accurate or repeatable enough. Environmental factors, such as the state of battery charge during operation and mechanisms wearing in through use, can all affect time-based actions. Fortunately, there is a way to give feedback to the robot about how it is operating by using sensors; devices that are used to collect information about the robot and the environment around it.
With Elapsed Time, in order to get the robot to move to a specific distance, you had to estimate the amount of time and the percentage of duty cycle needed to get from point a to point b. However, the REV motors come with built in encoders, which provide feedback in the form of ticks ( or counts) per revolution of the motor. The information provided by the encoders can be used to move the motor to a target position, or a target distance.
Moving the motors to a specific position, using the encoders, removes any potential inaccuracies or inconsistencies from using Elapsed Time. The focus of this section is to move the robot to a target position using encoders.
There are two articles in that go through the basics of Encoders. Using Encoders goes through the basics of the different types of motor modes, as well as a few application examples of using these modes in code. In this section we will focus on using RUN_TO_POSITION
.
The other article, Encoders, focuses on the general functionality of an encoder.
It is recommended that you review both articles before moving on with this guide.
Start by creating a basic op mode calledHelloRobot_EncoderAuton
.
When creating an op mode a decision needs to be made on whether or not to set it to autonomous mode. For applications under 30 seconds, typically required for competitive game play changing the op mode type to autonomous is recommended. For applications over 30 seconds, setting the code to the autonomous op mode type will limit your autonomous code to 30 seconds of run time. If you plan on exceeding the 30 seconds built into the SDK, keeping the code as a teleoperated op mode type is recommended.
For information on how op modes work please visit the Introduction to Programming section.
For more information on how to change the op mode type check out the Test Bed - OnBot Java section.
The op mode structure below is simplified and only includes the necessary components needed to create the encoder based code.
As with all drivetrain related navigation, the directionality of one of the motors needs to be reversed in order for both motors to move in the same direction. Since the Class Bot V2 is still being used add the line rightmotor.setDirection(DcMotor.Direction.REVERSE);
to the code beneath the rightmotor = hardwareMap.get(DcMotor.class, "rightmotor");
code line.
For more information on the directionality of motor check out the Basics of Programming Drivetrains section.
Recall from Using Encoders that using RUN_TO_POSITION
mode requires a three step process. The first step is setting target position. To set target position add the lines leftmotor.setTargetPosition(1000);
and rightmotor.setTargetPosition(1000);
to the op mode after the waitForStart();
command. To get a target position that equates to a target distance requires so calculations, which will be covered later. For now, set target position to 1000 ticks.
The next step is to set both motors to the RUN_TO_POSITION
mode. Add the lines leftmotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
and rightmotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
to your code, beneath the setTargetPosition
code lines.
The main focus of the three step process is to set a target, tell the robot to move to that target, and at what speed (or velocity) the robot should get to that target. Normally, the recommended next step is to calculate velocity and set a target velocity based on ticks. However, this requires quite a bit of math to find the appropriate velocity. For testing purposes, its more important to make sure that the main part of the code is working before getting too deep into the creation of the code. Since the setPower
function was covered in previous sections and will communicate to the system what relative speed (or in this case duty cycle) is needed to get to the target, this can be used in the place of setVelocity
for now.
Add the lines to set the power of both motors to 80% of duty cycle.
Now that all three RUN_TO_POSITION
steps have been added to the code the code can be tested. However, if you want to wait for the motor to reach its target position before continuing in your program, you can use a while loop that checks if the motor is busy (not yet at its target). For this program lets edit the while (opModeIsActive()){}
Recall that, within a linear op mode, a while loop must always have the opModeIsActive()
Boolean as a condition. This condition ensures that the while loop will terminate when the stop button is pressed.
Edit the while loop to include the leftmotor.isBusy()
and righmotor.isBusy()
functions. This will check if the left motor and right motor are busy running to a target position. The while loop will stop when either motor reaches the target position.
Right now the while loop is waiting for the either motor to reach the target. There may be occasions when you want to wait for both motors to reach their target position, in this case the following loop can be used.
while (opModeIsActive() && (leftmotor.isBusy() || rightmotor.isBusy()))
Save and run the op mode two times in a row. Does the robot move as expected the second time?
Try turning the Control Hub off and then back on. How does the robot move?
In the Basic Encoder Concepts section, it is clarified that all encoder ports start at 0 ticks when the Control Hub is turned on. Since you did not turn off the Control Hub in between runs, the second time you ran the op mode the motors were already at, or around, the target position. When you run a code, you want to ensure that certain variables start in a known state. For the encoder ticks, this can be achieved by setting the mode to STOP_AND_RESET_ENCODER
. Add this block to the op mode in the initialization section. Each time the op mode is initialized, the encoder ticks will be reset to zero.
For more information on the motor mode STOP_AND_RESET_ENCODERS
check out the STOP_AND_RESET_ENCODERS section of the Using Encoders guide.
In the previous section, the basic structure needed to use RUN_TO_POSITION
was created. The placement of leftmotor.setTargetPosition(1000);
and rightmotor.setTargetPosition(1000);
within the code, set the target position to 1000 ticks. What is the distance from the starting point of the robot and the point the robot moves to after running this code?
Rather than attempt to measure, or estimate, the distance the robot moves, the encoder ticks can be converted from amount of ticks per revolution of the encoder to how many encoder ticks it takes to move the robot a unit of distance, like a millimeter or inch. Knowing the amount of ticks per a unit of measure allows you to set a specific distance. For instance, if you work through the conversion process and find out that a drivetrain takes 700 ticks to move an inch, this can be used to find the total number of ticks need to move the robot 24 inches.
Reminder that the basis for this guide is the Class Bot V2. The REV DUO Build System is a metric system. Since part of the conversion process references the diameter of the wheels, this section will convert to ticks per mm.
For the conversion process the following information is needed:
Ticks per revolution of the encoder
Total gear reduction on the motor
Including gearboxes and motion transmission components like gears, sprockets and chain, or belts and pulleys
Circumference of the driven wheels
The amount of ticks per revolution of the encoder shaft is dependent on the motor and encoder. Manufacturers of motors with built-in encoders will have information on the amount of ticks per revolution. For HD Hex Motors the encoder counts 28 ticks per revolution of the motor shaft.
Visit the manufacturers website for your motor or encoders for more information on encoder counts. For HD Hex Motors or Core Hex Motors visit our Motor documentation.
Since ticks per revolution of the encoder shaft is before any gear reduction calculating the total gear reduction is needed. This includes the gearbox and any addition reduction from motion transmission components. To find the total gear reduction use the Compound Gearing formula.
For the Class Bot V2 there are two UltraPlanetary Cartridges, 4:1 and 5:1, and an additional gear reduction from the UltraPlanetary Output to the wheels, 72T:45T ratio.
The UltraPlanetary Cartridges use the nominal gear ratio as a descriptor. The actual gear ratios can be found in the UltraPlanetary Users Manual's Cartridge Details.
Using the compound gearing formula for the Class Bot V2 the total gear reduction is:
Unlike the the spur gears used to transfer motion to the wheels, the UltraPlanetary Gearbox Cartridges are planetary gear systems. To make calculations easier the gear ratios for the Cartridges are already reduced.
The Class Bot V2 uses the 90mm Traction Wheels. 90mm is the diameter of the wheel. To get the appropriate circumference use the following formula
You can calculate this by hand, but for the purpose of this guide, this can be calculated within the code.
Due to wear and manufacturing tolerances, the diameter of some wheels may be nominally different. For the most accurate results consider measuring your wheel to confirm that the diameter is accurate.
To summarize, for the Class Bot V2 the following information is true:
Each of these pieces of information will be used to find the number of encoder ticks (or counts) per mm that the wheel moves. Rather than worry about calculating this information by hand, these values can be added to the code as constant variables. To do this create three variables:
COUNTS_PER_MOTOR_REV
DRIVE_GEAR_REDUCTION
WHEEL_CIRCUMFERENCE_MM
The common naming convention for constant variables is known as CONSTANT_CASE, where the variable name is in all caps and words are separated by and underscore.
Add the variables to op mode class, where the hardware variables are defined. Defining the variables within the bounds of the class but outside of the op mode, allows them to be referenced in other methods of functions within the class. To ensure variables are referenceable they are set as static final double
variables. Static allows references to the variables anywhere within the class and final dictates that these variables are constant and unchanged elsewhere within the code. Since these variables are not integers they are classified as double variables.
Now that these three variables have been defined, they can be used to calculate two other variables: the amount of encoder counts per rotation of the wheel and the number of counts per mm that the wheel moves.
To calculate counts per wheel revolution multipleCOUNTS_PER_MOTOR_REV
by DRIVE_GEAR_REDUCTION
Use the following formula:
Where,
Create the COUNTS_PER_WHEEL_REV
variable within the code. This will also be a static final double
variable.
Once COUNTS_PER_WHEEL_REV
is calculated, use it to calculate the counts per mm that the wheel moves. To do this divide theCOUNTS_PER_WHEEL_REV
by the WHEEL_CIRCUMFERENCE_MM
. Use the following formula.
Where,
Create the COUNTS_PER_MM
variable within the code. This will also be a static final double
variable.
COUNTS_PER_WHEEL_REV
will be created as a separate variable fromCOUNTS_PER_MM
as it is used in calculating a target velocity.
Now that you have created the constant variables needed to calculate the amount of ticks per mm moved, you can use this to set a target distance. For instance, if you would like to have the robot move forward two feet, converting from feet to millimeters and multiplying by the COUNTS_PER_MM
will give you the amount of counts (or ticks) needed to reach that distance.
Create two more variables called leftTarget
andrightTarget
. These variables can be fluctuated and edited in your code to tell the motors what positions to go to, rather than place them with the constant variables, create these variables within the op mode but above the waitForStart();
command.
The setTargetPosition();
function takes in a integer (or int) data type as its parameter, rather than a double. Since both the leftTarget
and rightTarget
will be used to set the target position, create both variables as int variables.
Right now the main distance factor is COUNTS_PER_MM
, however you may want to go a distance that is in the imperial system, such as 2 feet (or 24 inches). The target distance in this case will need to be converted to mm. To convert from feet to millimeters use the following formula:
If you convert 2 feet to millimeters, it comes out the be 609.6 millimeters. For the purpose of this guide, lets go ahead an round this to be 610 millimeters. Multiply 610 millimeters by theCOUNTS_PER_MM
variable to get the number of ticks needed to move the robot 2 feet. Since the intent is to have the robot move in a straight line, set both the leftTarget
and rightTarget
, to be equal to 610 * COUNTS_PER_MM
As previously mentioned the setTargetPosition();
function requires that its parameter must be an integer data type. The leftTarget
and rightTarget
variables have been set to be integers, however theCOUNTS_PER_MM
variable is a double. Since these are two different data types, a conversion of data types needs to be done.
In this case theCOUNTS_PER_MM
needs to be converted to an integer. This is as simple as adding the line (int) in front of the double variable. However, you need to be cautious of potential rounding errors. Since COUNTS_PER_MM
is part of an equation it is recommended that you convert to an integer after the result of the equation is found. The example of how to do this is exhibited below.
Edit the setTargetPosition();
lines so that both motors are set to the appropriate target position. To do this add the leftTarget
and rightTarget
variables to their respective motor.
Try running the code and observing the behavior of the robot. Consider some of the following
Is the robot moving forward by two feet?
Does the robot seem to be moving in straight line?
Is the code running without error?
Velocity is a closed loop control within the SDK that uses the encoder counts to determine the approximate power/speed the motors need to go in order to meet the set velocity. When working with encoder setting a velocity is recommended over setting a power level, as it offers a higher level of control.
To set a velocity, its important to understand the maximum velocity in RPM your motor is capable of. For the Class Bot V2 the motors are capable of a maximum RPM of 300. With a drivetrain, you are likely to get better control by setting velocity lower than the maximum. In this case, lets set the velocity to 175 RPM
Recall that setVelocity
is measure in ticks per second.
Create a new double variable called TPS
. Add TPS
the to the op mode under where rightTarget
is defined.
Since RPM is the amount of revolutions per minute a conversion needs to be made from RPM to ticks per second. To do this divide the RPM by 60, to get the amount of rotations per second. Rotations per second can the be multiplied by COUNTS_PER_WHEEL_REV
, to get the amount of ticks per second.
Exchange the setPower();
functions for setVelocity();
. AddTPS
as the parameter for setVelocity();
.
Try to build the code. Do you get errors?
With the current state of the code you are likely to get errors similar to the ones pictured below:
This is because the setVelocity();
function is a function of theDcMotorEx
Interface. The DcMotorEx
Interface is an extension of the DcMotor
Interface, that provides enhanced motor functionality, such as access to closed loop control functions. To use setVelocity();
the motor variables need to be changed to DcMotorEx
. To do this both the private variable creation of the motors, and the hardware mapping need to be changed to DcMotorEx
.
Since DcMotorEx
is an extension of DcMotor
, DcMotor
specific functions can be used by variables defined as DcMotorEx
.
Once you have made these changes the basic, drive two feet code is done! The code below is the finalized version of the code. In this the other hardware components and telemetry have been added.
In the Robot Navigation - OnBot Java section, the mechanism of setPower();
was discussed. setPower();
dictates what direction and speed a motor moves in. On a drivetrain this dictates whether the robot moves in forward, reverse, or turns.
In RUN_TO_POSITION
mode the encoder counts ( or setTargetPosition();
) are used instead of setPower();
to dictate directionality of the motor. If a target position value is greater than the current position of the encoder, the motor moves forward. If the target position value is less than the current position of the encoder, the motor moves backwards
Since speed an directionality impacts how a robot turns, setTargetPostion();
and setVelocity();
need to be edited to get the robot to turn. Consider the following code:
The rightTarget
has been changed to be a negative target position. Assuming that the encoder starts at zero due to STOP_AND_RESET_ENCODER
this causes the robot to turn to the right. Velocity remains the same for both motors. If you try running this code, you may notice that the robot pivots along its center of rotation. To get a wider turn changing the velocity so that the right motor is running at a lower velocity than the left motor. Adjust the velocity and target position as needed to get the turn you need.
For more information on how direction and speed impact the movement of a robot please refer to the explanation of setPower();
in the Robot Navigation section.
The following code walks through adding a turn to the program, after the robot moves forward for 2 feet. After the robot reaches the 2 foot goal, there is a call to STOP_AND_RESET_ENCODERS
this will reduce the need to calculate what position to go to after a position has been reached.
To start, create two variablesand . Both variables will be doubles.
Assign as y = -gamepad1.right_stick_y;
, which is the y-axis of the right joystick.
Assign the as the x = gamepad1.right_stick_x;
, which is the x axis of the right gamepad joystick. The x-axis of the joystick does not need to be inverted.
Setting x = gamepad1.right_stick_x;
and y = -gamepad1.right_stick_y;
assigns values from the gamepad joystick to and . As previously mentioned, the joystick gives values along a two dimension coordinate system. receives the value from the y- axis and receives the value from the x-axis. Both axis output values between -1 and 1.
The table below assumes that the the values from the gamepad have been inverted in code when assigned to the variable .
= COUNTS_PER_MOTOR_REV
= DRIVE_GEAR_REDUCTION
= COUNTS_PER_WHEEL_REV
= COUNTS_PER_MOTOR_REV
= DRIVE_GEAR_REDUCTION
= WHEEL_CIRCUMFERENCE_MM
= COUNTS_PER_WHEEL_REV
= COUNTS_PER_MM
Sections
Goals of Section
What to consider when programming drivetrain motors and how to apply this to an arcade style teleoperated control.
rightmotor.setPower = leftmotor.setPower
Forward or Reverse
rightmotor.setPower > leftmotor.setPower
Left Turn
rightmotor.setPower < leftmotor.setPower
Right Turn
Ticks per revolution
28 ticks
Total gear reduction
30.21
Circumference of the wheel
Joystick Direction
0
1
0
-1
-1
0
1
0
Joystick Direction
(X,Y)
rightmotor
leftmotor
(0,1)
1
1
(0,-1)
-1
-1
(-1,0)
1
-1
(1,0)
-1
1