def run():
	conn = Connection(3)
	msg = messages.GetBatteryLevel()
	conn.send(msg)
	resp = conn.receive()
	print('received response: %s' % type(resp))
	print('battery voltage is %d mV.' % resp.millivolts)
Exemple #2
0
def run():
    conn = Connection(3)
    msg = messages.GetBatteryLevel()
    conn.send(msg)
    resp = conn.receive()
    print('received response: %s' % type(resp))
    print('battery voltage is %d mV.' % resp.millivolts)
Exemple #3
0
def runSorter():
	conn = Connection('/dev/rfcomm0')
	port = enum.InputPort(1)
	print(conn)
	conn.send(messages.SetInputMode(
		port,
		messages.SensorType.switch,
		messages.SensorMode.boolean,
	))
	#print(', '.join(field[:4] for field in messages.InputValues.fields))
	#querySorter(conn,port)
	#cycle_motor_a(conn)
	conn.close()
Exemple #4
0
	def __init__(self, options):
		self.conn = Connection(options.port)
		if options.scale_a:
			self.scale_a = options.scale_a
		if options.scale_b:
			self.scale_b = options.scale_b
		if options.scale_c:
			self.scale_c = options.scale_c
		try:
			self.input = Joystick.enumerate_devices()[0]
		except IndexError:
			raise RuntimeError("Could not find any joystick controllers.")
		# keep track of the state of the controller (initial state
		#  assumes all values are zero).
		self.controller_state = defaultdict(lambda: 0)

		# register the joystick on_axis event
		self.input.event(self.on_axis)
Exemple #5
0
def runSorter():
    conn = Connection('/dev/rfcomm0')
    port = enum.InputPort(1)
    print(conn)
    conn.send(
        messages.SetInputMode(
            port,
            messages.SensorType.switch,
            messages.SensorMode.boolean,
        ))
    #print(', '.join(field[:4] for field in messages.InputValues.fields))
    #querySorter(conn,port)
    #cycle_motor_a(conn)
    conn.close()
Exemple #6
0
def log():
    with open('bluetooth.log', 'w') as log_file:
        print("Establishing connection...")
        conn = Connection(PORT, timeout=5)
        print('Logging output...')
        while True:
            print('Listening for output...')
            try:
                resp = conn.receive()
            except struct.error:
                print("Timed out")
                conn.close()
                time.sleep(1)
                conn.open()
            else:
                msg = parse_message(resp)
                print msg
                if msg.startswith('DISTANCE'):
                    log_file.write('%s %s\n' % (datetime.now().time(), msg))
Exemple #7
0
import time
import sys
from jaraco.nxt import Connection, messages
from jaraco.nxt.routine import get_port
from jaraco.nxt.messages import RegulationMode, RunState
from jaraco.nxt import _enum as enum

conn = Connection("/dev/tty.NXT-DevB")
right_port = enum.InputPort(1)
left_port = enum.InputPort(2)
light_port = left_port
motor_port_a = get_port('a', messages.OutputPort)
motor_port_b = get_port('b', messages.OutputPort)
conn.send(
    messages.SetInputMode(light_port, messages.SensorType.light_active,
                          messages.SensorMode.raw))

Blue_Reading = 540
Gray_Reading = 580


def moveMotor(conn, port, power, time):
    cmd = messages.SetOutputState(port,
                                  motor_on=True,
                                  set_power=power,
                                  run_state=messages.RunState.running)
    conn.send(cmd)
    time.sleep(time)
    cmd = messages.SetOutputState(port, motor_on=False)
    conn.send(cmd)
Exemple #8
0
def run():
    conn = Connection(5)

    conn.send(SetOutputState(OutputPort.b))
    conn.send(SetOutputState(OutputPort.c))

    regulation_params = dict(
        use_regulation=True,
        regulation_mode=RegulationMode.motor_sync,
        turn_ratio=100,
    )
    run_params = dict(
        run_state=RunState.running,
        set_power=75,
        motor_on=True,
    )
    all_params = dict(regulation_params)
    all_params.update(run_params)
    reg_cmd = SetOutputState(OutputPort.b, **all_params)
    conn.send(reg_cmd)
    time.sleep(2)
    run_cmd = SetOutputState(OutputPort.c, **all_params)
    run_cmd.turn_ratio = 5
    conn.send(run_cmd)

    time.sleep(5)

    stop_cmd = SetOutputState(OutputPort.b)
    conn.send(stop_cmd)
    stop_cmd = SetOutputState(OutputPort.c)
    conn.send(stop_cmd)
