caution - packaged application KY 040 from aliexpress is defective product
- switch signal is constantly random raised...moreover on turreting action
minor detail - because of this, on youtube about KY-040 clip
...omit the switch operation or ... maybe cunningly hidden
rotary encoder 3 pin - detect clock switch
EC11 rotary encoder : pin map, connection circuit
(+)---R(1k~10k)---detect pin switch---R(1k~10k)---(+)
(-)---ground pin rotary
(+)---R(1k~10k)----clock pin ground---(-)
rotary encoder direction signal pulse pattern(phase 90 proceeding)
pin signals.
right - clock-wise -> increase
clock 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1...
detect 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0...
all combination cases: 0100,0010,1011,1101
left - counter-clock-wise -> decrease
clock 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0...
detect 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1...
all combination cases: 1000,0001,0111,1110
switch - 0,1
micropython-thonny : source code below
from machine import Pin,I2C
class Rotary: # detector, clock, switch(= push button)
def __init__(self, detect_pin, clock_pin, switch_pin, callback):
self.detect = Pin(detect_pin, Pin.IN)
self.clock = Pin(clock_pin, Pin.IN)
self.switch = Pin(switch_pin, Pin.IN)
self.callback = callback
self.detect.irq(handler=self.rotate, trigger = Pin.IRQ_RISING | Pin.IRQ_FALLING)
self.clock.irq(handler=self.rotate, trigger = Pin.IRQ_RISING | Pin.IRQ_FALLING)
self.switch.irq(handler=self.switching, trigger = Pin.IRQ_RISING | Pin.IRQ_FALLING)
self.values = [0,0,self.clock.value(),self.detect.value()]
self.last_wise = ""
self.last_switch_value = 0
self.direction = "CW"
self.cws = ['0100','0010','1011','1101']
self.ccws = ['1000','0001','0111','1110']
def switching(self,pin):
swval = self.switch.value()
if swval != self.last_switch_value and swval == 1:
print("switch call back here \n")
self.last_switch_value = swval
def rotate(self,pin):
# print("clock",clock_value,"detect",detect_value,"switch",switch_value,"values",self.values)
if clock_value == self.values[0] and detect_value == self.values[1]:
return
self.values.pop(0)
self.values.pop(0)
self.values.append(clock_value)
self.values.append(detect_value)
sv = "".join(map(str,self.values))
if sv in self.cws:
self.direction = 'CW'
elif sv in self.ccws:
self.direction = 'CCW'
# print("clock",clock_value,"detect",detect_value,"switch",switch_value,"values",self.values)
if clock_value == 1 and detect_value == 1 and sv != '1111':
if clock_value == detect_value:
if self.direction == 'CW':
print("+")
# self.callback.crease(1)
elif self.direction == 'CCW':
print("-")
# self.callback.crease(-1)
#=========================================================================
try:
ec11 = Rotary(detect_pin=27, clock_pin=26, switch_pin=28, callback=None)
except KeyboardInterrupt:
pass