Emakefun Matrix Keyboard Arduino Lib 1.0.1
Loading...
Searching...
No Matches
debouncer.h
1#pragma once
2
3#ifndef _EMAKEFUN_DEBOUNCER_H_
4#define _EMAKEFUN_DEBOUNCER_H_
5
6#include <Arduino.h>
7#include <stdint.h>
8
9namespace emakefun {
10template <typename T>
11class Debouncer {
12 public:
13 static constexpr uint64_t kDefaultDebounceDurationMs = 20;
14
15 Debouncer(const T& value, uint64_t debounce_duration_ms = kDefaultDebounceDurationMs)
16 : debouncing_value_(value), last_value_(value), debounce_duration_ms_(debounce_duration_ms) {
17 }
18
19 const T& Debounce(const T& value) {
20 if (start_debounce_time_ == UINT64_MAX || value != debouncing_value_) {
21 debouncing_value_ = value;
22 start_debounce_time_ = millis();
23 } else if (last_value_ != debouncing_value_ && millis() - start_debounce_time_ >= debounce_duration_ms_) {
24 last_value_ = debouncing_value_;
25 }
26
27 return last_value_;
28 }
29
30 inline const T& operator()(const T& value) {
31 return Debounce(value);
32 }
33
34 inline const T& operator=(const T& value) {
35 return Debounce(value);
36 }
37
38 inline const T& operator()() const {
39 return last_value_;
40 }
41
42 private:
43 T debouncing_value_;
44 T last_value_;
45 const uint64_t debounce_duration_ms_ = kDefaultDebounceDurationMs;
46 uint64_t start_debounce_time_ = UINT64_MAX;
47};
48} // namespace emakefun
49
50#endif