Skip to content

Commit edb763e

Browse files
committed
add rotaryEncoder example
1 parent 3bb2485 commit edb763e

File tree

1 file changed

+131
-0
lines changed

1 file changed

+131
-0
lines changed
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
//
2+
// FILE: PCF8574_rotaryEncoder.ino
3+
// AUTHOR: Rob Tillaart
4+
// DATE: 2021-05-08
5+
//
6+
// PUPROSE: demo PCF8574 as rotary encoder reader.
7+
8+
//
9+
// RotaryEncoder PCF8574 UNO
10+
// --------------------------------------
11+
// pin A pin 0 (add pull ups, also for not connected lines)
12+
// pin B pin 1
13+
// .... .... (up to 4 RE)
14+
//
15+
// SDA A4
16+
// SCL A5
17+
// INT 2
18+
//
19+
// note: a dedicated rotary decoder class is created
20+
// - https://github.com/RobTillaart/rotaryDecoder -
21+
22+
23+
#include "PCF8574.h"
24+
25+
PCF8574 decoder(0x20);
26+
27+
28+
// hold position of 4 RE + last position
29+
uint8_t lastpos[4] = {0, 0, 0, 0};
30+
int32_t encoder[4] = {0, 0, 0, 0};
31+
volatile bool flag = false;
32+
33+
void moved()
34+
{
35+
flag = true;
36+
}
37+
38+
39+
void setup()
40+
{
41+
Serial.begin(115200);
42+
Serial.println(__FILE__);
43+
Serial.print("PCF8574_LIB_VERSION:\t");
44+
Serial.println(PCF8574_LIB_VERSION);
45+
46+
pinMode(2, INPUT_PULLUP);
47+
attachInterrupt(0, moved, FALLING);
48+
flag = false;
49+
50+
Wire.begin();
51+
if (decoder.begin() == false)
52+
{
53+
Serial.println("\nERROR: cannot communicate to keypad.\nPlease reboot / adjust address.\n");
54+
while (1);
55+
}
56+
Wire.setClock(600000);
57+
58+
initRotaryDecoder();
59+
60+
uint32_t start = micros();
61+
for (int i = 0; i < 10; i++)
62+
{
63+
updateRotaryDecoder();
64+
}
65+
uint32_t stop = micros();
66+
Serial.println((stop - start) * 0.1);
67+
}
68+
69+
70+
void loop()
71+
{
72+
if (flag)
73+
{
74+
updateRotaryDecoder();
75+
flag = false;
76+
for (int i = 0; i < 4; i++)
77+
{
78+
Serial.print("\t");
79+
Serial.print(encoder[i]);
80+
}
81+
Serial.println();
82+
}
83+
}
84+
85+
86+
void initRotaryDecoder()
87+
{
88+
uint8_t val = decoder.read8();
89+
for (uint8_t i = 0; i < 4; i++)
90+
{
91+
lastpos[i] = val & 0x03;
92+
val >>= 2;
93+
}
94+
}
95+
96+
97+
// assumes 4 rotary encoders connected to one PCF8574
98+
void updateRotaryDecoder()
99+
{
100+
uint8_t val = decoder.read8();
101+
102+
// check which of 4 has changed
103+
for (uint8_t i = 0; i < 4; i++)
104+
{
105+
uint8_t currentpos = (val & 0x03);
106+
if (lastpos[i] != currentpos) // moved!
107+
{
108+
uint8_t change = (lastpos[i] << 2) | currentpos;
109+
switch (change)
110+
{
111+
case 0b0001: // fall through..
112+
case 0b0111:
113+
case 0b1110:
114+
case 0b1000:
115+
encoder[i]++;
116+
break;
117+
case 0b0010:
118+
case 0b0100:
119+
case 0b1101:
120+
case 0b1011:
121+
encoder[i]--;
122+
break;
123+
}
124+
lastpos[i] = currentpos;
125+
val >>= 2;
126+
}
127+
}
128+
}
129+
130+
131+
// -- END OF FILE --

0 commit comments

Comments
 (0)