In Java, using the set command with a CANSparkmax will control the motor’s speed.
Prerequisites: Installation of revlib 3rd party library
The sparkmax is a motor controller developed by RevRobotics. It’s typically controlled through the CAN bus and requires more complex commands than just a PWM signal. To alleviate this, RevRobotics has created their own code library, revlib, which requires installation.
Within VScode command pallet (ctrl+shift+p)
>WPIlib: Manage Vendor libraries -> Install New Library Online -> https://software-metadata.revrobotics.com/REVLib-2024.json
Revlib installation instructions
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 CANSparkMax (VS code may do this for you)
import com.revrobotics.CANSparkMax;
import com.revrobotics.CANSparkLowLevel.MotorType;
public class Robot extends TimedRobot {
//1. declare PWMSpark max motor
public CANSparkMax basicMotor;
@Override
public void robotInit() {
//2. Initialize basic motor with CAN id and motor type
basicMotor = new CANSparkMax(1, MotorType.kBrushless);
}
@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 CAN 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 may automatically do this)
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.TimedRobot;
//0. Import CANSparkMax (VS code may do this for you)
import com.revrobotics.CANSparkMax;
import com.revrobotics.CANSparkLowLevel.MotorType;
public class Robot extends TimedRobot {
// declare the joystick object
public Joystick joystick;
// declare CANSpark max motor
public CANSparkMax basicMotor;
@Override
public void robotInit() {
//Initialize the joystick to port 0
joystick = new Joystick(0);
//Initialize basic motor with CAN id and motor type
basicMotor = new CANSparkMax(1, MotorType.kBrushless);
}
@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