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