Skip to content

Instantly share code, notes, and snippets.

@greggjaskiewicz
Created September 19, 2022 10:16
Show Gist options
  • Save greggjaskiewicz/1d41c9fdc4c6b9a7e6fa16f9d3739459 to your computer and use it in GitHub Desktop.
Save greggjaskiewicz/1d41c9fdc4c6b9a7e6fa16f9d3739459 to your computer and use it in GitHub Desktop.
Rotary Encoder On IRQ RaspberryPi Pico
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
import framebuf
import utime
DT_Pin = Pin(15, Pin.IN)#, Pin.PULL_UP)
CLK_Pin = Pin(14, Pin.IN)#, Pin.PULL_UP)
SW = Pin(2, Pin.IN)#, Pin.PULL_UP)
i2c = I2C(0, scl = Pin(17), sda = Pin(16), freq=400000)
display = SSD1306_I2C(128, 64, i2c)
display.rotate(2)
value = 0
inTurn=0 # -1 for left, +1 for right, 0 - for none
elimateStartClk = 0 # value of utime.ticks_us() when we started eliminating input
IGNORE_MS=500 # when something goes wrong, how long we will ignore input for
lastTick=0
def CLK_Pin_ISR(chn):
global lastTick
global elimateStartClk
global inTurn
global IGNORE_MS
global value
print("CLK %s" % str(chn.value()))
if elimateStartClk != 0: #do we ignore it?
currentClk = utime.ticks_us()
diff = currentClk-elimateStartClk
if (diff < IGNORE_MS) & (diff > 0):
print("rejected1 %s" % str(diff))
return
elimateStartClk = 0
if chn.value() == 0:
if inTurn == 0:
inTurn=-1
print("start right")
else:
if inTurn == -1:
inTurn = 0
value += 1
if inTurn == -1 | inTurn == 1:
pass
else:
elimateStartClk = utime.ticks_us() #something's wrong
def DT_Pin_ISR(chn):
global lastTick
global elimateStartClk
global inTurn
global IGNORE_MS
global value
print("DT %s" % str(chn.value()))
if elimateStartClk != 0: #do we ignore it?
currentClk = utime.ticks_us()
diff = currentClk-elimateStartClk
if (diff < IGNORE_MS) & (diff > 0):
print("rejected2 %s" % str(diff))
return
elimateStartClk = 0
if chn.value() == 0:
if inTurn == 0:
print("start left")
inTurn=1
else:
if inTurn == 1:
inTurn = 0
value -= 1
if inTurn == -1 | inTurn == 1:
pass
else:
elimateStartClk = utime.ticks_us() #something's wrong
CLK_Pin.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=CLK_Pin_ISR)
DT_Pin.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=DT_Pin_ISR)
while True:
display.text('Counter:',0,0)
display.text(str(value), 0,14)
display.text(str(utime.ticks_us()), 0,30)
display.show()
display.fill(0)
utime.sleep(0.05)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment