class Robot: def __init__(self): print 'Searching for NXT bricks...' self.robot = nxt.locator.find_one_brick() print 'NXT brick found' self.right_motor = Motor(self.robot, PORT_B) self.left_motor = Motor(self.robot, PORT_C) self.locator = Ultrasonic(self.robot, PORT_1) self.haptic = Touch(self.robot, PORT_4) def forward(self): if(random.random() > .5): self.right_motor.run(-STRAIGHT_POWER) self.left_motor.run(-STRAIGHT_POWER) else: self.left_motor.run(-STRAIGHT_POWER) self.right_motor.run(-STRAIGHT_POWER) sleep(SECONDS) if(random.random() > .5): self.right_motor.idle() self.left_motor.idle() else: self.left_motor.idle() self.right_motor.idle() def back(self): self.right_motor.run(STRAIGHT_POWER) self.left_motor.run(STRAIGHT_POWER) sleep(SECONDS) self.right_motor.idle() self.left_motor.idle() def right(self): self.left_motor.turn(-TURN_POWER, ANGLE) def left(self): self.right_motor.turn(-TURN_POWER, ANGLE) def distance(self): return self.locator.get_sample() def is_touching(self): return self.haptic.get_sample() def beep_ok(self): self.robot.play_tone_and_wait(FREQ_C, DURATION) self.robot.play_tone_and_wait(FREQ_D, DURATION) self.robot.play_tone_and_wait(FREQ_E, DURATION) def beep_not_ok(self): self.robot.play_tone_and_wait(FREQ_E, DURATION) self.robot.play_tone_and_wait(FREQ_D, DURATION) self.robot.play_tone_and_wait(FREQ_C, DURATION)
class Car: brick = None left = None right = None def __init__ (self): brick = nxt.locator.find_one_brick() self.brick = brick self.left = Motor(brick, PORT_A) self.right = Motor(brick, PORT_C) self.light = Light(brick, PORT_3) self.ultrasonic = Ultrasonic(brick, PORT_4) print "Connection established." def turn (self, angle=100, speed = 30): if angle > 0: self.left.turn(angle, speed) elif angle < 0: self.right.turn(-angle, speed) def forward (self, distance=50, speed=30): self.left.run(power=speed) self.right.run(power=speed) sleep(distance/speed) self.left.idle() self.right.idle() def range(self): return self.ultrasonic.get_sample() def surface(self): return self.light.get_sample()
def getCompass(self, port): if self._bricks: try: port = int(port) except: pass if (port in NXT_SENSOR_PORTS): try: port_aux = NXT_SENSOR_PORTS[port] sensor = Ultrasonic(self._bricks[self.active_nxt], port_aux) return sensor.get_sample() except: return ERROR else: raise logoerror(ERROR_PORT_S % port) else: raise logoerror(ERROR_BRICK)
def getDistance(self, port): if self._bricks: try: port = int(port) except: pass if (port in NXT_SENSOR_PORTS): try: port_aux = NXT_SENSOR_PORTS[port] sensor = Ultrasonic(self._bricks[self.active_nxt], port_aux) return sensor.get_sample() except: return ERROR else: raise logoerror(ERROR_PORT_S % port) else: raise logoerror(ERROR_BRICK)
def see(self, ultrasonicPort='PORT_4', ultrasonicDistance=25, operator='<', initial=False): """ Use the ultrasonic sensor to see obstacles (0-255) with 25 being about a foot away ultrasonicPort (str): The port used for the ultrasonic sensor (default='PORT_4') ultrasonicDistance (int): The distance that the ultrasonic returns true [0-255, 25~1foot] (default=25) operator (str): The operator for comparing distance ['<','>','=','!='] (default='<') """ ultrasonic=Ultrasonic(self.nxt.brick, eval(ultrasonicPort)) if initial: return False #don't return true until actually checked sensor value else: data = ultrasonic.get_sample() #integer between 0 and 255 output = operation(data,operator,ultrasonicDistance) if output: print 'Ultrasonic Distsance is '+operator+' '+str(ultrasonicDistance) return output
def getDistance(self, port): if self._bricks: time.sleep(0.5) try: port = int(port) except: pass if (port in NXT_SENSOR_PORTS): res = ERROR #try: port_aux = NXT_SENSOR_PORTS[port] sensor = Ultrasonic(self._bricks[self.active_nxt], port_aux) res = sensor.get_sample() #except: #pass return res else: pass else: pass
class AlphaRex(object): r'''A high-level controller for the Alpha Rex model. This class implements methods for the most obvious actions performable by Alpha Rex, such as walk, wave its arms, and retrieve sensor samples. Additionally, it also allows direct access to the robot's components through public attributes. ''' def __init__(self, brick='NXT'): r'''Creates a new Alpha Rex controller. brick Either an nxt.brick.Brick object, or an NXT brick's name as a string. If omitted, a Brick named 'NXT' is looked up. ''' if isinstance(brick, str): brick = find_one_brick(name=brick) self.brick = brick self.arms = Motor(brick, PORT_A) self.legs = [Motor(brick, PORT_B), Motor(brick, PORT_C)] self.touch = Touch(brick, PORT_1) self.sound = Sound(brick, PORT_2) self.light = Light(brick, PORT_3) self.ultrasonic = Ultrasonic(brick, PORT_4) def echolocate(self): r'''Reads the Ultrasonic sensor's output. ''' return self.ultrasonic.get_sample() def feel(self): r'''Reads the Touch sensor's output. ''' return self.touch.get_sample() def hear(self): r'''Reads the Sound sensor's output. ''' return self.sound.get_sample() def say(self, line, times=1): r'''Plays a sound file named (line + '.rso'), which is expected to be stored in the brick. The file is played (times) times. line The name of a sound file stored in the brick. times How many times the sound file will be played before this method returns. ''' for i in range(0, times): self.brick.play_sound_file(False, line + '.rso') sleep(1) def see(self): r'''Reads the Light sensor's output. ''' return self.light.get_sample() def walk(self, secs, power=FORTH): r'''Simultaneously activates the leg motors, causing Alpha Rex to walk. secs How long the motors will rotate. power The strength effected by the motors. Positive values will cause Alpha Rex to walk forward, while negative values will cause it to walk backwards. If you are unsure about how much force to apply, the special values FORTH and BACK provide reasonable defaults. If omitted, FORTH is used. ''' for motor in self.legs: motor.run(power=power) sleep(secs) for motor in self.legs: motor.idle() def wave(self, secs, power=100): r'''Make Alpha Rex move its arms. secs How long the arms' motor will rotate. power The strength effected by the motor. If omitted, (100) is used. ''' self.arms.run(power=power) sleep(secs) self.arms.idle()
class DrivarNxt(Drivar): def __init__(self): self.m_initialized = False self.m_block = None self.m_leftMotor = None self.m_rightMotor = None self.m_penMotor = None self.m_ultrasonicSensor = None self.m_lightSensor = None self.m_moving = False def initialize(self): super(DrivarNxt, self).initialize() self.m_block = nxt.locator.find_one_brick() self.m_leftMotor = Motor(self.m_block, PORT_A) self.m_rightMotor = Motor(self.m_block, PORT_C) self.m_penMotor = Motor(self.m_block, PORT_B) self.m_ultrasonicSensor = Ultrasonic(self.m_block, PORT_4) self.m_lightSensor = Light(self.m_block, PORT_3) self.m_initialized = True def move(self, direction=Drivar.DIR_FORWARD, durationInMs=1000, callback=None): durationInMs = max(durationInMs, 100) _direct = direction self.rotateWheels(direction=_direct) time.sleep(durationInMs / 1000) self.stop() if callback is not None: callback() def rotateWheels(self, wheelSet=Drivar.WHEELS_BOTH, direction=Drivar.DIR_FORWARD, speedLevel=Drivar.SPEED_FAST, callback=None): power = self._getNxtSpeed(speedLevel) # Correct the power (positive vs negative) depending on the direction if (direction == Drivar.DIR_FORWARD): if (power < 0): power = power * -1 if (direction == Drivar.DIR_BACKWARD): if (power > 0): power = power * -1 # Get the wheels turning if (wheelSet == Drivar.WHEELS_LEFT or wheelSet == Drivar.WHEELS_BOTH): self.m_leftMotor.run(power) if (wheelSet == Drivar.WHEELS_RIGHT or wheelSet == Drivar.WHEELS_BOTH): self.m_rightMotor.run(power) self.m_moving = True if callback is not None: callback() def turn(self, direction=Drivar.DIR_LEFT, angle=90, callback=None): left_power = -100 right_power = 100 if (direction == Drivar.DIR_RIGHT): left_power *= -1 right_power *= -1 self.m_leftMotor.turn(left_power, angle) self.m_rightMotor.turn(right_power, angle) def stop(self, callback=None): self.m_leftMotor.idle() self.m_rightMotor.idle() self.m_moving = False if callback is not None: callback() ''' Return the distance to the nearest obstacle, in centimeters ''' def getDistanceToObstacle(self): return self.m_ultrasonicSensor.get_sample() ''' Indicate with a boolean whether there is an obstacle within the given distance ''' def isObstacleWithin(self, distance): dist = self.m_ultrasonicSensor.get_sample() if (dist <= distance): return True else: return False def rotatePen(self, angle): power = 70 if angle < 0: angle = -1 * angle power = -70 self.m_penMotor.turn(power, angle) def getReflectivityMeasurement(self): self.m_lightSensor.set_illuminated(True) return self.m_lightSensor.get_sample() def wait(self, milliseconds): time.sleep(milliseconds / 1000) ''' Return the NXT speed equivalent for the given DRIVAR speed flag ''' @staticmethod def _getNxtSpeed(speed): if (speed == Drivar.SPEED_SLOW): return 70 elif (speed == Drivar.SPEED_MEDIUM): return 100 elif (speed == Drivar.SPEED_FAST): return 127 else: return 100
class DrivarNxt(Drivar): def __init__(self): self.m_initialized = False self.m_block = None self.m_leftMotor = None self.m_rightMotor = None self.m_ultrasonicSensor = None self.m_moving = False def initialize(self): super(DrivarNxt,self).initialize() self.m_block = nxt.locator.find_one_brick() self.m_leftMotor = Motor(self.m_block, PORT_A) self.m_rightMotor = Motor(self.m_block, PORT_C) self.m_ultrasonicSensor = Ultrasonic(self.m_block, PORT_4) self.m_initialized = True def move(self, direction=Drivar.DIR_FORWARD,durationInMs=1000, callback = None): durationInMs = max(durationInMs,100) _direct = direction self.rotateWheels(direction = _direct) time.sleep(durationInMs/1000) self.stop() if callback is not None: callback() def rotateWheels(self, wheelSet = Drivar.WHEELS_BOTH, direction = Drivar.DIR_FORWARD, speedLevel = Drivar.SPEED_FAST, callback = None): power = self._getNxtSpeed(speedLevel) # Correct the power (positive vs negative) depending on the direction if(direction == Drivar.DIR_FORWARD): if(power < 0): power = power * -1 if(direction == Drivar.DIR_BACKWARD): if(power > 0): power = power * -1 # Get the wheels turning if(wheelSet == Drivar.WHEELS_LEFT or wheelSet == Drivar.WHEELS_BOTH): self.m_leftMotor.run(power) if(wheelSet == Drivar.WHEELS_RIGHT or wheelSet == Drivar.WHEELS_BOTH): self.m_rightMotor.run(power) self.m_moving = True if callback is not None: callback() def turn(self, direction = Drivar.DIR_LEFT, angle = 90): left_power = -100 right_power = 100 if(direction == Drivar.DIR_RIGHT): left_power *= -1 right_power *= -1 self.m_leftMotor.turn(left_power, angle) self.m_rightMotor.turn(right_power, angle) def stop(self, callback = None): self.m_leftMotor.idle() self.m_rightMotor.idle() self.m_moving = False if callback is not None: callback() ''' Return the distance to the nearest obstacle, in centimeters ''' def getDistanceToObstacle(self): return self.m_ultrasonicSensor.get_sample() ''' Indicate with a boolean whether there is an obstacle within the given distance ''' def isObstacleWithin(self, distance): dist = self.m_ultrasonicSensor.get_sample() if(dist <= distance): return True else: return False ''' Return the NXT speed equivalent for the given DRIVAR speed flag ''' @staticmethod def _getNxtSpeed(speed): if(speed==Drivar.SPEED_SLOW): return 70 elif(speed==Drivar.SPEED_MEDIUM): return 100 elif(speed==Drivar.SPEED_FAST): return 127 else : return 100
class Robot(object): def __init__(self, brick="NXT"): r"""Creates a new Robot controller. brick Either an nxt.brick.Brick object, or an NXT brick's name as a string. If omitted, a Brick named 'NXT' is looked up. """ if isinstance(brick, basestring): brick = find_one_brick(name=brick) self.brick = brick self.tool = Motor(brick, PORT_B) self.tracks = [Motor(brick, PORT_A), Motor(brick, PORT_C)] self.ultrasonic = Ultrasonic(brick, PORT_1) self.sound = Sound(brick, PORT_2) self.light = Light(brick, PORT_3) self.touch = Touch(brick, PORT_4) def turn(self, power, angle): for motor in self.tracks: motor.turn(power, angle) def move(self, power=FORTH): r"""Simultaneously activates the tracks motors, causing Robot to move. power The strength effected by the motors. Positive values will cause Robot to move forward, while negative values will cause it to move backwards. If you are unsure about how much force to apply, the special values FORTH and BACK provide reasonable defaults. If omitted, FORTH is used. """ for motor in self.tracks: motor.run(power=power) def wait(self, seconds): """ secsonds How long the motors will rotate. Will this take values < 0? Most motor commands work in ms. Try passing sleep 1/seconds (miliseconds) """ sleep(seconds) def stop(self): for motor in self.tracks: motor.idle() def tacho(self): """ returns an array of two elements which are the motor tacho readings """ tachos = [] for motor in self.tracks: # tachos.append(motor.get_tacho()) tachos.append(motor.tacho_count) # , rotation_count return tachos def act(self, power=FORTH): r"""Make Robot move its tool. power The strength effected by the motor. If omitted, (100) is used. """ self.tool.run(power=power) def echolocate(self): r"""Reads the Ultrasonic sensor's output. """ return self.ultrasonic.get_sample() def feel(self): r"""Reads the Touch sensor's output. """ return self.touch.get_sample() def hear(self): r"""Reads the Sound sensor's output. """ return self.sound.get_sample() def say(self, line, times=1): r"""Plays a sound file named (line + '.rso'), which is expected to be stored in the brick. The file is played (times) times. line The name of a sound file stored in the brick. times How many times the sound file will be played before this method returns. """ for i in range(0, times): self.brick.play_sound_file(False, line + ".rso") sleep(1) def see(self): r"""Reads the Light sensor's output. """ return self.light.get_sample()
class NxtRobot(Robot): FULL_ROTATE_FACTOR = 5.5 CELL_MOVE_FACTOR = 2.35 def __init__(self, world): Robot.__init__(self, world, 2, Orientation.NORTH) self.noise = 0 self.brick = find_one_brick() self.motor1 = Motor(self.brick, PORT_B) self.motor2 = Motor(self.brick, PORT_C) self.ultrasonic = Ultrasonic(self.brick, PORT_4) self.motor1.reset_position(False) self.motor2.reset_position(False) def move(self, direction): if direction == Direction.FORWARD: pass elif direction == Direction.RIGHT: self._rotate(-0.25) pass elif direction == Direction.BACK: self._rotate(0.5) pass elif direction == Direction.LEFT: self._rotate(0.25) pass m = self.ultrasonic.get_sample() if m > 26: t1 = threading.Thread(target=self.motor1.turn, args=(50, self.CELL_MOVE_FACTOR * 360)) t2 = threading.Thread(target=self.motor2.turn, args=(50, self.CELL_MOVE_FACTOR * 360)) t1.start() t2.start() t1.join() t2.join() def measure(self): m = [] for i in range(4): m.append(self.ultrasonic.get_sample()) self._rotate(0.25) return m def sync(self): m = self.ultrasonic.get_sample() while m == 255: self._rotate(0.17) m = self.ultrasonic.get_sample() def _rotate(self, degree): if degree == 0: return sign = 1 if degree < 0: sign = -1 degree = abs(degree) t1 = threading.Thread(target=self.motor1.turn, args=(sign * 50, self.FULL_ROTATE_FACTOR * 360 * degree)) t2 = threading.Thread(target=self.motor2.turn, args=(sign * -50, self.FULL_ROTATE_FACTOR * 360 * degree)) t1.start() t2.start() t1.join() t2.join()
class Seng(object): def __init__(self, brick='NXT'): r'''Creates a new Alpha Rex controller. brick Either an nxt.brick.Brick object, or an NXT brick's name as a string. If omitted, a Brick named 'NXT' is looked up. ''' if isinstance(brick, basestring): brick = find_one_brick(name=brick) self.brick = brick self.arms = Motor(brick, PORT_C) self.left = Motor(brick, PORT_A) self.right = Motor(brick, PORT_B) self.direction = HTCompass(brick, PORT_2) self.ultrasonic = Ultrasonic(brick, PORT_4) def echolocate(self): r'''Reads the Ultrasonic sensor's output. ''' return self.ultrasonic.get_sample() def compass(self): return self.direction.get_sample() def walk_seng(self, secs, power): r'''Simultaneously activates the leg motors, causing Alpha Rex to walk. secs How long the motors will rotate. power The strength effected by the motors. Positive values will cause Alpha Rex to walk forward, while negative values will cause it to walk backwards. If you are unsure about how much force to apply, the special values FORTH and BACK provide reasonable defaults. If omitted, FORTH is used. ''' self.left.run(power=power) self.right.run(power=power) sleep(secs) self.left.idle() self.right.idle() def walk_seng_start(self, power): self.left.run(power=power) self.right.run(power=power) def walk_seng_stop(self): self.left.idle() self.right.idle() def turn_seng(self, secs, power): self.left.run(power=power) self.right.run(power=-power) sleep(secs) self.left.idle() self.right.idle() def turn_seng_start(self, power): self.left.run(power=power) self.right.run(power=-power) def turn_seng_stopp(self): self.left.idle() self.right.idle()
class Robot(object): def __init__(self, brick='NXT'): r'''Creates a new Robot controller. brick Either an nxt.brick.Brick object, or an NXT brick's name as a string. If omitted, a Brick named 'NXT' is looked up. ''' if isinstance(brick, basestring): brick = find_one_brick(name=brick) self.brick = brick self.tool = Motor(brick, PORT_B) self.tracks = [Motor(brick, PORT_A), Motor(brick, PORT_C)] self.ultrasonic = Ultrasonic(brick, PORT_1) self.sound = Sound(brick, PORT_2) self.light = Light(brick, PORT_3) self.touch = Touch(brick, PORT_4) def turn(self, power, angle): for motor in self.tracks: motor.turn(power, angle) def move(self, power=FORTH): r'''Simultaneously activates the tracks motors, causing Robot to move. power The strength effected by the motors. Positive values will cause Robot to move forward, while negative values will cause it to move backwards. If you are unsure about how much force to apply, the special values FORTH and BACK provide reasonable defaults. If omitted, FORTH is used. ''' for motor in self.tracks: motor.run(power=power) def wait(self, seconds): ''' secsonds How long the motors will rotate. Will this take values < 0? Most motor commands work in ms. Try passing sleep 1/seconds (miliseconds) ''' sleep(seconds) def stop(self): for motor in self.tracks: motor.idle() def tacho(self): ''' returns an array of two elements which are the motor tacho readings ''' tachos = [] for motor in self.tracks: #tachos.append(motor.get_tacho()) tachos.append(motor.tacho_count) #, rotation_count return tachos def act(self, power=FORTH): r'''Make Robot move its tool. power The strength effected by the motor. If omitted, (100) is used. ''' self.tool.run(power=power) def echolocate(self): r'''Reads the Ultrasonic sensor's output. ''' return self.ultrasonic.get_sample() def feel(self): r'''Reads the Touch sensor's output. ''' return self.touch.get_sample() def hear(self): r'''Reads the Sound sensor's output. ''' return self.sound.get_sample() def say(self, line, times=1): r'''Plays a sound file named (line + '.rso'), which is expected to be stored in the brick. The file is played (times) times. line The name of a sound file stored in the brick. times How many times the sound file will be played before this method returns. ''' for i in range(0, times): self.brick.play_sound_file(False, line + '.rso') sleep(1) def see(self): r'''Reads the Light sensor's output. ''' return self.light.get_sample()
from time import sleep from nxt.motor import SynchronizedMotors # see files in library ( /usr/local/lib/python2.7/dist-packages/nxt ) # for a more comprehensive list of ports / commands available from nxt.motor import Motor, PORT_A, PORT_B, PORT_C from nxt.sensor import Light, Sound, Touch, Ultrasonic from nxt.sensor import PORT_1, PORT_2, PORT_3, PORT_4 try: motorLeft = Motor(brick, PORT_A) # plug motor into Port A motorRight = Motor(brick, PORT_B) # plug motor into Port B motorBoth = nxt.SynchronizedMotors(motorRight, motorLeft, 0) ultraSensor = Ultrasonic(brick, PORT_1) # plug ultrasonic sensor into Port 1 #motorSync = SynchronizedMotors(motorA, motorB, 10000) #motorSync.idle() while ultraSensor.get_sample() > 10: print("Current ultrasonic sensor state: {}".format( ultraSensor.get_sample())) motorBoth.run(power=-120) '''motorA.run(power = -128) #go forward motorB.run(power = -128) #go forward''' finally: Motor(brick, PORT_A).idle() # otherwise motor keeps running Motor(brick, PORT_B).idle() # otherwise motor keeps running print("Terminating Program") brick.sock.close()