使用Python代码加速二次解码器循环
我正在使用BeagleBone Black,并且在用Adafruit的IO Python库。写了一个简单的四分频解码函数,当电机以大约1800转每分钟的速度运行时,它工作得很好。
但是,当电机速度更高时,代码开始漏掉一些中断,编码器的计数开始出现错误。
你们有没有什么建议,可以让我代码更高效,或者有没有什么函数可以让中断以更高的频率循环?
谢谢,
Kel
这是代码:
# Define encoder count function
def encodercount(term):
global counts
global Encoder_A
global Encoder_A_old
global Encoder_B
global Encoder_B_old
global error
Encoder_A = GPIO.input('P8_7') # stores the value of the encoders at time of interrupt
Encoder_B = GPIO.input('P8_8')
if Encoder_A == Encoder_A_old and Encoder_B == Encoder_B_old:
# this will be an error
error += 1
print 'Error count is %s' %error
elif (Encoder_A == 1 and Encoder_B_old == 0) or (Encoder_A == 0 and Encoder_B_old == 1):
# this will be clockwise rotation
counts += 1
print 'Encoder count is %s' %counts
print 'AB is %s %s' % (Encoder_A, Encoder_B)
elif (Encoder_A == 1 and Encoder_B_old == 1) or (Encoder_A == 0 and Encoder_B_old == 0):
# this will be counter-clockwise rotation
counts -= 1
print 'Encoder count is %s' %counts
print 'AB is %s %s' % (Encoder_A, Encoder_B)
else:
#this will be an error as well
error += 1
print 'Error count is %s' %error
Encoder_A_old = Encoder_A # store the current encoder values as old values to be used as comparison in the next loop
Encoder_B_old = 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)
1 个回答
2
让代码更高效...
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)
最大的好处来自于只调用一次 print
。一般来说,打印到 stdout
(标准输出)是比较慢的,这会影响你程序的运行速度。你可以考虑每隔20次才打印一次,或者更少一些。