Esempio n. 1
0
def main():
    # get command line args
    args = handleArgs()
    port = args['port']
    dt = args['sleep']

    # create print monitor
    mon = Monitor()

    # create robot
    bot = pycreate2.Create2(port)
    bot.start()
    bot.safe()

    # now run forever, until someone hits ctrl-C
    try:
        while True:
            try:
                sensor_state = bot.get_sensors()
                mon.display_raw(sensor_state)
                time.sleep(dt)
            except Exception as e:
                print(e)
                continue
            except:
                raise
    except KeyboardInterrupt:
        print('bye ... ')
Esempio n. 2
0
    def __init__(self, sock):
        command = "ls /dev | grep cu.usb"  # !ここに実行したいコマンドを書く!
        proc = subprocess.Popen(command,
                                shell=True,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)

        stdout_data, stderr_data = proc.communicate()  # 処理実行を待つ
        rmb_port = "/dev/" + stdout_data.decode("utf-8")[:-1]  # 標準出力の確認

        rmb_baudrate = 115200
        self.rmb = pycreate2.Create2(rmb_port, rmb_baudrate)

        # 学習時にはTrue 評価時にはFalse
        # self.learnFlag = True
        self.learnFlag = True

        self.nowSpeed = [0, 0]
        self.max_speed = 500
        self.name = 'rmb'
        cv2.namedWindow(self.name)
        self.cap = cv2.VideoCapture(0)
        self.cap.set(3, 640)  # カメラの横のサイズ
        self.cap.set(4, 480)  # カメラの縦のサイズ
        self.lineXs = [320 + 100, 320 - 100]
        self.lineYs = [100, 200, 300, 350]
        self.clf = tree.DecisionTreeClassifier(max_depth=6)
        if self.learnFlag == True:
            self.datafile, self.writer = self.openDataFile()
        else:
            self.data_analysis()
        self.sock = sock
        print("init")
        self.rmb_start()
Esempio n. 3
0
def main():
    args = handleArgs()
    port = args['port']
    baud = args['baud']

    bot = pycreate2.Create2(port=port, baud=baud)

    bot.start()
    ret = bot.reset()
    print(ret)
Esempio n. 4
0
def main():
    port = "/dev/ttyUSB0"
    baud = 115200

    bot = pycreate2.Create2(port=port, baud=baud)

    bot.start()
    ret = bot.reset()
    print(ret)

    packet = bot.SCI.read_and_print_all()
Esempio n. 5
0
    def __init__(self, port='/dev/ttyUSB0'):
        self.bot = pycreate2.Create2(port)
        # self.js = Joystick()
        self.camera = Camera(cam='cv')
        self.camera.init(win=(320, 240), cameraNumber=0)

        # only create if on linux, because:
        #   imu needs access to i2c
        #   adc needs access to spi
        # if platform.system() == 'Linux':
        # 	self.imu = IMU()
        # 	self.adc = MCP3208()
        print('Start')
        print(self.bot.inputCommands([35]))
Esempio n. 6
0
def main():
	port = '/dev/ttyUSB0'
	bot = bot = pycreate2.Create2(port)
	bot.start()
	bot.safe()
	bot.drive_stop()

	image_size = (320, 240)
	camera = Camera(cam='pi')
	camera.init(win=image_size)

	imu = IMU()

	bag = BagWriter()
	bag.open(['camera', 'accel', 'mag', 'cr'])
	bag.stringify('camera')
	bag.use_compression = True

	try:
		for i in range(100):
			ret, frame = camera.read()
			if ret:
				bag.push('camera', frame)
			else:
				print('>> bad frame', i)

			sen = bot.get_sensors()
			bag.push('cr', sen)

			a, m, g = imu.get()
			bag.push('accel', a)
			bag.push('mag', m)

			# time.sleep(0.025)

			print(i)

	except KeyboardInterrupt:
		print(' ctrl-c pressed, bye ...')

	except Exception as e:
		print('')
		print('Something else happened ... :(')
		print('Maybe the robot is not on ... press the start button')
		print('-'*30)
		print(e)

	bag.write('test.json')
Esempio n. 7
0
def testConstructor():
    bot = pycreate2.Create2(port="COM43", baud=115200)
    bot.start()
    bot.safe()
    # bot.clean()
    bot.enableVacuum()
    time.sleep(3)
    bot.disableVaacum()

    # bot.reset()
    # time.sleep(10)
    # bot.drive_direct(-50, -50)
    # time.sleep(1)
    # bot.stop()
    # bot.enableVacuum()
    # time.sleep(3)
    # bot.disableVaacum()
    assert True
Esempio n. 8
0
def main():
    port = "/dev/ttyUSB0"
    baud = 115200

    bot = pycreate2.Create2(port=port, baud=baud)

    bot.start()
    bot.power()

    while True:
        try:
            sensor = bot.get_sensors()

            print(sensor.battery_charge, sensor.battery_capacity)

            time.sleep(5)

        except KeyboardInterrupt:
            break
