Mutila: Mouse's Utilities for Arduino
Oft-used utilities: debouncing buttons, averaging samples, and so on.
DiscretePot.cpp
1 #include <Arduino.h>
2 #include "DiscretePot.h"
3 #include "Millis.h"
4 
5 DiscretePot::DiscretePot(const uint8_t pin) :
6  _pin(pin)
7 {
8 }
9 
10 void DiscretePot::begin(int8_t min, int8_t max, bool reversed, uint8_t threshold, uint8_t delay)
11 {
12  _min = min;
13  _max = max;
14  _reversed = reversed;
15  _threshold = threshold;
16  _delay = delay;
17  setState(_min);
18 }
19 
21 {
22  if (DoEvery(_delay, _lastUpdate)) {
23  int8_t valueNow = _value();
24  if (valueNow != _state) {
25  _counter++;
26  if (_counter > _threshold) {
27  setState(valueNow);
28  }
29  } else if (_counter > 0) {
30  _counter = 0;
31  }
32  }
33 }
34 
36 {
37  return _state;
38 }
39 
40 int8_t DiscretePot::_value()
41 {
42  // 0 <= raw < 1024
43  int raw = analogRead(_pin);
44  int stepsize = 1023/(_max - _min);
45  if (_reversed) {
46  return _max-(raw/stepsize);
47  } else {
48  return (raw/stepsize)+_min;
49  }
50 }
51 
52 void DiscretePot::setState(int8_t newState)
53 {
54  _lastStateChange = Millis();
55  _state = newState;
56  _counter = 0;
57 }
58 
int8_t value()
Definition: DiscretePot.cpp:35
DiscretePot(const uint8_t pin)
Definition: DiscretePot.cpp:5
void update()
Definition: DiscretePot.cpp:20
void begin(int8_t min=0, int8_t max=11, bool reversed=false, uint8_t threshold=AbstractDebouncedButton::DefaultThreshold, uint8_t delay=AbstractDebouncedButton::DefaultButtonDelay)
Definition: DiscretePot.cpp:10