CTRE Phoenix 6 C++ 25.1.0
Loading...
Searching...
No Matches
SwerveModule.hpp
Go to the documentation of this file.
1/*
2 * Copyright (C) Cross The Road Electronics.  All rights reserved.
3 * License information can be found in CTRE_LICENSE.txt
4 * For support and suggestions contact support@ctr-electronics.com or file
5 * an issue tracker at https://github.com/CrossTheRoadElec/Phoenix-Releases
6 */
7#pragma once
8
12
13namespace ctre {
14namespace phoenix6 {
15namespace swerve {
16
19
20/**
21 * \brief Swerve Module class that encapsulates a swerve module powered by
22 * CTR Electronics devices.
23 *
24 * This class handles the hardware devices and configures them for
25 * swerve module operation using the Phoenix 6 API.
26 *
27 * This class constructs hardware devices internally, so the user
28 * only specifies the constants (IDs, PID gains, gear ratios, etc).
29 * Getters for these hardware devices are available.
30 */
31template <
32 typename DriveMotorT,
33 typename SteerMotorT,
34 typename EncoderT,
35 typename = std::enable_if_t<std::is_base_of_v<hardware::traits::CommonTalon, DriveMotorT>>,
36 typename = std::enable_if_t<std::is_base_of_v<hardware::traits::CommonTalon, SteerMotorT>>,
37 typename = std::enable_if_t<std::is_base_of_v<hardware::ParentDevice, EncoderT>>
38>
40public:
41 /**
42 * \brief Contains everything the swerve module needs to apply a request.
43 */
45
46protected:
47 /** \brief Number of times to attempt config applies. */
48 static constexpr int kNumConfigAttempts = 2;
49
50 /** \brief The underlying swerve module instance. */
52
53private:
54 DriveMotorT _driveMotor;
55 SteerMotorT _steerMotor;
56 EncoderT _encoder;
57
58public:
59 /**
60 * \brief Construct a SwerveModule with the specified constants.
61 *
62 * \param constants Constants used to construct the module
63 * \param canbusName The name of the CAN bus this module is on
64 * \param module The impl#SwerveModuleImpl to use
65 */
66 template <
67 typename DriveMotorConfigsT,
68 typename SteerMotorConfigsT,
69 typename EncoderConfigsT,
70 typename = std::enable_if_t<std::is_base_of_v<configs::ParentConfiguration, DriveMotorConfigsT>>,
71 typename = std::enable_if_t<std::is_base_of_v<configs::ParentConfiguration, SteerMotorConfigsT>>,
72 typename = std::enable_if_t<std::is_base_of_v<configs::ParentConfiguration, EncoderConfigsT>>
73 >
76 std::string_view canbusName,
78 ) :
79 _module{&module},
80 _driveMotor{constants.DriveMotorId, std::string{canbusName}},
81 _steerMotor{constants.SteerMotorId, std::string{canbusName}},
82 _encoder{constants.EncoderId, std::string{canbusName}}
83 {
85
86 DriveMotorConfigsT driveConfigs = constants.DriveMotorInitialConfigs;
87 driveConfigs.MotorOutput.NeutralMode = signals::NeutralModeValue::Brake;
88
89 driveConfigs.Slot0 = constants.DriveMotorGains;
90 driveConfigs.TorqueCurrent.PeakForwardTorqueCurrent = constants.SlipCurrent;
91 driveConfigs.TorqueCurrent.PeakReverseTorqueCurrent = -constants.SlipCurrent;
92 driveConfigs.CurrentLimits.StatorCurrentLimit = constants.SlipCurrent;
93 driveConfigs.CurrentLimits.StatorCurrentLimitEnable = true;
94
95 driveConfigs.MotorOutput.Inverted = constants.DriveMotorInverted ? signals::InvertedValue::Clockwise_Positive
97 for (int i = 0; i < kNumConfigAttempts; ++i) {
98 response = GetDriveMotor().GetConfigurator().Apply(driveConfigs);
99 if (response.IsOK()) break;
100 }
101 if (!response.IsOK()) {
102 printf("Talon ID %d failed config with error %s\n", GetDriveMotor().GetDeviceID(), response.GetName());
103 }
104
105 SteerMotorConfigsT steerConfigs = constants.SteerMotorInitialConfigs;
106 steerConfigs.MotorOutput.NeutralMode = signals::NeutralModeValue::Brake;
107
108 steerConfigs.Slot0 = constants.SteerMotorGains;
109 /* Modify configuration to use remote encoder setting */
110 steerConfigs.Feedback.FeedbackRemoteSensorID = constants.EncoderId;
111 switch (constants.FeedbackSource) {
113 steerConfigs.Feedback.FeedbackSensorSource = signals::FeedbackSensorSourceValue::FusedCANcoder;
114 break;
116 steerConfigs.Feedback.FeedbackSensorSource = signals::FeedbackSensorSourceValue::SyncCANcoder;
117 break;
119 steerConfigs.Feedback.FeedbackSensorSource = signals::FeedbackSensorSourceValue::RemoteCANcoder;
120 break;
121 }
122 steerConfigs.Feedback.RotorToSensorRatio = constants.SteerMotorGearRatio;
123
124 steerConfigs.MotionMagic.MotionMagicExpo_kV = 0.12_V / 1_tps * constants.SteerMotorGearRatio;
125 steerConfigs.MotionMagic.MotionMagicExpo_kA = 0.8_V / 1_tr_per_s_sq / constants.SteerMotorGearRatio;
126
127 steerConfigs.ClosedLoopGeneral.ContinuousWrap = true; // Enable continuous wrap for swerve modules
128
129 steerConfigs.MotorOutput.Inverted = constants.SteerMotorInverted
132 for (int i = 0; i < kNumConfigAttempts; ++i) {
133 response = GetSteerMotor().GetConfigurator().Apply(steerConfigs);
134 if (response.IsOK()) break;
135 }
136 if (!response.IsOK()) {
137 printf("Talon ID %d failed config with error %s\n", GetSteerMotor().GetDeviceID(), response.GetName());
138 }
139
140 configs::CANcoderConfiguration encoderConfigs = constants.EncoderInitialConfigs;
141 encoderConfigs.MagnetSensor.MagnetOffset = constants.EncoderOffset;
142 encoderConfigs.MagnetSensor.SensorDirection = constants.EncoderInverted
145 for (int i = 0; i < kNumConfigAttempts; ++i) {
146 response = GetEncoder().GetConfigurator().Apply(encoderConfigs);
147 if (response.IsOK()) break;
148 }
149 if (!response.IsOK()) {
150 printf("Encoder ID %d failed config with error %s\n", GetEncoder().GetDeviceID(), response.GetName());
151 }
152 }
153
154 virtual ~SwerveModule() = default;
155
156 /**
157 * \brief Applies the desired ModuleRequest to this module.
158 *
159 * \param moduleRequest The request to apply to this module
160 */
161 virtual void Apply(ModuleRequest const &moduleRequest)
162 {
163 return _module->Apply(moduleRequest);
164 }
165
166 /**
167 * \brief Controls this module using the specified drive and steer control requests.
168 *
169 * This is intended only to be used for characterization of the robot; do not use this for normal use.
170 *
171 * \param driveRequest The control request to apply to the drive motor
172 * \param steerRequest The control request to apply to the steer motor
173 */
174 template <typename DriveReq, typename SteerReq>
175 void Apply(DriveReq &&driveRequest, SteerReq &&steerRequest)
176 {
177 return _module->Apply(std::forward<DriveReq>(driveRequest), std::forward<SteerReq>(steerRequest));
178 }
179
180 /**
181 * \brief Gets the state of this module and passes it back as a
182 * SwerveModulePosition object with latency compensated values.
183 *
184 * This function is blocking when it performs a refresh.
185 *
186 * \param refresh True if the signals should be refreshed
187 * \returns SwerveModulePosition containing this module's state.
188 */
189 SwerveModulePosition GetPosition(bool refresh)
190 {
191 return _module->GetPosition(refresh);
192 }
193
194 /**
195 * \brief Gets the last cached swerve module position.
196 * This differs from #GetPosition in that it will not
197 * perform any latency compensation or refresh the signals.
198 *
199 * \returns Last cached SwerveModulePosition
200 */
201 SwerveModulePosition GetCachedPosition() const
202 {
203 return _module->GetCachedPosition();
204 }
205
206 /**
207 * \brief Get the current state of the module.
208 *
209 * This is typically used for telemetry, as the SwerveModulePosition
210 * is used for odometry.
211 *
212 * \returns Current state of the module
213 */
214 SwerveModuleState GetCurrentState() const
215 {
216 return _module->GetCurrentState();
217 }
218
219 /**
220 * \brief Get the target state of the module.
221 *
222 * This is typically used for telemetry.
223 *
224 * \returns Target state of the module
225 */
226 SwerveModuleState GetTargetState() const
227 {
228 return _module->GetTargetState();
229 }
230
231 /**
232 * \brief Resets this module's drive motor position to 0 rotations.
233 */
234 virtual void ResetPosition()
235 {
236 return _module->ResetPosition();
237 }
238
239 /**
240 * \brief Gets the closed-loop output type to use for the drive motor.
241 *
242 * \returns Drive motor closed-loop output type
243 */
248
249 /**
250 * \brief Gets the closed-loop output type to use for the steer motor.
251 *
252 * \returns Steer motor closed-loop output type
253 */
258
259 /**
260 * \brief Gets this module's Drive Motor reference.
261 *
262 * This should be used only to access signals and change configurations that the
263 * swerve drivetrain does not configure itself.
264 *
265 * \returns This module's Drive Motor reference
266 */
267 DriveMotorT &GetDriveMotor()
268 {
269 return _driveMotor;
270 }
271
272 /**
273 * \brief Gets this module's Steer Motor reference.
274 *
275 * This should be used only to access signals and change configurations that the
276 * swerve drivetrain does not configure itself.
277 *
278 * \returns This module's Steer Motor reference
279 */
280 SteerMotorT &GetSteerMotor()
281 {
282 return _steerMotor;
283 }
284
285 /**
286 * \brief Gets this module's azimuth encoder reference.
287 *
288 * This should be used only to access signals and change configurations that the
289 * swerve drivetrain does not configure itself.
290 *
291 * \returns This module's azimuth encoder reference
292 */
293 EncoderT &GetEncoder()
294 {
295 return _encoder;
296 }
297};
298
299}
300}
301}
Class for CANcoder, a CAN based magnetic encoder that provides absolute and relative position along w...
Definition CoreCANcoder.hpp:38
MagnetSensorConfigs MagnetSensor
Configs that affect the magnet sensor and how to interpret it.
Definition CoreCANcoder.hpp:65
units::angle::turn_t MagnetOffset
This offset is added to the reported position, allowing the application to trim the zero position.
Definition Configs.hpp:79
signals::SensorDirectionValue SensorDirection
Direction of the sensor to determine positive rotation, as seen facing the LED side of the CANcoder.
Definition Configs.hpp:67
static constexpr int RemoteCANcoder
Use another CANcoder on the same CAN bus (this also requires setting FeedbackRemoteSensorID).
Definition SpnEnums.hpp:2324
static constexpr int SyncCANcoder
Requires Phoenix Pro; Talon will synchronize its internal rotor position against another CANcoder,...
Definition SpnEnums.hpp:2365
static constexpr int FusedCANcoder
Requires Phoenix Pro; Talon will fuse another CANcoder's information with the internal rotor,...
Definition SpnEnums.hpp:2353
static constexpr int CounterClockwise_Positive
Positive motor output results in clockwise motion.
Definition SpnEnums.hpp:2129
static constexpr int Clockwise_Positive
Positive motor output results in counter-clockwise motion.
Definition SpnEnums.hpp:2133
static constexpr int Brake
Definition SpnEnums.hpp:2207
static constexpr int CounterClockwise_Positive
Counter-clockwise motion reports positive rotation.
Definition SpnEnums.hpp:277
static constexpr int Clockwise_Positive
Clockwise motion reports positive rotation.
Definition SpnEnums.hpp:281
Swerve Module class that encapsulates a swerve module powered by CTR Electronics devices.
Definition SwerveModule.hpp:39
virtual void Apply(ModuleRequest const &moduleRequest)
Applies the desired ModuleRequest to this module.
Definition SwerveModule.hpp:161
virtual void ResetPosition()
Resets this module's drive motor position to 0 rotations.
Definition SwerveModule.hpp:234
SwerveModulePosition GetPosition(bool refresh)
Gets the state of this module and passes it back as a SwerveModulePosition object with latency compen...
Definition SwerveModule.hpp:189
SwerveModuleState GetTargetState() const
Get the target state of the module.
Definition SwerveModule.hpp:226
impl::SwerveModuleImpl * _module
The underlying swerve module instance.
Definition SwerveModule.hpp:51
SwerveModule(SwerveModuleConstants< DriveMotorConfigsT, SteerMotorConfigsT, EncoderConfigsT > const &constants, std::string_view canbusName, impl::SwerveModuleImpl &module)
Construct a SwerveModule with the specified constants.
Definition SwerveModule.hpp:74
EncoderT & GetEncoder()
Gets this module's azimuth encoder reference.
Definition SwerveModule.hpp:293
ClosedLoopOutputType GetDriveClosedLoopOutputType() const
Gets the closed-loop output type to use for the drive motor.
Definition SwerveModule.hpp:244
void Apply(DriveReq &&driveRequest, SteerReq &&steerRequest)
Controls this module using the specified drive and steer control requests.
Definition SwerveModule.hpp:175
DriveMotorT & GetDriveMotor()
Gets this module's Drive Motor reference.
Definition SwerveModule.hpp:267
SwerveModulePosition GetCachedPosition() const
Gets the last cached swerve module position.
Definition SwerveModule.hpp:201
ClosedLoopOutputType GetSteerClosedLoopOutputType() const
Gets the closed-loop output type to use for the steer motor.
Definition SwerveModule.hpp:254
static constexpr int kNumConfigAttempts
Number of times to attempt config applies.
Definition SwerveModule.hpp:48
SteerMotorT & GetSteerMotor()
Gets this module's Steer Motor reference.
Definition SwerveModule.hpp:280
SwerveModuleState GetCurrentState() const
Get the current state of the module.
Definition SwerveModule.hpp:214
Swerve Module class that encapsulates a swerve module powered by CTR Electronics devices.
Definition SwerveModuleImpl.hpp:60
SwerveModuleState GetCurrentState() const
Get the current state of the module.
Definition SwerveModuleImpl.hpp:336
ClosedLoopOutputType GetSteerClosedLoopOutputType() const
Gets the closed-loop output type to use for the steer motor.
Definition SwerveModuleImpl.hpp:374
SwerveModuleState GetTargetState() const
Get the target state of the module.
Definition SwerveModuleImpl.hpp:348
void Apply(ModuleRequest const &moduleRequest)
Applies the desired ModuleRequest to this module.
ClosedLoopOutputType GetDriveClosedLoopOutputType() const
Gets the closed-loop output type to use for the drive motor.
Definition SwerveModuleImpl.hpp:364
SwerveModulePosition GetPosition(bool refresh)
Gets the state of this module and passes it back as a SwerveModulePosition object with latency compen...
void ResetPosition()
Resets this module's drive motor position to 0 rotations.
Definition SwerveModuleImpl.hpp:353
SwerveModulePosition GetCachedPosition() const
Gets the last cached swerve module position.
Definition SwerveModuleImpl.hpp:326
Status codes reported by APIs, including OK, warnings, and errors.
Definition StatusCodes.h:27
SteerRequestType
All possible control requests for the module steer motor.
Definition SwerveModuleImpl.hpp:24
DriveRequestType
All possible control requests for the module drive motor.
Definition SwerveModuleImpl.hpp:40
ClosedLoopOutputType
Supported closed-loop output types.
Definition SwerveModuleConstants.hpp:23
@ FusedCANcoder
Requires Pro; Use signals::FeedbackSensorSourceValue::FusedCANcoder for the steer motor.
@ SyncCANcoder
Requires Pro; Use signals::FeedbackSensorSourceValue::SyncCANcoder for the steer motor.
@ RemoteCANcoder
Use signals::FeedbackSensorSourceValue::RemoteCANcoder for the steer motor.
Definition MotionMagicExpoTorqueCurrentFOC.hpp:18
Definition span.hpp:401
All constants for a swerve module.
Definition SwerveModuleConstants.hpp:117
bool DriveMotorInverted
True if the drive motor is inverted.
Definition SwerveModuleConstants.hpp:149
configs::Slot0Configs SteerMotorGains
The steer motor closed-loop gains.
Definition SwerveModuleConstants.hpp:191
SteerFeedbackType FeedbackSource
Choose how the feedback sensors should be configured.
Definition SwerveModuleConstants.hpp:247
EncoderConfigsT EncoderInitialConfigs
The initial configs used to configure the azimuth encoder of the swerve module.
Definition SwerveModuleConstants.hpp:310
units::angle::turn_t EncoderOffset
Offset of the azimuth encoder.
Definition SwerveModuleConstants.hpp:135
SteerMotorConfigsT SteerMotorInitialConfigs
The initial configs used to configure the steer motor of the swerve module.
Definition SwerveModuleConstants.hpp:294
units::current::ampere_t SlipCurrent
The maximum amount of stator current the drive motors can apply without slippage.
Definition SwerveModuleConstants.hpp:213
DriveMotorConfigsT DriveMotorInitialConfigs
The initial configs used to configure the drive motor of the swerve module.
Definition SwerveModuleConstants.hpp:269
bool EncoderInverted
True if the azimuth encoder is inverted from the azimuth.
Definition SwerveModuleConstants.hpp:161
bool SteerMotorInverted
True if the steer motor is inverted from the azimuth.
Definition SwerveModuleConstants.hpp:155
int EncoderId
CAN ID of the absolute encoder used for azimuth.
Definition SwerveModuleConstants.hpp:131
units::dimensionless::scalar_t SteerMotorGearRatio
Gear ratio between the steer motor and the azimuth encoder.
Definition SwerveModuleConstants.hpp:170
configs::Slot0Configs DriveMotorGains
The drive motor closed-loop gains.
Definition SwerveModuleConstants.hpp:200
Contains everything the swerve module needs to apply a request.
Definition SwerveModuleImpl.hpp:65