Python serial.Serial() Examples

The following are 30 code examples of serial.Serial(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module serial , or try the search function .
Example #1
Source File: serial_list.py    From wio-cli with MIT License 15 votes vote down vote up
def serial_ports():
    """ Lists serial port names

        :raises EnvironmentError:
            On unsupported or unknown platforms
        :returns:
            A list of the serial ports available on the system
    """
    if sys.platform.startswith('win'):
        ports = ['COM%s' % (i + 1) for i in range(256)]
    elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
        # this excludes your current terminal "/dev/tty"
        ports = glob.glob('/dev/ttyUSB*') # ubuntu is /dev/ttyUSB0
    elif sys.platform.startswith('darwin'):
        # ports = glob.glob('/dev/tty.*')
        ports = glob.glob('/dev/tty.SLAB_USBtoUART*')
    else:
        raise EnvironmentError('Unsupported platform')

    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            result.append(port)
        except serial.SerialException as e:
            if e.errno == 13:
                raise e
            pass
        except OSError:
            pass
    return result


# if __name__ == '__main__':
#     print(serial_ports()) 
Example #2
Source File: bsl.py    From BHSTools with GNU General Public License v3.0 6 votes vote down vote up
def load_stg1(ser:Serial, program:bytes):
	maxlen = 0xFC00 - 0xFA60
	if len(program) > maxlen:
		raise IndexError('Maximum program size is {} bytes'.format(maxlen))
	
	pgmlen = tohex(struct.pack('<H', len(program)))
	
	stage1 = fromhex(''.join([
		'E6F160FA',    # mov r1, #0FA60h
		'E6F2'+pgmlen, # mov r2, len(program)
		# wait:
		'9AB7FE70',    # jnb S0RIR, wait
		'7EB7',        # bclr S0RIR
		'F2F3B2FE',    # mov r3, S0RBUF
		'B961',        # movb [r1], rl3
		'0811',        # add r1, #1
		'2821',        # sub r2, #1
		'3DF7',        # jmpr cc_NZ, wait
		'CC00',        # nop
		'CC00',        # nop
		'CC00'         # nop
	]))

	load_bsl(ser, stage1+program, allow_overflow=True) 
Example #3
Source File: biaxe.py    From crappy with GNU General Public License v2.0 6 votes vote down vote up
def open(self):
    self.ser = serial.Serial(self.port, self.baudrate,
                             serial.EIGHTBITS, serial.PARITY_EVEN,
                             serial.STOPBITS_ONE, self.timeout)
    self.clear_errors()
    self.speed = None 
Example #4
Source File: dashgo_driver.py    From dashgo with Apache License 2.0 5 votes vote down vote up
def connect(self):
        try:
            print "Connecting to Arduino on port", self.port, "..."
            self.port = Serial(port=self.port, baudrate=self.baudrate, timeout=self.timeout, writeTimeout=self.writeTimeout)
            # The next line is necessary to give the firmware time to wake up.
            time.sleep(1)
            test = self.get_baud()
            if test != self.baudrate:
                time.sleep(1)
                test = self.get_baud()   
                if test != self.baudrate:
                    raise SerialException
            print "Connected at", self.baudrate
            print "Arduino is ready."

        except SerialException:
            print "Serial Exception:"
            print sys.exc_info()
            print "Traceback follows:"
            traceback.print_exc(file=sys.stdout)
            print "Cannot connect to Arduino!"
            os._exit(1) 
Example #5
Source File: layer_2_protocol.py    From Faraday-Software with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, port, baud, timeout):
        self._port = port
        self._baud = baud
        self._timeout = timeout
        self.serial_rx_queue = Queue.Queue()  # Infinite
        self.serial_tx_queue = Queue.Queue()  # Infinite
        self.enabled = True
        try:
            self.ser = serial.Serial(port, baud, timeout=timeout)
        except serial.SerialException as e:
            logger.error(e)
            sys.exit(1)  # Sys.exit(1) is an error

        #Start
        threading.Thread.__init__(self)
        self.start()  #Starts the run() function and thread 
Example #6
Source File: PDDemulate.py    From knitlib with GNU Lesser General Public License v3.0 5 votes vote down vote up
def open(self, cport='/dev/ttyUSB0'):
        if self.noserial is False:
            self.ser = serial.Serial(port=cport, baudrate=9600, parity='N', stopbits=1, timeout=1, xonxoff=0, rtscts=0,
                                     dsrdtr=0)
            #            self.ser.setRTS(True)
            if self.ser is None:
                logging.error('Unable to open serial device %s' % cport)
                raise IOError
        return 
