In cpp, 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 typicclaly 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:
#include "Robot.h"
#include <fmt/core.h>
//1. import CANSparkMax library
#include "rev/CANSparkMax.h"
//2. declare motor with it's CAN id and motor type in between {}
rev::CANSparkMax basicMotor{1, rev::CANSparkMax::MotorType::kBrushless};
void Robot::TeleopPeriodic() {
//3. set motor to run 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:
#include "Robot.h"
#include <fmt/core.h>
//1. include Joystick library
#include "frc/Joystick.h"
//2. include PWMSparkMax library
#include "rev/CANSparkMax.h"
//3. declare joystick object
frc::Joystick joystick{0};
//4. declare motor with it's CAN id and motor type in between {}
rev::CANSparkMax basicMotor{1, rev::CANSparkMax::MotorType::kBrushless};
void Robot::TeleopPeriodic() {
if (joystick.GetRawButton(1) == true) {
//if button 1 is pressed, turn on motor full speed clock wise
basicMotor.Set(-1.0);
} else {
//else stop motor
basicMotor.Set(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