【发布时间】:2022-06-17 07:32:55
【问题描述】:
我在使用 Python 处理 Raspberry Pi 4 的中断时遇到了一些麻烦。
我有一个DC motor with an encoder,我想控制这个电机的速度。但是我在用我的 Raspberry 读取编码器值时遇到了一些问题。
这是我运行的代码:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
HallA = 5 # GPIO pin for Hall A
HallB = 6 # GPIO pin for Hall B
GPIO.setup(HallA, GPIO.IN) #set up the input
GPIO.setup(HallB, GPIO.IN)
incmot = 0 # set up the counter
def encodeur_inc(channel) : #function of the interruption
B = GPIO.input(HallB) #read the second signal
global incmot
if B == 1 :
incmot = incmot +1
else :
incmot = incmot -1
GPIO.add_event_detect(HallA, GPIO.RISING, callback = encodeur_inc) #setting up the interruption
try :
while True :
print(incmot)
except :
GPIO.cleanup()
问题是,对于相同的转数,我每次获得不同数量的脉冲(从每转 480 到 650 个脉冲,而制造商宣布为 690)。我试图确定问题可能来自哪里:
- 不是来自编码器,我在示波器上显示了编码器两个输出的信号,确实是相位正交矩形波
- 树莓派不会错过中断,通过在进入中断时将引脚拉高然后在离开时将引脚拉低,我在示波器上显示了中断的输入和输出。
GPIO.output(20, GPIO.HIGH) #at the beginning of the function
GPIO.output(20, GPIO.LOW) #at the end of the function
所以我看不出我看到的不一致来自哪里。我有任何线索可以帮助我不要犹豫。
感谢您的帮助!
【问题讨论】:
-
起初我会怀疑python是否能够跟上,但切换输出
20应该意味着它确实跟上了。中断的频率是多少? (你的直流电机转多快?) -
看起来 Python 跟上了。最大电机转速为每分钟 251 转。中断频率约为 3 kHz
-
那么,
B不是1吗?即当旋转电机以获得递增的incmot时,如果B不是1,那么incmot将递减。你能告诉这是否会发生吗?这将解释差异。 -
发生这样的情况,前移B为1,后移B为0
-
是的,我知道这是理论上的,但是如果您期望
incmot从0递增到690,但您只会得到650,那么如果它递减 40次,那么这将解释差异。你能做这个实验吗?你可以让电机旋转,例如在incmot = incmot -1之后添加print(-1)吗?
标签: python raspberry-pi interrupt