Robot does not stop

497 views Asked by At

Attached is a code that moves the robot to a particular distance, however i want it to stop moving as it approaches and obstacle. How do i do this? i have tried adding the ultrasonic to detect an obstacle. I am using 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

There are 1 answers

4
sloth On BEST ANSWER

Your problem is that you check for obstacles only once after your robot moved.

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

you should check for obstacles continually in another thread.


Do make things easier, you could tweak nxc-python a little bit.

Change the turn method of BaseMotor in motor.py to

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

and add the following code to the while loop in that method:

        while True:

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

Then you could easily write your code as:

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