Python - Driving straight with interrupts
现在,我将Raspberry Pi连接到两个带有光传感器的直流电动机,每当一个带有孔的塑料小轮穿过树莓派时,树莓派就会向Raspberry发送信号。
由于电机的强度不同,因此当我将它们全部置于全功率状态时,它们将驱动曲线。我希望机器人直线行驶。我想将其与光传感器和中断一起存档。我打算这样做:两台电机同时启动,触发一个光传感器后将发生中断。在此中断内部应更改变量。在循环中,存在一个if问题,即触发中断时电机在哪里停止。电机停止,直到另一个车轮触发了中断。基本上是这样的:左电机触发中断,右电机触发中断,依此类推。
如果两者都正常运行,则车轮应该在正确的时间停止并启动,以便机器人直线行驶。这是我的Python代码:
def interrupt_routinerechts(callback):
global zaehler_r
global zaehler_l
print"Interrupt Rechts"
zaehler_r = 1
zaehler_l = 2
def interrupt_routinelinks(callback):
global zaehler_l
global zaehler_r
print"Interrupt Links"
zaehler_l = 1
zaehler_r = 2
GPIO.add_event_detect(4, GPIO.FALLING, callback=interrupt_routinerechts)
GPIO.add_event_detect(6, GPIO.FALLING, callback=interrupt_routinelinks)
print"Los Geht's"
runProgram = True
while runProgram:
try:
forward()
if zaehler_r == 1:
stoppr()
elif zaehler_r == 2:
forwardr()
if zaehler_l == 1:
stoppl()
elif zaehler_l == 2:
forwardl()
except KeyboardInterrupt:
print"Exception thrown -> Abort"
runProgram = False
GPIO.cleanup()
GPIO.cleanup()
我的问题是,中断没有像我想象的那样触发,因此机器人沿曲线行驶。这就是它们被触发的方式。" Interrupt Links"表示" Interrupt Left"," Interrupt Rechts"表示" Interrupt Right"。
enter image description here
如果不够清晰,这就是我对光传感器和塑料轮的意思。
enter image description here
代码的问题在于,您只有两种状态,在一种状态下,机器人会向左转,而在另一种状态下,机器人会向右转。
您将需要重新编写代码,以使每个车轮都有一个计数器。 如果计数器中的任何一个较高,则机器人应关闭指定的电动机。 如果两个计数器相等,则机器人应打开两个电动机。
尝试这个:
def interrupt_right(callback):
global right_counter
print"Interrupt Right"
right_counter=right_counter+1
def interrupt_left(callback):
global left_counter
print"Interrupt left"
left_counter=left_counter+1
global left_counter=0
global right_counter=0
GPIO.add_event_detect(4, GPIO.FALLING, callback=interrupt_right)
GPIO.add_event_detect(6, GPIO.FALLING, callback=interrupt_left)
print"Los Geht's"
runProgram = True
while runProgram:
try:
if right_counter==left_counter:
forward()
elif right_counter>left_counter:
stop_right()
start_left()
elif left_counter>right_counter:
stop_left()
start_right()
except KeyboardInterrupt:
print"Exception thrown -> Abort"
runProgram = False
GPIO.cleanup()
GPIO.cleanup()
网友评论