def connect(self, serial = None, baud = None): # Initialize an ArduinoBoard instance. This is where you specify baud rate and # serial timeout. If you are using a non ATmega328 board, you might also need # to set the data sizes (bytes for integers, longs, floats, and doubles). timestamp=time.time() if serial == None: serial = self.ardu_serial if baud == None: baud = self.ardu_baud try: print("Connecting Arduino") arduino = PyCmdMessenger.ArduinoBoard(serial, baud, timeout=4) commands = [ ["KCommandList", ""], ["KTakepic", "bI"], ["KPower_up", "b"], ["KPower_down", "b"], ["KWake_up", ""] ] # Initialize the messenger self.c = PyCmdMessenger.CmdMessenger(arduino,commands) return timestamp, True except Exception as e: return timestamp, e
def set_comm(self, comm_args): try: if comm_args['type'] == 'Serial': self.arduino = PyCmdMessenger.ArduinoBoard(comm_args['port'], comm_args['baudrate'], timeout=3.0, settle_time=3.0, int_bytes=self.data_size['int_bytes'], float_bytes=self.data_size['float_bytes'], double_bytes=self.data_size['double_bytes'], long_bytes=self.data_size['long_bytes']) self.comm = PyCmdMessenger.CmdMessenger(self.arduino, self.commands) elif comm_args['type'] == 'WiFi': pass elif comm_args['type'] == 'Bluetooth': self.arduino = Communication.ArduinoBoardBluetooth(mac_addr=comm_args['mac_addr'], int_bytes=self.data_size['int_bytes'], float_bytes=self.data_size['float_bytes'], double_bytes=self.data_size['double_bytes'], long_bytes=self.data_size['long_bytes']) self.comm = PyCmdMessenger.CmdMessenger(self.arduino, self.commands) except Exception as err: print(err.__class__) print(err) if self.recv_thread and self.recv_thread.isRunning(): self.recv_thread.stop() return False else: return True
def __init__(self, width: int, height: int, canvas: Canvas): self.width = width self.height = height index = 0 self.canvas = canvas self.clocks_matrix = [[0 for x in range(height)] for y in range(width)] self.last_time = datetime.now() - timedelta(minutes=15) self.last_animated = datetime.now() for i in range(0, int(width / 2)): cmd = None port = "/dev/ttyACM" + str(i) if platform.system() == "Windows": port = "COM" + str(i + 8) try: arduino = PyCmdMessenger.ArduinoBoard(port, baud_rate=57600) cmd = (PyCmdMessenger.CmdMessenger(arduino, commands)) except Exception as e: print(e) self.dues.append(cmd) for i in range(0, width * height): pos = self.index2pos(i) c = Clock(pos) self.clocks.append(c) self.clocks_matrix[pos[0]][pos[1]] = c
def main(argv=None): if argv == None: argv = sys.argv[1:] try: serial_device = argv[0] except IndexError: err = "Incorrect arguments. Usage:\n\n{}\n\n".format(__usage__) raise IndexError(err) a = PyCmdMessenger.ArduinoBoard(serial_device, 115200) c = PyCmdMessenger.CmdMessenger( a, [["double_ping", "d"], ["double_pong", "d"]]) for i in range(10000): value = 2 * (random.random() - 0.5) c.send("double_ping", value) received_cmd = c.receive() cmd = received_cmd[0] received = received_cmd[1][0] if abs(received - value) < 0.000001: success = "PASS" else: success = "FAIL" print("{:10s} --> {:10.6f} --> {:10.6f} --> {:4}".format( cmd, value, received, success))
def _find_serial(self): """ Search through attached serial devices until one reports the specified self._device_name when probed by "who_are_you". """ # if there is already a serial connection, move on if self._hardware_is_found: return tty_devices = [d for d in os.listdir("/dev") if d.startswith("ttyA")] for d in tty_devices: try: tmp_tty = os.path.join("/dev", d) a = PyCmdMessenger.ArduinoBoard(tmp_tty, self._BAUD_RATE) cmd = PyCmdMessenger.CmdMessenger(a, self._COMMANDS) cmd.send("who_are_you") reply = cmd.receive() if reply != None: if reply[0] == "who_are_you_return": if reply[1][0] == self._device_name: self._arduino_raw_serial = a self._arduino_msg = cmd self._device_tty = tmp_tty self._hardware_is_found = True break # something went wrong ... not a device we can use. except IndexError: pass
def init_arduino(self): # TODO: Get this into a config file PORTS = [ "/dev/cu.usbmodem1421", "/dev/cu.usbmodem1411", "/dev/cu.usbmodemFA131" ] ser = None err = None # Look for a device on the given port, if not found then abort this Scriptlet for port in PORTS: try: ser = serial.Serial(port) break except serial.serialutil.SerialException as e: err = e continue # If no port found, abandon if not ser: raise err or serial.serialutil.SerialException arduino = PyCmdMessenger.ArduinoBoard(port, baud_rate=115200) # The order of commands must exactly match the Arduino sketch file mpf_arduino.ino commands = [ # ["clear_display", ""], # ["show_number", "i"], ["draw_bmp", "s"], ["clear_ledsegment", ""], ["show_ledsegment_letters", "s"], ["show_ledsegment_number", "i"], ] # Open a serial connection via PyCmdMessenger self._c = PyCmdMessenger.CmdMessenger(arduino, commands) self._last_bmp = None
def get_messenger(): if DEBUG: return get_debug_messenger() # Initialize an ArduinoBoard instance. This is where you specify baud rate and # serial timeout. If you are using a non ATmega328 board, you might also need # to set the data sizes (bytes for integers, longs, floats, and doubles). arduino = PyCmdMessenger.ArduinoBoard(ARDUINO_DEV_PATH, baud_rate=ARDUINO_BAUD_RATE) return PyCmdMessenger.CmdMessenger(arduino, COMMANDS)
def __init__(self, device): """ Creates a new instance of Vest. Inputs: device: The path to the device, e.g.: "/dev/ttyACM0" or "COM3" """ self._board = PyCmdMessenger.ArduinoBoard(device, baud_rate=115200) self._connection = PyCmdMessenger.CmdMessenger(self._board, Vest.commands, warnings=False)
def __init__(self): # IR frame source self.kinect = pkr.PyKinectRuntime(pk.FrameSourceTypes_Infrared) # current IR frame # always a binary uint8 matrix (512x424) self.frame = None # coords of the white pixels self.xy = [] # CmdMessenger init arduino = cmd.ArduinoBoard("COM8", baud_rate=9600) commands = [["coords", "i*"], ["num", "i"], ["unblock", ""]] self.c = cmd.CmdMessenger(arduino, commands)
def __init__(self, device_name, device_tty=None, door_move_time=5): """ device_name: name that the device will return if pinged by "who_are_you" arduino sketch device_tty: serial device for arduino. if None, look for the device under /dev/ttyA* devices door_move_time: time to wait for door before checking on it (s) """ self._COMMANDS = (("who_are_you", ""), ("query", ""), ("open_door", ""), ("close_door", ""), ("who_are_you_return", "s"), ("query_return", "iii"), ("door_open_return", "i"), ("door_close_return", "i"), ("communication_error", "s")) self._BAUD_RATE = 9600 self._device_name = device_name self._device_tty = device_tty self._door_move_time = door_move_time self._last_check = -1 # Status that indicates whether the software device has actually found # any hardware. self._hardware_is_found = False # Try to connect to specified device if self._device_tty is not None: try: self._arudino_raw_serial = PyCmdMessenger.ArduinoBoard( self._device_tty, baud_rate=self._BAUD_RATE) self._arduino_msg = PyCmdMessenger.CmdMessenger( self._arduino_raw_serial, self._COMMANDS) self._hardware_is_found = True except: pass # Or look for the device else: self._find_serial() if not self._hardware_is_found: err = "Could not connect to door hardware.\n" raise DoorException(err) # Find current state of the system self._query()
def init(): """ Init method to begin comms with the arduino and set the scores to zeroes """ global arduino global messenger #Try and discover which serial/usb port the arduino is attached to ard_device = get_arduino_serial_port() if ard_device is None: raise InvalidUsage( message="Arduino not found in serial deviceswhen connecting") #Attempt connection to the arduino try: arduino = PyCmdMessenger.ArduinoBoard(ard_device, baud_rate=115200, int_bytes=2, long_bytes=4, float_bytes=4, double_bytes=4) except (ValueError, SerialException) as err: raise InvalidUsage(message=err, status_code=503, payload={ 'settings': { 'address': ard_device, 'baud_rate': 115200, 'int_bytes': 2, 'long_bytes': 4, 'float_bytes': 4, 'double_bytes': 4 } }) messenger = PyCmdMessenger.CmdMessenger(arduino, commands, field_separator=',', command_separator='#') #Attempt to read ready message from arduino #timeout if nothing returned ready = messenger.receive() print(ready) if ready[0] != 'kAcknowledge': raise ArduinoError(message="Error communicating with Arduino", status_code=400) return get_success(response=ready)
def init_arduinos(self, width: int) -> list: arduinos = [] for i in range(0, int(math.floor(width / 2))): port = "/dev/ttyACM" + str(i) if platform.system() == "Windows": port = coms[i] try: arduino = PyCmdMessenger.ArduinoBoard(port, baud_rate=57600) cmd = (PyCmdMessenger.CmdMessenger(arduino, commands)) arduinos.append(cmd) except Exception as e: print(e) virtual_arduino = Arduino(i) self.virtual_arduinos.append(virtual_arduino) return arduinos
def __init__(self): # depth frame source self.kinect = pkr.PyKinectRuntime(pk.FrameSourceTypes_Depth) # current depth frame self.frame = None # binarized frame # always a binary uint8 matrix (512x424) self.bin = None # coords of the white pixels in the binarized frame self.data = [] # CmdMessenger init port = "COM8" # Edit the port to which the Arduino is connected here. arduino = cmd.ArduinoBoard(port, baud_rate=9600) commands = [["coords", "i*"], ["num", "l"], ["unblock", ""]] self.c = cmd.CmdMessenger(arduino, commands)
def __init__(self, type_name, board, test_class, command="kValuePing", delay=0.1): """ Initialize class. type_name: type to test. Something like kBBool (binary boolean). see TYPE_LIST for possibilities. board: instance of ArduinoBoard class initialized with correct baud rate etc. test_class: instance of Test class (or derivative) that describes what tests to run and what success means. command: command in COMMAND_NAMES to test delay: time between send and recieve (seconds) """ self.type_name = type_name self.connection = PyCmdMessenger.CmdMessenger(board_instance=board, commands=COMMANDS, warnings=False) self.test_class = test_class self.command = command self.delay = delay # Check connection self.connection.send("kAreYouReady") # Clear welcome message etc. from buffer i = 0 success = False while i < 3: value = self.connection.receive() time.sleep(0.2) if value != None: success = True i += 1 # Make sure we're connected if not success: err = "Could not connect." raise Exception(err) # Figure out what the type id will be to pass to arduino (this is an # integer determined by the enumeration over TYPE_LIST in the arduino # sketch) self.type_dict = dict([(k, i) for i, k in enumerate(TYPE_LIST)]) if self.type_name == "multivalue": self._type = "multivalue" else: self._type = self.type_dict[self.type_name]
def check_usb_power(): global usb_power_on global usb_used global arduino global c if usb_power_on == False: p = subprocess.Popen(["./usb_power_on.sh"], stdout=subprocess.PIPE) aiy.audio.say('Please wait', lang='en-GB') print("Powering USB & HDMI on") usb_power_on = True time.sleep(1) print("USB Arduino and HDMI initialized") arduino = PyCmdMessenger.ArduinoBoard( "/dev/serial/by-id/usb-Arduino__www.arduino.cc__0042_557363233393519142B0-if00", baud_rate=9600, timeout=300.0) c = PyCmdMessenger.CmdMessenger(arduino, commands) usb_used = True
def connect(self, serial=None, baud=None): if serial == None: serial = self.ardu_serial if baud == None: baud = self.ardu_baud try: print("Connecting Arduino") arduino = PyCmdMessenger.ArduinoBoard(serial, baud, timeout=4) commands = [["KCommandList", ""], ["KTakepic", "bI"], ["KPower_up", "b"], ["KPower_down", "b"], ["KWake_up", ""]] # Initialize the messenger self.c = PyCmdMessenger.CmdMessenger(arduino, commands) print("Arduino connecté") except Exception as e: print("Impossible de se connecter à l'Arduino") print(e)
def main(argv=None): if argv == None: argv = sys.argv[1:] try: serial_device = argv[0] except IndexError: err = "Incorrect arguments. Usage:\n\n{}\n\n".format(__usage__) raise IndexError(err) a = PyCmdMessenger.ArduinoBoard(serial_device, 115200) c = PyCmdMessenger.CmdMessenger( a, [["double_ping", "fff"], ["double_pong", "fff"]]) for i in range(10): values = [ 2 * (random.random() - 0.5), 2 * (random.random() - 0.5), 2 * (random.random() - 0.5) ] c.send("double_ping", *values) received_cmd = c.receive() cmd = received_cmd[0] received = received_cmd[1] success = 1 for i, r in enumerate(received): if abs(r - values[i]) < 0.000001: success *= 1 else: success = 0 if success == 0: success = "FAIL" else: success = "PASS" print(("{:10s} --> {} --> {} --> {:4}".format(cmd, values, received, success)))
def main(argv=None): if argv == None: argv = sys.argv[1:] try: serial_device = argv[0] except IndexError: err = "Incorrect arguments. Usage:\n\n{}\n\n".format(__usage__) raise IndexError(err) a = PyCmdMessenger.ArduinoBoard(serial_device, 115200) c = PyCmdMessenger.CmdMessenger( a, [["multi_ping", "i*"], ["multi_pong", "i*"]]) for i in range(10): num_args = random.choice(range(1, 10)) sent_values = [random.choice(range(10)) for j in range(num_args)] c.send("multi_ping", len(sent_values), *sent_values) received_cmd = c.receive() cmd = received_cmd[0] received = received_cmd[1] success = 1 for i, r in enumerate(received): if sent_values[i] == r: success *= 1 else: success = 0 if success == 0: success = "FAIL" else: success = "PASS" print("{:10s} --> {} --> {} --> {:4}".format(cmd, sent_values, received, success))
def __init__(self): # make sure this baudrate matches the baudrate on the Arduino self.running = False self.baud = 9600 self.sem = QSemaphore(1) print(self.sem) # the following enum sequence has to correspond to the sequence of the enum in the Arduino part self.commands = [['commError', ''], ['comment', ''], ['sendAcknowledge', 's'], ['areYouReady', ''], ['error', ''], ['askUsIfReady', ''], ['youAreReady', ''], ['sendMeasuredValue', ''], ['turnOnMeasurements', ''], ['turnOffMeasurements', ''], ['resetMeasurements', ''], ['floatValue', 'f'], ['int16Value', 'i']] try: # try to open the relevant usb port # self.port_name = self.list_usb_ports()[3][0] # self.port_name = '/dev/cu.wchusbserial1410' self.port_name = '/dev/ttyUSB0' # print('Serial port name = ',self.port_name) self.serial_port = serial.Serial(self.port_name, self.baud, timeout=0) except (serial.SerialException, IndexError): raise SystemExit('Could not open serial port.') else: print('Serial port', self.port_name, ' sucessfully opened.\n') # setup the cmdMessenger print('Set-up PyCmdMessenger on serial port') # Initialize an ArduinoBoard instance. This is where you specify baud rate and # serial timeout. If you are using a non ATmega328 board, you might also need # to set the data sizes (bytes for integers, longs, floats, and doubles). self.arduino = PyCmdMessenger.ArduinoBoard(self.port_name, baud_rate=9600) # Initialize the messenger self.messenger = PyCmdMessenger.CmdMessenger( self.arduino, self.commands)
def __init__(self): self._serial = "/dev/cu.usbmodem1411" # You might need to configure this. Use the Arduino IDE to find out which serial port Arduino is on # Initialize an ArduinoBoard instance. This is where you specify baud rate and # serial timeout. If you are using a non ATmega328 board, you might also need # to set the data sizes (bytes for integers, longs, floats, and doubles). self._arduino = PyCmdMessenger.ArduinoBoard(self._serial, baud_rate=9600) # List of commands and their associated argument formats. These must be in the # same order as in the sketch. self._oncomingPassenger = "oncomingPassenger" self._oncomingFreight = "oncomingFreight" self._switchStatus = "switchStatus" self._error = "error" self._commands = [[self._oncomingPassenger, ""], [self._oncomingFreight, ""], [self._switchStatus, "s"], [self._error, "s"]] # Initialize the messenger self.com = PyCmdMessenger.CmdMessenger(self._arduino, self._commands)
#!/usr/bin/env python import rospy from std_msgs.msg import String import PyCmdMessenger import threading # Initialize an ArduinoBoard instance. This is where you specify baud rate and # serial timeout. If you are using a non ATmega328 board, you might also need # to set the data sizes (bytes for integers, longs, floats, and doubles). arduino = PyCmdMessenger.ArduinoBoard("/dev/ttyACM0", baud_rate=115200) commands = [ ["cmd_steer", "i"], ["cmd_throttle", "i"], ["cmd_rpm", "i"], ["cmd_sonar", "ii"], ["cmd_toggle_ebrake", "?"], ["cmd_govern_forward", "i"], ["cmd_govern_reverse", "i"], ["cmd_set_mode", "?"], ["cmd_set_steer_bias", "i"], ["cmd_info", "s"] ] # Initialize the messenger commander = PyCmdMessenger.CmdMessenger(arduino, commands) print("--------PLAYBACK-----------") def callback(data): print('PLAYBACK RCVD:', data)
def __init__(self, port = "/dev/ttyACM0"): self.port = port self.arduino = PyCmdMessenger.ArduinoBoard(port,baud_rate=9600) self.c = PyCmdMessenger.CmdMessenger(arduino,commands) self.name = self.get_name()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os, sys, random import PyCmdMessenger try: bin_file = sys.argv[1] except: print("\nUsage: %s /path/to/amiibo.bin\n" % sys.argv[0]) raise SystemExit(0) arduino = PyCmdMessenger.ArduinoBoard("COM3", baud_rate=9600, timeout=30.0) commands = [ ["kSendNFCUID", ""], ["kReciveNFCUID", "bbbbbbb"], ["kWriteBinNFC", ""], ["kWriteLocksNFC", ""], ["kSendMessage", "?"], ["kFillData", "ib"], ] c = PyCmdMessenger.CmdMessenger(arduino, commands) c.send("kSendNFCUID") msg = c.receive() uid0 = msg[1][0] uid1 = msg[1][1] uid2 = msg[1][2] bcc0 = uid0 ^ uid1 ^ uid2 ^ ord('\x88') uid3 = msg[1][3] uid4 = msg[1][4] uid5 = msg[1][5] uid6 = msg[1][6]
["humidity","i"], ["air temp","s"], ["CO2",""]] ''' Heater = AC1 Lights = AC2 Humidifier = AC3 FAN1 = DC1 FAN2 = DC2 ''' def __init__(self, arduino): self.arduino = PyCmdMessenger.ArduinoBoard(arduino) self.cmd = PyCmdMessenger.CmdMessenger(self.arduino,commands) def toggleDevice(self, device, value): cmd.send(device + value) def pollSensors(self): data = {} for sensor in sensors: cmd.send(sensor[0]) data[sensor[0]] = cmd.receive()[0][0] return data
import serial import logging import platform import subprocess import sys import aiy.assistant.auth_helpers from aiy.assistant.library import Assistant import aiy.audio import aiy.voicehat from google.assistant.library.event import EventType import threading # Initialize an ArduinoBoard instance. This is where you specify baud rate #arduino = PyCmdMessenger.ArduinoBoard("/dev/ttyACM0",baud_rate=9600,timeout=300.0) arduino = PyCmdMessenger.ArduinoBoard( "/dev/serial/by-id/usb-Arduino__www.arduino.cc__0042_557363233393519142B0-if00", baud_rate=9600, timeout=300.0) # List of K8 Arduino command names (and formats for their associated arguments). These must be in the same order as in the sketch. commands = [["spin", ""], ["anticlockwise", "i"], ["anticlockwise_until", ""], ["clockwise", "i"], ["clockwise_until", ""], ["backup", "i"], ["forward", "i"], ["forward_until", ""], ["ping_all", ""], ["pan_tilt_test", ""], ["lidar_read", ""], ["follow_right_wall", "d"], ["follow_left_wall", "d"], ["pings", "iii"], ["lidar_val", "ii"], ["error", "s"]] c = PyCmdMessenger.CmdMessenger(arduino, commands) usb_power_on = True usb_used = True location = "Kitchen"
def __init__(self, arduino): self.arduino = PyCmdMessenger.ArduinoBoard(arduino)
def moveInvKin(objCoords,refObjX,refObjY): #function for inverse kinemics motor control arduino = PyCmdMessenger.ArduinoBoard("COM3",baud_rate=115200) commands = [["motor_steps","fff"], ["motor_run",""], ["motor_state_prep","f"], ["motor_state_run","f"] ] # Initialize the messenger c = PyCmdMessenger.CmdMessenger(arduino,commands) Len1= 250 #length of link 1 in mm Len2= 140#139 #length of link 2 in mm theta_S_prev=0 theta_E_prev=0 z_prev=0 #some constants SumLenSqrd = Len1*Len1+Len2*Len2 ProdOfLens = 2*Len1*Len2 DiffLenSqrd= Len1*Len1-Len2*Len2 #steps per degree*(SPD) microstepping= 1/16 SPD_1=(16/1.8)*(40/20) #40/20 is the gear ratio SPD_2=(16/1.8)*(40/16) #steps per mm(for motor MZ,z-axis) SPM=800/8 #since lead is 8 mm (goes 8 mm in 800 steps(1/4 micro stepping) .Therefore, Z-axis accuracy is 0.01mm) #c.send("motor_steps",0,0,15000) #c.send("motor_run") for i in range(len(objCoords)): objX,objY=objCoords[i] objX=refObjX+objX objY=refObjY+objY print(objX,objY) XkinPos=objX YkinPos=objY z=0 Temp1= XkinPos*XkinPos+YkinPos*YkinPos Temp2= (Temp1- SumLenSqrd)/ProdOfLens lefthand=0 if (abs(Temp2)<=1) : #Inverse Kinematics if(XkinPos>0): #always gives right hand calculation XkinPos=-XkinPos lefthand=1 theta_E= math.acos(Temp2) theta_Q= math.acos((Temp1+DiffLenSqrd)/(2*Len1*math.sqrt(Temp1))) arctan=math.atan2(YkinPos,XkinPos) theta_S= arctan - theta_Q theta_E=(180/(22/7))*theta_E theta_S=((180/(22/7))*theta_S) if(YkinPos<0 and lefthand==0): theta_S=360+theta_S if(lefthand==1): theta_E=-theta_E theta_S=180-theta_S if(YkinPos<0): theta_S=theta_S-360 lefthand=0 if(theta_S<0 or theta_S>180): print("Joint0 limit exceeded! Try lowering y coordinate") #motor control #z=z_prev-ZkinPos theta_S_new=theta_S-theta_S_prev theta_E_new=theta_E-theta_E_prev steps_M0=theta_S_new*SPD_1 #positive is clockwise and negative is anti-clockwise steps_M1=theta_E_new*SPD_2 steps_M2=0#z*SPM c.send("motor_steps",steps_M0,steps_M1,steps_M2) msg= c.receive() print(msg) print("Moving") c.send("motor_run") msg = c.receive() print(msg) #z_prev=ZkinPos theta_E_prev=theta_E theta_S_prev=theta_S #------------- else : print("Co-ordinate of object is beyond reachable workspace") time.sleep(2)
# asynchronous audio processing callbacks current_in_data = None data_queue = deque() def callback(in_data, frame_count, time_info, status): global current_in_data # data_queue.appendleft(in_data) current_in_data = in_data return (in_data, pyaudio.paContinue) # arduino serial connector i_mult = 1 arduino_leds = numrects serial_baud = 9600 serial_port = "/dev/cu.usbmodem144101" serial_object = PyCmdMessenger.ArduinoBoard(serial_port, baud_rate=serial_baud) serial_commands = [["receive_frameL", "i" * int(arduino_leds / 2)], ["receive_frameR", "i" * int(arduino_leds / 2)]] serial_messenger = PyCmdMessenger.CmdMessenger(serial_object, serial_commands) serial_ints = [0] * arduino_leds def serial_update(rh): for i in range(arduino_leds): serial_ints[i] = int((100 * rh[i]) * i_mult) if serial_ints[i] > 100: serial_ints[i] = 100 siL = serial_ints[:len(serial_ints) // 2] siR = serial_ints[len(serial_ints) // 2:] serial_messenger.send("receive_frameL", *siL) serial_messenger.send("receive_frameR", *siR)
import PyCmdMessenger from time import sleep from inputs import get_gamepad from threading import Thread import numpy as np import sys arduino = PyCmdMessenger.ArduinoBoard(sys.argv[1], baud_rate=9600) # List of command names (and formats for their associated arguments). These must # be in the same order as in the sketch. commands = [ ["asd", ""], ["steer", "iiii"] ] # Initialize the messenger c = PyCmdMessenger.CmdMessenger(arduino, commands) x = 0 y = 0 a = 0 DEADZONE = 0.1 R = 0.05 L1 = L2 = 0.16 def input_thread(): global x, y, a try: while True: events = get_gamepad()
def main(argv=None): """ Parse command line and run tests. """ if argv == None: argv = sys.argv[1:] # Parse command line try: serial_device = argv[0] except IndexError: err = "Incorrect arguments. Usage: \n\n{}\n\n".format(__usage__) raise IndexError(err) run_string_tests = False try: if argv[1] == "s": run_string_tests = True else: err = "flag {} not recognized. Usage: \n\n{}\n\n".format( argv[1], __usage__) raise ValueError(err) except IndexError: pass # Create an arduino board instance with a serial connection board = PyCmdMessenger.ArduinoBoard(serial_device, baud_rate=BAUD_RATE, timeout=0.1) # Create a series of test instances bool_test = BoolTest() byte_test = ByteTest() int_test = IntTest() long_test = LongTest() float_test = FloatTest() char_test = CharTest() string_test = StringTest() multi_test = MultiTest() print("******************************************************************") print("* Test passing values to and from arduino with PyCmdMessenger *") print("******************************************************************") binary_trials = [] t = PingPong("kBBool", board, bool_test) binary_trials.extend( t.run_tests(send_arg_formats="g?", receive_arg_formats="?")) t = PingPong("kBByte", board, byte_test) binary_trials.extend( t.run_tests(send_arg_formats="gb", receive_arg_formats="b")) t = PingPong("kChar", board, char_test) binary_trials.extend( t.run_tests(send_arg_formats="gc", receive_arg_formats="c")) t = PingPong("kBInt16", board, int_test) binary_trials.extend( t.run_tests(send_arg_formats="gi", receive_arg_formats="i")) t = PingPong("kBInt32", board, int_test) binary_trials.extend( t.run_tests(send_arg_formats="gl", receive_arg_formats="l")) t = PingPong("kBFloat", board, float_test) binary_trials.extend( t.run_tests(send_arg_formats="gf", receive_arg_formats="f")) t = PingPong("kBDouble", board, float_test) binary_trials.extend( t.run_tests(send_arg_formats="gd", receive_arg_formats="d")) t = PingPong("kString", board, string_test) binary_trials.extend( t.run_tests(send_arg_formats="gs", receive_arg_formats="s")) t = PingPong("kEscString", board, string_test) binary_trials.extend( t.run_tests(send_arg_formats="gs", receive_arg_formats="s")) t = PingPong("multivalue", board, multi_test, command="kMultiValuePing") binary_trials.extend( t.run_tests(send_arg_formats="ilf", receive_arg_formats="ilf")) print("******************************************************************") print("* FINAL SUMMARY *") print("******************************************************************") print() print("SUMMARY: Passed {} of {} binary interface tests".format( sum(binary_trials), len(binary_trials))) if sum(binary_trials) != len(binary_trials): print("WARNING: some tests failed!") print() if not run_string_tests: return print("******************************************************************") print("* Test using string interface (will fail a lot) *") print("******************************************************************") string_trials = [] t = PingPong("kBool", board, bool_test) string_trials.extend(t.run_tests()) t = PingPong("kChar", board, char_test) string_trials.extend(t.run_tests()) t = PingPong("kInt16", board, int_test) string_trials.extend(t.run_tests()) t = PingPong("kInt32", board, int_test) string_trials.extend(t.run_tests()) t = PingPong("kFloat", board, float_test) string_trials.extend(t.run_tests()) t = PingPong("kFloatSci", board, float_test) string_trials.extend(t.run_tests()) t = PingPong("kDouble", board, float_test) string_trials.extend(t.run_tests()) t = PingPong("kDoubleSci", board, float_test) string_trials.extend(t.run_tests()) t = PingPong("kString", board, string_test) string_trials.extend(t.run_tests()) t = PingPong("kEscString", board, string_test) string_trials.extend(t.run_tests()) print("******************************************************************") print("* FINAL SUMMARY *") print("******************************************************************") print() print("SUMMARY: Passed {} of {} string interface tests".format( sum(string_trials), len(string_trials))) print() if sum(string_trials) != len(string_trials): print("WARNING: some tests failed!") print( "This is normal using the string interface, as it is not robust.") print( "This is why guessing on the argument formats (g) is a *bad* idea." ) print()