Python serial.PARITY_NONE Examples

The following are 30 code examples of serial.PARITY_NONE(). 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: fonagps.py    From fona-pi-zero with MIT License 7 votes vote down vote up
def getCoord():
	# Start the serial connection
	ser=serial.Serial('/dev/ttyAMA0', 115200, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=1)
	ser.write("AT+CGNSINF\r")
	while True:
		response = ser.readline()
		if "+CGNSINF: 1," in response:
			# Split the reading by commas and return the parts referencing lat and long
			array = response.split(",")
			lat = array[3]
			print lat
			lon = array[4]
			print lon
			return (lat,lon)


# Start the program by opening the cellular connection and creating a bucket for our data 
Example #2
Source File: terminal.py    From pros-cli2 with Mozilla Public License 2.0 7 votes vote down vote up
def terminal(port):
    click.echo(click.style('NOTE: This is an early prototype of the terminal.'
                           ' Nothing is guaranteed to work.', bold=True))
    if port == 'default':
        if len(prosflasher.ports.list_com_ports()) == 1:
            port = prosflasher.ports.list_com_ports()[0].device
        elif len(prosflasher.ports.list_com_ports()) > 1:
            click.echo('Multiple ports were found:')
            click.echo(prosflasher.ports.create_port_list())
            port = click.prompt('Select a port to open',
                                type=click.Choice([p.device for p in prosflasher.ports.list_com_ports()]))
        else:
            click.echo('No ports were found.')
            click.get_current_context().abort()
            sys.exit()
    ser = prosflasher.ports.create_serial(port, serial.PARITY_NONE)
    term = proscli.serial_terminal.Terminal(ser)
    signal.signal(signal.SIGINT, term.stop)
    term.start()
    while term.alive:
        time.sleep(0.005)
    term.join()
    ser.close()
    print('Exited successfully')
    sys.exit(0) 
Example #3
Source File: com_monitor.py    From SerialPort-RealTime-Data-Plotter with MIT License 7 votes vote down vote up
def __init__(   self, 
                    data_q, error_q, 
                    port_num,
                    port_baud,
                    port_stopbits = serial.STOPBITS_ONE,
                    port_parity   = serial.PARITY_NONE,
                    port_timeout  = 0.01):
        threading.Thread.__init__(self)
        
        self.serial_port = None
        self.serial_arg  = dict( port      = port_num,
                                 baudrate  = port_baud,
                                 stopbits  = port_stopbits,
                                 parity    = port_parity,
                                 timeout   = port_timeout)

        self.data_q   = data_q
        self.error_q  = error_q
        
        self.alive    = threading.Event()
        self.alive.set()
    #------------------------------------------------------ 
Example #4
Source File: fonagps.py    From fona-raspberry-pi-3 with MIT License 6 votes vote down vote up
def getCoord():
	# Start the serial connection
	ser=serial.Serial('/dev/serial0', 115200, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=1)
	ser.write("AT+CGNSINF\r")
	while True:
		response = ser.readline()
		if "+CGNSINF: 1," in response:
			# Split the reading by commas and return the parts referencing lat and long
			array = response.split(",")
			lat = array[3]
			print lat
			lon = array[4]
			print lon
			return (lat,lon)


# Start the program by opening the cellular connection and creating a bucket for our data 
Example #5
Source File: protocol.py    From pyshtrih with MIT License 6 votes vote down vote up
def __init__(self, port, baudrate, timeout, fs=False):
        """
        Класс описывающий протокол взаимодействия в устройством.

        :type port: str
        :param port: порт взаимодействия с устройством
        :type baudrate: int
        :param baudrate: скорость взаимодействия с устройством
        :type timeout: float
        :param timeout: время таймаута ответа устройства
        :type fs: bool
        :param fs: признак наличия ФН (фискальный накопитель)
        """

        self.port = port
        self.serial = serial.Serial(
            baudrate=baudrate,
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            timeout=timeout,
            writeTimeout=timeout
        )
        self.fs = fs
        self.connected = False 
