2012-10-10 206 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