Search code examples
pythonraspberry-piencoder

Getting no input at all from Python Incremental Rotary Encoder


Everyone, hello!

I have recently purchased two incremental rotary encoder. One of them is the KY-040 which operates under 3.3v:

enter image description here

The suggested code to get this working under Python is:

from RPi import GPIO
from time import sleep

clk = 17
dt = 18

GPIO.setmode(GPIO.BCM)
GPIO.setup(clk, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(dt, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

counter = 0
clkLastState = GPIO.input(clk)

try:

        while True:
                clkState = GPIO.input(clk)
                dtState = GPIO.input(dt)
                if clkState != clkLastState:
                        if dtState != clkState:
                                counter += 1
                        else:
                                counter -= 1
                        print counter
                clkLastState = clkState
                sleep(0.01)
finally:
        GPIO.cleanup()

So far this works really well, given I use those pins for the GPIO for my Raspberry Pi.

Now, when I have a more beefy and sensitive encoder (although wildly sold on Ebay/Amazon, it seems to have no real maker/type?):

enter image description here

I'm not able to get any read on it at all. I could have sworn the day before I used the same code and it worked.

They both seem incremental encoders, and both have 2 phase outputs. What is going on? How come I can't get it to work?


Solution

  • That encoder is described as having open-collector outputs, which means that you need pull-up resistors on them in order to ever see a high logic level on them. You have your GPIO pins configured with pull-downs, instead.