Control Surface disable-pipes
MIDI Control Surface library for Arduino
Hysteresis.hpp
Go to the documentation of this file.
1#pragma once
2
4AH_DIAGNOSTIC_WERROR() // Enable errors on warnings
5
6#include <stdint.h>
7
10
35template <uint8_t Bits, class T_in = uint16_t, class T_out = uint8_t>
37 public:
48 bool update(T_in inputLevel) {
49 T_in prevLevelFull = (T_in(prevLevel) << Bits) | offset;
50 T_in lowerbound = prevLevel > 0 ? prevLevelFull - margin : 0;
51 T_in upperbound = prevLevel < max_out ? prevLevelFull + margin : max_in;
52 if (inputLevel < lowerbound || inputLevel > upperbound) {
53 setValue(inputLevel);
54 return true;
55 }
56 return false;
57 }
58
64 T_out getValue() const { return prevLevel; }
65
69 void setValue(T_in inputLevel) { prevLevel = inputLevel >> Bits; }
70
71 private:
72 T_out prevLevel = 0;
73 constexpr static T_in margin = (1ul << Bits) - 1ul;
74 constexpr static T_in offset = Bits >= 1 ? 1ul << (Bits - 1) : 0;
75 constexpr static T_in max_in = static_cast<T_in>(-1);
76 constexpr static T_out max_out = static_cast<T_out>(max_in >> Bits);
77 static_assert(max_in > 0, "Error: only unsigned types are supported");
78};
79
80template <class T_in, class T_out>
81class Hysteresis<0, T_in, T_out> {
82 public:
83 bool update(T_in inputLevel) {
84 bool changed = inputLevel != prevLevel;
85 prevLevel = inputLevel;
86 return changed;
87 }
88
89 T_out getValue() const { return prevLevel; }
90 void setValue(T_in inputLevel) const { prevLevel = inputLevel; }
91
92 private:
93 T_in prevLevel = 0;
94};
95
97
#define AH_DIAGNOSTIC_POP()
Definition: Warnings.hpp:53
#define AH_DIAGNOSTIC_WERROR()
Definition: Warnings.hpp:52
bool update(T_in inputLevel)
Definition: Hysteresis.hpp:83
void setValue(T_in inputLevel) const
Definition: Hysteresis.hpp:90
A class for applying hysteresis to a given input.
Definition: Hysteresis.hpp:36
static constexpr T_out max_out
Definition: Hysteresis.hpp:76
bool update(T_in inputLevel)
Update the hysteresis output with a new input value.
Definition: Hysteresis.hpp:48
T_out prevLevel
Definition: Hysteresis.hpp:72
static constexpr T_in max_in
Definition: Hysteresis.hpp:75
void setValue(T_in inputLevel)
Forcefully update the internal state to the given level.
Definition: Hysteresis.hpp:69
T_out getValue() const
Get the current output level.
Definition: Hysteresis.hpp:64
static constexpr T_in offset
Definition: Hysteresis.hpp:74
static constexpr T_in margin
Definition: Hysteresis.hpp:73