Example #7
Source File: bsl.py    From BHSTools with GNU General Public License v3.0 5 votes vote down vote up
def load_bsl(ser:Serial, program:bytes, allow_overflow=False):
	if len(program) > 32 and not allow_overflow:
		raise ValueError('Maximum program size is 32 bytes')

	ser.reset_input_buffer()
	ser.write(b'\0')
	if ser.read(1)[0] != 0xD5:
		raise BSLCommError('Incorrect identification byte returned')
	
	program += b'\0' * (32 - len(program))
	ser.write(program) 
Example #8
Source File: main.py    From BHSTools with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, port, baudrate=38400):
		self.serial = Serial(port=port, baudrate=baudrate) 
Example #9
Source File: wlt_2_nextion.py    From WLANThermo_v2 with GNU General Public License v3.0 5 votes vote down vote up
def NX_waitok():
    endcount = 0
    bytecount = 0
    ok = False
    byte = ''

    while endcount != 3:
        try:
            byte = ser.read()
        except termios.error, e:
            logger.error(_(u'termios.error in NX_waitok: {}').format(e[1]))
        
        if byte == '':
            logger.info(_(u'Serial Communication Timeout!'))
            break
        bytecount += 1
        if (byte[0] == '\xff'):
            endcount += 1
        elif (byte[0] == '\x01' and bytecount == 1):
            endcount = 0
            ok = True
        else:
            endcount = 0 
Example #10
Source File: pioupload.py    From web2board with GNU Lesser General Public License v3.0 5 votes vote down vote up
def TouchSerialPort(env, port, baudrate):
    if "windows" not in get_systype():
        try:
            s = Serial(env.subst(port))
            s.close()
        except:  # pylint: disable=W0702
            pass
    s = Serial(port=env.subst(port), baudrate=baudrate)
    s.setDTR(False)
    s.close()
    sleep(0.4) 
Example #11
Source File: pioupload.py    From web2board with GNU Lesser General Public License v3.0 5 votes vote down vote up
def FlushSerialBuffer(env, port):
    s = Serial(env.subst(port))
    s.flushInput()
    s.setDTR(False)
    s.setRTS(False)
    sleep(0.1)
    s.setDTR(True)
    s.setRTS(True)
    s.close() 
Example #12
Source File: SerialMonitorHub.py    From web2board with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, port, baudrate, on_received_callback):
        self.serial = serial.Serial()
        self.serial.port = port
        self.serial.baudrate = baudrate
        self.serial.open()
        self.on_received_callback = on_received_callback
        self.__getData()
        self.is_about_to_be_closed = False 
Example #13
Source File: nextion_hwclock.py    From WLANThermo_v2 with GNU General Public License v3.0 5 votes vote down vote up
def NX_init(port, baudrate):
    global ser, NX_lf
    ser.port = port
    ser.baudrate = baudrate
    ser.timeout = 0.2
    ser.open()
    
    import fcntl, serial

    try:
        fcntl.flock(ser.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        print ('Serial port is busy')
        return False
    # Buffer des Displays leeren
    # - Ungültigen Befehl senden
    # - Aufwachbefehl senden
    ser.write(b'nop' + NX_lf)
    ser.write(b'sleep=0' + NX_lf)
    # - Warten
    ser.flush()
    time.sleep(0.5)
    # - Empfangene Zeichen löschen
    ser.flushInput()
    # Immer eine Rückmeldung erhalten
    ser.write(b'ref 0' + NX_lf)
    ser.flush()
    return NX_waitok() 
Example #14
Source File: arduino.py    From crappy with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, *args):

    kwargs = args[0]  # Because one cannot pass multiple kwargs when creating
    #  a process...

    for key, value in kwargs.items():
      setattr(self, key, value)
    self.arduino_ser = serial.Serial(port=self.port,
                                     baudrate=self.baudrate)

    self.collect_serial_queue = Queue_threading()  # To collect serial
    self.submit_serial_queue = Queue_threading()  # To send in serial

    # A thread that runs independently to collect serial port continuously.
    self.collect_serial_threaded = Thread(target=collect_serial,
                                          args=(self.arduino_ser,
                                                self.collect_serial_queue))
    self.collect_serial_threaded.daemon = True
    self.init_main_window()
    self.collect_serial_threaded.start()
    self.bool_loop = True

    self.main_loop() 
Example #15
Source File: opsens.py    From crappy with GNU General Public License v2.0 5 votes vote down vote up
def open(self):
    self.s = serial.Serial(port=self.device, baudrate=57600)
    self.send_cmd("meas:rate min") 
