正交设计 python算法_Python中读取正交编码器的最有效算法

在项目中,作者遇到使用PD控制3个电机和正交编码器时的效率问题。初始代码通过轮询读取编码器,但在处理多个电机时效率低下。尝试使用`GPIO.add_event_detect`提高效率,但导致计数丢失。作者寻求一种更有效的算法,能正确处理编码器的4种状态,尤其是在高速旋转时。
摘要由CSDN通过智能技术生成

我正在做一个项目,我使用PD控制3电机与光学正交编码器和效率是必须的,因为我不想失去一些计数和破坏定位。在

首先,我创建了一个名为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的对象。然后:

^{pr2}$

然而,我的代码效率不高,无法处理多个电机,而且在使用rospy时也变得非常低效。这就是为什么我尝试使用add_event_detect as proposedhere

我终于得到了这样的结果: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个计数,但是“高效”算法失去了我所有的计数。而且,我旋转转子的速度越快,它错过的计数就越多。在

请,如果有一种更有效的方法来读取编码器的所有四种情况下的计数,或者我自己犯了一个错误,我将非常感谢如果你张贴它。在

警察:对于那些在4种情况下不明白我意思的人:|PinA|PinB|

1| 0 | 0 |

2| 0 | 1 |

3| 1 | 0 |

4| 1 | 1 |

Pd2:我将使用rospy并将这些计数发送到topic,而发布过程需要一些时间,因此我需要代码尽可能高效

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值