I am interfacing rotary encoder with raspberry Pi using the interrupt method and want to show its value on tkinter
Label
.
1st I tested my interrupt callback function with main, where my rotary encoder works perfectly i.e. counter=1000 in one rotation of encoder but when I add the tkinter
part it slows down i.e. counter=800 in one rotation of encoder.
I think there is some issue with the way of handling tkinter
function, but not able to trace the issue.
Here I am providing my two different codes with output.
from RPi import GPIO
from time import sleep
import math
import Adafruit_MCP4725
dac=Adafruit_MCP4725.MCP4725(address=0x61)
a=22
b=23
GPIO.setmode(GPIO.BCM)
GPIO.setup(a,GPIO.IN)
GPIO.setup(b,GPIO.IN)
clkLastState=GPIO.input(a)
def my_callback(channel):
global clkLastState
global counter
clkState=GPIO.input(a)
if clkState != clkLastState:
dtState=GPIO.input(b)
if dtState != clkState:
counter +=1
else:
counter -=1
text=str(counter/2)
print (text[0:-2])
clkLastState=clkState
# sleep(0.001)
#finally:
counter=0
clkLastState=GPIO.input(a)
def main():
global counter
try:
# GPIO.add_event_detect(23,GPIO.BOTH,callback=my_callback)
while (1):
print(counter/2)
dac.set_voltage(int(counter/2))
vlt=int(counter/2)/4096*5.0
print(vlt)
sleep(1)
except KeyboardInterrupt:
print("end it")
GPIO.cleanup()
GPIO.add_event_detect(23,GPIO.BOTH,callback=my_callback)
#input("enter anything")
if __name__=='__main__':
# input("do")
main()
This is the code where it is working as per encoder specification.
955
955
956
956
957
957
958
958
959
959.0
1.170654296875
Here program with tkinter.
from RPi import GPIO
from time import sleep
import tkinter as tk
a=22
b=23
GPIO.setmode(GPIO.BCM)
GPIO.setup(a,GPIO.IN)
GPIO.setup(b,GPIO.IN)
root=tk.Tk()
clkLastState=GPIO.input(a)
def my_callback(channel):
global clkLastState
global counter
clkState=GPIO.input(a)
if clkState != clkLastState:
dtState=GPIO.input(b)
if dtState != clkState:
counter +=1
else:
counter -=1
text=str(counter/2)
print (text[0:-2])
var.set(text)
clkLastState=clkState
# sleep(0.001)
counter=0
clkLastState=GPIO.input(a)
GPIO.add_event_detect(23,GPIO.BOTH,callback=my_callback)
print (counter)
var=tk.IntVar()
L1=tk.Label(root,bg="orange",fg="red",textvariable=var)
L1.pack()
# var.set(counter)
# root.after(500,main)
root.geometry("100x100")
root.mainloop()
#var=tk.IntVar()
#L1=tk.Label(root,bg="orange",fg="red",textvariable=var)
#L1.pack()
#GPIO.add_event_detect(23,GPIO.BOTH,callback=my_callback)
input("enter anything")
GPIO.cleanup()
And here is its output.
759
760
761
762
763
763
For more details, here is my encoder datasheet<http://dien-congnghiep.com/upload/ls_mecapion/encoder_ls_mecapion_s40.pdf>