Faster quadrature decoder loops with Python code

丶灬走出姿态 提交于 2019-12-06 20:27:28

Making the code more efficient...

def encodercount(term):
global counts       
global Encoder_A
global Encoder_A_old
global Encoder_B
global Encoder_B_old
global error

Encoder_A,Encoder_B = GPIO.input('P8_7'),GPIO.input('P8_8')

if ((Encoder_A,Encoder_B_old) == (1,0)) or ((Encoder_A,Encoder_B_old) == (0,1)):
# this will be clockwise rotation
    counts += 1
    print 'Encoder count is %s\nAB is %s %s' % (counts, Encoder_A, Encoder_B)

elif ((Encoder_A,Encoder_B_old) == (1,1)) or ((Encoder_A,Encoder_B_old) == (0,0)):
# this will be counter-clockwise rotation
    counts -= 1
    print 'Encoder count is %s\nAB is %s %s' % (counts, Encoder_A, Encoder_B)

else:
#this will be an error
    error += 1
    print 'Error count is %s' %error

Encoder_A_old,Encoder_B_old = Encoder_A,Encoder_B

# Initialize the interrupts - these trigger on the both the rising and falling 
GPIO.add_event_detect('P8_7', GPIO.BOTH, callback = encodercount)   # Encoder A
GPIO.add_event_detect('P8_8', GPIO.BOTH, callback = encodercount)   # Encoder B

# This is the part of the code which runs normally in the background
while True:
    time.sleep(1)

The greatest benefit will come from the single call of print. Printing to the stdout is slow in general and this will limit the performance of your program. You should consider to print out only every 20th time or somewhat less often.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!