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