Esempio n. 9
0
def main():

    args = handleArgs()
    port = args['port']
    baud = args['baud']

    bot = pycreate2.Create2(port=port, baud=baud)

    bot.start()
    time.sleep(0.25)
    bot.power()  # this seems to shut it down more than stop ... confused
    # bot.shutdown()
    time.sleep(0.25)
    bot.stop()
    time.sleep(1)

    print('=====================================================')
    print('\n\tCreate Shutdown')
    print('\tHit power button to wake-up\n')
    print('=====================================================')
Esempio n. 10
0
def main():
    port = "/dev/ttyUSB0"
    baud = 115200

    bot = pycreate2.Create2(port=port, baud=baud)

    bot.start()

    while True:
        try:
            print("waking")

            bot.wake()

            packet = bot.SCI.read_all()
            if packet:
                print(packet)

        except KeyboardInterrupt:
            bot.power()
            print("Stoping")
            break
Esempio n. 11
0
    def __init__(self, port='/dev/ttyUSB0'):
        self.bot = pycreate2.Create2(port)

        # only create if on linux:
        image_size = (640, 480)
        if platform.system() == 'Linux':
            self.camera = Camera(cam='pi')
            self.camera.init(win=image_size)
            self.imu = IMU()
        else:
            self.camera = Camera(cam='cv')
            self.camera.init(win=image_size, cameraNumber=0)

        self.sensors = {'create': None, 'imu': None, 'camera': None}

        self.distance = 0.0

        self.ahrs = AHRS()

        self.modes = {
            'js': JoyStickMode(self.bot),
            'demo': DemoMode(self.bot),
            'auto': AutoMode(self.bot),
            'idle': IdleMode(self.bot),
            'sensors': Sensors(self.bot)
        }

        # self.bag = Bag('./data/robot-{}.json'.format(time.ctime().replace(' ', '-')), ['imu', 'camera', 'create'])

        self.current_mode = 'idle'

        self.last_time = time.time()

        self.data = {
            # 'r': CircularBuffer(30),
            # 'p': CircularBuffer(30),
            'y': CircularBuffer(30),
        }
Esempio n. 12
0
def main():

    # init roomba
    global bot, path
    port = '/dev/ttyUSB0'
    baud = {
        'default': 115200,
        'alt':
        19200  # shouldn't need this unless you accidentally set it to this
    }

    bot = pycreate2.Create2(port=port, baud=baud['default'])

    bot.start()
    bot.safe()

    t_go = threading.Thread(target=go, args=(3, ))
    t_get_Motor_Speed = threading.Thread(target=get_Motor_Speed, args=(3, ))

    t_go.start()
    t_get_Motor_Speed.setDaemon(True)
    t_get_Motor_Speed.start()
    t_get_Motor_Speed.join()
Esempio n. 13
0
def write():
	bag = Bag(filename, ['imu', 'create'])
	# cap = cv2.VideoCapture(0)
	imu = IMU()
	bot = pycreate2.Create2('/dev/ttyUSB0')
	bot.start()
	bot.safe()

	for i in range(100):
		# grab IMU
		a, m, g = imu.get()
		bag.push('imu', (a, m, g))

		# grab create sensors
		s = bot.inputCommands()
		bag.push('create', s)

		# grab images
		# ret, frame = cap.read()
		# if not ret:
		# 	frame = None

		time.sleep(0.03)
Esempio n. 14
0
    def run(self):
        # setup create 2
        port = '/dev/ttyUSB0'
        self.cr = pycreate2.Create2(port)
        self.cr.start()
        self.cr.safe()

        pkts = [46, 47, 48, 49, 50, 51]
        sensor_pkt_len = calc_query_data_len(pkts)

        # setup pygecko
        kb_sub = zmqSub(['twist_kb'], ('192.168.1.8', 9000), hwm=20)

        while True:
            raw = self.cr.query_list(pkts, sensor_pkt_len)

            topic, msg = kb_sub.recv()
            if msg:
                # print('Msg:', msg)
                vel = msg.linear.x
                rot = msg.angular.z
                print('raw', vel, rot)

                if rot == 0.0:
                    # self.cr.drive_straight(vel)
                    pass
                else:
                    i = int(rot * 10)
                    i = 0 if i < 0 else i
                    i = 10 if i > 10 else i
                    r = range(1100, 0, -100)
                    radius = r[i]
                    # self.cr.drive_turn(vel, radius)
                    print('cmd:', vel, radius)
            else:
                print('no command')
Esempio n. 15
0
import pycreate2
import time
import math
from myMovement import meArm
from easydetect import detect