Example #6
Source File: test_win32serialport.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_serialPortDefaultArgs(self):
        """
        Test correct positional and keyword arguments have been
        passed to the C{serial.Serial} object.
        """
        port = RegularFileSerialPort(self.protocol, self.path, self.reactor)
        # Validate args
        self.assertEqual((self.path,), port._serial.captured_args)
        # Validate kwargs
        kwargs = port._serial.captured_kwargs
        self.assertEqual(9600,                kwargs["baudrate"])
        self.assertEqual(serial.EIGHTBITS,    kwargs["bytesize"])
        self.assertEqual(serial.PARITY_NONE,  kwargs["parity"])
        self.assertEqual(serial.STOPBITS_ONE, kwargs["stopbits"])
        self.assertEqual(0,                   kwargs["xonxoff"])
        self.assertEqual(0,                   kwargs["rtscts"])
        self.assertEqual(None,                kwargs["timeout"])
        port.connectionLost(Failure(Exception("Cleanup"))) 
Example #7
Source File: grid.py    From grid-control with GNU General Public License v3.0 6 votes vote down vote up
def setup_serial(ser, port, lock):
    """Setup all parameters for the serial communication"""
    try:
        with lock:
            ser.baudrate = 4800
            ser.port = port
            ser.bytesize = serial.EIGHTBITS
            ser.stopbits = serial.STOPBITS_ONE
            ser.parity = serial.PARITY_NONE
            ser.timeout = 0.1  # Read timeout in seconds
            ser.write_timeout = 0.1  # Write timeout in seconds
    except Exception as e:
        helper.show_error("Problem initializing serial port " + port + ".\n\n"
                          "Exception:\n" + str(e) + "\n\n"
                          "The application will now exit.")
        sys.exit(0) 
Example #8
Source File: test_shared.py    From sim-module with MIT License 6 votes vote down vote up
def initializeUartPort(
        portName,
        baudrate = 57600,
        bytesize = serial.EIGHTBITS,
        parity   = serial.PARITY_NONE,
        stopbits = serial.STOPBITS_ONE,
        timeout  = 0
    ):

    port = serial.Serial()

    #tuning port object
    port.port         = portName
    port.baudrate     = baudrate
    port.bytesize     = bytesize
    port.parity       = parity
    port.stopbits     = stopbits
    port.timeout      = timeout

    return port 
Example #9
Source File: auto_cal_p5.py    From MPMD-AutoBedLevel-Cal with MIT License 6 votes vote down vote up
def establish_serial_connection(port, speed=115200, timeout=10, writeTimeout=10000):
    # Hack for USB connection
    # There must be a way to do it cleaner, but I can't seem to find it
    try:
        temp = Serial(port, speed, timeout=timeout, writeTimeout=writeTimeout, parity=PARITY_ODD)
        if sys.platform == 'win32':
            temp.close()
        conn = Serial(port, speed, timeout=timeout, writeTimeout=writeTimeout, parity=PARITY_NONE)
        conn.setRTS(False)#needed on mac
        if sys.platform != 'win32':
            temp.close()
        return conn
    except SerialException as e:
        print ("Could not connect to {0} at baudrate {1}\nSerial error: {2}".format(port, str(speed), e))
        return None
    except IOError as e:
        print ("Could not connect to {0} at baudrate {1}\nIO error: {2}".format(port, str(speed), e))
        return None 
Example #10
Source File: auto_cal.py    From MPMD-AutoBedLevel-Cal with MIT License 6 votes vote down vote up
def establishSerialConnection(port, speed=115200, timeout=10, writeTimeout=10000):
        # Hack for USB connection
        # There must be a way to do it cleaner, but I can't seem to find it
        try:
            temp = Serial(port, speed, timeout=timeout, writeTimeout=writeTimeout, parity=PARITY_ODD)
            if sys.platform == 'win32':
                temp.close()
            conn = Serial(port, speed, timeout=timeout, writeTimeout=writeTimeout, parity=PARITY_NONE)
            conn.setRTS(False) #needed on mac
            if sys.platform != 'win32':
                temp.close()
            return conn
        except SerialException as e:
            print ("Could not connect to {0} at baudrate {1}\nSerial error: {2}".format(port, str(speed), e))
            raise e
        except IOError as e:
            print ("Could not connect to {0} at baudrate {1}\nIO error: {2}".format(port, str(speed), e))
            raise e 
