This is an old version of the documentation. View the latest version here.
Control Surface  1.0.0
MIDI Control Surface library for Arduino
Hysteresis.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 #include <stdint.h>
4 
7 
32 template <uint8_t BITS, class T_in = uint16_t, class T_out = uint8_t>
33 class Hysteresis {
34  public:
45  bool update(T_in inputLevel) {
46  T_in prevLevelFull = (T_in(prevLevel) << BITS) | offset;
47  T_in lowerbound = prevLevel > 0 ? prevLevelFull - margin : 0;
48  T_in upperbound = prevLevel < max_out ? prevLevelFull + margin : max_in;
49  if (inputLevel < lowerbound || inputLevel > upperbound) {
50  prevLevel = inputLevel >> BITS;
51  return true;
52  }
53  return false;
54  }
55 
61  T_out getValue() const { return prevLevel; }
62 
63  private:
64  T_out prevLevel = 0;
65  constexpr static T_in margin = (1 << BITS) - 1;
66  constexpr static T_in offset = 1 << (BITS - 1);
67  constexpr static T_in max_in = -1;
68  constexpr static T_out max_out = static_cast<T_out>(max_in >> BITS);
69  static_assert(max_in > 0, "Error: only unsigned types are supported");
70 };
71 
72 /// @}
Hysteresis::margin
constexpr static T_in margin
Definition: Hysteresis.hpp:65
Hysteresis::offset
constexpr static T_in offset
Definition: Hysteresis.hpp:66
Hysteresis
A class for applying hysteresis to a given input.
Definition: Hysteresis.hpp:33
Hysteresis::max_out
constexpr static T_out max_out
Definition: Hysteresis.hpp:68
Hysteresis::max_in
constexpr static T_in max_in
Definition: Hysteresis.hpp:67
Hysteresis::update
bool update(T_in inputLevel)
Update the hysteresis output with a new input value.
Definition: Hysteresis.hpp:45
Hysteresis::getValue
T_out getValue() const
Get the current output level.
Definition: Hysteresis.hpp:61
Hysteresis::prevLevel
T_out prevLevel
Definition: Hysteresis.hpp:64