我正在做一个项目,我对 3 个带有光学正交编码器的电机使用 PD 控制,效率是必须的,因为我不想丢失一些计数并破坏定位。
首先,我创建了一个名为 CMotor 的类,我在其中定义了一些属性和方法。在这些方法中,我定义了 RotaryDeal,它负责处理计数。
一开始它看起来像这样:
class CMotor:
def RotaryDeal(self):
self.LastB = GPIO.input(self.PinB)
self.LastA = GPIO.input(self.PinA)
while (self.LastA==GPIO.input(self.PinA) and self.LastB==GPIO.input(self.PinB) ):
flag = 1
self.CurrentB = GPIO.input(self.PinB)
self.CurrentA = GPIO.input(self.PinA)
if self.CurrentA:
if self.CurrentB:
if self.LastA:
self.Cuentas-=1
else:
self.Cuentas+=1
else:
if self.LastA:
self.Cuentas+=1
else:
self.Cuentas-=1
else:
if self.CurrentB:
if self.LastA:
self.Cuentas-=1
else:
self.Cuentas+=1
else:
if self.LastA:
self.Cuentas+=1
else:
self.Cuentas-=1
print 'Cuentas %s = %d' % (self.Nombre, self.Cuentas)
#(Cuentas is Counts btw)
为了使用它,我导入了这个文件并创建了一个名为 M3 的对象。然后:
try:
while 1:
M3.RotaryDeal()
except KeyboardInterrupt:
GPIO.cleanup()
尽管如此,我的代码效率不高,无法与多个电机一起工作,而且在使用 rospy 时效率也变得非常低。这就是为什么我尝试使用这里建议的 add_event_detect
我终于得到了这样的东西:
class CMotor:
#Some other functions and the __init__
def RotaryDeal(self, ev = None):
self.CurrentB = GPIO.input(self.PinB)
self.CurrentA = GPIO.input(self.PinA)
if self.CurrentA:
if self.CurrentB:
if self.LastA:
self.Cuentas-=1
else:
self.Cuentas+=1
else:
if self.LastA:
self.Cuentas+=1
else:
self.Cuentas-=1
else:
if self.CurrentB:
if self.LastA:
self.Cuentas-=1
else:
self.Cuentas+=1
else:
if self.LastA:
self.Cuentas+=1
else:
self.Cuentas-=1
self.LastA = self.CurrentA
self.LastB = self.CurrentB
print 'Cuentas %s = %d' % (self.Nombre, self.Cuentas)
#sorry for the indentation, im copying it from the terminal (using ubuntu mate)
并这样称呼它:
try:
GPIO.add_event_detect(M3.PinA, GPIO.BOTH, callback=M3.RotaryDeal)
GPIO.add_event_detect(M3.PinB, GPIO.BOTH, callback=M3.RotaryDeal)
while 1:
pass
except KeyBoardInterrupt:
GPIO.cleanup()
尽管它应该更有效,但它却恰恰相反。当我试图转动它时,我得到了与原来完全不同的结果。如果您阅读全部 4 种情况,它应该每转读取 3200 个计数,但是“高效”算法正在失去我所有的计数。此外,我旋转转子的速度越快,它错过的计数就越多。
请,如果有一种更有效的方式来读取编码器的所有四种情况下的计数,或者我自己犯了一个错误,如果你发布它,我会非常感激。
PD.:对于那些不明白我在 4 种情况下的意思的人:
|PinA|PinB|
1| 0 | 0 |
2| 0 | 1 |
3| 1 | 0 |
4| 1 | 1 |
PD 2:我将使用 rospy 并将此计数发送到主题,并且发布过程会消耗一些时间,因此我需要代码尽可能高效