【问题标题】:Python - Driving straight with interruptsPython - 带中断直行
【发布时间】:2018-05-15 21:52:21
【问题描述】:

现在,我将 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 Rechts”表示“右中断”。



如果不够清楚,这就是我对光传感器和塑料轮的意思。

【问题讨论】:

    标签: python raspberry-pi interrupt driving-directions


    【解决方案1】:

    您的代码的问题是您只有两种状态,一种状态是机器人向左转,另一种状态是机器人向右转。

    您需要重新编写代码,以便为每个轮子设置一个计数器。如果任一计数器较高,机器人应关闭指定的电机。如果两个计数器相等,机器人应该打开两个电机。

    试试这个:

    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()
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-14
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 2013-09-13
      相关资源
      最近更新 更多