CPP | PWM Sparkmax control Using Set

In cpp, 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:

#include "Robot.h"

#include <fmt/core.h>
//1. import PWMSparkMax library
#include "frc/motorcontrol/PWMSparkMax.h"

//2. declare basic motor object with PWM port number inbetween {}
frc::PWMSparkMax basicMotor{0};

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 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:

#include "Robot.h"

#include <fmt/core.h>
//1. include Joystick library
#include "frc/Joystick.h"
//2. include PWMSparkMax library
#include "frc/motorcontrol/PWMSparkMax.h"

//3. declare joystick object
frc::Joystick joystick{0};
//4. declare basic motor object with PWM port number inbetween {}
frc::PWMSparkMax basicMotor{0};

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