Example #11
Source File: auto_cal_marlin4mpmd.py    From MPMD-AutoBedLevel-Cal with MIT License 6 votes vote down vote up
def establish_serial_connection(port, speed=115200, timeout=10, writeTimeout=10000):
    # Hack for USB connection
    # There must be a way to do it cleaner, but I can't seem to find it
    try:
        temp = Serial(port, speed, timeout=timeout, writeTimeout=writeTimeout, parity=PARITY_ODD)
        if sys.platform == 'win32':
            temp.close()
        conn = Serial(port, speed, timeout=timeout, writeTimeout=writeTimeout, parity=PARITY_NONE)
        conn.setRTS(False)#needed on mac
        if sys.platform != 'win32':
            temp.close()
        return conn
    except SerialException as e:
        print ("Could not connect to {0} at baudrate {1}\nSerial error: {2}".format(port, str(speed), e))
        return None
    except IOError as e:
        print ("Could not connect to {0} at baudrate {1}\nIO error: {2}".format(port, str(speed), e))
        return None 
Example #12
Source File: auto_cal_v2.py    From MPMD-AutoBedLevel-Cal with MIT License 6 votes vote down vote up
def establish_serial_connection(port, speed=115200, timeout=10, writeTimeout=10000):
    # Hack for USB connection
    # There must be a way to do it cleaner, but I can't seem to find it
    try:
        temp = Serial(port, speed, timeout=timeout, writeTimeout=writeTimeout, parity=PARITY_ODD)
        if sys.platform == 'win32':
            temp.close()
        conn = Serial(port, speed, timeout=timeout, writeTimeout=writeTimeout, parity=PARITY_NONE)
        conn.setRTS(False)#needed on mac
        if sys.platform != 'win32':
            temp.close()
        return conn
    except SerialException as e:
        print ("Could not connect to {0} at baudrate {1}\nSerial error: {2}".format(port, str(speed), e))
        return None
    except IOError as e:
        print ("Could not connect to {0} at baudrate {1}\nIO error: {2}".format(port, str(speed), e))
        return None 
Example #13
Source File: client.py    From pysunspec with MIT License 6 votes vote down vote up
def modbus_rtu_client(name=None, baudrate=None, parity=None):

    global modbus_rtu_clients

    client = modbus_rtu_clients.get(name)
    if client is not None:
        if baudrate is not None and client.baudrate != baudrate:
            raise ModbusClientError('Modbus client baudrate mismatch')
        if parity is not None and client.parity != parity:
            raise ModbusClientError('Modbus client parity mismatch')
    else:
        if baudrate is None:
            baudrate = 9600
        if parity is None:
            parity = PARITY_NONE

        client = ModbusClientRTU(name, baudrate, parity)
        modbus_rtu_clients[name] = client

    return client 
Example #14
Source File: modbus.py    From dyode with GNU General Public License v3.0 6 votes vote down vote up
def modbus_send_serial(data, properties):
    modbus_data = pickle.dumps(data)
    data_length = len(modbus_data)
    encoded_data = base64.b64encode(modbus_data)
    data_size = sys.getsizeof(encoded_data)
    log.debug('Data size : %s' % data_size)

    ser = serial.Serial(
        port='/dev/ttyAMA0',
        baudrate = 57600,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS,
        timeout=0.5
        )

    ser.write(encoded_data)
    log.debug(encoded_data) 
