WPILibC++ 2024.3.2
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/Types.h>
12
13#include "frc/Counter.h"
14#include "frc/CounterBase.h"
15
16namespace frc {
17
18class DigitalSource;
19class DigitalGlitchFilter;
20class DMA;
21class DMASample;
22
23/**
24 * Class to read quad encoders.
25 *
26 * Quadrature encoders are devices that count shaft rotation and can sense
27 * direction. The output of the QuadEncoder class is an integer that can count
28 * either up or down, and can go negative for reverse direction counting. When
29 * creating QuadEncoders, a direction is supplied that changes the sense of the
30 * output to make code more readable if the encoder is mounted such that forward
31 * movement generates negative values. Quadrature encoders have two digital
32 * outputs, an A Channel and a B Channel that are out of phase with each other
33 * to allow the FPGA to do direction sensing.
34 *
35 * All encoders will immediately start counting - Reset() them if you need them
36 * to be zeroed before use.
37 */
38class Encoder : public CounterBase,
39 public wpi::Sendable,
40 public wpi::SendableHelper<Encoder> {
41 friend class DMA;
42 friend class DMASample;
43
44 public:
45 /**
46 * Encoder indexing types.
47 */
49 /// Reset while the signal is high.
51 /// Reset while the signal is low.
53 /// Reset on falling edge of the signal.
55 /// Reset on rising edge of the signal.
57 };
58
59 /**
60 * Encoder constructor.
61 *
62 * Construct a Encoder given a and b channels.
63 *
64 * The counter will start counting immediately.
65 *
66 * @param aChannel The a channel DIO channel. 0-9 are on-board, 10-25
67 * are on the MXP port
68 * @param bChannel The b channel DIO channel. 0-9 are on-board, 10-25
69 * are on the MXP port
70 * @param reverseDirection represents the orientation of the encoder and
71 * inverts the output values if necessary so forward
72 * represents positive values.
73 * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X
74 * decoding. If 4X is selected, then an encoder FPGA
75 * object is used and the returned counts will be 4x
76 * the encoder spec'd value since all rising and
77 * falling edges are counted. If 1X or 2X are selected
78 * then a counter object will be used and the returned
79 * value will either exactly match the spec'd count or
80 * be double (2x) the spec'd count.
81 */
82 Encoder(int aChannel, int bChannel, bool reverseDirection = false,
83 EncodingType encodingType = k4X);
84
85 /**
86 * Encoder constructor.
87 *
88 * Construct a Encoder given a and b channels as digital inputs. This is used
89 * in the case where the digital inputs are shared. The Encoder class will not
90 * allocate the digital inputs and assume that they already are counted.
91 *
92 * The counter will start counting immediately.
93 *
94 * @param aSource The source that should be used for the a channel.
95 * @param bSource the source that should be used for the b channel.
96 * @param reverseDirection represents the orientation of the encoder and
97 * inverts the output values if necessary so forward
98 * represents positive values.
99 * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X
100 * decoding. If 4X is selected, then an encoder FPGA
101 * object is used and the returned counts will be 4x
102 * the encoder spec'd value since all rising and
103 * falling edges are counted. If 1X or 2X are selected
104 * then a counter object will be used and the returned
105 * value will either exactly match the spec'd count or
106 * be double (2x) the spec'd count.
107 */
109 bool reverseDirection = false, EncodingType encodingType = k4X);
110
111 /**
112 * Encoder constructor.
113 *
114 * Construct a Encoder given a and b channels as digital inputs. This is used
115 * in the case where the digital inputs are shared. The Encoder class will not
116 * allocate the digital inputs and assume that they already are counted.
117 *
118 * The counter will start counting immediately.
119 *
120 * @param aSource The source that should be used for the a channel.
121 * @param bSource the source that should be used for the b channel.
122 * @param reverseDirection represents the orientation of the encoder and
123 * inverts the output values if necessary so forward
124 * represents positive values.
125 * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X
126 * decoding. If 4X is selected, then an encoder FPGA
127 * object is used and the returned counts will be 4x
128 * the encoder spec'd value since all rising and
129 * falling edges are counted. If 1X or 2X are selected
130 * then a counter object will be used and the returned
131 * value will either exactly match the spec'd count or
132 * be double (2x) the spec'd count.
133 */
135 bool reverseDirection = false, EncodingType encodingType = k4X);
136
137 Encoder(std::shared_ptr<DigitalSource> aSource,
138 std::shared_ptr<DigitalSource> bSource, bool reverseDirection = false,
139 EncodingType encodingType = k4X);
140
141 ~Encoder() override;
142
143 Encoder(Encoder&&) = default;
144 Encoder& operator=(Encoder&&) = default;
145
146 // CounterBase interface
147 /**
148 * Gets the current count.
149 *
150 * Returns the current count on the Encoder. This method compensates for the
151 * decoding type.
152 *
153 * @return Current count from the Encoder adjusted for the 1x, 2x, or 4x scale
154 * factor.
155 */
156 int Get() const override;
157
158 /**
159 * Reset the Encoder distance to zero.
160 *
161 * Resets the current count to zero on the encoder.
162 */
163 void Reset() override;
164
165 /**
166 * Returns the period of the most recent pulse.
167 *
168 * Returns the period of the most recent Encoder pulse in seconds. This method
169 * compensates for the decoding type.
170 *
171 * Warning: This returns unscaled periods. Use GetRate() for rates that are
172 * scaled using the value from SetDistancePerPulse().
173 *
174 * @return Period in seconds of the most recent pulse.
175 * @deprecated Use getRate() in favor of this method.
176 */
177 [[deprecated("Use GetRate() in favor of this method")]]
178 units::second_t GetPeriod() const override;
179
180 /**
181 * Sets the maximum period for stopped detection.
182 *
183 * Sets the value that represents the maximum period of the Encoder before it
184 * will assume that the attached device is stopped. This timeout allows users
185 * to determine if the wheels or other shaft has stopped rotating.
186 * This method compensates for the decoding type.
187 *
188 * @param maxPeriod The maximum time between rising and falling edges before
189 * the FPGA will report the device stopped. This is expressed
190 * in seconds.
191 * @deprecated Use SetMinRate() in favor of this method. This takes unscaled
192 * periods and SetMinRate() scales using value from
193 * SetDistancePerPulse().
194 */
195 [[deprecated(
196 "Use SetMinRate() in favor of this method. This takes unscaled periods "
197 "and SetMinRate() scales using value from SetDistancePerPulse().")]]
198 void SetMaxPeriod(units::second_t maxPeriod) override;
199
200 /**
201 * Determine if the encoder is stopped.
202 *
203 * Using the MaxPeriod value, a boolean is returned that is true if the
204 * encoder is considered stopped and false if it is still moving. A stopped
205 * encoder is one where the most recent pulse width exceeds the MaxPeriod.
206 *
207 * @return True if the encoder is considered stopped.
208 */
209 bool GetStopped() const override;
210
211 /**
212 * The last direction the encoder value changed.
213 *
214 * @return The last direction the encoder value changed.
215 */
216 bool GetDirection() const override;
217
218 /**
219 * Gets the raw value from the encoder.
220 *
221 * The raw value is the actual count unscaled by the 1x, 2x, or 4x scale
222 * factor.
223 *
224 * @return Current raw count from the encoder
225 */
226 int GetRaw() const;
227
228 /**
229 * The encoding scale factor 1x, 2x, or 4x, per the requested encodingType.
230 *
231 * Used to divide raw edge counts down to spec'd counts.
232 */
233 int GetEncodingScale() const;
234
235 /**
236 * Get the distance the robot has driven since the last reset.
237 *
238 * @return The distance driven since the last reset as scaled by the value
239 * from SetDistancePerPulse().
240 */
241 double GetDistance() const;
242
243 /**
244 * Get the current rate of the encoder.
245 *
246 * Units are distance per second as scaled by the value from
247 * SetDistancePerPulse().
248 *
249 * @return The current rate of the encoder.
250 */
251 double GetRate() const;
252
253 /**
254 * Set the minimum rate of the device before the hardware reports it stopped.
255 *
256 * @param minRate The minimum rate. The units are in distance per second as
257 * scaled by the value from SetDistancePerPulse().
258 */
259 void SetMinRate(double minRate);
260
261 /**
262 * Set the distance per pulse for this encoder.
263 *
264 * This sets the multiplier used to determine the distance driven based on the
265 * count value from the encoder.
266 *
267 * Do not include the decoding type in this scale. The library already
268 * compensates for the decoding type.
269 *
270 * Set this value based on the encoder's rated Pulses per Revolution and
271 * factor in gearing reductions following the encoder shaft.
272 *
273 * This distance can be in any units you like, linear or angular.
274 *
275 * @param distancePerPulse The scale factor that will be used to convert
276 * pulses to useful units.
277 */
278 void SetDistancePerPulse(double distancePerPulse);
279
280 /**
281 * Get the distance per pulse for this encoder.
282 *
283 * @return The scale factor that will be used to convert pulses to useful
284 * units.
285 */
286 double GetDistancePerPulse() const;
287
288 /**
289 * Set the direction sensing for this encoder.
290 *
291 * This sets the direction sensing on the encoder so that it could count in
292 * the correct software direction regardless of the mounting.
293 *
294 * @param reverseDirection true if the encoder direction should be reversed
295 */
296 void SetReverseDirection(bool reverseDirection);
297
298 /**
299 * Set the Samples to Average which specifies the number of samples of the
300 * timer to average when calculating the period.
301 *
302 * Perform averaging to account for mechanical imperfections or as
303 * oversampling to increase resolution.
304 *
305 * @param samplesToAverage The number of samples to average from 1 to 127.
306 */
307 void SetSamplesToAverage(int samplesToAverage);
308
309 /**
310 * Get the Samples to Average which specifies the number of samples of the
311 * timer to average when calculating the period.
312 *
313 * Perform averaging to account for mechanical imperfections or as
314 * oversampling to increase resolution.
315 *
316 * @return The number of samples being averaged (from 1 to 127)
317 */
319
320 /**
321 * Set the index source for the encoder.
322 *
323 * When this source is activated, the encoder count automatically resets.
324 *
325 * @param channel A DIO channel to set as the encoder index
326 * @param type The state that will cause the encoder to reset
327 */
329
330 /**
331 * Set the index source for the encoder.
332 *
333 * When this source is activated, the encoder count automatically resets.
334 *
335 * @param source A digital source to set as the encoder index
336 * @param type The state that will cause the encoder to reset
337 */
340
341 /**
342 * Indicates this encoder is used by a simulated device.
343 *
344 * @param device simulated device handle
345 */
347
348 int GetFPGAIndex() const;
349
350 void InitSendable(wpi::SendableBuilder& builder) override;
351
352 private:
353 /**
354 * Common initialization code for Encoders.
355 *
356 * This code allocates resources for Encoders and is common to all
357 * constructors. The counter will start counting immediately.
358 *
359 * @param reverseDirection If true, counts down instead of up (this is all
360 * relative)
361 * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X
362 * decoding. If 4X is selected, then an encoder FPGA
363 * object is used and the returned counts will be 4x
364 * the encoder spec'd value since all rising and
365 * falling edges are counted. If 1X or 2X are selected
366 * then a counter object will be used and the returned
367 * value will either exactly match the spec'd count or
368 * be double (2x) the spec'd count.
369 */
370 void InitEncoder(bool reverseDirection, EncodingType encodingType);
371
372 /**
373 * The scale needed to convert a raw counter value into a number of encoder
374 * pulses.
375 */
376 double DecodingScaleFactor() const;
377
378 std::shared_ptr<DigitalSource> m_aSource; // The A phase of the quad encoder
379 std::shared_ptr<DigitalSource> m_bSource; // The B phase of the quad encoder
380 std::shared_ptr<DigitalSource> m_indexSource = nullptr;
382
384};
385
386} // 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 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:111
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:40
int GetFPGAIndex() const
int GetRaw() const
Gets the raw value from the encoder.
IndexingType
Encoder indexing types.
Definition: Encoder.h:48
@ kResetOnRisingEdge
Reset on rising edge of the signal.
Definition: Encoder.h:56
@ kResetOnFallingEdge
Reset on falling edge of the signal.
Definition: Encoder.h:54
@ kResetWhileLow
Reset while the signal is low.
Definition: Encoder.h:52
@ kResetWhileHigh
Reset while the signal is high.
Definition: Encoder.h:50
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.
~Encoder() override
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.
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
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:19
Interface for Sendable objects.
Definition: Sendable.h:16
HAL_Handle HAL_SimDeviceHandle
Definition: Types.h:53
type
Definition: core.h:556
Definition: AprilTagPoseEstimator.h:15