Example #16
Source File: t110.py    From BerePi with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def read_co2(self):
	    GPIO.setwarnings(False)
	    GPIO.cleanup()
	    GPIO.setmode(GPIO.BCM)
	    GPIO.setup(18, GPIO.OUT)
	    GPIO.setup(23, GPIO.OUT)
	    GPIO.setup(24, GPIO.OUT)
	    GPIO.setup(25, GPIO.OUT)

	    self.serial_in_device = serial.Serial('/dev/ttyAMA0',38400)

	    in_byte = self.serial_in_device.read(self.SERIAL_READ_BYTE)

	    if not (len(in_byte) is self.SERIAL_READ_BYTE):
		return False

	    if not in_byte[9] is 'm':
		shift_byte = self.checkAlignment(in_byte)
		in_byte = shift_byte

	    if ('ppm' in in_byte):
		self.ppm = self._get_buffer(in_byte)
	    else:
		self.ppm = False
	    #print self.ppm

	    return self.ppm 
Example #17
Source File: t110.py    From BerePi with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self):
    	'''
	    GPIO.setwarnings(False)
	    GPIO.cleanup()
	    GPIO.setmode(GPIO.BCM)
	    GPIO.setup(18, GPIO.OUT)
	    GPIO.setup(23, GPIO.OUT)
	    GPIO.setup(24, GPIO.OUT)
	    GPIO.setup(25, GPIO.OUT)

	    self.serial_in_device = serial.Serial('/dev/ttyAMA0',38400)
        '''
	pass 
Example #18
Source File: specter_hwi.py    From specter-desktop with MIT License 5 votes vote down vote up
def __init__(self, path):
        self.ser = serial.Serial(baudrate=115200, timeout=30)
        self.ser.port = path 
Example #19
Source File: phatsniffer.py    From phatsniffer with MIT License 5 votes vote down vote up
def send_command(command):
	comm = serial.Serial('/dev/serial0', 115200)
	if comm.isOpen():
		comm.close()
	comm.open()
	comm.flushInput()
	comm.write(command+'\n')
	time.sleep(0.1)
	return comm.readline() 
Example #20
Source File: autosetup_tty.py    From openplotter with GNU General Public License v2.0 5 votes vote down vote up
def readNMEA2000(self, port, baudrate):
		try:
			self.serial = serial.Serial(port, baudrate, timeout=1)
		except:
			return False
		timewait = time.time() + 0.5
		print 'search NMEA2000 on ' + port + ' with baudrate ' + baudrate

		data = [0x10, 0x2, 0xa1, 0x01, 0x01, 0x5d, 0x10, 0x03]
		for i in data:
			self.serial.write(chr(i))
		while time.time() < timewait:
			try:
				c = self.serial.read(1)
			except: c = ''
			if c != '':
				b = ord(c)
				if b == 0x10:
					try:
						c = self.serial.read(1)
					except: c = ''
					if c != '':
						b = ord(c)
						if b == 0x02:
							print 'found NMEA2000 on ' + port + ' with baudrate ' + str(baudrate)
							wx.Yield()
							return True
		print 'not found NMEA2000 on ' + port + ' with baudrate ' + str(baudrate)
		wx.Yield()
		return False 
Example #21
Source File: autosetup_tty.py    From openplotter with GNU General Public License v2.0 5 votes vote down vote up
def readNMEA0183name(self, port, baudrate):
		self.serial = serial.Serial(port, baudrate, timeout=1)
		timewait = time.time() + 10.1
		name_list = []
		nmea = self.serial.readline()
		while time.time() < timewait:
			wx.Yield()
			nmea = self.serial.readline()
			print '	' + nmea[:-2]
			if len(nmea) > 7:
				if nmea[1:3] not in name_list:
					name_list.append(nmea[1:3])

		if len(name_list) > 1:
			self.mpx+=1
			return 'MPX'+str(self.mpx)
		elif len(name_list) == 1:
			return name_list[0]
		else:
			return 'UNDEF' 
Example #22
Source File: autosetup_tty.py    From openplotter with GNU General Public License v2.0 5 votes vote down vote up
def readNMEA0183false(self, port, baudrate):
		try:
			self.serial = serial.Serial(port, baudrate, timeout=1)
		except:
			return False
		timewait = time.time() + 1.5
		index = 0
		countwrong = 0
		print 'search NMEA0183 on ' + port + ' with baudrate ' + baudrate
		text = ''
		nmea = self.serial.readline()
		while time.time() < timewait:
			nmea = self.serial.readline()
			if len(nmea)>0:
			  if nmea[0] in ['$', '!']:
				index += 4
			  else:
				countwrong += 1
			else:
				countwrong += 1

		if index > 10 and countwrong < 2:
			print 'found NMEA0183 on ' + port + ' with baudrate ' + str(baudrate)
			return True
		else:
			return False 
