Closed Loop Control Getting Started

Setting up Closed-Loop Control

Closed-loop control in REVLib is accessed through the SPARK's closed loop controller object. This object is specific to each motor and contains all the methods needed to control your motor with closed-loop control. It can be accessed as shown below:

// Initialize the motor (Flex/MAX are setup the same way)
SparkFlex m_motor = new SparkFlex(deviceID, MotorType.kBrushless);

// Initialize the closed loop controller
SparkClosedLoopController m_controller = m_motor.getClosedLoopController();

API Docs: SparkFlex, SparkClosedLoopController

To drive your motor in a closed-loop control mode, address the closed loop controller object and give it a set point (a target in whatever units are required by your control mode: position, velocity, or current) and a control mode as shown below:

This will run your motor in the provided mode, but it won't move until you've configured the PID constants.

// Set the setpoint of the PID controller in raw position mode
m_controller.setReference(setPoint, ControlType.kPosition);

API Docs: setReference, ControlType

The provided example above runs the motor in position control mode, which is just a conventional PID loop reading the motor's current position from the configured encoder and taking a setpoint in rotations.

PID Constants and Configuration

To run a PID loop, several constants are required. More advanced controllers require additional parameters to be set and tuned.

To read more about configuration, see this page on general configuration. For more information about SPARK specific configuration, see this page.

PID Parameters

A PID controller has 3 core parameters or gains. For more information on these gains and how to tune them, see Getting Started with PID Tuning.

These gains can be configured on the with the closedLoop member of a SparkFlexConfigor SparkMaxConfig object as seen below:

Feedforward Parameters

There are several Feedforward parameters that can be used to model your system and help support the PID controller, resulting in more precise and consistent motions. These are explained on the Feed Forward Control page.

MAXMotion Parameters

MAXMotion has parameters that allow you to configure and tune the motion profiles generated by MAXMotion. The parameters can be set through the maxMotion member of the closedLoop config.

API Docs: MAXMotionConfig

Cruise Velocity is in units of Revolutions per Minute (RPM) by default

Maximum Acceleration is in units of RPM per Second (RPM/s) by default

Slots

The SPARK MAX and SPARK Flex each have 4 closed-loop slots, each with their own set of constants. These slots are numbered 0-3. You can pass the desired as an argument to each of the applicable configurations.

When applying the setpoint, pass the slot number and the motor controller will switch to the appropriate config.

Last updated

Was this helpful?