WPILibC++ 2025.2.1
Loading...
Searching...
No Matches
Encoder.h
Go to the documentation of this file.
1// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
4
5#pragma once
6
7#include <memory>
8
9#include <hal/Encoder.h>
10#include <hal/Types.h>
13
14#include "frc/Counter.h"
15#include "frc/CounterBase.h"
16
17namespace frc {
18
19class DigitalSource;
20class DigitalGlitchFilter;
21class DMA;
22class DMASample;
23
24/**
25 * Class to read quad encoders.
26 *
27 * Quadrature encoders are devices that count shaft rotation and can sense
28 * direction. The output of the QuadEncoder class is an integer that can count
29 * either up or down, and can go negative for reverse direction counting. When
30 * creating QuadEncoders, a direction is supplied that changes the sense of the
31 * output to make code more readable if the encoder is mounted such that forward
32 * movement generates negative values. Quadrature encoders have two digital
33 * outputs, an A Channel and a B Channel that are out of phase with each other
34 * to allow the FPGA to do direction sensing.
35 *
36 * All encoders will immediately start counting - Reset() them if you need them
37 * to be zeroed before use.
38 */
39class Encoder : public CounterBase,
40 public wpi::Sendable,
41 public wpi::SendableHelper<Encoder> {
42 friend class DMA;
43 friend class DMASample;
44
45 public:
46 /**
47 * Encoder indexing types.
48 */
50 /// Reset while the signal is high.
52 /// Reset while the signal is low.
54 /// Reset on falling edge of the signal.
56 /// Reset on rising edge of the signal.
58 };
59
60 /**
61 * Encoder constructor.
62 *
63 * Construct a Encoder given a and b channels.
64 *
65 * The counter will start counting immediately.
66 *
67 * @param aChannel The a channel DIO channel. 0-9 are on-board, 10-25
68 * are on the MXP port
69 * @param bChannel The b channel DIO channel. 0-9 are on-board, 10-25
70 * are on the MXP port
71 * @param reverseDirection represents the orientation of the encoder and
72 * inverts the output values if necessary so forward
73 * represents positive values.
74 * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X
75 * decoding. If 4X is selected, then an encoder FPGA
76 * object is used and the returned counts will be 4x
77 * the encoder spec'd value since all rising and
78 * falling edges are counted. If 1X or 2X are selected
79 * then a counter object will be used and the returned
80 * value will either exactly match the spec'd count or
81 * be double (2x) the spec'd count.
82 */
83 Encoder(int aChannel, int bChannel, bool reverseDirection = false,
84 EncodingType encodingType = k4X);
85
86 /**
87 * Encoder constructor.
88 *
89 * Construct a Encoder given a and b channels as digital inputs. This is used
90 * in the case where the digital inputs are shared. The Encoder class will not
91 * allocate the digital inputs and assume that they already are counted.
92 *
93 * The counter will start counting immediately.
94 *
95 * @param aSource The source that should be used for the a channel.
96 * @param bSource the source that should be used for the b channel.
97 * @param reverseDirection represents the orientation of the encoder and
98 * inverts the output values if necessary so forward
99 * represents positive values.
100 * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X
101 * decoding. If 4X is selected, then an encoder FPGA
102 * object is used and the returned counts will be 4x
103 * the encoder spec'd value since all rising and
104 * falling edges are counted. If 1X or 2X are selected
105 * then a counter object will be used and the returned
106 * value will either exactly match the spec'd count or
107 * be double (2x) the spec'd count.
108 */
110 bool reverseDirection = false, EncodingType encodingType = k4X);
111
112 /**
113 * Encoder constructor.
114 *
115 * Construct a Encoder given a and b channels as digital inputs. This is used
116 * in the case where the digital inputs are shared. The Encoder class will not
117 * allocate the digital inputs and assume that they already are counted.
118 *
119 * The counter will start counting immediately.
120 *
121 * @param aSource The source that should be used for the a channel.
122 * @param bSource the source that should be used for the b channel.
123 * @param reverseDirection represents the orientation of the encoder and
124 * inverts the output values if necessary so forward
125 * represents positive values.
126 * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X
127 * decoding. If 4X is selected, then an encoder FPGA
128 * object is used and the returned counts will be 4x
129 * the encoder spec'd value since all rising and
130 * falling edges are counted. If 1X or 2X are selected
131 * then a counter object will be used and the returned
132 * value will either exactly match the spec'd count or
133 * be double (2x) the spec'd count.
134 */
136 bool reverseDirection = false, EncodingType encodingType = k4X);
137
138 Encoder(std::shared_ptr<DigitalSource> aSource,
139 std::shared_ptr<DigitalSource> bSource, bool reverseDirection = false,
140 EncodingType encodingType = k4X);
141
142 Encoder(Encoder&&) = default;
143 Encoder& operator=(Encoder&&) = default;
144
145 ~Encoder() override = default;
146
147 // CounterBase interface
148 /**
149 * Gets the current count.
150 *
151 * Returns the current count on the Encoder. This method compensates for the
152 * decoding type.
153 *
154 * @return Current count from the Encoder adjusted for the 1x, 2x, or 4x scale
155 * factor.
156 */
157 int Get() const override;
158
159 /**
160 * Reset the Encoder distance to zero.
161 *
162 * Resets the current count to zero on the encoder.
163 */
164 void Reset() override;
165
166 /**
167 * Returns the period of the most recent pulse.
168 *
169 * Returns the period of the most recent Encoder pulse in seconds. This method
170 * compensates for the decoding type.
171 *
172 * Warning: This returns unscaled periods. Use GetRate() for rates that are
173 * scaled using the value from SetDistancePerPulse().
174 *
175 * @return Period in seconds of the most recent pulse.
176 * @deprecated Use getRate() in favor of this method.
177 */
178 [[deprecated("Use GetRate() in favor of this method")]]
179 units::second_t GetPeriod() const override;
180
181 /**
182 * Sets the maximum period for stopped detection.
183 *
184 * Sets the value that represents the maximum period of the Encoder before it
185 * will assume that the attached device is stopped. This timeout allows users
186 * to determine if the wheels or other shaft has stopped rotating.
187 * This method compensates for the decoding type.
188 *
189 * @param maxPeriod The maximum time between rising and falling edges before
190 * the FPGA will report the device stopped. This is expressed
191 * in seconds.
192 * @deprecated Use SetMinRate() in favor of this method. This takes unscaled
193 * periods and SetMinRate() scales using value from
194 * SetDistancePerPulse().
195 */
196 [[deprecated(
197 "Use SetMinRate() in favor of this method. This takes unscaled periods "
198 "and SetMinRate() scales using value from SetDistancePerPulse().")]]
199 void SetMaxPeriod(units::second_t maxPeriod) override;
200
201 /**
202 * Determine if the encoder is stopped.
203 *
204 * Using the MaxPeriod value, a boolean is returned that is true if the
205 * encoder is considered stopped and false if it is still moving. A stopped
206 * encoder is one where the most recent pulse width exceeds the MaxPeriod.
207 *
208 * @return True if the encoder is considered stopped.
209 */
210 bool GetStopped() const override;
211
212 /**
213 * The last direction the encoder value changed.
214 *
215 * @return The last direction the encoder value changed.
216 */
217 bool GetDirection() const override;
218
219 /**
220 * Gets the raw value from the encoder.
221 *
222 * The raw value is the actual count unscaled by the 1x, 2x, or 4x scale
223 * factor.
224 *
225 * @return Current raw count from the encoder
226 */
227 int GetRaw() const;
228
229 /**
230 * The encoding scale factor 1x, 2x, or 4x, per the requested encodingType.
231 *
232 * Used to divide raw edge counts down to spec'd counts.
233 */
234 int GetEncodingScale() const;
235
236 /**
237 * Get the distance the robot has driven since the last reset.
238 *
239 * @return The distance driven since the last reset as scaled by the value
240 * from SetDistancePerPulse().
241 */
242 double GetDistance() const;
243
244 /**
245 * Get the current rate of the encoder.
246 *
247 * Units are distance per second as scaled by the value from
248 * SetDistancePerPulse().
249 *
250 * @return The current rate of the encoder.
251 */
252 double GetRate() const;
253
254 /**
255 * Set the minimum rate of the device before the hardware reports it stopped.
256 *
257 * @param minRate The minimum rate. The units are in distance per second as
258 * scaled by the value from SetDistancePerPulse().
259 */
260 void SetMinRate(double minRate);
261
262 /**
263 * Set the distance per pulse for this encoder.
264 *
265 * This sets the multiplier used to determine the distance driven based on the
266 * count value from the encoder.
267 *
268 * Do not include the decoding type in this scale. The library already
269 * compensates for the decoding type.
270 *
271 * Set this value based on the encoder's rated Pulses per Revolution and
272 * factor in gearing reductions following the encoder shaft.
273 *
274 * This distance can be in any units you like, linear or angular.
275 *
276 * @param distancePerPulse The scale factor that will be used to convert
277 * pulses to useful units.
278 */
279 void SetDistancePerPulse(double distancePerPulse);
280
281 /**
282 * Get the distance per pulse for this encoder.
283 *
284 * @return The scale factor that will be used to convert pulses to useful
285 * units.
286 */
287 double GetDistancePerPulse() const;
288
289 /**
290 * Set the direction sensing for this encoder.
291 *
292 * This sets the direction sensing on the encoder so that it could count in
293 * the correct software direction regardless of the mounting.
294 *
295 * @param reverseDirection true if the encoder direction should be reversed
296 */
297 void SetReverseDirection(bool reverseDirection);
298
299 /**
300 * Set the Samples to Average which specifies the number of samples of the
301 * timer to average when calculating the period.
302 *
303 * Perform averaging to account for mechanical imperfections or as
304 * oversampling to increase resolution.
305 *
306 * @param samplesToAverage The number of samples to average from 1 to 127.
307 */
308 void SetSamplesToAverage(int samplesToAverage);
309
310 /**
311 * Get the Samples to Average which specifies the number of samples of the
312 * timer to average when calculating the period.
313 *
314 * Perform averaging to account for mechanical imperfections or as
315 * oversampling to increase resolution.
316 *
317 * @return The number of samples being averaged (from 1 to 127)
318 */
320
321 /**
322 * Set the index source for the encoder.
323 *
324 * When this source is activated, the encoder count automatically resets.
325 *
326 * @param channel A DIO channel to set as the encoder index
327 * @param type The state that will cause the encoder to reset
328 */
330
331 /**
332 * Set the index source for the encoder.
333 *
334 * When this source is activated, the encoder count automatically resets.
335 *
336 * @param source A digital source to set as the encoder index
337 * @param type The state that will cause the encoder to reset
338 */
341
342 /**
343 * Indicates this encoder is used by a simulated device.
344 *
345 * @param device simulated device handle
346 */
348
349 int GetFPGAIndex() const;
350
351 void InitSendable(wpi::SendableBuilder& builder) override;
352
353 private:
354 /**
355 * Common initialization code for Encoders.
356 *
357 * This code allocates resources for Encoders and is common to all
358 * constructors. The counter will start counting immediately.
359 *
360 * @param reverseDirection If true, counts down instead of up (this is all
361 * relative)
362 * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X
363 * decoding. If 4X is selected, then an encoder FPGA
364 * object is used and the returned counts will be 4x
365 * the encoder spec'd value since all rising and
366 * falling edges are counted. If 1X or 2X are selected
367 * then a counter object will be used and the returned
368 * value will either exactly match the spec'd count or
369 * be double (2x) the spec'd count.
370 */
371 void InitEncoder(bool reverseDirection, EncodingType encodingType);
372
373 /**
374 * The scale needed to convert a raw counter value into a number of encoder
375 * pulses.
376 */
377 double DecodingScaleFactor() const;
378
379 std::shared_ptr<DigitalSource> m_aSource; // The A phase of the quad encoder
380 std::shared_ptr<DigitalSource> m_bSource; // The B phase of the quad encoder
381 std::shared_ptr<DigitalSource> m_indexSource = nullptr;
383
385};
386
387} // namespace frc
and restrictions which apply to each piece of software is included later in this file and or inside of the individual applicable source files The disclaimer of warranty in the WPILib license above applies to all code in and nothing in any of the other licenses gives permission to use the names of FIRST nor the names of the WPILib contributors to endorse or promote products derived from this software The following pieces of software have additional or alternate and or and nanopb were all modified for use in Google Inc All rights reserved Redistribution and use in source and binary with or without are permitted provided that the following conditions are this list of conditions and the following disclaimer *Redistributions in binary form must reproduce the above copyright this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution *Neither the name of Google Inc nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED BUT NOT LIMITED THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY OR CONSEQUENTIAL WHETHER IN STRICT OR EVEN IF ADVISED OF THE POSSIBILITY OF SUCH January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation source
Definition ThirdPartyNotices.txt:124
Interface for counting the number of ticks on a digital input channel.
Definition CounterBase.h:20
EncodingType
Definition CounterBase.h:22
@ k4X
Definition CounterBase.h:22
Class for configuring Direct Memory Access (DMA) of FPGA inputs.
Definition DMA.h:23
DMA sample.
Definition DMASample.h:23
Class to enable glitch filtering on a set of digital inputs.
Definition DigitalGlitchFilter.h:30
DigitalSource Interface.
Definition DigitalSource.h:22
Class to read quad encoders.
Definition Encoder.h:41
int GetFPGAIndex() const
int GetRaw() const
Gets the raw value from the encoder.
IndexingType
Encoder indexing types.
Definition Encoder.h:49
@ kResetOnRisingEdge
Reset on rising edge of the signal.
Definition Encoder.h:57
@ kResetOnFallingEdge
Reset on falling edge of the signal.
Definition Encoder.h:55
@ kResetWhileLow
Reset while the signal is low.
Definition Encoder.h:53
@ kResetWhileHigh
Reset while the signal is high.
Definition Encoder.h:51
Encoder(int aChannel, int bChannel, bool reverseDirection=false, EncodingType encodingType=k4X)
Encoder constructor.
Encoder(DigitalSource *aSource, DigitalSource *bSource, bool reverseDirection=false, EncodingType encodingType=k4X)
Encoder constructor.
Encoder(std::shared_ptr< DigitalSource > aSource, std::shared_ptr< DigitalSource > bSource, bool reverseDirection=false, EncodingType encodingType=k4X)
void SetIndexSource(const DigitalSource &source, IndexingType type=kResetOnRisingEdge)
Set the index source for the encoder.
bool GetDirection() const override
The last direction the encoder value changed.
void SetMinRate(double minRate)
Set the minimum rate of the device before the hardware reports it stopped.
int Get() const override
Gets the current count.
void SetReverseDirection(bool reverseDirection)
Set the direction sensing for this encoder.
int GetEncodingScale() const
The encoding scale factor 1x, 2x, or 4x, per the requested encodingType.
void InitSendable(wpi::SendableBuilder &builder) override
Initializes this Sendable object.
void Reset() override
Reset the Encoder distance to zero.
double GetRate() const
Get the current rate of the encoder.
void SetSimDevice(HAL_SimDeviceHandle device)
Indicates this encoder is used by a simulated device.
void SetSamplesToAverage(int samplesToAverage)
Set the Samples to Average which specifies the number of samples of the timer to average when calcula...
int GetSamplesToAverage() const
Get the Samples to Average which specifies the number of samples of the timer to average when calcula...
void SetMaxPeriod(units::second_t maxPeriod) override
Sets the maximum period for stopped detection.
Encoder & operator=(Encoder &&)=default
void SetDistancePerPulse(double distancePerPulse)
Set the distance per pulse for this encoder.
void SetIndexSource(int channel, IndexingType type=kResetOnRisingEdge)
Set the index source for the encoder.
bool GetStopped() const override
Determine if the encoder is stopped.
Encoder(DigitalSource &aSource, DigitalSource &bSource, bool reverseDirection=false, EncodingType encodingType=k4X)
Encoder constructor.
~Encoder() override=default
double GetDistance() const
Get the distance the robot has driven since the last reset.
double GetDistancePerPulse() const
Get the distance per pulse for this encoder.
units::second_t GetPeriod() const override
Returns the period of the most recent pulse.
Encoder(Encoder &&)=default
A move-only C++ wrapper around a HAL handle.
Definition Types.h:96
Helper class for building Sendable dashboard representations.
Definition SendableBuilder.h:21
A helper class for use with objects that add themselves to SendableRegistry.
Definition SendableHelper.h:21
Interface for Sendable objects.
Definition Sendable.h:16
HAL_Handle HAL_SimDeviceHandle
Definition Types.h:53
Definition CAN.h:11