In Java, using the set command with a PWM Sparkmax will control the motor’s speed.
Syntax: motorcontroller_name.set(double speed)
Parameters:
- speed: value from -1.0 to 1.0 where 0 is stopped
Example:
package frc.robot;
import edu.wpi.first.wpilibj.TimedRobot;
//0. import PWMSparkMax (VS code will automatically do this after you declare your motor)
import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax;
public class Robot extends TimedRobot {
//1. declare PWMSpark max motor
public PWMSparkMax basicMotor;
@Override
public void robotInit() {
//2. Initialize basic motor to use PWM channel Zero
basicMotor = new PWMSparkMax(0);
}
@Override
public void teleopPeriodic() {
//3. Run the motor at 50% speed counter clockwise
basicMotor.set(0.5);
}
}
The above example shows the steps to run a PWM Sparkmax with the “timed robot template” in vs code. But that’s not super useful! Here’s an example of controlling it with a button on you joystick:
package frc.robot;
// import Joystick (VS code will automatically do this after you declare your joystick)
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.TimedRobot;
//0. import PWMSparkMax (VS code will automatically do this after you declare your motor)
import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax;
public class Robot extends TimedRobot {
// declare the joystick object
public Joystick joystick;
// declare PWMSpark max motor
public PWMSparkMax basicMotor;
@Override
public void robotInit() {
//Initialize the joystick to port 0
joystick = new Joystick(0);
//Initialize basic motor to use PWM channel Zero
basicMotor = new PWMSparkMax(0);
}
@Override
public void teleopPeriodic() {
//if joystick button 1 is pressed
if (joystick.getRawButton(1) == true) {
// Run the motor at 100% speed clockwise
basicMotor.set(-1.0);
}
else {
//if button isn't pressed, stop the motor
basicMotor.set(0.0);
}
}
}
Full code examples can be found here: https://github.com/sweddavid178/FRCExamples/tree/main/Sparkmax
If you have questions or requests reach out to contact.rcrobot@gmail.com