-
Notifications
You must be signed in to change notification settings - Fork 4
/
RotaryEncoder.cpp
93 lines (74 loc) · 1.81 KB
/
RotaryEncoder.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//
// Encoder code modified from:
// http://hifiduino.wordpress.com/2010/10/20/rotaryencoder-hw-sw-no-debounce/
//
#include "Arduino.h"
#include "RotaryEncoder.h"
RotaryEncoder::RotaryEncoder(uint8_t pin_a, uint8_t pin_b, uint8_t pin_c)
{
this->pin_a = pin_a;
this->pin_b = pin_b;
this->pin_c = pin_c;
pinMode(this->pin_a, INPUT_PULLUP);
pinMode(this->pin_b, INPUT_PULLUP);
pinMode(this->pin_c, INPUT_PULLUP);
if(digitalRead(this->pin_c) == 1)
{
this->state |= 0b00000010;
}
if(digitalRead(this->pin_b) == 1)
{
this->state |= 0b00000001;
}
}
void RotaryEncoder::init()
{
// Read the encoder and throw away the first reading. This is important,
// otherwise the first reading of the rotary encoder might incorrectly
// report a state change.
this->read();
}
int8_t RotaryEncoder::read()
{
state <<= 2;
// add current state
if(digitalRead(this->pin_c) == 1)
{
state |= 0b00000010;
}
if(digitalRead(this->pin_b) == 1)
{
state |= 0b00000001;
}
return (this->enc_states[( state & 0x0f )]); // 0x0F == 0000 1111
}
int8_t RotaryEncoder::readButton()
{
return (! digitalRead(this->pin_a));
}
boolean RotaryEncoder::pressed()
{
if ((millis() - last_debounce_time) > debounce_delay)
{
boolean button_value = ! digitalRead(this->pin_a);
if(old_button_value != button_value) last_debounce_time = millis();
if(old_button_value == false && button_value == true)
{
old_button_value = button_value;
return(true);
}
old_button_value = button_value;
return(false);
}
}
boolean RotaryEncoder::released()
{
boolean button_value = ! digitalRead(this->pin_a);
if(old_button_value == true && button_value == false)
{
old_button_value = button_value;
return(true);
}
old_button_value = button_value;
return(false);
}