Exemple #9
0
class MotorController(object):
	"""
	Interfaces a jaraco.input Joystick with the NXT motors

	Maps the left thumb y axis to output port B
	Maps the right thumb y axis to output port C
	Maps the left and right triggers to output port A
	"""

	motor_map = dict(
		l_thumb_y = OutputPort.b,
		r_thumb_y = OutputPort.c,
		)
	scale_exponent = .3
	scale_a = 1
	scale_b = 1
	scale_c = 1

	def __init__(self, options):
		self.conn = Connection(options.port)
		if options.scale_a:
			self.scale_a = options.scale_a
		if options.scale_b:
			self.scale_b = options.scale_b
		if options.scale_c:
			self.scale_c = options.scale_c
		try:
			self.input = Joystick.enumerate_devices()[0]
		except IndexError:
			raise RuntimeError("Could not find any joystick controllers.")
		# keep track of the state of the controller (initial state
		#  assumes all values are zero).
		self.controller_state = defaultdict(lambda: 0)

		# register the joystick on_axis event
		self.input.event(self.on_axis)

	def on_axis(self, axis, value):
		self.controller_state[axis] = value
		self.on_state_changed()

	def on_state_changed(self):
		st = self.controller_state

		# let the left trigger be reverse and the right trigger be forward,
		# use the difference to determine the motor power.
		a_reverse = st['left_trigger']
		a_forward = st['right_trigger']
		a_power = a_forward - a_reverse
		a_power *= self.scale_a

		# note a_power in [-1, 1]
		self.set_port(OutputPort.a, a_power)

		# multiply by 2 because it's a signed value [-0.5,0.5]
		b_power = st['l_thumb_y']*2
		b_power *= self.scale_b
		self.set_port(OutputPort.b, b_power)

		c_power = st['r_thumb_y']*2
		c_power *= self.scale_c
		self.set_port(OutputPort.c, c_power)

	def set_port(self, port, power):
		"Set the output port to the specified power"

		# first, scale the power using the provided exponent
		#  A scale_exponent < 1 makes the sensor less sensitive near
		#  the origin (0) and thus more sensitive toward the extremes
		scaled_power = abs(power) ** self.scale_exponent
		if power < 0:
			power = -scaled_power
		else:
			power = scaled_power

		# NXT expects a power between -100 and 100.
		power *= 100
		# with rounding errors, sometimes the power is greater than 100
		#  or less than -100.
		# TODO: should I just round here?
		#  i.e. power = int(round(power))
		power = max(min(power, 100), -100)
		# here, I'm disabling the motor if the output is less than 50, because
		#  those levels of power don't seem to be able to do much to actuate
		#  movement.
		# I note now that the regulation mode may be useful to actuate movement when
		#  the load is preventing movement at that power level.
		if abs(power) > 50:
			cmd = SetOutputState(port, motor_on=True, set_power=power, run_state=RunState.running)
		else:
			cmd = SetOutputState(port)
		self.conn.send(cmd)

	@staticmethod
	def add_options(parser):
		parser.add_option('--scale_a', type="float")
		parser.add_option('--scale_b', type="float")
		parser.add_option('--scale_c', type="float")
Exemple #10
0
def run():
	conn = Connection('COM4')
	cycle_motor_a(conn)

	conn.close()
Exemple #11
0
                motor_on=True,
                regulation_mode=RegulationMode.motor_sync,
                run_state=RunState.running,
                set_power=power_mul * 75,  # slower is more accurate
                tacho_limit=quarter_turn_ticks,
                turn_ratio=100,  # turn right
            ),
        ]

        list(map(connection.send, cmds))

        # leave the bot time to start turning
        time.sleep(1)

        # Check for the end of rotation
        wait_for_motor(connection, OutputPort.b)

        # give it a little time to correct its mistakes (hey synchronisation
        # mode :-)
        time.sleep(2)

        # apparently we've stopped!
        # then release the motors
        initialize()


if __name__ == '__main__':
    connection = Connection(port)
    initialize()
    run()
Exemple #12
0
import time
import sys
from jaraco.nxt import Connection, messages
from jaraco.nxt.routine import get_port
from jaraco.nxt.messages import RegulationMode, RunState
from jaraco.nxt import _enum as enum

conn = Connection("/dev/tty.NXT-DevB")
right_port = enum.InputPort(1)
left_port = enum.InputPort(2)
light_port = left_port
motor_port_a = get_port('a', messages.OutputPort)
motor_port_b = get_port('b', messages.OutputPort)
conn.send(messages.SetInputMode(light_port, messages.SensorType.light_active, messages.SensorMode.raw))


Blue_Reading = 540
Gray_Reading = 580


def moveMotor(conn,port,power,time):
    cmd = messages.SetOutputState(port, motor_on = True, set_power = power, run_state = messages.RunState.running)
    conn.send(cmd)
    time.sleep(time)
    cmd = messages.SetOutputState(port, motor_on = False)
    conn.send(cmd)


def calibrateMAX(conn,port,n):
    for i in xrange(n):
        conn.send(messages.GetInputValues(port))