if __name__ == "__main__":
    arm = meArm()
    port = '/dev/ttyUSB0'  # this is the serial port on my raspberry pi
    baud = {
        'default': 115200,
        'alt':
        19200  # shouldn't need this unless you accidentally set it to this
    }

    bot = pycreate2.Create2(port=port, baud=baud['default'])
    #can pick locations arbitrarily
    location1 = [50, 50]
    location2 = [-50, -50]
    location3 = [50, 100]

    currentLocation = [0, 0]
    currentAngle = 0

    #assumes no obstacle
    #if obstacle, moveTo intermittent locations to go around obstace
    def moveTo(current, heading, destination):
        distance = (destination[0] - current[0])**2
        distance += (destination[1] - current[1])**2
        distance **= 1 / 2
        angle = math.atan2(destination[1] - current[1],
        State.__init__(self, outcomes=['e'])

    def execute(self, userdata):
        while not rospy.is_shutdown():
            bot.drive_direct(0, 0)
            if x != 3:
                return 'e'  # return to normal


#define subscriber callback
x = 0


def callback(msg):
    global x, x1
    x = msg.data


if __name__ == '__main__':
    rospy.init_node('state')  #node
    sub = rospy.Subscriber('navigator', Int32, callback)  #subscriber
    port = '/dev/ttyUSB0'
    bot = pycreate2.Create2(port=port, baud=115200)  #serial port

    sm = StateMachine(outcomes=['normal'])  #define state machine
    with sm:
        StateMachine.add('NORMAL', Normal(), transitions={'e': 'EMERGENCY'})
        StateMachine.add('EMERGENCY', Emergency(), transitions={'e': 'NORMAL'})

    sm.execute()
Esempio n. 17
0
    print('-' * 70)
    for k, v in sensors.items():
        print('{:>40} | {:<5}'.format(k, v))


if __name__ == "__main__":
    # Create a Create2 Bot
    port = '/dev/tty.usbserial-DA01NX3Z'
    baud = {
        'default': 115200,
        'alt':
        19200  # shouldn't need this unless you accidentally set it to this
    }

    # setup create 2
    bot = pycreate2.Create2(port)
    bot.start()
    bot.safe()

    bot.digit_led_ascii('hi')  # set a nice message
    bot.led(1)  # turn on debris light

    sensors = {}

    pkts = [46, 47, 48, 49, 50, 51]

    try:
        while True:
            sensors = bot.inputCommands(pkts)
            if sensors:
                prettyPrint(sensors)
Esempio n. 18
0
 def __init__(self, port='/dev/ttyUSB0'):
     self.cr = pycreate2.Create2(port)
Esempio n. 19
0

def handleArgs():
    parser = argparse.ArgumentParser(
        description=DESCRIPTION, formatter_class=argparse.RawTextHelpFormatter)
    # parser.add_argument('-m', '--max', help='max id', type=int, default=253)
    # parser.add_argument('-s', '--sleep', help='time in seconds between samples, default 1.0', type=float, default=1.0)
    parser.add_argument('-b',
                        '--baud',
                        help='baudrate, default is 115200',
                        type=int,
                        default=115200)
    parser.add_argument('port',
                        help='serial port name, Ex: /dev/ttyUSB0 or COM1',
                        type=str)

    args = vars(parser.parse_args())
    return args


if __name__ == "__main__":
    args = handleArgs()
    port = args['port']
    baud = args['baud']

    bot = pycreate2.Create2(port=port, baud=baud)

    bot.start()
    ret = bot.reset()
    print(ret)
Esempio n. 20
0
    #config["transport"] = 'tcp'
    #config["transport"] = 'mqtt'
    #config["transport"] = 'echo'
    #config["transport"] = ''       # For use with serial port interface

    config["server_ip_addr"] = '192.168.1.145'  #'10.0.0.3' #'192.168.1.114'

    config["robot"] = 'Ranger'
    #config["robot"] = 'Create2'

    config["logfile_name"] = 'mBot_Ranger_U2_log_'

    #config[port] = '/dev/ttyUSB0'  # this is the serial port on Ubuntu laptop
    #config["baud"] = 115200

    bot = pycreate2.Create2(config)
    #bot.SCI.buffersize = 1024 # Uncomment this parameter when not using UDP interface

    bot.start()
    bot.safe()

    # define a set of commands for the robot to execute
    commands = [['Move_Dist', 125, 40, 'for_dist'],
                ['Move_Dist', -125, 40, 'backward_dist'],
                ['stop', 0, 0.2, 'stop'],
                ['Turn_Angle', 100, 90, 'Rotate_left'],
                ['Turn_Angle', 100, -90, 'Rotate_right'],
                ['stop', 0, 0.2, 'stop'], ['forward', 125, 2, 'for'],
                ['back', -125, 2, 'back'], ['stop', 0, 0.2, 'stop'],
                ['turn right', 100, 3, 'rite'], ['turn left', 100, 6, 'left'],
                ['turn right', 100, 3, 'rite'], ['stop', 0, 0.2, 'stop']]