def __init__(self, mac, protokoll, identitaet, color, outbox = 5, inbox = 1): self.brick = find_one_brick(host = mac, method = Method(usb = True, bluetooth = True)) self.color = color self.ausrichtung = 90; # 0 - 359 Grad; 0 Osten, 90 Norden, 180 Westen, 270 Sueden self.calibrationFactor = 1 self.phase_lock = threading.Lock() self.phase = mcc.model.wahl.STATE_INIT self.protokoll = protokoll self.identitaet = identitaet self.status = -1 self.status_lock = threading.Lock() self.sensor = -1 self.sensor_lock = threading.Lock() self.handle = None self.active = False self.blockiert = False self.blockiert_lock = threading.Lock() self.payload = -1 self.payload_lock = threading.Lock() self.abbruch = True self.abbruch_lock = threading.Lock() self.robot_type = NXT_TYPE self.message_id = 0 self.position_lock = threading.Lock() self.position = {'x': 0.0, 'y': 0.0} self.outbox = outbox self.inbox = 10 + inbox self.start_app("explorer.rxe") random.seed() dispatcher = threading.Thread(target = self.dispatch, args = ()) dispatcher.setDaemon(True) dispatcher.start() worker = threading.Thread(target = self.work, args = ()) worker.setDaemon(True) worker.start()
def main(): b = find_one_brick() eyes = Motor(b, PORT_A) wheels = [Motor(b, PORT_B), Motor(b, PORT_C)] ultrasonic = Ultrasonic(b, PORT_4) phizic(eyes, wheels, ultrasonic)
def main(): brick = locator.find_one_brick(debug=True) robot = Robot(brick, debug=True, verbose=True, power=80) # Excessive output # Motors robot.init_synchronized_motors(PORT_A, PORT_C) robot.move_forward(seconds=3, wait=True) robot.move_backwards(seconds=3, wait=True)
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 __init__(self, baddr, pin, direct=False, method='bluetooth', dryrun=False): ''' initialize robot. by default robot is found using bluetooth, remember to install bluetooth lib before usage! :param baddr: The bluetooth mac address :param pin: The pin to ensure the connection ''' self.dryrun = dryrun if self.dryrun: print('Running in dryrun mode, will NOT initialize!') return if method == 'bluetooth': # Pair with nxt via bluetooth before connecting self.stable_connection = Pair(baddr, pin) self.brick = BlueSock(baddr).connect() elif method == 'usb': # explicitly deactivate bluetooth usb_only = Method(usb=True, bluetooth=False) self.brick = find_one_brick(method=usb_only, debug=True) # initialize basic functions self.init_motors() self.init_sensors() # initialize some useful vars self.touch_right = False self.touch_left = False # locked is used to stop robo from moving when it has collided # getting orders from http-server self.locked = False self.calibrating = False # player for beeps and stuff self.player = Nxt_Player(self.brick) # Initialize pad and autopilot modules # TODO: do not start padmode if server if direct: self.pad_controller = PadController(self) self.autopilot = AutoPilot(self) self.calibrate()
def __init__(self, brick=None, debug=True, verbose=False, **kwargs): """ Initialize a new Robot object. :param brick: The brick. Use nxt.locator.find_one_brick. If none brick is given, an attempt to find one brick will be made. :param debug: Whether print debug messages or not. :param verbose: Whether print high verbosity messages or not :param kwargs: """ if brick is None: self.brick = find_one_brick(debug=debug) else: self.brick = brick self.debug = print if debug else lambda *x, **y: None self.verbose = print if verbose else lambda *x, **y: None self.lock = threading.Lock() self._running = False # Check if any sensor was given as kwarg if 'light' in kwargs: self.light = kwargs['light'] if 'sound' in kwargs: self.sound = kwargs['sound'] if 'touch' in kwargs: self.touch = kwargs['touch'] if 'ultrasound' in kwargs: self.ultrasonic = kwargs['ultrasound'] # Now check if a global power was given self.power = kwargs.get('power', 100) # Is there a SynchronizedMotors? if 'synchronized' in kwargs: self.movement_motor = kwargs['synchronized'] self.left_motor = self.movement_motor.leader self.right_motor = self.movement_motor.follower else: self.right_motor = kwargs.get('right_motor', None) self.left_motor = kwargs.get('left_motor', None) if type(self.left_motor) is Motor and type(self.right_motor) is Motor: self.movement_motor = SynchronizedMotors(self.left_motor, self.right_motor, 0) else: self.movement_motor = None # Is there a Servo? self.servo = kwargs.get('servo', None)
def __init__(self, brick="NXT"): if isinstance(brick, basestring): brick = find_one_brick(name=brick) self.brick = brick self.motor = True self.sensor = True try: self.brick = brick except: print("No brick found") try: self.wheels = [Motor(brick, PORT_A), Motor(brick, PORT_B)] except: self.motor = False print("No motors detected!")
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 __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 __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 __init__(self, proj, brick='NXT', brickMAC='00:16:53:14:1B:33'): """ Initialization handler for NXT robots. If you are unsure of the mac address, please pass brickMac='none'. Your NXT Device will be located. brickMAC (str): The MAC address of the nxt brick (default='00:16:53:14:1B:33') """ if isinstance(brick, basestring): if brickMAC!='none': #check to see if user has given a mac address for the brick try: brick = bluesock.BlueSock('00:16:53:14:1B:33').connect() #attempt a connect with the mac address except: print "Can't find given mac, searching for any brick" else: brick = find_one_brick(name=brick) #attempt to find an NXT device if no mac address is given self.brick = brick
def reset(remote=False): global b, L, R, M, lmove, rmove, _lock, light, sonic, touch print("Connecting") connect_method = locator.Method(not remote, remote) b = locator.find_one_brick(method=connect_method, debug=True) print("Connection to brick established\n") print("Initializing sensors") L = m_left = Motor(b, PORT_B) R = m_right = Motor(b, PORT_C) M = SynchronizedMotors(L, R, 2) lmove = Thread() rmove = Thread() _lock = False light = Light(b, PORT_3) sonic = Ultrasonic(b, PORT_2) touch = Touch(b, PORT_4) print("Initialization completed\n") print("Loading Actions")
def run(self): # Start a BT connection over to the NXT print "Initializing Bluetooth" try: brick = nxt.bluesock.BlueSock(BRICK_ADDR).connect() except: print "Brick {0} not found. Trying search by name...".format( BRICK_ADDR) try: brick = find_one_brick(name=BRICK_NAME) except: print "Brick {0} not found".format(BRICK_NAME) return bt_motors = (Motor(brick, PORT_A), Motor(brick, PORT_B), Motor(brick, PORT_C)) while running: # use shoulder buttons on the game pad to make the omnibot rotate around it's axis. turnpower = 0 if gp_state['btn_r1']: turnpower = 60 if gp_state['btn_l1']: turnpower = -60 # read and scale joysticks joy_x = scale(gp_state['move_x'], STICK_RANGE, (-100, 100)) joy_y = scale(gp_state['move_y'], STICK_RANGE, (-100, 100)) # convert joystick x and y to a direction and power (deviation from the centre) joy_direction = math.atan2(joy_x, joy_y) # in radians joy_power = (joy_x**2 + joy_y**2)**0.5 # pythagoras i = 0 for motor in bt_motors: # for each motor the angle has a different offset (0, 120 and 240 degrees) angle = i * 2 * 3.1415 / 3 + joy_direction # motor power calculation. A simple sin. motorpower = math.sin(angle) * joy_power + turnpower motorpower = round(clamp(motorpower, (-100, 100))) motor.run(motorpower, regulated=True) i += 1 # wait a bit before sending more commands. If we don't the BT buffer overflows. btloop.throttle()
def __init__(self, brick="NXT"): r"""Creates a new Strider 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.back_leg = Motor(brick, PORT_B) self.left_leg = Motor(brick, PORT_C) self.right_leg = Motor(brick, PORT_A) # self.touch = Touch(brick, PORT_1) # self.sound = Sound(brick, PORT_2) # self.light = Light(brick, PORT_3) # self.ultrasonic = Ultrasonic(brick, PORT_4) self.colour = Color20(brick, PORT_3)
def run(self): # Start a BT connection over to the NXT print "Initializing Bluetooth" try: brick = nxt.bluesock.BlueSock(BRICK_ADDR).connect() except: print "Brick {0} not found. Trying search by name...".format(BRICK_ADDR) try: brick = find_one_brick(name=BRICK_NAME) except: print "Brick {0} not found".format(BRICK_NAME) return bt_motors = (Motor(brick, PORT_A), Motor(brick, PORT_B), Motor(brick, PORT_C)) while running: # use shoulder buttons on the game pad to make the omnibot rotate around it's axis. turnpower = 0 if gp_state['btn_r1']: turnpower = 60 if gp_state['btn_l1']: turnpower = -60 # read and scale joysticks joy_x = scale(gp_state['move_x'], STICK_RANGE, (-100, 100)) joy_y = scale(gp_state['move_y'], STICK_RANGE, (-100, 100)) # convert joystick x and y to a direction and power (deviation from the centre) joy_direction = math.atan2(joy_x, joy_y) # in radians joy_power = (joy_x ** 2 + joy_y ** 2) ** 0.5 # pythagoras i = 0 for motor in bt_motors: # for each motor the angle has a different offset (0, 120 and 240 degrees) angle = i * 2 * 3.1415 / 3 + joy_direction # motor power calculation. A simple sin. motorpower = math.sin(angle) * joy_power + turnpower motorpower = round(clamp(motorpower, (-100, 100))) motor.run(motorpower, regulated=True) i += 1 # wait a bit before sending more commands. If we don't the BT buffer overflows. btloop.throttle()
def __init__(self, proj, brick='NXT', brickMAC='00:16:53:14:1B:33'): """ Initialization handler for NXT robots. If you are unsure of the mac address, please pass brickMac='none'. Your NXT Device will be located. brickMAC (str): The MAC address of the nxt brick (default='00:16:53:14:1B:33') """ if isinstance(brick, basestring): if brickMAC != 'none': #check to see if user has given a mac address for the brick try: brick = bluesock.BlueSock('00:16:53:14:1B:33').connect( ) #attempt a connect with the mac address except: print "Can't find given mac, searching for any brick" else: brick = find_one_brick( name=brick ) #attempt to find an NXT device if no mac address is given self.brick = brick
def main(): brick = locator.find_one_brick(debug=True) robot = Robot(brick, debug=True, verbose=True, power=80) # Excessive output # Motors robot.init_synchronized_motors(PORT_A, PORT_C) robot.init_servo(PORT_B) light = robot.init_light_sensor(PORT_2) robot.turn_light_sensor(ON) robot.set_servo(SERVO_DOWN) table_value = normalize(light.get_sample(), 0, 1023) print(table_value) def until(): print(normalize(light.get_sample(), 0, 1023)) return normalize(light.get_sample(), 0, 1023) < 0.3 robot.move_forward(until=until, until_args=(), until_kwargs={}, wait=True) robot.turn_light_sensor(OFF)
def __init__(self, brick_name='NXT'): sock = find_one_brick(name=brick_name) brick = self.brick = sock.connect() self.arm = 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) self.busy = False self.arg_d = {"forward": (self.forward, 2), "backward": (self.backward, 2), "left": (self.turn_left, 2), "right": (self.turn_right, 2), #"power": (self.add_arm_power, 1), #"kick": (self.release_arm, 0), "boot": (self.boot, 0), "sing": (self.sing, 0), "talk": (self.talk, 0)}
def do(self): b = nxtl.find_one_brick(debug=True, strict=True, method=nxtl.Method(usb=True, bluetooth=False)) start = time.time() time_bomb = random.randint(25, 35) if b: while (True): elapsed_time = time.time() - start if elapsed_time < time_bomb: anomaly = False else: anomaly = True start = time.time() time_bomb = random.randint(25, 35) # execute the action self.spin_around(b, anomaly) else: print('No NXT bricks found')
m_left = Motor(robot, PORT_B) m_right = Motor(robot, PORT_A) touch_right = Touch(robot, PORT_2) touch_left = Touch(robot, PORT_1) ultrason = Ultrasonic(robot, PORT_3) DEFAULT_POWER = 80 DISTANCE_LIMIT = 20 TURN_TIME = 1.5 # Début while True: m_left.run(power=DEFAULT_POWER) m_right.run(power=DEFAULT_POWER) while not touch_right.is_pressed() and not touch_left.is_pressed() and ultrason.get_distance() > DISTANCE_LIMIT: sleep(0.01) print("Aieee") if touch_right.is_pressed(): m_left.run(power=DEFAULT_POWER) m_left.run(power=-DEFAULT_POWER) else: m_left.run(power=-DEFAULT_POWER) m_left.run(power=DEFAULT_POWER) sleep(TURN_TIME) main(find_one_brick())
# coding=utf-8 # Больше информации и пример работы: http://mic-dm.blogspot.com/2012/07/blog-post.html. from time import sleep import nxt from nxt.locator import find_one_brick from nxt.sensor.generic import Touch # Определяем кирпич, мотор и кнопку: brick = find_one_brick() motor = nxt.Motor(brick, nxt.PORT_B) sensor = Touch(brick, nxt.PORT_1) # "Мотор запаркован" у нас будет означать, что # кочерга мотора находится в нижнем положении: is_parked = False while True: if sensor.is_pressed(): # Если кнопка нажата, ждем недолго и крутим мотор, # чтобы освободить кнопку: sleep(1) motor.turn(-20, 40, False) is_parked = False elif not is_parked: # Если кнопка отжата, но мотор не запаркован, # паркуем: motor.turn(20, 40, False) is_parked = True sleep(0.1)
self.stopQueue.put(_stop_token) break except Queue.Empty: pass # deal with results: try: result = self.resQueue.get( timeout=ResultQueueChecker.reqWait) except Queue.Empty: continue logging.debug('fetched %s', result) if __name__ == '__main__': b = find_one_brick(name='NAMANI') logging.debug("Found brick: %s", b) # main thread's signal queue: sq = Queue.Queue() # motors and sensors for driving the car: ma = MotorRunThread(b, nm.PORT_A, sq, name='motor_A') mb = MotorRunThread(b, nm.PORT_B, sq, name='motor_B') ts1 = MotorTouchThread(b, ns.PORT_1, ma, sq, name='touch_1') ts2 = MotorTouchThread(b, ns.PORT_2, mb, sq, name='touch_2') # motor to turn ultrasound sensor and sensor itelf: mc = MotorRunThread(b, nm.PORT_C, sq, name='motor_C') us = UltrasonicThread(b, ns.PORT_4, mc, MotorRunThread.power, sq, name='ultra_s')
from nxt.locator import find_one_brick from nxt.motor import * from time import sleep, clock pygame.init() done = False joystick_count=pygame.joystick.get_count() if joystick_count == 0: print ("Error, I didn't find any joysticks.") else: my_joystick = pygame.joystick.Joystick(0) my_joystick.init() brick = find_one_brick() mc = brick.mc left_engine = Motor(brick, PORT_B) right_engine = Motor(brick, PORT_C) vehicle = SynchronizedMotors(left_engine, right_engine, 0) angle = 0 angle_prev = 0 mc.start() sleep(1) while done == False:
def main(): brick = locator.find_one_brick(debug=True) robot = Robot(brick, debug=True, verbose=True, power=80) # Excessive output # Motors robot.init_synchronized_motors(PORT_A, PORT_C) robot.init_servo(PORT_B) # Sensors light = robot.init_light_sensor(PORT_2) sound = robot.init_sound_sensor(PORT_4) # Intial setup robot.set_servo(SERVO_UP) robot.turn_light_sensor(ON) # Calibration (light) # light_off, light_on = robot.calibrate_light(interactive=True) # FIXME: Output says 'Point the sensor to black line' light_off, light_on = 229, 900 # Sound sensor calibration quiet, loud = 15, 1024 # robot.calibrate_sound(interactive=True) # Thresholds lower = 5 * (10**-1) lower_noise = 1 # 9 * (10 ** -1) upper = 5 * (10**-1) # until = lambda *args, ls=light, **kwargs: normalize(ls.get_lightness(), light_off, light_on) > upper print('starting...') sleep(3) # TODO I should probably lock the access to light sensor. def until(light_sensor, **kwargs): # Must explicitly state **kwargs as his argument. return normalize(light_sensor.get_lightness(), light_off, light_on) < lower robot.move_forward(until=until, until_args=(light, )) while robot.running: light_level = normalize(light.get_lightness(), light_off, light_on) robot.debug('Current light level: ', light_level) if light_level < lower: robot.turn_right( 50, 15) # Turn right 15° to see if we correct the course light_level_tmp = normalize(light.get_lightness(), light_off, light_on) robot.debug('temp lecture at right', light_level_tmp) if light_level_tmp > light_level: robot.debug( 'Right turn didn\'t improve course. Turning left...') robot.turn_left(50, 30) sleep(.4) s = sound.get_sample() loudness = normalize(s, quiet, loud) robot.debug('Value of loudness is ', loudness, s) if loudness > lower_noise: robot.stop() robot.morse('SOS') robot.move_backwards(seconds=3, wait=True) if not until(light): robot.move_forward(until=until, until_args=( light, )) # FIXME: Does this cause an infinite loop? robot.turn_light_sensor(OFF) print('DONE: Won\'t do anything else.') exit(0)
def __init__(self): """Constructs a robot object which can be used to control the nxt brick.""" self.brick = find_one_brick() self.sensors = [Touch(self.brick, PORT_1)] self.motors = [Motor(self.brick, PORT_A), Motor(self.brick, PORT_B)]
touch_right = Touch(robot, PORT_2) touch_left = Touch(robot, PORT_1) ultrason = Ultrasonic(robot, PORT_3) DEFAULT_POWER = 80 DISTANCE_LIMIT = 20 TURN_TIME = 1.5 # Début while True: m_left.run(power=DEFAULT_POWER) m_right.run(power=DEFAULT_POWER) while not touch_right.is_pressed() and not touch_left.is_pressed( ) and ultrason.get_distance() > DISTANCE_LIMIT: sleep(0.01) print("Aieee") if touch_right.is_pressed(): m_left.run(power=DEFAULT_POWER) m_left.run(power=-DEFAULT_POWER) else: m_left.run(power=-DEFAULT_POWER) m_left.run(power=DEFAULT_POWER) sleep(TURN_TIME) main(find_one_brick())
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from nxt.locator import find_one_brick from nxt.motor import Motor, PORT_A, PORT_B, PORT_C robot = find_one_brick() for port in (PORT_A, PORT_B, PORT_C): try: Motor(robot, port).brake() except: pass
from nxt import locator, motor import nxtprinter b = locator.find_one_brick() p = nxtprinter.NxtPrinter(b, motor.PORT_B, motor.PORT_A, motor.PORT_C) p.write(raw_input("print: "), 15)