OpenMPTL - Helper Library
C++ Microprocessor Template Library
debouncer.hpp
Go to the documentation of this file.
1 /*
2  * OpenMPTL - C++ Microprocessor Template Library
3  *
4  * Copyright (C) 2012-2017 Axel Burri <axel@tty0.ch>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <http://www.gnu.org/licenses/>.
18  *
19  */
20 
21 #ifndef DEBOUNCER_HPP_INCLUDED
22 #define DEBOUNCER_HPP_INCLUDED
23 
24 /**
25  * Debounce a value on a given time base
26  *
27  * NOTE: time_func() must return a growing value!
28  */
29 template< typename T,
30  T (*poll_func)(void), // polling function
31  unsigned (*time_func)(void), // timer get function (must return a growing value)
32  unsigned int time_freq, // time_func frequency in hz
33  unsigned wait_time_ms = 50 // debounce time in milliseconds
34  >
35 class debouncer
36 {
37  T value;
38  T current;
39  unsigned hold_time;
40 
41  static constexpr unsigned wait_time_ticks = (((unsigned long long)time_freq * (unsigned long long)wait_time_ms) / 1000L);
42 
43 public:
44 
45  debouncer(T _value) : value(_value), current(_value), hold_time(0) { };
46 
47  /**
48  * Feed debouncer with a new value.
49  * Returns true if the value has changed.
50  */
51  bool poll(void) {
52  T new_value = poll_func();
53  unsigned now = time_func();
54  if(current != new_value) {
55  current = new_value;
56  hold_time = now + wait_time_ticks;
57  }
58 
59  if((hold_time > now) || (value == current))
60  return false;
61 
62  value = current;
63  return true;
64  }
65 
66  T get(void) const {
67  return value;
68  }
69 
70  operator T() const {
71  return get();
72  }
73 };
74 
75 #endif // DEBOUNCER_HPP_INCLUDED
debouncer(T _value)
Definition: debouncer.hpp:45
bool poll(void)
Feed debouncer with a new value.
Definition: debouncer.hpp:51
Debounce a value on a given time base.
Definition: debouncer.hpp:35