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 created or reset within the code.
Since this section focuses on creating an autonomous program using ElapsedTime it is important to understand where the elapsed time related blocks are located. At the top of the Categorize Blocks section there is a drop down menu for Utilities. The utilities drop down is a list of various utilities in alphabetical order. Towards the bottom of the the list select Time drop down menu. From there you can select Elapsed Time.
Start by creating a new op mode call HelloWorld_ElapsedTime
using the BasicOpMode
sample.
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 - Blocks section.
Create a variable named runtime
.
For information on creating variables in blocks please revisit the Test Bed - Blocks section.
Use tape to mark the distance from where the robot starts to where you would like it to end up. Try running the code using the following conditions:
Press the init button and immediately press play
Press the init button, wait 30 seconds and then press play
What difference in behavior did you notice?
As mentioned in previous sections, it can be beneficial to have a telemetry output when testing code. In the following example telemetry is used to output the amount of time that has passed with the timer.
The above code will allow your motor to drive straight for 3 seconds. Additional movements can be added by duplicating the while loop. Right click the while loop block and select duplicate
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 in the section of code that occurs when the op mode is initialized. There is no option to stop the ElapsedTime timer. Instead, the block can be used within your code to reset the timer at various intervals.
Once the timer has been reset, the amount of time that has elapsed is queried by calling blocks like . The time given by the queried blocks can be used in loops to dictate how long a specific action should take place.
Add the block to the op mode below the comment block.
In order to utilize elements of the ElapsedTime
, runtime
will act as the ElapsedTime
variable. Add the block to the block.
Before moving on to the rest of the ElapsedTime
structure lets go ahead and add the motor related blocks. Add to the op mode to the while loop.
When there are multiple of the same type of variable (such as multiple Dc Motor variables) the variable specific blocks will choose a default variable based on alphabetical order. For this example Op Mode Dc Motor blocks will default to the arm variable. Click the arrow next to the motor name to change the arm motor variable to the rightmotor variable. Use the variable drop down menu on the block to change from arm to rightmotor.
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 block to the op mode under the the block set.
The goal is to have the motor move forward for 3 seconds. To accomplish this the While loops needs to be edited so that it triggers when the op mode is active and the ElapsedTime timer is less than or equal to 3 seconds. Lets start by creating the less than or equal to condition. Grab the from the Logic menu.
Select the block from the Elapsed Time menu. Drop the block into the left side of the block. Use the drop down menu to change the generic to the variable.
Grab the block from the Math menu.
Add the number block to the right side of the block. Change the number block to 3.
Right now the is equal to three. Use the arrow next to the equal sign to choose the less than or equal to sign from the drop down menu.
Set this block set to the side for now. Grab an block from the Logic menu
Add the call block to the left side of the block. Add the block set to the right side of the block.
This block set will replace the block that is currently attached to the while loop. With this block set in place the while loop will now activate when both conditions of the and block are true.
It is important to know that, within a linear op mode, a while loop must always have the Boolean as a condition. This condition ensures that the while loop will terminate when the stop button is pressed.
Recall that theElapsedTime
timer starts when the timer is created, which occurs where theblock is placed. Since the timer is created prior to , the timer will start when the program is initialized.
If you tested the program you may have noticed that the robot didn't move the during the second run. Depending on how long you wait to start after initialization the timer may be close to or past 3 seconds by the time the program is played. To keep this from happening the timer should be reset once the op mode is active. Grab the call block. Use the drop down menu on the variable block to change the to .
Add the to the op mode beneath the comment and above the while loop.
Once you have duplicated the while loop you can change some of the basic information like motor power or the time interval of the loop. You will also need to add a block between the two loops.
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 are applicable to autonomous control, including the section Elapsed Time.
For controlling the Class Bot V2 drivetrain, being able to control two motors simultaneously is important. This is done through the dual motor block within Blocks. To access the dual motor block, at the top of the Categorize Blocks section there is a drop down menu for Actuators. Selecting DcMotor will drop down the options Dual and another drop down menu Extended. Select Dual to access the dual motor blocks.
When there are multiple of the same type of variable (such as multiple Dc Motor variables) the variable specific blocks will choose a default variable based on alphabetical order. For this example Op Mode Dc Motor blocks will default to the arm variable.
Use the variable drop down menu on the block to change from arm to rightmotor.
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.
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).
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.
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.
With this you now have a functional teleoperated arcade drive!
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.
It is recommended that you review both articles before moving on with this guide.
Start by creating a basic op mode called HelloRobot_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.
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?
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.
When using encoders built into motors, converting from ticks per revolution to ticks per unit of measure moved requires the following information:
Ticks per revolution of the encoder shaft
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.
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.
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 the initialization section of the op mode.
Now that these three variables have been defined, we can use them 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,
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,
COUNTS_PER_WHEEL_REV
will be created as a separate variable fromCOUNTS_PER_MM
as it is used in calculating a target velocity.
Create these variables in Blocks and add then to the op mode under the other constant variables.
OnceCOUNTS_PER_WHEEL_MM
is set, this completes the conversion process, and all constant variables are set.
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.
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
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.
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.
With the velocity set, this is the final thing needed to complete the objective of driving in a straight line. Consider adding telemetry and other hardware components as you begin fleshing out your full autonomous code.
Since speed an directionality impacts how a robot turns, target position and velocity 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 is 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.
Add the block to op mode while loop.
For the Class Bot, the robot pivots to the right, so the right motor will be reversed. Add to the op mode class, under the comment block.
Adding the block changes the direction of the right motor so that both motors will run in the same direction when power is set to one.
To start, create two variables and . Add the andblocks to the while loop.
will be assigned as , which is the y-axis of the right joystick.
Assign as the , which is the x axis of the right gamepad joystick. The x-axis of the joystick does not need to be inverted.
The and block sets assign 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 .
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 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).
When both motors are 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 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, and send values to the Control System from the game pad joystick. In contrast, interprets numerical information set in the code and sends the appropriate current to the motors to dictate how the motors behave.
From the math menu grab the and blocks and add them to the respective motor in the block.
Next add the and to the formula blocks.
There are two articles in that go through the basics of 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, , focuses on the general functionality of an encoder.
For information on how op modes work please visit the section.
For more information on how to change the op mode type check out thesection.
Add the block to the op mode under the .This will change the direction of the rotation of the right motor to be the same direction as the left motor.
For more information on the directionality of motor check out the section.
Recall from that using RUN_TO_POSITION
mode requires a three step process. The first step is setting target position. To set target position, grab the block and add it to the op mode under the comment. 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.
When there are multiple of the same type of variable (such as multiple Dc Motor variables) the variable specific blocks will choose a default variable based on alphabetical order. For this example Op Mode Dc Motor blocks will default to the arm variable. Click the arrow next to the motor name to change the arm motor variable to the rightmotor variable. Use the variable drop down menu on the block to change from arm to rightmotor.
The next step is to set both motors to the RUN_TO_POSITION
mode. Place the block beneath the block.
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 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 velocity for now.
Add the block to the op mode beneath the block. Change the duty cycle (or power) of both motors to 0.8, instead of 1.
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 block.
Recall that, within a linear op mode, a while loop must always have the Boolean as a condition. This condition ensures that the while loop will terminate when the stop button is pressed.
Grab an block from the logic menu and add it to the while loop. On the left side of the block add the block. On the right side add the block.
Embed the in another block. Place the on the right side of the block. On the left side add the block.
Right now the while loop is waiting for the right and left motors to reach their respective targets. There may be occasions when you want to wait for both motors to reach their target position, in this case the can be used.
In the section, it is clarified that ell 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 . 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 section of the Using Encoders guide.
In the previous section, the basic structure needed to use RUN_TO_POSITION
was created. The placement ofwithin 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?
Reminder that the basis for this guide is the . 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.
Visit the manufacturers website for your motor or encoders for more information on encoder counts. For HD Hex Motors or Core Hex Motors visit the 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 .
The UltraPlanetary Cartridges use the nominal gear ratio as a descriptor. The actual gear ratios can be found in the .
Once the variables are created and added to the op mode, use the blocks to set the variables to the respective values. For WHEEL_CIRCUMFERENCE_MM
a combination of the , , and blocks to get the circumference of the wheel. The
= 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
Again math blocks need to be used to define these variables. Lets start with the COUNTS_PER_WHEEL_REV
variable. Add a to the block. Add the and blocks to either side of the block.
Since COUNTS_PER_WHEEL_REV
has been calculated it can be used to calculate COUNTS_PER_MM
add the to the . On the left side of the add the block. On the right side of the add the .
Create two more variables called leftTarget
andrightTarget
. Add the and blocks to the op mode above the block.
Edit the so that both motors are set to the appropriate target position. To do this add the and blocks to their respective motor.
Create a new variable called TPS. Add the to the op mode under the comment block.
Add a block to the block. On the right side of the block add the . One the left side of the add the block. Add the chosen RPM to the left side of the block and 60 to the right side.
Now that the target ticks per second has been set, swap the block for a block. Add the to both motors.
In the section, the mechanism of was discussed. dictates what direction and speed a motor moves in. On a drivetrain the combined direction and speed of the motors dictates whether the robot moves in forward, backwards, or turns.
In RUN_TO_POSITION
mode the encoder counts are used instead of 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
For more information on how direction and speed impact the movement of a robot please refer to the explanation of in the section.
Sections
Goals of Section
What to consider when programming drivetrain motors and how to apply this to an arcade style teleoperated control.
rightMotor = leftMotor
Forward or Reverse
rightMotor > leftMotor
Left Turn
rightMotor < leftMotor
Right Turn
Joystick Direction
0
1
0
-1
-1
0
1
0
Joystick Direction
( , )
rightmotor
leftmotor
(0,1)
1
1
(0,-1)
-1
-1
(-1,0)
1
-1
(1,0)
-1
1
Ticks per revolution | 28 ticks |
Total gear reduction | 30.21 |
Circumference of the wheel |