Example #23
Source File: autosetup_tty.py    From openplotter with GNU General Public License v2.0 5 votes vote down vote up
def readNMEA0183(self, port, baudrate):
		try:
			self.serial = serial.Serial(port, baudrate, timeout=1)
		except:
			return False
		timewait = time.time() + 1.5
		index = 0
		countwrong = 0
		print 'search NMEA0183 on ' + port + ' with baudrate ' + baudrate
		text = ''
		while time.time() < timewait:
			wx.Yield()
			try:
				c = self.serial.read(1)
			except: c = ''
			if c != '':
				b = ord(c)
				# print c
				if b == 10 or b == 13 or (32 <= b < 128):
					index += 1
					if b == 13:
						print '	' + text[:-1]
						text = ''
					elif b == 10:
						pass
					else:
						text += c

				else:
					#print 'countwrong ', b
					countwrong += 1

		if index > 10 and countwrong < index/10:
			print 'found NMEA0183 on ' + port + ' with baudrate ' + str(baudrate)
			return True
		else:
			return False 
Example #24
Source File: poll_sensors_backup.py    From openag_brain_box with GNU General Public License v3.0 5 votes vote down vote up
def groveO2Init():
    port = serial.Serial("/dev/serial/by-id/usb-Numato_Systems_Pvt._Ltd._Numato_Lab_8_Channel_USB_GPIO_Module-if00", 19200, timeout=1)
    return port 
Example #25
Source File: grove_o2.py    From openag_brain_box with GNU General Public License v3.0 5 votes vote down vote up
def connect(self):
        if self.pseudo:
            logger.info('Connected to pseudo sensor')
            return
        try:
            self.serial = serial.Serial(self.serial_port, 19200, timeout=1)
            logger.debug("self.serial.isOpen() = {}".format(self.serial.isOpen()))
            if not self.sensor_is_connected:
                self.sensor_is_connected = True
                logger.info('Connected to sensor')
        except:
            if self.sensor_is_connected:
                self.sensor_is_connected = False
                logger.warning('Unable to connect to sensor') 
Example #26
Source File: shell.py    From python-xbee with MIT License 5 votes vote down vote up
def __init__(self):
		cmd.Cmd.__init__(self)
		self.prompt = "xbee% "
		self.serial = serial.Serial() 
Example #27
Source File: alarm.py    From python-xbee with MIT License 5 votes vote down vote up
def __init__(self, serial_port, remote_addr):
        # Open serial port, construct XBee1, configure remote device,
        # store as hardware
        self.remote_addr = remote_addr

        ser = serial.Serial(serial_port)
        xbee = XBee(ser)

        super(XBeeAlarm, self).__init__(xbee)

        # Reset remote device
        self._reset() 
Example #28
Source File: tornado_example.py    From python-xbee with MIT License 5 votes vote down vote up
def main():
    try:
        # Open serial port
        ser = serial.Serial('/dev/ttys009', 9600)

        # Create XBee Series 1 object
        xbee = XBee(ser, callback=handle_data)

        while True:
            yield gen.sleep(1)
            # Send AT packet
            xbee.send('at', frame_id='B', command='DL')
    except KeyboardInterrupt:
        ioloop.IOLoop.current().stop()
    finally:
        xbee.halt()
        ser.close() 
Example #29
Source File: __init__.py    From mote with MIT License 5 votes vote down vote up
def __init__(self, port_name=None, white_point=(1.0, 1.0, 1.0)):
        self.port_name = port_name
        self._channel_count = 4
        self._channels = [None] * self._channel_count
        self._channel_flags = [0] * self._channel_count
        self._clear_on_exit = False

        self.white_point = white_point

        if self.port_name is None:
            self.port_name = self._find_serial_port(VID, PID, NAME)

            if self.port_name is None:
                raise IOError("Unable to find Mote device")

        self.port = serial.Serial(self.port_name, 115200, timeout=1) 
Example #30
Source File: hwidevice.py    From specter-diy with MIT License 5 votes vote down vote up
def __init__(self, path):
        self.ser = serial.Serial(baudrate=115200, timeout=30)
        self.ser.port = path