Lesson 4.2: Turning Joystick X and Y into Smooth Drive Control
Technical Context
The gamepad joysticks provide a range of motion used for proportional speed control. However, by default, the Y-axis on the gamepad is negative when pushed up and positive when pushed down. If a programmer fails to negate this value in the Java code, the robot will drive backward when the driver intends to move forward, leading to high-speed collisions and potential drivetrain failure.
How Joystick Values Become Drive Commands
Joysticks are members of the gamepad object and are stored as double precision variables with a range of -1.0 to 1.0. The center position of the joystick is exactly 0.0. In a Differential Drive (or Tank Drive) configuration, the Y-axis input is typically used to command the voltage of the DC Motors. To correct the hardware's inverted logical bias, the programmer must perform a simple math operation: double forwardPower = -gamepad1.left_stick_y;.
Annotated Code
@TeleOp(name="Joystick_Scaling", group="Unit4")
public class JoystickScaling extends OpMode {
@Override
public void init() {
telemetry.addData("Status", "Drive Initialized");
}
@Override
public void loop() {
// Correcting the negative 'up' bias of the Y-axis
double drivePower = -gamepad1.left_stick_y;
// Streaming the raw and scaled data back to the Driver Station
telemetry.addData("Raw Stick Y", gamepad1.left_stick_y);
telemetry.addData("Scaled Drive Power", drivePower);
}
}
Fill-in-the-Blank Practice
- A gamepad joystick returns values as a/an
__________datatype. - When a joystick is pushed fully toward the top of the controller, its Y-value is
__________. - The X-axis of a joystick is
__________when pushed to the left and positive to the right.
Show answers
double- -1.0 (negative: this is the hardware bias that must be corrected)
- negative
Simulator Challenge
Robot Scenario: Your robot's drivetrain is too fast for a rookie driver. Create a program that scales the joystick's Y-axis input to 50% of its maximum value and negates it so the robot moves forward when the stick is pushed up.
Show answer
@Override
public void loop() {
double safePower = -gamepad1.left_stick_y / 2.0;
telemetry.addData("Safe Power", safePower);
}
Ready to move on?
Sign in with Google to save your progress with Telemark, or continue without saving.
Stuck on this lesson?
Ask about anything on this page. It can see which lesson you have open and which part you are reading.