Unit 5: Basic FRC Coding
This is where the code meets the physical world. In this lesson, we'll write our first lines of functional code to take input from a joystick and use it to spin a motor—the fundamental building block of every robot action.
To make a motor spin with a joystick, we need to connect three things in our code:
This object represents the physical electronic device your motor is plugged into (e.g., a Spark, Talon, or Victor). We create an object in our code to send commands to this hardware.
This object represents the physical joystick plugged into your Driver Station laptop. We create it to read the position of its axes and the state of its buttons.
This is the "glue" that connects the joystick to the motor. We write code that says, "Get the position of the joystick's Y-axis, and set the motor's speed to that value."
For this first example, we'll put our code directly inside the `Robot.java` file. While this isn't how you'll structure your final competition code (we'll use the Command-Based model for that), it's the simplest way to see the direct cause-and-effect of programming a motor.
// Import the necessary classes at the top of Robot.java
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.motorcontrol.Spark;
public class Robot extends TimedRobot {
// 1. Declare your objects as private member variables
private Spark m_motor;
private Joystick m_joystick;
@Override
public void robotInit() {
// 2. Initialize your objects in robotInit()
// The number in the parentheses is the port number.
// PWM Port 0 for the motor, USB Port 0 for the joystick.
m_motor = new Spark(0);
m_joystick = new Joystick(0);
}
@Override
public void teleopPeriodic() {
// 3. Write your control logic in teleopPeriodic()
// This method runs 50 times per second during driver control.
// Get the joystick's Y-axis value (-1.0 to 1.0)
// The negative sign is used because joysticks typically return a negative value when pushed forward.
double speed = -m_joystick.getY();
// Send the speed value to the motor.
m_motor.set(speed);
}
}
Question: In a simple, non-command-based robot project, which lifecycle method is the correct place to put the code that continuously reads the joystick and updates the motor speed?