I want to be able to stop my robot from moving when it meets an obstacle. However the turn method in the SynchronizedMotors
class under motor.py
doesn't allow me to do so. How could I fix that? Is there any direct solution? I did try using a thread, but it didn't work.
Asked
Active
Viewed 1,254 times
1

Carl Smith
- 3,025
- 24
- 36

Edward
- 93
- 10
1 Answers
1
I had no problems getting the servos to react to sensor input. The following should make the robot go forwards at full power until one or more of its touch sensors are pressed, then it stops, waits a moment, then cuts all power to the servos.
from time import sleep
import nxt
from nxt.motor import Motor, PORT_B, PORT_C
from nxt.sensor import Touch, PORT_1, PORT_2
class Robot(object):
def __init__(self, brick):
self.brick = brick
# left and right motors
self.lmotor = Motor(brick, PORT_B)
self.rmotor = Motor(brick, PORT_C)
# left and right touch sensors
self.ltouch = Touch(brick, PORT_1)
self.rtouch = Touch(brick, PORT_2)
def roll(self, left, right):
'''
Non-blocking function for modifying power to servos.
The servos will continue to operate at these power
levels until told to do otherwise. Values are given
as percentages of full power, so torque will change
as the battery loses charge. A negative value will
reverse the rotation of the respective servo.
For example, to spin on the spot, clockwise and at
full power, do
self.roll(100, -100)
'''
self.lmotor.run(left)
self.rmotor.run(right)
def halt(self):
'''
Stops and then holds both servos steady for
0.2 seconds, then cuts power to both servos.
'''
self.lmotor.brake()
self.rmotor.brake()
sleep(0.2)
self.lmotor.idle()
self.rmotor.idle()
brick = nxt.find_one_brick(name='R2')
robot = Robot(brick)
robot.roll(100, 100)
while True:
if robot.ltouch.is_pressed() or robot.rtouch.is_pressed():
robot.halt()

Carl Smith
- 3,025
- 24
- 36
-
whats with NameError: name 'PORT_B' is not defined ? – Jaxx0rr Jan 14 '22 at 00:52