Example #15
Source File: ReceiptSerialDriver.py    From fiscalberry with Apache License 2.0 6 votes vote down vote up
def __init__(self, devfile="/dev/ttyS0", baudrate=9600, bytesize=8, timeout=1,
                 parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE,
                 xonxoff=False, dsrdtr=True, codepage="cp858", *args, **kwargs):
        """
        @param devfile  : Device file under dev filesystem
        @param baudrate : Baud rate for serial transmission
        @param bytesize : Serial buffer size
        @param timeout  : Read/Write timeout
        """
        escpos.Escpos.__init__(self, *args, **kwargs)
        self.devfile = devfile
        self.baudrate = baudrate
        self.bytesize = bytesize
        self.timeout = timeout
        self.parity = parity
        self.stopbits = stopbits
        self.xonxoff = xonxoff
        self.dsrdtr = dsrdtr
        self.codepage = codepage 
Example #16
Source File: api.py    From dorna with MIT License 6 votes vote down vote up
def _port_open(self, port):
		if self._port: # port is already open
			return True

		prt = serial.Serial()
		prt.port = port
		prt.baudrate = 115200
		prt.bytesize = serial.EIGHTBITS  # number of bits per bytes
		prt.parity = serial.PARITY_NONE  # set parity check: no parity
		prt.stopbits = serial.STOPBITS_ONE  # number of stop bits
		prt.timeout = .001  # non-block read
		prt.writeTimeout = None  # timeout for write
		try:
			prt.open()
			self._port = prt
			return True
		except Exception as ex:
			return False 
Example #17
Source File: ArduinoFlash.py    From piupdue with MIT License 6 votes vote down vote up
def SetSamBA():
    """ 
    Initial triggering of chip into SAM-BA mode. 
    On the Programming Port there is an ATMEGA16U2 chip, acting as a USB bridge to expose the SAM UART as USB. 
    If the host is connected to the programming port at baud rate 1200, the ATMEGA16U2 will assert the Erase pin and Reset pin of the SAM3X, forcing it to the SAM-BA bootloader mode. 
    The port remains the same number but to access SAM-BA Baud rate must be changed to 115200.
    """
    log.Log("Setting into SAM-BA...")
    
    ser = serial.Serial(port=ArduinoFlashHardValues.arduinoPort,\
                        baudrate=1200,\
                        parity=serial.PARITY_NONE,\
                        stopbits=serial.STOPBITS_ONE,\
                        bytesize=serial.EIGHTBITS,\
                        timeout=2000)
                        
    time.sleep(10)
    
    ser.close() 
    log.Log("SAM-BA Set.") 
Example #18
Source File: piupdue.py    From piupdue with MIT License 6 votes vote down vote up
def Checks(Port, SketchFile):
    """ Does basic checks that sketch file exists and port is connected."""
    if not os.path.isfile(SketchFile):
        log.Log("Sketch File Does Not Exist: " + SketchFile)
        sys.exit()
    
    try:
        ser = serial.Serial(port=Port,\
            baudrate=1200,\
            parity=serial.PARITY_NONE,\
            stopbits=serial.STOPBITS_ONE,\
            bytesize=serial.EIGHTBITS,\
            timeout=2000)
        
    except serial.SerialException:
        log.Log("Problem with selected Port. Double check it is correct.")
        sys.exit()
    except Exception:
        raise Exception("Unexpected excetion in Checks(): " + traceback.format_exc()) 
Example #19
Source File: piupdue.py    From piupdue with MIT License 6 votes vote down vote up
def SetSamBA(DueSerialPort):
    """ 
    Initial triggering of chip into SAM-BA mode. 
    On the Programming Port there is an ATMEGA16U2 chip, acting as a USB bridge to expose the SAM UART as USB. 
    If the host is connected to the programming port at baud rate 1200, the ATMEGA16U2 will assert the Erase pin and Reset pin of the SAM3X, forcing it to the SAM-BA bootloader mode. 
    The port remains the same number but to access SAM-BA Baud rate must be changed to 115200.
    """
    log.Log("Setting into SAM-BA..." + DueSerialPort)
    
    ser = serial.Serial(port=DueSerialPort,\
                        baudrate=1200,\
                        parity=serial.PARITY_NONE,\
                        stopbits=serial.STOPBITS_ONE,\
                        bytesize=serial.EIGHTBITS,\
                        timeout=2000)       
    
    ser.write("\n")
    time.sleep(3)
    ser.close() 
    
    log.Log("SAM-BA Set.") 
