def locateport(): """ Function Name: locateport() Input Args: None Output: port The port at which the arduino is connected Description: This function checks th OS it is running on and also identifies the com port the ARDUINO BOARD is connected to. And also returns the COM port the ARDUINO BOARD is connected. """ port = '' if sys.platform.startswith('win'): # For WINDOWS # port = '' ports = list(comports()) for i in ports: for j in i: if 'Arduino' in j: port = i[0] elif sys.platform.startswith('linux'): # For LINUX b = [] # port = '' ports = list(comports()) for i in range(len(ports)): for x in range(7): portname = "/dev/ttyACM"+str(x) if ports[i][0] == portname: b.append(ports[i][0]) port = b[0] return port
def comportRefresh(self, dbg=False): #Detect devices hwgrep = [] for i in comports(): if dbg: #Print list to console if requested comport = '' for j in i: comport+=j+"\t" print(comport) for hw in i[2].split(' '): hwgrep += ["hwgrep://"+hw+"\t"+i[1]] #Populate combobox devices = sorted([x[0]+"\t"+x[1] for x in comports()]) devices += [''] devices += sorted(set(hwgrep)) devices += [''] devices += sorted(["spy://"+x[0]+"?raw"+"\t(Debug) "+x[1] for x in comports()]) devices += ['', 'socket://localhost:23', 'rfc2217://localhost:2217'] #Clean neighbour duplicates devices_clean = [] devprev = ''; for i in devices: if i.split("\t")[0] != devprev: devices_clean += [i] devprev = i.split("\t")[0] self.portCombo.fill(devices_clean)
def connect_serial(port, baudrate=115200, timeout=1, writeTimeout=1): """ Return Serial object after making sure that the port is accessible and that the port is expressed as a string. :param port: str or int (ie "COM4" or 4 for Windows). :param baudrate: baudrate. :param timeout: read timeout in seconds, default 1 sec. :param writeTimeout: write timeout in seconds, default 1 sec. :return: serial port object. :rtype: serial.Serial """ if isinstance(port, int): port = "COM{0}".format(port) names_list = list() for i in list_ports.comports(): names_list.append(i[0]) if port not in names_list: print ("Serial not found on {0}.".format(port)) print ("Listing current serial ports with devices:") for ser in list_ports.comports(): ser_str = "\t{0}: {1}".format(ser[0], ser[1]) print ser_str time.sleep(0.01) # just to let the above lines print before the exemption is raised. cleans console output. raise serial.SerialException("Requested COM port: {0} is not listed as connected.".format(port)) else: return serial.Serial(port, baudrate=baudrate, timeout=timeout, writeTimeout=writeTimeout)
def find_serial_port(): """ tries to connect to all available serial ports, returns of first successful connection. exit if none works :return: serial interface object """ if settings.debug_port_detection: for port in list_ports.comports(): print('trying {}'.format(port[0])) return serial.Serial(settings.forced_port, settings.baud_rate, timeout=1) else: for port in (list_ports.comports()): print('trying {}'.format(port[0])) try: serial_interface = serial.Serial(port[0], settings.baud_rate, timeout=2) sleep(2) # wait for the device to be ready # send hello command serial_interface.write(settings.handshake_challenge) # check if this device knows what to reply reply = serial_interface.read(len(settings.handshake_response)) print(reply) if reply == settings.handshake_response: return serial_interface except serial.SerialException: # print("opening serial failed") pass raise ConnectionError("Couldn't connect to any serial ports, exiting...")
def get_port(self): """Detect Buspirate and return first detected port Returns ------- str First valid port name """ try: import serial.tools.list_ports as list_ports except ImportError: raise ImportError('Pyserial version with serial.tools.list_port required') import serial # the API in version 2 and 3 is different if serial.VERSION[0] == '2': ports = list_ports.comports() for port in ports: if len(port) == 3 and '0403:6001' in port[2]: return port[0] if len(port) == 3 and 'VID_0403+PID_6001' in port[2]: return port[0] else: ports = list_ports.comports() for port in ports: if hasattr(port, 'pid') and hasattr(port, 'vid'): if port.vid == 1027 and port.pid == 24577: return port.device
def list_com_ports(): port_list = list_ports.comports() if port_list is not None and len(port_list) is not 0: print "Available Serial ports - " for port in list_ports.comports(): print "\t"+port[0] else: print "No serial ports found by pySerial - you might be using cygwin where you can use /dev/ttySXX where XX = (nn-1) with nn being the COM port number (so COM11 is /dev/ttyS10)"
def refresh(self): self.portComboBox.setStyleSheet('QComboBox {color: black;}') ports = list_ports.comports() if ports != self.ports: self.ports = ports self.portComboBox.clear() for port in list_ports.comports(): name = port[0] if name.startswith('/dev/ttyACM') or name.startswith('/dev/ttyUSB') or name.startswith('COM'): self.portComboBox.addItem(name)
def refresh(self): self.portComboBox.setPalette(self.originalPalette) ports = list_ports.comports() if ports != self.ports: self.ports = ports self.portComboBox.clear() for port in list_ports.comports(): name = port[0] if name.startswith('/dev/ttyACM') or name.startswith('/dev/ttyUSB') or name.startswith('COM'): self.portComboBox.addItem(name)
def get_serial_ports(): ''' Returns a list object for all available serial ports ''' if os.name == 'nt': # windows _comports = [port for port in list_ports.comports()] if _comports.__len__()>0: _serial_ports = ['\\\\.\\'+port[0] for port in list_ports.comports()] else: _serial_ports = [] else: # unix _serial_ports = [port[0] for port in list_ports.comports()] return _serial_ports
def serial_ports(): ''' Returns a generator for all available serial ports ''' if os.name == 'nt': # windows _comports = [port for port in list_ports.comports()] if _comports.__len__()>0: _serial_ports = [p for p in _comports[0]] else: _serial_ports = [] else: # unix _serial_ports = [port[0] for port in list_ports.comports()] return _serial_ports
def list_available_ports(cls): ports = [x.device for x in list_ports.comports()] espport = os.getenv('ESPPORT') if not espport: # It's a little hard filter out invalid port with `serial.tools.list_ports.grep()`: # The check condition in `grep` is: `if r.search(port) or r.search(desc) or r.search(hwid)`. # This means we need to make all 3 conditions fail, to filter out the port. # So some part of the filters will not be straight forward to users. # And negative regular expression (`^((?!aa|bb|cc).)*$`) is not easy to understand. # Filter out invalid port by our own will be much simpler. return [x for x in ports if not cls.INVALID_PORT_PATTERN.search(x)] # On MacOs with python3.6: type of espport is already utf8 if isinstance(espport, type(u'')): port_hint = espport else: port_hint = espport.decode('utf8') # If $ESPPORT is a valid port, make it appear first in the list if port_hint in ports: ports.remove(port_hint) return [port_hint] + ports # On macOS, user may set ESPPORT to /dev/tty.xxx while # pySerial lists only the corresponding /dev/cu.xxx port if sys.platform == 'darwin' and 'tty.' in port_hint: port_hint = port_hint.replace('tty.', 'cu.') if port_hint in ports: ports.remove(port_hint) return [port_hint] + ports return ports
def find_tty(self): for port in comports(): print port if re.search(r'PID=2458:0*1', port[2]): return port[0] return None
def _port_search(self): print 'Automatically detecting COM ports.' ports = list(comports()) print 'Detected %i ports.' % len(ports) port = ports[0][0] print 'Trying port ' + port + '.' return port
def open_arduino_port(): available = [] if os.name == 'nt': # Windows for i in range(256): try: s = serial.Serial(i) available.append('COM'+str(i + 1)) s.close() except serial.SerialException: pass if len(possible) < 1: print 'Error: unable to find Arduino: no COM ports detected. Check drivers.' return [] print 'Possible list of available serial ports:' print available else: # Mac / Linux available = [port[0] for port in list_ports.comports()] print 'Possible list of available serial ports:' print available available = [s for s in available if ".us" in s] if len(available) < 1: print 'Error: unable to find Arduino port named ".us": check drivers' print 'assuming Arduino attached to port %s' %(available[0]) serPort = serial.Serial(available[0], 115200, timeout=1) serPort.write("\xb1\xa3\xa9\xa9") #set to keyboard mode 177,163,169,169 serPort.flushInput() serPort.write("\xa9\xa3\xa9\xa9") #get current mode 169,163,169,169 we expect the reply 169,163,169,169 serPort.flush() #send command obs = serPort.read(4) if obs != "\xa9\xa3\xa9\xa9" : print 'Warning: the selected port does not have a StimSync attached' return serPort
def detect_tty(self): for p in comports(): if re.search(r'PID=2458:0*1', p[2]): print('using device:', p[0]) return p[0] return None
def scan_for_device(self): ports = [x[0] for x in list_ports.comports()] retport = None self._log("Searching for an active bootloader") for p in ports: try: rsp = self._send_ping(p) if not rsp == None: ver = self._get_version(p) if not ver: version = '<=0.1.2' else: version = '.'.join( [str(x) for x in (ver.major, ver.minor, ver.bugfix)]) self._log("Found bootloader ver: {} on: {}".format(version, p)) retport = p break else: raise IOError() except IOError: pass return retport
def main(): top=Tk() top.title("Zigbee_IDReader") top.resizable(0,0) Label(top,text=" NetID:").grid(row=0,sticky=E) Label(top,text="NodeID:").grid(row=1,sticky=E) #e1 = Entry(top) #e2 = Entry(top) #e1.grid(row=0, column=1) #e2.grid(row=1, column=1) entry_font = tkFont.Font(size=12) EdNetID=Entry(top,font=entry_font) EdNodeID=Entry(top,font=entry_font) EdNetID.grid(row=0,column=1, columnspan=4,sticky=E,padx=5,pady=5) EdNodeID.grid(row=1,column=1,columnspan=4,sticky=E,padx=5,pady=5) if comports: for port, desc, hwid in sorted(comports()): com=port print com WriteButton=Button(top,text="Write",command=lambda: Write_to_sreial(EdNetID,EdNodeID,com)) WriteButton.grid(row=2,column=2) mainloop()
def find_port(self): a = list(list_ports.comports()) for portStruct in a: m = re.search('(/dev/cu\.usbmodem.*)', portStruct[0]) if m: print "found port: ", m.group(0) return m.group(0)
def ask_for_port(): """\ Show a list of ports and ask the user for a choice. To make selection easier on systems with long device names, also allow the input of an index. """ try: raw_input except NameError: raw_input = input # in python3 it's "raw" unichr = chr sys.stderr.write('\n--- Available ports:\n') ports = [] for n, (port, desc, hwid) in enumerate(sorted(comports()), 1): #~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid)) sys.stderr.write('--- {:2}: {:20} {}\n'.format(n, port, desc)) ports.append(port) while True: port = raw_input('--- Enter port index or full name [1]: ') or 1 try: index = int(port) - 1 if not 0 <= index < len(ports): sys.stderr.write('--- Invalid index!\n') continue except ValueError: pass else: port = ports[index] return port
def __init__(self): wx.Dialog.__init__( self, None, title="DAQControl", style=(wx.STAY_ON_TOP | wx.CAPTION)) self.horizontal_sizer = wx.BoxSizer(wx.HORIZONTAL) self.vertical_sizer = wx.BoxSizer(wx.VERTICAL) self.gauge = wx.Gauge(self, range=100, size=(100, 15)) self.horizontal_sizer.Add(self.gauge, wx.EXPAND) avaiable_ports = list(comports()) self.sample_list = [] if len(avaiable_ports) != 0: for nombre in avaiable_ports: self.sample_list.append(nombre[0]) self.label_hear = wx.StaticText(self, label="Select Serial Port") self.edit_hear = wx.ComboBox( self, size=(95, -1), choices=self.sample_list, style=wx.CB_READONLY) self.edit_hear.SetSelection(0) self.horizontal_sizer.Add(self.label_hear, wx.EXPAND) self.horizontal_sizer.Add(self.edit_hear, wx.EXPAND) self.button_ok = wx.Button(self, label="OK") self.Bind(wx.EVT_BUTTON, self.ok_event, self.button_ok) self.button_cancel = wx.Button(self, label="Cancel", pos=(115, 22)) self.Bind(wx.EVT_BUTTON, self.cancel_event, self.button_cancel) self.vertical_sizer.Add(self.horizontal_sizer, wx.EXPAND) self.vertical_sizer.Add(self.button_ok, wx.EXPAND) self.gauge.Show(False) self.SetSizer(self.vertical_sizer) self.SetAutoLayout(1) self.vertical_sizer.Fit(self)
def get_cgr(): portlist = comports() # Add undetectable serial ports here portlist.append(('/dev/ttyS0', 'ttyS0', 'n/a')) portlist.append(('/dev/ttyS9', 'ttyS9', 'n/a')) portlist.append(('/dev/ttyS3', 'ttyS3', 'n/a')) for serport in portlist: rawstr = '' try: cgr = serial.Serial() cgr.baudrate = 230400 cgr.timeout = 0.1 # Set timeout to 100ms cgr.port = serport[0] cgr.open() # If the port can be configured, it might be a CGR. Check # to make sure. retnum = cgr.write("i\r\n") # Request the identity string rawstr = cgr.read(10) # Read a small number of bytes cgr.close() if rawstr.count('Syscomp') == 1: module_logger.info('Connecting to CGR-101 at ' + str(serport[0])) return cgr else: module_logger.info('Could not open ' + serport[0]) if serport == portlist[-1]: # This is the last port module_logger.error('Did not find any CGR-101 units') sys.exit() except serial.serialutil.SerialException: module_logger.info('Could not open ' + serport[0]) if serport == portlist[-1]: # This is the last port module_logger.error('Did not find any CGR-101 units') sys.exit()
def find_port(baud, timeout): """ Find the first port that is connected to an arduino with a compatible sketch installed. """ if platform.system() == 'Windows': ports = enumerate_serial_ports() elif platform.system() == 'Darwin': ports = [i[0] for i in list_ports.comports()] else: ports = glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*") for p in ports: log.debug('Found {0}, testing...'.format(p)) try: sr = serial.Serial(p, baud, timeout=timeout) except (serial.serialutil.SerialException, OSError) as e: log.debug(str(e)) continue time.sleep(2) version = get_version(sr) if version != 'version': log.debug('Bad version {0}. This is not a Shrimp/Arduino!'.format( version)) sr.close() continue log.info('Using port {0}.'.format(p)) if sr: return sr return None
def locateport(): ports = list(comports()) for i in ports: for j in i: if 'Arduino' in j: port = i[0] return port
def find_all_serial_ports(): """ :return: a list of serial port info tuples :rtype: """ all_ports = list_ports.comports() return iter(all_ports)
def scanComPort(self): port_list=list(list_ports.comports()) num=len(port_list) #print 'num=', num for i in xrange(num): str=port_list[i][2].split('=') #print str if(str[0]=='USB VID:PID'): str=str[1].split(' ')[0] #Extract VID and PID from string. str=str.split(':') print str if(str[0] in usb_id): if(str[1].lower() in usb_id[str[0]]): port=port_list[i][0] try: __port = serial.Serial(port, baudrate=38400, bytesize=8, parity ='N', stopbits=1, xonxoff=False, dsrdtr=False, timeout=5) except serial.SerialException, e: print e.message continue time.sleep(0.5) while(True): num=__port.inWaiting() if(num==0): break else: print '-', __port.flushInput() #Clear input buffer. time.sleep(0.1) __port.close() return port
def serial_ports(): """ Returns a generator for all available serial ports based on: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python WARNING: works with pyserial>=2.7 """ ports = [] if os.name == 'nt': # windows for i in range(256): try: s = serial.Serial(i) s.close() ports.append('COM' + str(i + 1)) except serial.SerialException: pass else: # unix for port in list_ports.comports(): if 'USB' in port[0] or 'ACM' in port[0]: # yield port[0] ports.append(port[0]) return ports
def list_serial_ports(self): try: ports = list(comports()) except Exception, e: if comports != win32_comports_bruteforce: LOG.error("Failed to detect win32 serial ports: %s" % e) ports = win32_comports_bruteforce()
def __init__(self, portpattern="/dev/ttyACM"): """ Encuentra el puerto serial, con el patron definido en portpattern, abre la conexion serial """ self.index = 0 #patron para buscar el puerto self.portpattern = portpattern self.portname = None self.certname = None self.certxt = None self.port = None self.presses = 0 self.print_time = None self.print_duration = None self.start_time = None self.isPrinting = False self.orderCertificate = False self.report = None self.tiempo = time.time() self.printer_buffer = [] if comports: for pname in comports(): if(pname[0].find(portpattern) == 0): self.portname = pname[0] #print portname try: self.port = serial.Serial(self.portname, 115200) print "Open connection on: ", self.portname except Exception, error: print error sys.exit("Error trying to connect to serial port")
def find_microbit(): """ Returns the port for the first micro:bit found connected to the computer. """ for port in comports(): if port.vid == MICROBIT_VID and port.pid == MICROBIT_PID: return port.device
def ListAllPorts(): portsList = [] allSerial = list_ports.comports() for ser in allSerial: portsList.append(ser[0]) return portsList
def get_openmv_port(): for port in list_ports.comports(): if 'OpenMV Cam USB' in port.description: return port.device return None
i = int(data[key], 16) print("(%s)%s : %s" % (timestamp, key.encode("utf-8"), str(i))) else: value = convertNonNumeric(data[key]) print("(%s)%s : %s" % (timestamp, key.encode("utf-8"), str(value))) print("-----------------------------------------------------") #----------------------------------------------------------------------------- if __name__ == '__main__': timestamp = sys.argv[1] correctPort = '' while correctPort == '': possiblePorts = listPorts.comports() for port in possiblePorts: if port.description == 'VE Direct cable': correctPort = port.device if correctPort == '': log("Serial Port for Charge Controller not found, retrying...") ve = vedirect(correctPort, timestamp) # swap sendToSQL with printToConsole for debugging ve.read(sendToSQL) log("Packet sent, exiting...")
def list_ports() -> List[list_ports_common.ListPortInfo]: ''' Listing exist serial ports ''' return list_ports.comports()
print b.readline() # with Bridge12() as b: b.set_freq(9.500401e9) # Print out the com ports, so we know what we're looking for # [(j.device, j.hwid, j.vid, j.description, j.manufacturer) for j in comports()] #list comprehension # ## Code for MW Power Test # check that all the ``set_`` functions work correctly: # with Bridge12() as b: print "initial wg status:", b.wgstatus_int() b.set_wg(True) print "initial amp status:", b.ampstatus_int() b.set_amp(True) print "initial rf status:", b.rfstatus_int()
def search_connected() -> List[Wixel]: result = [] for cp in filter(is_wixel_port, comports()): result.append(Wixel(cp.serial_number, cp.device)) return result
def find_microbit_comport(): ports = list(list_ports.comports()) for p in ports: if (p.pid == 516) and (p.vid == 3368): return str(p.device)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ experiment.py: set up and run an automated experiment for measuring the hyperfine structure of rubidium. """ from serialinstrument import SerialInstrument from serial.tools import list_ports if __name__ == '__main__': serial_devices = list_ports.comports() print("Found" + str(len(serial_devices)) + " connected serial devices") instruments = [] for device in serial_devices: instruments.append(SerialInstrument(port = device.device)) print("Device IDs:") for instrument in instruments: print(instrument._identity + " on " + instrument._port)
mfreq_band = tk.StringVar() #status values mRadioStatus = tk.StringVar() mTemp = tk.StringVar() mdownDBm = tk.StringVar() mupDBm = tk.StringVar() mRFDistance = tk.StringVar() #own messages infoStatus = tk.StringVar() #changeable values (user can edit) selectedConnection = tk.StringVar() if tool_started == 0: lsSerialDevices = lsPorts.comports() serialDevicesInfo = [] serialDIcounter = -1 for i in lsSerialDevices: serialDevicesInfo.append(i.device) serialDevicesInfo.append(i.description) if len(serialDevicesInfo) >= 2: for i in serialDevicesInfo: if i.find("STM32 STLink") != -1: autoUSBpath = str(serialDevicesInfo[serialDIcounter]) print("USB auto-config set to: ", autoUSBpath) serialDIcounter += 1 else: autoUSBpath = "" print("USB Auto-Config Failed")
def SerialPorts(self) -> bool: '''Checks to see if the port you choose is available The line of code below this line will take >5 seconds to run if bluetooth is enabled -- DISABLE BLUETOOTH''' ports = [port.device for port in list_ports.comports()] return ports
import serial import serial.tools.list_ports as list import socket import threading import scipy import scipy.integrate as integrate from pykeyboard import PyKeyboard import MatlabSender #inicialitzem el teclat k = PyKeyboard() #inicialtzem la interficie amb matlab p2m = MatlabSender.MatlabSender() #iterem sobre els ports serie per a executar un protocol de comunicació. devices = list.comports() for d in devices: try: s = serial.Serial(d[0], 9600) time.sleep(2) #esperem a que s'inicialitzi la connexió s.write('who') time.sleep(2) if 'arduino' in s.readline(): s.write('OK') #arduino detectat, indiquem que podem rebre dades time.sleep(2) print 'arduino port found:', d[0] a = [[], [], []] pos = [] while (1): aux = s.readline() #print aux
def find_port(): for port in comports(): if VID_PID in port[2]: return port[0] return None
data = '' while ser.inWaiting() > 0: #data.append(hex(ser.read(1))) data = data + str(binascii.b2a_hex(ser.read(1)))[2:-1] + ' ' #data.append(ser.read(1)) print('接收数据:', data) sleep(0.5) return data #data+=binascii.b2a_hex(ser.read(1)) if __name__ == '__main__': from serial.tools import list_ports print('\n当前可用串口:') for port_list in list(list_ports.comports()): print(port_list) com_id = input('\n打开串口:') com_id = 'COM' + com_id #baud = input('设置波特率:') ser = serial.Serial(com_id, 115200) ser.close() ser.open() qh_sprotocol = Yomde_sprotocol() qh_sprotocol.send_start_command() qh_sprotocol.send_SOH(1) qh_sprotocol.send_STX() qh_sprotocol.send_EOT() qh_sprotocol.send_SOH(0) print('升级成功')
def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent self.parent.title('Serial to XLS') self.parent.resizable(False, False) self.pack(pady=20, padx=40) # machine machine_label = tk.Label(self, text='Macchina') self.machine_field = tk.Entry(self) # folder folder_label = tk.Label(self, text='Esporta in') self.folder_field = tk.Entry(self) self.folder_field.insert(0, desktop) self.folder_field.bind("<Button-1>", self.open_folder) # port self.port_var = tk.StringVar(self.parent) self.ports = {p.device: p for p in comports()} if len(self.ports.keys()) > 0: self.port_var.set(list(self.ports.keys()).pop(0)) port_menu = tk.OptionMenu(self, self.port_var, *self.ports.keys()) else: port_menu = tk.OptionMenu(self, self.port_var, None) port_label = tk.Label(self, text="Port") # baudrate baud_label = tk.Label(self, text='Baudrate') self.baud_field = tk.Entry(self) self.baud_field.insert(0, 9600) # bytesize self.byte_var = tk.IntVar(self.parent) self.byte_var.set(SEVENBITS) byte_label = tk.Label(self, text='Bytetype') byte_menu = tk.OptionMenu(self, self.byte_var, *[FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS]) # parity self.parity_var = tk.StringVar(self.parent) self.parity_var.set(PARITY_EVEN) parity_label = tk.Label(self, text='Parity') parity_menu = tk.OptionMenu( self, self.parity_var, *[PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE]) # stopbit self.stopbit_var = tk.DoubleVar(self.parent) self.stopbit_var.set(STOPBITS_ONE) stopbit_label = tk.Label(self, text='Stopbit') stopbit_menu = tk.OptionMenu( self, self.stopbit_var, *[STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO]) # logarea self.log_area = ScrolledText(self.parent, width=40, height=10) self.button = tk.Button( self, text="Start", fg="red", height=5, width=10, command=self.toggle, state='disabled' if len(self.ports.keys()) == 0 else 'normal') machine_label.grid(row=0, column=0) self.machine_field.grid(row=0, column=1) folder_label.grid(row=1, column=0) self.folder_field.grid(row=1, column=1) port_label.grid(row=2, column=0) port_menu.grid(row=2, column=1, sticky=E + W) baud_label.grid(row=3, column=0) self.baud_field.grid(row=3, column=1, sticky=E + W) byte_label.grid(row=4, column=0) byte_menu.grid(row=4, column=1, sticky=E + W) parity_label.grid(row=5, column=0) parity_menu.grid(row=5, column=1, sticky=E + W) stopbit_label.grid(row=6, column=0) stopbit_menu.grid(row=6, column=1, sticky=E + W) self.button.grid(row=0, column=2, rowspan=6, sticky=N + S + E) self.log_area.pack() self.running = False self.current_port = None self.thread = None self.buffer = ''
def list_serial_ports(): # Scan for available ports. return list_ports.comports()
camera_position_x = config.getint('robot', 'camera-position-x') camera_position_y = config.getint('robot', 'camera-position-y') camera_height = config.getfloat('robot', 'camera-height') robot_height = config.getfloat('robot', 'robot-height') vision_perspective_corrected = VisionPerspectiveCorrection( vision_daemon, Position(camera_position_x, camera_position_y), camera_height, robot_height) world_map = Map(vision_perspective_corrected, world_map_service, table_calibration_service) arduino_pid = config.getint('robot', 'arduino-pid') arduino_vid = config.getint('robot', 'arduino-vid') polulu_pid = config.getint('robot', 'polulu-pid') polulu_vid = config.getint('robot', 'polulu-vid') arduino_baudrate = config.getint('robot', 'arduino-baudrate') ports = lp.comports() arduino_port = list( filter( lambda port: port.pid == arduino_pid and port.vid == arduino_vid, ports)) polulu_port = list( filter( lambda port: port.pid == polulu_pid and port.vid == polulu_vid, ports)) polulu_port_hardcoded = '/dev/ttyACM0' assert (len(list(arduino_port)) != 0) assert (len(list(polulu_port)) != 0) real_polulu_port = min(map(lambda x: x.device, polulu_port)) polulu_serial_port = serial.Serial(port=real_polulu_port) arduino_serial_port = serial.Serial(port=arduino_port[0].device, baudrate=arduino_baudrate,
def __init__(self, *args, **kwargs): # Grab the port labeled as Arduino (since the Bridge12 microcontroller is an Arduino) portlist = [j.device for j in comports() if u'Arduino Due' in j.description] assert len(portlist)==1 thisport = portlist[0] super(self.__class__, self).__init__(thisport, timeout=3, baudrate=115200)
def ScanComPort(self): port_list = list(list_ports.comports()) num = len(port_list) for i in xrange(num): str = port_list[i][2].split('=') if (str[0] == 'USB VID:PID'): str = str[1].split(' ')[0] #Extract VID and PID from string. str = str.split(':') print str if ((str[1] == '0043') or (str[1] == '0045')): self.chnum = 2 #2 channel. elif ((str[1] == '0044') or (str[1] == '0046')): self.chnum = 4 #4 channel. if ((str[0] == '2184') and ((self.chnum == 2) or (self.chnum == 4))): if (self.nodename == 'win'): #Win32 port = port_list[i][0][3:] com = int(port) if (com > 0): self.IO = serial.Serial(com - 1, baudrate=384000, bytesize=8, parity='N', stopbits=1, xonxoff=False, dsrdtr=False, timeout=5) time.sleep(0.5) while (True): num = self.IO.inWaiting() if (num == 0): break else: print '-', self.IO.flushInput() #Clear input buffer. time.sleep(0.1) self.write('*IDN?\n') name = self.read().split(',') #Query *IDN? print('%s connected!\n' % name[1] ) #Print model name. return com - 1 else: #unix or Raspberry Pi port = port_list[i][0] if (port[0:11] == '/dev/ttyACM'): self.IO = serial.Serial(port, baudrate=384000, bytesize=8, parity='N', stopbits=1, xonxoff=False, dsrdtr=False, timeout=5) time.sleep(0.5) while (True): num = self.IO.inWaiting() if (num == 0): break else: print '-', self.IO.flushInput() #Clear input buffer. time.sleep(0.1) self.write('*IDN?\n') name = self.read().split(',') #Query *IDN? print('%s connected!\n' % name[1] ) #Print model name. return 0 else: return -1 print('Device not found!') self.chnum = 4 #Offline operation(default :4 channel). return -1
def get_port_list(self): devices = [] for info in list_ports.comports(): devices.append(info.device) return (devices)
#17/02/2018 # Aplicação #################################################### print("comecou") from enlace import * import time from serial.tools import list_ports # voce deverá descomentar e configurar a porta com através da qual ira fazer a # comunicaçao # Serial Com Port # para saber a sua porta, execute no terminal : # python -m serial.tools.list_ports # se estiver usando windows, o gerenciador de dispositivos informa a porta if len(list_ports.comports()) > 1: serialName = list_ports.comports()[1].device else: serialName = "/dev/ttyACM0" # Ubuntu (variacao de) #serialName = "/dev/tty.usbmodem1411" # Mac (variacao de) #serialName = "COM5" # Windows(variacao de) print("porta COM aberta com sucesso") def main(): # Inicializa enlace ... variavel com possui todos os metodos e propriedades do enlace, que funciona em threading com = enlace(serialName) # Ativa comunicacao com.enable()
Slider Trinkey Hue Brightness Python Example (Requires Hue and Monitor Brightness CircuitPython example to be running on the Slider Trinkey) """ import sys from phue import Bridge import serial from serial.tools import list_ports # Update this to the room, zone or individual lamp you want to control. LAMP_OR_GROUP_NAME = "Office" # Update this to the IP address of your Hue Bridge. b = Bridge("0.0.0.0") slider_trinkey_port = None ports = list_ports.comports(include_links=False) for p in ports: if p.pid is not None: print("Port:", p.device, "-", hex(p.pid), end="\t") if p.pid == 0x8102: slider_trinkey_port = p print("Found Slider Trinkey!") trinkey = serial.Serial(p.device) break else: print("Did not find Slider Trinkey port :(") sys.exit() # If the app is not registered and the button on the Hue Bridge is not pressed, press the button # and call connect() (this only needs to be run a single time) b.connect()
def getPortList(): port_list = list(list_ports.comports()) if len(port_list) == 0: return else: return port_list
#print "a is",repr(a) print "look for",this_str,"try",j+1 if this_str in a: print "found: ",this_str break look_for('MPS Started') look_for('System Ready') return # print out the com ports, so we know what we're looking for # In[14]: [(j.device, j.hwid, j.vid, j.description, j.manufacturer) for j in comports()] #list comprehension # Grab the port labeled as Arduino (since the Bridge12 microcontroller is an Arduino) # In[15]: portlist = [j.device for j in comports() if u'Arduino Due' in j.description] assert len(portlist)==1 thisport = portlist[0] # try the help command -- start with the simplest way possible, which uses very long wait times: # In[8]:
def _get_serial_ports(): ports = [""] for port, desc, hwid in sorted(list_ports.comports()): ports.append(port) return ports
# coding: utf-8 # In[4]: %pylab inline from serial.tools.list_ports import comports import serial # What serial ports are available? # --> this is not used, but just shows what the results of ``comports()`` looks like # In[7]: [j for j in comports()] # Here, I search through the comports in order to identify the instrument that I'm interested in. This (or something like this) should work on either Windows or Mac/Linux. # I can use this to initialize a class. # In[ ]: def id_instrument(textidn): """Identify the instrument that returns an ID string containing ``textidn`` """ for j in comports(): port_id = j[0] # based on the previous, this is the port number with serial.Serial(port_id) as s: s.write('*idn?\n') result = s.readline()
# ver 1.6g - Aug 2020 - Lunches GUI when no parameters specified (code contributed by John Gerrard)... requires PySimpleGUI module "pip install PySimpleGUI" # - small fixes to the output # ver 1.6h - fixed bug with SPI==y version = "1.6e" import argparse import serial, os import time import PySimpleGUI as sg import sys sg.theme('DarkAmber') # Add a touch of color form = sg.FlexForm('Eprom emulator Uploader V3') from serial.tools.list_ports import comports com = [p.device for p in comports()] layout = [ [ sg.Text('Eprom Type'), sg.InputCombo(('2716', '2732', '2764', '27128', '27256', '27512'), size=(10, 6)) ], [sg.Text('COM port '), sg.InputCombo(com, size=(10, 1))], [sg.Checkbox('Save to SPI', default=False)], [sg.Checkbox('Auto Start', default=False)], [sg.Text('Choose A File', size=(35, 1))], [sg.In(), sg.FileBrowse(file_types=(("Hex files", "*.hex"), ))], [sg.Submit(), sg.Cancel()], ]
def fetch_serial_devices(self): return list_ports.comports()
quit("No files/folders selected", "") if (LOG_FILE_MODE): Window_Name = "Displaying log: " + filename else: Window_Name = "Displaying Real Time Data" if ENABLE_DISPLAYER: cv2.namedWindow(Window_Name, cv2.WINDOW_NORMAL) cv2.resizeWindow(Window_Name, WIDTH, HEIGHT) log_start_time = 0 log_end_time = 0 info = lst.comports() ser = serial.Serial() def find_Device(): for port in info: if (port.product.find("Pyboard") != -1): return port.device, port.product for port in info: if (port.product.find("STM32") != -1): return port.device, port.product return None, None def open_device(dev):
def trng3live(values, window): global thread_cap global zscore_array global index_number_array thread_cap = True sample_value = int(values["live_bit_count"]) interval_value = int(values["live_time_count"]) file_name = time.strftime( f"%Y%m%d-%H%M%S_trng_s{sample_value}_i{interval_value}") file_name = f"1-SavedFiles/{file_name}" index_number = 0 csv_ones = [] zscore_array = [] index_number_array = [] blocksize = int(sample_value / 8) ports_avaiable = list(list_ports.comports()) rng_com_port = None # Loop on all available ports to find TrueRNG for temp in ports_avaiable: if temp[1].startswith("TrueRNG"): if rng_com_port == None: # always chooses the 1st TrueRNG found rng_com_port = str(temp[0]) while thread_cap: start_cap = time.time() index_number += 1 with open(file_name + '.bin', "ab+") as bin_file: # save binary file try: ser = serial.Serial( port=rng_com_port, timeout=10 ) # timeout set at 10 seconds in case the read fails except Exception: thread_cap = False rm.popupmsg( "Warning!", f"Port Not Usable! Do you have permissions set to read {rng_com_port}?" ) window['live_plot'].update("Start") window["stat_live"].update(" Idle", text_color="orange") return # Open the serial port if it isn't open if (ser.isOpen() == False): try: ser.open() except Exception: thread_cap = False sg.popup_non_blocking( 'WARNING !!!', "Something went wrong, is the device attached? Attach it and try again!!!", keep_on_top=True, no_titlebar=False, grab_anywhere=True, font="Calibri, 18", icon="src/BitB.ico") window['live_plot'].update("Start") window["stat_live"].update(" Idle", text_color="orange") return # Set Data Terminal Ready to start flow ser.setDTR(True) # This clears the receive buffer so we aren't using buffered data ser.flushInput() try: chunk = ser.read(blocksize) # read bytes from serial port except Exception: thread_cap = False rm.popupmsg("Warning!", "Read Failed!!!") window['live_plot'].update("Start") window["stat_live"].update(" Idle", text_color="orange") return bin_file.write(chunk) # Close the serial port ser.close() bin_hex = BitArray(chunk) # bin to hex bin_ascii = bin_hex.bin # hex to ASCII num_ones_array = int( bin_ascii.count('1')) # count numbers of ones in the 2048 string csv_ones.append(num_ones_array) sums_csv = sum(csv_ones) avrg_csv = sums_csv / index_number zscore_csv = (avrg_csv - (sample_value / 2)) / (((sample_value / 4)**0.5) / (index_number**0.5)) zscore_array.append(zscore_csv) index_number_array.append(index_number) with open( file_name + '.csv', "a+" ) as write_file: # open file and append time and number of ones write_file.write( f'{strftime("%H:%M:%S", localtime())} {num_ones_array}\n') end_cap = time.time() # print(interval_value - (end_cap - start_cap) / 1000) try: time.sleep(interval_value - (end_cap - start_cap)) except Exception: pass
def get_serial_ports(): """Returns a list of all serial ports found, e.g. 'COM1' in Windows""" return sorted([port.device for port in list_ports.comports()])
def showport(self): self.port.clear() for port, desc, hwid in comports(): self.port.addItem(port)