Exemple #13
0
def run():
	"""runs the bot"""

	dev = Connection("COM4") # whichever connection the bot is on, can change

	# read the values from this port
	port1 = enum.InputPort(1)
	port3 = enum.InputPort(3)
	#port = get_port(3)

	# configure the input mode
	dev.send(messages.SetInputMode(
		port1,
		messages.SensorType.light_active,
		messages.SensorMode.boolean))

	dev.send(messages.SetInputMode(
		port3,
		messages.SensorType.light_active,
		messages.SensorMode.boolean))

	# print out the field names once
	#print(', '.join(field[:4] for field in messages.InputValues.fields))
	#print(messages.InputValues.fields[9])

	green_1 = calibrate(dev, "green", port1)
	green_3 = calibrate(dev, "green", port3)
	gray_1 = calibrate(dev, "gray", port1)
	gray_3 = calibrate(dev, "gray", port3)
	blue_1 = calibrate(dev, "blue", port1)
	blue_3 = calibrate(dev, "blue", port3)

	print "green_1 = " + str(green_1)
	print "green_3 = " + str(green_3)
	print "gray_1 = " + str(gray_1)
	print "gray_3 = " + str(gray_3)
	print "blue_1 = " + str(blue_1)
	print "blue_3 = " + str(blue_3)

	forward(dev)

	try:
		while True: # continuously query port status, output values
			sys.stdout.write('\r')
			port1_status = query_status(dev, port1) - 35
			port3_status = query_status(dev, port3) - 35

			if port3_status <= blue_3 and port1_status <= blue_1: # if both sensors read blue, brake.
				sys.stdout.write('port 3: '+str(port3_status))
				sys.stdout.write('  brake  ')
				sys.stdout.write('port 1: '+str(port1_status))
				brake(dev)
		#	else:
		#		pass

			elif port1_status < gray_1: # if righthand port reads "green":

				if port3_status < gray_3:  # if lefthand reads "green" too, forward
					sys.stdout.write('port 3: '+str(port3_status))
					sys.stdout.write(' forward ')
					sys.stdout.write('port 1: '+str(port1_status))
					forward(dev)

				else:	# otherwise, turn right
					sys.stdout.write('port 3: '+str(port3_status))
					sys.stdout.write('  right  ')
					sys.stdout.write('port 1: '+str(port1_status))
					turn_right(dev)

			elif port1_status > green_1: # if righthand port reads "gray":

				if (port3_status < gray_3): # if lefthand port is "green," turn left
					sys.stdout.write('port 3: '+str(port3_status))
					sys.stdout.write('   left  ')
					sys.stdout.write('port 1: '+str(port1_status))
					turn_left(dev)

				else: # if both are gray, reverse?
					sys.stdout.write('port 3: '+str(port3_status))
					sys.stdout.write(' reverse ')
					sys.stdout.write('port 1: '+str(port1_status))
					back_it_up(dev)

		#	if (port1_status > 500 & port3_status < 500):
				# if righthand sensor reads lower, turn left
		#		sys.stdout.write('3'+str(port3_status))
		#		sys.stdout.write('   left  ')
		#		sys.stdout.write('1'+str(port1_status))
		#		turn_left(dev)

		#	elif (port1_status < 500 & port3_status > 500):
				# if lefthand sensor reads lower, turn right
		#		sys.stdout.write(str(port3_status))
		#		sys.stdout.write('  right  ')
		#		sys.stdout.write(str(port1_status))
		#		turn_right(dev)

		#	elif (port1_status < 500) & (port3_status < 500):
		#		sys.stdout.write(str(port3_status))
		#		sys.stdout.write(' forward ')
		#		sys.stdout.write(str(port1_status))
		#		forward(dev)



	except KeyboardInterrupt:
		sys.stdout.write('\n')
Exemple #14
0
def run():
	conn = Connection('COM4')
	cycle_motor(conn, 'b')

	conn.close()
Exemple #15
0
def run():
    conn = Connection('COM4')
    cycle_motor(conn, 'b')

    conn.close()
Exemple #16
0
def run():
    conn = Connection('COM4')
    cycle_motor_a(conn)

    conn.close()
Exemple #17
0
def run():
	conn = Connection(5)

	conn.send(SetOutputState(OutputPort.b))
	conn.send(SetOutputState(OutputPort.c))

	regulation_params = dict(
		use_regulation=True,
		regulation_mode=RegulationMode.motor_sync,
		turn_ratio=100,
		)
	run_params = dict(
		run_state = RunState.running,
		set_power = 75,
		motor_on=True,
		)
	all_params = dict(regulation_params)
	all_params.update(run_params)
	reg_cmd = SetOutputState(OutputPort.b, **all_params)
	conn.send(reg_cmd)
	time.sleep(2)
	run_cmd = SetOutputState(OutputPort.c, **all_params)
	run_cmd.turn_ratio=5
	conn.send(run_cmd)

	time.sleep(5)

	stop_cmd = SetOutputState(OutputPort.b)
	conn.send(stop_cmd)
	stop_cmd = SetOutputState(OutputPort.c)
	conn.send(stop_cmd)