2012-10-10 242 views
0

附加是一种将机器人移动到特定距离的代码,但是我希望它在接近和障碍时停止移动。我该怎么做呢?我曾尝试添加超声波来检测障碍物。我使用NXT-python的机器人不会停止

def move_to(brick, bx, by ,rx, ry): 
    wheel_circumference = (pi * wheel_diameter) 
    distance_per_turn = (wheel_circumference/360) 
    distance = math.sqrt((math.pow((bx - rx),2)) + (math.pow((by - ry),2))) 
    rotations = ((distance/distance_per_turn)/360) 
    tacho_units = (round((rotations) * 360)) 
    both.turn(power=power, tacho_units=tacho_units, brake=False) 
    if(ultrasonic.get_sample() < 20): 
     both.brake() 

def activate2(): 

    update_coordinates() 
    bx,by = get_ballxy() 
    rx,ry,a = get_robotxya() 

    if(ultrasonic.get_sample() < 15): 
     both.turn(power=-65, tacho_units=380, brake= False) 

    time.sleep(1) 
    turn_to(brick,bx,by,rx,ry,a) 
    time.sleep(0.5) 
    move_to(brick,bx,by,rx,ry) 
    kickBall(brick,by,ry) 


Thread(target=update_coordinates).start() 
connect() 
update_coordinates() 
while True: 
    #activate() 
    activate2() 
    time.sleep(3) 
+1

大声笑...我希望你选择了一个这实际上有助于解决您提出的问题。无论如何,我不能帮你解决这个问题 – musefan

+0

btw,你使用的是哪种nxt-python版本? – sloth

+0

@ Mr.Steak nxt-python 2.2.2 – Edward

回答

1

你的问题是,你检查的障碍只有一次后,你的机器人移动。

both.turn(power=power, tacho_units=tacho_units, brake=False) 
# the turn function blocks, so this check comes to late 
if(ultrasonic.get_sample() < 20): 
    both.brake() 

你应该在另一个线程中连续检查障碍物。


做的事情比较简单,你可以稍微调整nxc-python。

变化BaseMotormotor.pyturn方法

def turn(self, power, tacho_units, brake=True, timeout=1, emulate=True, cancel_when=None): 

和下面的代码添加到该方法中的while循环:

 while True: 

      # these lines are new 
      if cancel_when and cancel_when(): 
       break 

然后,你可以很容易地编写代码:

both.turn(power=power, tacho_units=tacho_units, brake=False, cancel_when=lambda: ultrasonic.get_sample() < 20) 
+0

所以你的意思是我必须在motor.py的BaseMotor的turn方法中包含while循环吗? – Edward

+0

'while'循环已经在那里;但是如果你愿意的话,你可以在'while True'部分的下面添加'if cancel_when和cancel_when():break'。我通过一点点挖掘了nxt-python源代码,并且'turn'方法在某些情况下不能停止(例如有障碍时)。也许'weak_turn'方法对你来说会更好,因为它不会阻塞。但实际上很难说,因为我不知道你的完整代码。你使用某种状态机或主循环来控制你的代码流?它会让事情变得更简单... – sloth

+0

你愿意让我向你展示主循环和我在这个问题中使用的方法吗?我现在可以编辑它 – Edward