Пример #1
0
 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
Пример #2
0
    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
Пример #3
0
    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
Пример #4
0
    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
Пример #5
0
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))
Пример #6
0
    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
Пример #7
0
    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 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)
Пример #11
0
    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()
Пример #12
0
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)
Пример #13
0
 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)
Пример #15
0
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
Пример #16
0
    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)
Пример #17
0
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)))
Пример #18
0
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)
Пример #21
0
myarduino = PyCmdMessenger.ArduinoBoard("/dev/ttyACM0", baud_rate=9600)

# List of commands and their associated argument formats. These must be in the
# same order as in the sketch.
commands = [
    ["motors", "iii"],  # motor power, left, right
    ["get_sonar", ""],  # commands a sonar sample
    ["sonar", "i"],  # result of sonar sample
    ["sonar_angle", "i"],  # commands a sonar servo angle
    ["line_tracker", "iiii"],  # output of line-follower senors
    ["ir_in", "f"],  # commands from IR remote control
    ["error", "s"]
]

# Initialize the messenger
c = PyCmdMessenger.CmdMessenger(myarduino, commands)


def scan(lidar):
    global stop
    time1 = time.time()
    while True:
        counter = 0
        print('Recording measurements... Press Crl+C to stop.')
        data = 0
        range_sum = 0
        lasttime = time.time()
        for measurment in lidar.iter_measurments():
            if stop == True:
                lidar.stop()
                lidar.stop_motor()
Пример #22
0
def test():
    arduino = PyCmdMessenger.ArduinoBoard("COM11", baud_rate=57600)
    cmd = (PyCmdMessenger.CmdMessenger(arduino, commands))
    return cmd
Пример #23
0
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)
Пример #24
0
    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)

    # set up closing methods
    def onclose():
        print("quitting")
Пример #25
0

from flask import Flask, render_template, request
app = Flask(__name__)

port = '/dev/ttyACM'
for i in range(0,5):
    file = Path(port+str(i))
    if file.exists():
        port = port + str(i)
        print("Found open serial port: {}".format(port))
        break

ard = PyCmdMessenger.ArduinoBoard(port, baud_rate=115200)
commands = [["setLed","i"]]
c = PyCmdMessenger.CmdMessenger(ard, commands)

@app.route("/asd")
def hello():
    return "Hello world"
   

@app.route("/")
def json():
    return render_template('json.html')
    
@app.route("/upload_are_we")
def upload_are_we():
    subprocess.run("sudo arduino-cli upload -p /dev/ttyACM0 --fqbn arduino:avr:uno /home/pi/Development/view-house-lights/are_we", shell=True)
    return "done"
Пример #26
0
# communication port for Arduino
com_valve = 'com6'  # Mega2560 board to control valves
# com_valve = 'com4'
com_MFC = 'com9'  # Uno board to control MFC
# com_MFC = 'com8'
# 20180918 change the com name for use with MacBook
#com_valve = '/dev/cu.usbmodem1411'  # Mega2560 board to control valves
#com_MFC = '/dev/cu.usbmodem1421'    # Uno board to control MFC
arduino_valve = PyCmdMessenger.ArduinoBoard(com_valve, baud_rate=115200)
# arduino = PyCmdMessenger.ArduinoBoard("/dev/cu.usbmodem1441", baud_rate=115200)
commands_valve = [['open_odor_valve', 'ci'], ['switch_panel', ''],
                  ['extra_flush', 'ii'], ['purge_system', 'i'],
                  ['solvent_wash', ''], ['open_CO2_valve', 'i'],
                  ['open_odor_CO2', 'ci']]
# attach commands to Arduino
cmd = PyCmdMessenger.CmdMessenger(arduino_valve, commands_valve)
arduino_MFC = PyCmdMessenger.ArduinoBoard(com_MFC, baud_rate=115200)
commands_MFC = [['flow_setup', 'iiiii'], ['trigger_markes', 'i']]
cmd_MFC = PyCmdMessenger.CmdMessenger(arduino_MFC, commands_MFC)

# default flow rates, set as string type
flow_carrier_default = '400'
flow_odor_default = '400'
flow_ctrl_default = '400'
flow_CO2_default = '65'
flow_ctrl2_default = '65'
# MFC calibration data
# x = np.array(range(255, 70, -20))
x = np.array([250, 200, 150, 100, 50])
y_odor = [456, 365, 275, 185, 95]
y_carrier = [914, 731, 548, 365, 184]
Пример #27
0
import PyCmdMessenger as cmd

arduino = cmd.ArduinoBoard("COM7", baud_rate=9600)
commands = [["coords", "i*"]]
c = cmd.CmdMessenger(arduino, commands)


def sendData(data):
    args = [2 * len(data)]
    for cord in data:
        args.append(cord[0])
        args.append(cord[1])
    print(args)
    c.send("coords", *args)


test = [(1, 2), (3, 4)]
sendData(test)
Пример #28
0
            ["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


	
Пример #29
0
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)
    rospy.loginfo(rospy.get_caller_id() + '%s', data.data)
    m =  ''.join(data.data.split(" ")[1:])
    rospy.loginfo(rospy.get_caller_id() + '%s', m)
    if(m.startswith("V79-T")):
        throttle_pos = int(m.split(":")[1])
        commander.send("cmd_throttle", throttle_pos)

    if(m.startswith("V79-S")):
        steer_angle = int(m.split(":")[1])
Пример #30
0
 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()