Example #20
Source File: com_monitor.py    From code-for-blog with The Unlicense 6 votes vote down vote up
def __init__(   self, 
                    data_q, error_q, 
                    port_num,
                    port_baud,
                    port_stopbits=serial.STOPBITS_ONE,
                    port_parity=serial.PARITY_NONE,
                    port_timeout=0.01):
        threading.Thread.__init__(self)
        
        self.serial_port = None
        self.serial_arg = dict( port=port_num,
                                baudrate=port_baud,
                                stopbits=port_stopbits,
                                parity=port_parity,
                                timeout=port_timeout)

        self.data_q = data_q
        self.error_q = error_q
        
        self.alive = threading.Event()
        self.alive.set() 
Example #21
Source File: UART.py    From peniot with MIT License 6 votes vote down vote up
def __init__(self, portnum=None, useByteQueue=False):
        self.ser = None
        try:
            self.ser = serial.Serial(
                port=portnum,
                baudrate=460800,
                bytesize=serial.EIGHTBITS,
                parity=serial.PARITY_NONE,
                stopbits=serial.STOPBITS_ONE,
                timeout=None,  # seconds
                writeTimeout=None,
                rtscts=True
            )

        except Exception as e:
            if self.ser:
                self.ser.close()
            raise

        self.useByteQueue = useByteQueue
        self.byteQueue = collections.deque()

        # if self.ser.name != None:
        # print "UART %s on port %s" % ("open" if self.ser else "closed", self.ser.name) 
Example #22
Source File: _javaserialport.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, protocol, deviceNameOrPortNumber, reactor, 
        baudrate = 9600, bytesize = EIGHTBITS, parity = PARITY_NONE,
        stopbits = STOPBITS_ONE, timeout = 3, xonxoff = 0, rtscts = 0):
        # do NOT use timeout = 0 !!
        self._serial = serial.Serial(deviceNameOrPortNumber, baudrate = baudrate, bytesize = bytesize, parity = parity, stopbits = stopbits, timeout = timeout, xonxoff = xonxoff, rtscts = rtscts)
        javareactor.JConnection.__init__(self, self._serial.sPort, protocol, None)
        self.flushInput()
        self.flushOutput()
        
        self.reactor = reactor
        self.protocol = protocol
        self.protocol.makeConnection(self)
        wb = javareactor.WriteBlocker(self, reactor.q)
        wb.start()
        self.writeBlocker = wb
        javareactor.ReadBlocker(self, reactor.q).start() 
Example #23
Source File: dobot.py    From pydobot with MIT License 6 votes vote down vote up
def __init__(self, port, verbose=False):
        threading.Thread.__init__(self)

        self._on = True
        self.verbose = verbose
        self.lock = threading.Lock()
        self.ser = serial.Serial(port,
                                 baudrate=115200,
                                 parity=serial.PARITY_NONE,
                                 stopbits=serial.STOPBITS_ONE,
                                 bytesize=serial.EIGHTBITS)
        is_open = self.ser.isOpen()
        if self.verbose:
            print('pydobot: %s open' % self.ser.name if is_open else 'failed to open serial port')

        self._set_queued_cmd_start_exec()
        self._set_queued_cmd_clear()
        self._set_ptp_joint_params(200, 200, 200, 200, 200, 200, 200, 200)
        self._set_ptp_coordinate_params(velocity=200, acceleration=200)
        self._set_ptp_jump_params(10, 200)
        self._set_ptp_common_params(velocity=100, acceleration=100)
        self._get_pose() 
