WPILibC++ 2024.3.2
Counter.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>
10#include <units/time.h>
13
14#include "frc/AnalogTrigger.h"
15#include "frc/CounterBase.h"
16
17namespace frc {
18
19class DigitalGlitchFilter;
20class DMA;
21class DMASample;
22
23/**
24 * Class for counting the number of ticks on a digital input channel.
25 *
26 * This is a general purpose class for counting repetitive events. It can return
27 * the number of counts, the period of the most recent cycle, and detect when
28 * the signal being counted has stopped by supplying a maximum cycle time.
29 *
30 * All counters will immediately start counting - Reset() them if you need them
31 * to be zeroed before use.
32 */
33class Counter : public CounterBase,
34 public wpi::Sendable,
35 public wpi::SendableHelper<Counter> {
36 friend class DMA;
37 friend class DMASample;
38
39 public:
40 enum Mode {
45 };
46
47 /**
48 * Create an instance of a counter where no sources are selected.
49 *
50 * They all must be selected by calling functions to specify the upsource and
51 * the downsource independently.
52 *
53 * This creates a ChipObject counter and initializes status variables
54 * appropriately.
55 *
56 * The counter will start counting immediately.
57 *
58 * @param mode The counter mode
59 */
60 explicit Counter(Mode mode = kTwoPulse);
61
62 /**
63 * Create an instance of a Counter object.
64 *
65 * Create an up-Counter instance given a channel.
66 *
67 * The counter will start counting immediately.
68 *
69 * @param channel The DIO channel to use as the up source. 0-9 are on-board,
70 * 10-25 are on the MXP
71 */
72 explicit Counter(int channel);
73
74 /**
75 * Create an instance of a counter from a Digital Source (such as a Digital
76 * Input).
77 *
78 * This is used if an existing digital input is to be shared by multiple other
79 * objects such as encoders or if the Digital Source is not a Digital Input
80 * channel (such as an Analog %Trigger).
81 *
82 * The counter will start counting immediately.
83 * @param source A pointer to the existing DigitalSource object. It will be
84 * set as the Up Source.
85 */
87
88 /**
89 * Create an instance of a counter from a Digital Source (such as a Digital
90 * Input).
91 *
92 * This is used if an existing digital input is to be shared by multiple other
93 * objects such as encoders or if the Digital Source is not a Digital Input
94 * channel (such as an Analog %Trigger).
95 *
96 * The counter will start counting immediately.
97 *
98 * @param source A pointer to the existing DigitalSource object. It will be
99 * set as the Up Source.
100 */
101 explicit Counter(std::shared_ptr<DigitalSource> source);
102
103 /**
104 * Create an instance of a Counter object.
105 *
106 * Create an instance of a simple up-Counter given an analog trigger.
107 * Use the trigger state output from the analog trigger.
108 *
109 * The counter will start counting immediately.
110 *
111 * @param trigger The reference to the existing AnalogTrigger object.
112 */
113 explicit Counter(const AnalogTrigger& trigger);
114
115 /**
116 * Create an instance of a Counter object.
117 *
118 * Creates a full up-down counter given two Digital Sources.
119 *
120 * @param encodingType The quadrature decoding mode (1x or 2x)
121 * @param upSource The pointer to the DigitalSource to set as the up
122 * source
123 * @param downSource The pointer to the DigitalSource to set as the down
124 * source
125 * @param inverted True to invert the output (reverse the direction)
126 */
127 Counter(EncodingType encodingType, DigitalSource* upSource,
128 DigitalSource* downSource, bool inverted);
129
130 /**
131 * Create an instance of a Counter object.
132 *
133 * Creates a full up-down counter given two Digital Sources.
134 *
135 * @param encodingType The quadrature decoding mode (1x or 2x)
136 * @param upSource The pointer to the DigitalSource to set as the up
137 * source
138 * @param downSource The pointer to the DigitalSource to set as the down
139 * source
140 * @param inverted True to invert the output (reverse the direction)
141 */
142 Counter(EncodingType encodingType, std::shared_ptr<DigitalSource> upSource,
143 std::shared_ptr<DigitalSource> downSource, bool inverted);
144
145 ~Counter() override;
146
147 Counter(Counter&&) = default;
148 Counter& operator=(Counter&&) = default;
149
150 /**
151 * Set the upsource for the counter as a digital input channel.
152 *
153 * @param channel The DIO channel to use as the up source. 0-9 are on-board,
154 * 10-25 are on the MXP
155 */
156 void SetUpSource(int channel);
157
158 /**
159 * Set the up counting source to be an analog trigger.
160 *
161 * @param analogTrigger The analog trigger object that is used for the Up
162 * Source
163 * @param triggerType The analog trigger output that will trigger the
164 * counter.
165 */
166 void SetUpSource(AnalogTrigger* analogTrigger, AnalogTriggerType triggerType);
167
168 /**
169 * Set the up counting source to be an analog trigger.
170 *
171 * @param analogTrigger The analog trigger object that is used for the Up
172 * Source
173 * @param triggerType The analog trigger output that will trigger the
174 * counter.
175 */
176 void SetUpSource(std::shared_ptr<AnalogTrigger> analogTrigger,
177 AnalogTriggerType triggerType);
178
180
181 /**
182 * Set the source object that causes the counter to count up.
183 *
184 * Set the up counting DigitalSource.
185 *
186 * @param source Pointer to the DigitalSource object to set as the up source
187 */
188 void SetUpSource(std::shared_ptr<DigitalSource> source);
189
190 /**
191 * Set the source object that causes the counter to count up.
192 *
193 * Set the up counting DigitalSource.
194 *
195 * @param source Reference to the DigitalSource object to set as the up source
196 */
198
199 /**
200 * Set the edge sensitivity on an up counting source.
201 *
202 * Set the up source to either detect rising edges or falling edges or both.
203 *
204 * @param risingEdge True to trigger on rising edges
205 * @param fallingEdge True to trigger on falling edges
206 */
207 void SetUpSourceEdge(bool risingEdge, bool fallingEdge);
208
209 /**
210 * Disable the up counting source to the counter.
211 */
213
214 /**
215 * Set the down counting source to be a digital input channel.
216 *
217 * @param channel The DIO channel to use as the up source. 0-9 are on-board,
218 * 10-25 are on the MXP
219 */
220 void SetDownSource(int channel);
221
222 /**
223 * Set the down counting source to be an analog trigger.
224 *
225 * @param analogTrigger The analog trigger object that is used for the Down
226 * Source
227 * @param triggerType The analog trigger output that will trigger the
228 * counter.
229 */
230 void SetDownSource(AnalogTrigger* analogTrigger,
231 AnalogTriggerType triggerType);
232
233 /**
234 * Set the down counting source to be an analog trigger.
235 *
236 * @param analogTrigger The analog trigger object that is used for the Down
237 * Source
238 * @param triggerType The analog trigger output that will trigger the
239 * counter.
240 */
241 void SetDownSource(std::shared_ptr<AnalogTrigger> analogTrigger,
242 AnalogTriggerType triggerType);
243
244 /**
245 * Set the source object that causes the counter to count down.
246 *
247 * Set the down counting DigitalSource.
248 *
249 * @param source Pointer to the DigitalSource object to set as the down source
250 */
252
253 /**
254 * Set the source object that causes the counter to count down.
255 *
256 * Set the down counting DigitalSource.
257 *
258 * @param source Reference to the DigitalSource object to set as the down
259 * source
260 */
262
263 void SetDownSource(std::shared_ptr<DigitalSource> source);
264
265 /**
266 * Set the edge sensitivity on a down counting source.
267 *
268 * Set the down source to either detect rising edges or falling edges.
269 *
270 * @param risingEdge True to trigger on rising edges
271 * @param fallingEdge True to trigger on falling edges
272 */
273 void SetDownSourceEdge(bool risingEdge, bool fallingEdge);
274
275 /**
276 * Disable the down counting source to the counter.
277 */
279
280 /**
281 * Set standard up / down counting mode on this counter.
282 *
283 * Up and down counts are sourced independently from two inputs.
284 */
286
287 /**
288 * Set external direction mode on this counter.
289 *
290 * Counts are sourced on the Up counter input.
291 * The Down counter input represents the direction to count.
292 */
294
295 /**
296 * Set Semi-period mode on this counter.
297 *
298 * Counts up on both rising and falling edges.
299 */
300 void SetSemiPeriodMode(bool highSemiPeriod);
301
302 /**
303 * Configure the counter to count in up or down based on the length of the
304 * input pulse.
305 *
306 * This mode is most useful for direction sensitive gear tooth sensors.
307 *
308 * @param threshold The pulse length beyond which the counter counts the
309 * opposite direction. Units are seconds.
310 */
311 void SetPulseLengthMode(double threshold);
312
313 /**
314 * Set the Counter to return reversed sensing on the direction.
315 *
316 * This allows counters to change the direction they are counting in the case
317 * of 1X and 2X quadrature encoding only. Any other counter mode isn't
318 * supported.
319 *
320 * @param reverseDirection true if the value counted should be negated.
321 */
322 void SetReverseDirection(bool reverseDirection);
323
324 /**
325 * Set the Samples to Average which specifies the number of samples of the
326 * timer to average when calculating the period. Perform averaging to account
327 * for mechanical imperfections or as oversampling to increase resolution.
328 *
329 * @param samplesToAverage The number of samples to average from 1 to 127.
330 */
331 void SetSamplesToAverage(int samplesToAverage);
332
333 /**
334 * Get the Samples to Average which specifies the number of samples of the
335 * timer to average when calculating the period.
336 *
337 * Perform averaging to account for mechanical imperfections or as
338 * oversampling to increase resolution.
339 *
340 * @return The number of samples being averaged (from 1 to 127)
341 */
343
344 int GetFPGAIndex() const;
345
346 /**
347 * Set the distance per pulse for this counter. This sets the multiplier used
348 * to determine the distance driven based on the count value from the encoder.
349 * Set this value based on the Pulses per Revolution and factor in any gearing
350 * reductions. This distance can be in any units you like, linear or angular.
351 *
352 * @param distancePerPulse The scale factor that will be used to convert
353 * pulses to useful units.
354 */
355 void SetDistancePerPulse(double distancePerPulse);
356
357 /**
358 * Read the current scaled counter value. Read the value at this instant,
359 * scaled by the distance per pulse (defaults to 1).
360 *
361 * @return The distance since the last reset
362 */
363 double GetDistance() const;
364
365 /**
366 * Get the current rate of the Counter. Read the current rate of the counter
367 * accounting for the distance per pulse value. The default value for distance
368 * per pulse (1) yields units of pulses per second.
369 *
370 * @return The rate in units/sec
371 */
372 double GetRate() const;
373
374 // CounterBase interface
375 /**
376 * Read the current counter value.
377 *
378 * Read the value at this instant. It may still be running, so it reflects the
379 * current value. Next time it is read, it might have a different value.
380 */
381 int Get() const override;
382
383 /**
384 * Reset the Counter to zero.
385 *
386 * Set the counter value to zero. This doesn't effect the running state of the
387 * counter, just sets the current value to zero.
388 */
389 void Reset() override;
390
391 /**
392 * Get the Period of the most recent count.
393 *
394 * Returns the time interval of the most recent count. This can be used for
395 * velocity calculations to determine shaft speed.
396 *
397 * @returns The period between the last two pulses in units of seconds.
398 */
399 units::second_t GetPeriod() const override;
400
401 /**
402 * Set the maximum period where the device is still considered "moving".
403 *
404 * Sets the maximum period where the device is considered moving. This value
405 * is used to determine the "stopped" state of the counter using the
406 * GetStopped method.
407 *
408 * @param maxPeriod The maximum period where the counted device is considered
409 * moving in seconds.
410 */
411 void SetMaxPeriod(units::second_t maxPeriod) final;
412
413 /**
414 * Select whether you want to continue updating the event timer output when
415 * there are no samples captured.
416 *
417 * The output of the event timer has a buffer of periods that are averaged and
418 * posted to a register on the FPGA. When the timer detects that the event
419 * source has stopped (based on the MaxPeriod) the buffer of samples to be
420 * averaged is emptied. If you enable the update when empty, you will be
421 * notified of the stopped source and the event time will report 0 samples.
422 * If you disable update when empty, the most recent average will remain on
423 * the output until a new sample is acquired. You will never see 0 samples
424 * output (except when there have been no events since an FPGA reset) and you
425 * will likely not see the stopped bit become true (since it is updated at the
426 * end of an average and there are no samples to average).
427 *
428 * @param enabled True to enable update when empty
429 */
430 void SetUpdateWhenEmpty(bool enabled);
431
432 /**
433 * Determine if the clock is stopped.
434 *
435 * Determine if the clocked input is stopped based on the MaxPeriod value set
436 * using the SetMaxPeriod method. If the clock exceeds the MaxPeriod, then the
437 * device (and counter) are assumed to be stopped and it returns true.
438 *
439 * @return Returns true if the most recent counter period exceeds the
440 * MaxPeriod value set by SetMaxPeriod.
441 */
442 bool GetStopped() const override;
443
444 /**
445 * The last direction the counter value changed.
446 *
447 * @return The last direction the counter value changed.
448 */
449 bool GetDirection() const override;
450
451 void InitSendable(wpi::SendableBuilder& builder) override;
452
453 protected:
454 /// Makes the counter count up.
455 std::shared_ptr<DigitalSource> m_upSource;
456
457 /// Makes the counter count down.
458 std::shared_ptr<DigitalSource> m_downSource;
459
460 /// The FPGA counter object
462
463 private:
464 /// The index of this counter.
465 int m_index = 0;
466
467 /// Distance of travel for each tick.
468 double m_distancePerPulse = 1;
469
471};
472
473} // 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
Definition: AnalogTrigger.h:21
Interface for counting the number of ticks on a digital input channel.
Definition: CounterBase.h:20
EncodingType
Definition: CounterBase.h:22
Class for counting the number of ticks on a digital input channel.
Definition: Counter.h:35
void SetSemiPeriodMode(bool highSemiPeriod)
Set Semi-period mode on this counter.
hal::Handle< HAL_CounterHandle > m_counter
The FPGA counter object.
Definition: Counter.h:461
void SetUpSource(std::shared_ptr< DigitalSource > source)
Set the source object that causes the counter to count up.
void ClearUpSource()
Disable the up counting source to the counter.
double GetDistance() const
Read the current scaled counter value.
void SetDistancePerPulse(double distancePerPulse)
Set the distance per pulse for this counter.
Counter(const AnalogTrigger &trigger)
Create an instance of a Counter object.
void SetUpSource(DigitalSource *source)
Counter & operator=(Counter &&)=default
Counter(EncodingType encodingType, DigitalSource *upSource, DigitalSource *downSource, bool inverted)
Create an instance of a Counter object.
void SetUpDownCounterMode()
Set standard up / down counting mode on this counter.
void Reset() override
Reset the Counter to zero.
void SetDownSource(std::shared_ptr< AnalogTrigger > analogTrigger, AnalogTriggerType triggerType)
Set the down counting source to be an analog trigger.
void SetExternalDirectionMode()
Set external direction mode on this counter.
std::shared_ptr< DigitalSource > m_downSource
Makes the counter count down.
Definition: Counter.h:458
~Counter() override
void SetUpSource(std::shared_ptr< AnalogTrigger > analogTrigger, AnalogTriggerType triggerType)
Set the up counting source to be an analog trigger.
void InitSendable(wpi::SendableBuilder &builder) override
Initializes this Sendable object.
bool GetDirection() const override
The last direction the counter value changed.
Counter(Counter &&)=default
units::second_t GetPeriod() const override
Get the Period of the most recent count.
void SetDownSource(DigitalSource *source)
Set the source object that causes the counter to count down.
void SetUpSource(DigitalSource &source)
Set the source object that causes the counter to count up.
void SetDownSource(int channel)
Set the down counting source to be a digital input channel.
Counter(DigitalSource *source)
Create an instance of a counter from a Digital Source (such as a Digital Input).
Counter(Mode mode=kTwoPulse)
Create an instance of a counter where no sources are selected.
int Get() const override
Read the current counter value.
void SetReverseDirection(bool reverseDirection)
Set the Counter to return reversed sensing on the direction.
Counter(int channel)
Create an instance of a Counter object.
double GetRate() const
Get the current rate of the Counter.
Mode
Definition: Counter.h:40
@ kTwoPulse
Definition: Counter.h:41
@ kSemiperiod
Definition: Counter.h:42
@ kPulseLength
Definition: Counter.h:43
@ kExternalDirection
Definition: Counter.h:44
void SetUpdateWhenEmpty(bool enabled)
Select whether you want to continue updating the event timer output when there are no samples capture...
void SetDownSource(AnalogTrigger *analogTrigger, AnalogTriggerType triggerType)
Set the down counting source to be an analog trigger.
int GetSamplesToAverage() const
Get the Samples to Average which specifies the number of samples of the timer to average when calcula...
void SetDownSourceEdge(bool risingEdge, bool fallingEdge)
Set the edge sensitivity on a down counting source.
void SetUpSource(AnalogTrigger *analogTrigger, AnalogTriggerType triggerType)
Set the up counting source to be an analog trigger.
void ClearDownSource()
Disable the down counting source to the counter.
void SetUpSource(int channel)
Set the upsource for the counter as a digital input channel.
void SetDownSource(std::shared_ptr< DigitalSource > source)
Counter(std::shared_ptr< DigitalSource > source)
Create an instance of a counter from a Digital Source (such as a Digital Input).
bool GetStopped() const override
Determine if the clock is stopped.
Counter(EncodingType encodingType, std::shared_ptr< DigitalSource > upSource, std::shared_ptr< DigitalSource > downSource, bool inverted)
Create an instance of a Counter object.
int GetFPGAIndex() const
void SetMaxPeriod(units::second_t maxPeriod) final
Set the maximum period where the device is still considered "moving".
std::shared_ptr< DigitalSource > m_upSource
Makes the counter count up.
Definition: Counter.h:455
void SetSamplesToAverage(int samplesToAverage)
Set the Samples to Average which specifies the number of samples of the timer to average when calcula...
void SetUpSourceEdge(bool risingEdge, bool fallingEdge)
Set the edge sensitivity on an up counting source.
void SetDownSource(DigitalSource &source)
Set the source object that causes the counter to count down.
void SetPulseLengthMode(double threshold)
Configure the counter to count in up or down based on the length of the input pulse.
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
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
Definition: AprilTagPoseEstimator.h:15
AnalogTriggerType
Defines the state in which the AnalogTrigger triggers.
Definition: AnalogTriggerType.h:10