WPILibC++  2020.3.2
SlewRateLimiter.h
1 /*----------------------------------------------------------------------------*/
2 /* Copyright (c) 2019 FIRST. All Rights Reserved. */
3 /* Open Source Software - may be modified and shared by FRC teams. The code */
4 /* must be accompanied by the FIRST BSD license file in the root directory of */
5 /* the project. */
6 /*----------------------------------------------------------------------------*/
7 
8 #pragma once
9 
10 #include <frc2/Timer.h>
11 
12 #include <algorithm>
13 
14 #include <units/units.h>
15 
16 namespace frc {
26 template <class Unit>
28  using Unit_t = units::unit_t<Unit>;
29  using Rate = units::compound_unit<Unit, units::inverse<units::seconds>>;
30  using Rate_t = units::unit_t<Rate>;
31 
32  public:
39  explicit SlewRateLimiter(Rate_t rateLimit, Unit_t initialValue = Unit_t{0})
40  : m_rateLimit{rateLimit}, m_prevVal{initialValue} {
41  m_timer.Start();
42  }
43 
51  Unit_t Calculate(Unit_t input) {
52  m_prevVal += std::clamp(input - m_prevVal, -m_rateLimit * m_timer.Get(),
53  m_rateLimit * m_timer.Get());
54  m_timer.Reset();
55  return m_prevVal;
56  }
57 
64  void Reset(Unit_t value) {
65  m_timer.Reset();
66  m_prevVal = value;
67  }
68 
69  private:
70  frc2::Timer m_timer;
71  Rate_t m_rateLimit;
72  Unit_t m_prevVal;
73 };
74 } // namespace frc
frc::SlewRateLimiter::Calculate
Unit_t Calculate(Unit_t input)
Filters the input to limit its slew rate.
Definition: SlewRateLimiter.h:51
frc2::Timer::Get
units::second_t Get() const
Get the current time from the timer.
frc2::Timer::Start
void Start()
Start the timer running.
frc2::Timer
A wrapper for the frc::Timer class that returns unit-typed values.
Definition: Timer.h:40
frc::SlewRateLimiter
A class that limits the rate of change of an input value.
Definition: SlewRateLimiter.h:27
frc::SlewRateLimiter::SlewRateLimiter
SlewRateLimiter(Rate_t rateLimit, Unit_t initialValue=Unit_t{0})
Creates a new SlewRateLimiter with the given rate limit and initial value.
Definition: SlewRateLimiter.h:39
frc2::Timer::Reset
void Reset()
Reset the timer by setting the time to 0.
frc::SlewRateLimiter::Reset
void Reset(Unit_t value)
Resets the slew rate limiter to the specified value; ignores the rate limit when doing so.
Definition: SlewRateLimiter.h:64
frc
A class that enforces constraints on the differential drive kinematics.
Definition: SPIAccelerometerSim.h:16