Example #24
Source File: SiUart.py    From basil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def init(self):
        super(SiUart, self).init()
        self._init.setdefault('board_id', None)
        self._init.setdefault('avoid_download', False)
        if self._init['board_id'] and int(self._init['board_id']) >= 0:
            self._ser = serial.Serial()
            if 'port' in self._init.keys():
                self._ser.setPort(self._init['port'])
            if 'baudrate' in self._init.keys():
                self._ser.setBaudrate(self._init['baudrate'])
            if 'parity' in self._init.keys() and self._init["parity"] == 0:
                self._ser.setParity(serial.PARITY_NONE)
            if 'stopbits' in self._init.keys():
                self._ser.setStopbits(self._init['stopbits'])
            if 'bytesize' in self._init.keys():
                self._ser.setByteSize(self._init['bytesize'])
            if 'timeout' in self._init.keys():
                self._ser.setTimeout(self._init['timeout'])

            self._ser.open()
            if not self._ser.isOpen():
                raise IOError("Port at %s not open" % self._ser.port)
        else:
            logger.info('Found board') 
Example #25
Source File: printer.py    From python-escpos with MIT License 6 votes vote down vote up
def __init__(self, devfile="/dev/ttyS0", baudrate=9600, bytesize=8, timeout=1,
                 parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE,
                 xonxoff=False, dsrdtr=True, *args, **kwargs):
        """

        :param devfile:  Device file under dev filesystem
        :param baudrate: Baud rate for serial transmission
        :param bytesize: Serial buffer size
        :param timeout:  Read/Write timeout
        :param parity:   Parity checking
        :param stopbits: Number of stop bits
        :param xonxoff:  Software flow control
        :param dsrdtr:   Hardware flow control (False to enable RTS/CTS)
        """
        Escpos.__init__(self, *args, **kwargs)
        self.devfile = devfile
        self.baudrate = baudrate
        self.bytesize = bytesize
        self.timeout = timeout
        self.parity = parity
        self.stopbits = stopbits
        self.xonxoff = xonxoff
        self.dsrdtr = dsrdtr

        self.open() 
Example #26
Source File: _posixserialport.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, protocol, deviceNameOrPortNumber, reactor, 
        baudrate = 9600, bytesize = EIGHTBITS, parity = PARITY_NONE,
        stopbits = STOPBITS_ONE, timeout = 0, xonxoff = 0, rtscts = 0):
        abstract.FileDescriptor.__init__(self, reactor)
        self._serial = serial.Serial(deviceNameOrPortNumber, baudrate = baudrate, bytesize = bytesize, parity = parity, stopbits = stopbits, timeout = timeout, xonxoff = xonxoff, rtscts = rtscts)
        self.reactor = reactor
        self.flushInput()
        self.flushOutput()
        self.protocol = protocol
        self.protocol.makeConnection(self)
        self.startReading() 
Example #27
Source File: mh_z19.py    From mh-z19 with MIT License 5 votes vote down vote up
def connect_serial():
  return serial.Serial(serial_dev,
                        baudrate=9600,
                        bytesize=serial.EIGHTBITS,
                        parity=serial.PARITY_NONE,
                        stopbits=serial.STOPBITS_ONE,
                        timeout=1.0) 
Example #28
Source File: board.py    From picochess with GNU General Public License v3.0 5 votes vote down vote up
def _open_serial(self, device: str):
        assert not self.serial, 'serial connection still active: %s' % self.serial
        try:
            self.serial = Serial(device, stopbits=STOPBITS_ONE, parity=PARITY_NONE, bytesize=EIGHTBITS, timeout=0.5)
        except SerialException:
            return False
        return True 
Example #29
Source File: __init__.py    From mh-z19 with MIT License 5 votes vote down vote up
def connect_serial():
  return serial.Serial(serial_dev,
                        baudrate=9600,
                        bytesize=serial.EIGHTBITS,
                        parity=serial.PARITY_NONE,
                        stopbits=serial.STOPBITS_ONE,
                        timeout=1.0) 
Example #30
Source File: rplidar.py    From rplidar with MIT License 5 votes vote down vote up
def connect(self):
        '''Connects to the serial port with the name `self.port`. If it was
        connected to another serial port disconnects from it first.'''
        if self._serial_port is not None:
            self.disconnect()
        try:
            self._serial_port = serial.Serial(
                self.port, self.baudrate,
                parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE,
                timeout=self.timeout, dsrdtr=True)
        except serial.SerialException as err:
            raise RPLidarException('Failed to connect to the sensor '
                                   'due to: %s' % err)