Mutila: Mouse's Utilities for Arduino
Oft-used utilities: debouncing buttons, averaging samples, and so on.
AbstractDebouncedButton.cpp
1 #include <Arduino.h>
2 #include "AbstractDebouncedButton.h"
3 #include "MutilaDebug.h"
4 #include "Millis.h"
5 
7 {
8 }
9 
10 void AbstractDebouncedButton::begin(uint8_t threshold, uint8_t delay)
11 {
12  _threshold = threshold;
13  _delay = delay;
14  _lastUpdate = 0;
15  _lastRepeat = 0;
16  setState(false);
17  _lastOnDuration = 0;
18 }
19 
21 {
22  bool r = _pushed;
23  if (!peek) { _pushed = false; }
24  return r;
25 }
26 
28 {
29  uint32_t r = _lastOnDuration;
30  if (!peek) { _lastOnDuration = 0; }
31  return r;
32 }
33 
35 {
36  return (on() && MillisSince(_lastStateChange) > ms);
37 }
38 
39 bool AbstractDebouncedButton::repeat(uint16_t initialMs, uint16_t repeatMs)
40 {
41  uint32_t now = Millis();
42  bool out = false;
43 
44  if (on() && _repeatCount == 0) {
45  out = true;
46  } else if (on() && MillisSince(_lastRepeat, now) > (_repeatCount == 1 ? initialMs : repeatMs)) {
47  out = true;
48  }
49 
50  if (out) {
51  _lastRepeat = now;
52  _repeatCount++;
53  }
54 
55  return out;
56 }
57 
59 {
60  uint32_t now = Millis();
61  if (newState) {
62  _pushed = true;
63  _repeatCount = 0;
64  _lastRepeat = now;
65  } else {
66  _lastOnDuration = MillisSince(_lastStateChange, now);
67  }
68  if (_state!=newState) {
69  _lastStateChange = now;
70  _state = newState;
71  _counter = 0;
72  }
73 }
74 
bool held(uint16_t ms=DefaultHeldMs)
bool repeat(uint16_t initialMs=DefaultButtonRepeatInitialMs, uint16_t repeatMs=DefaultButtonRepeatMs)
virtual void begin()
uint32_t tapped(bool peek=false)
virtual bool on()=0