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