Arduino Filters master
Filter 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) - 1;
74 constexpr static T_in offset = 1UL << (BITS - 1);
75 constexpr static T_in max_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
81
#define AH_DIAGNOSTIC_POP()
Definition: Warnings.hpp:36
#define AH_DIAGNOSTIC_WERROR()
Definition: Warnings.hpp:35
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