neteng
Posts: 24
Joined: Wed May 11, 2016 3:56 am

Rotary Encoder Script putting it as a function

Mon Oct 10, 2016 11:28 am

Hi All,

I have this script that is for a rotary encoder and is as such:

Code: Select all

from RPi import GPIO
from time import sleep

clk = 17
dt = 18
#lm1 = 4

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)
#GPIO.setup(lm1, 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
                        #if lm1 == 1 :
                                #counter = 0                        
                        print (counter)
                clkLastState = clkState
                
finally:
        GPIO.cleanup()


How would I write it such that is a function so that I can call it from other fucntions??

Thanks,
neteng

User avatar
joan
Posts: 14376
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: Rotary Encoder Script putting it as a function

Mon Oct 10, 2016 12:08 pm

That looks odd for rotary encoder code. I assume one of the phases is arbitrarily chosen as a clock. I suggest you convert it to a class.

Here is an example of the sort of thing you could do http://abyz.co.uk/rpi/pigpio/examples.h ... encoder_py

neteng
Posts: 24
Joined: Wed May 11, 2016 3:56 am

Re: Rotary Encoder Script putting it as a function

Tue Oct 11, 2016 12:43 am

joan wrote:That looks odd for rotary encoder code. I assume one of the phases is arbitrarily chosen as a clock. I suggest you convert it to a class.

Here is an example of the sort of thing you could do http://abyz.co.uk/rpi/pigpio/examples.h ... encoder_py
Thanks...Will try that out....

neteng

User avatar
joan
Posts: 14376
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: Rotary Encoder Script putting it as a function

Tue Oct 11, 2016 9:08 am

I had another look at the code.

It will be excellent for recording movement from one rotary encoder as long as that is the sole job of your software. It uses a busy spin to check for changes. When you do a busy spin you have no time left to do anything else.

With RPI.GPIO you should be using its event detect functions and callbacks (in a similar way to the code I linked). That means RPi.GPIO will be keeping track of the rotary encoder position as a background activity and leave time for the main part of the software to run to respond to the changes. It will also allow more than one rotary encoder to be monitored.

Return to “General discussion”