Skip to content

Python serial.Serial() Examples

John Hau edited this page Mar 17, 2022 · 1 revision

The following are 30 code examples for showing how to use serial.Serial(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module serial , or try the search function

image

image

image

image

Example 5 Project: WLANThermo_v2 Author: WLANThermo File: wlt_2_nextion.py License: GNU General Public License v3.0 6 votes vote downvote 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 6 Project: dashgo Author: EAIBOT File: dashgo_driver.py License: Apache License 2.0 6 votes vote downvote 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 7 Project: ToonRooter Author: martenjacobs File: rooter.py License: MIT License 5 votes vote downvote up def init(self, **params): if type(params['port']) is str: params['port']=serial.Serial( port=params['port'], baudrate=115200 ) self._port = params['port'] self._ssh_pubkey_data = params['ssh_pubkey_data'] self._has_jtag = params['has_jtag'] self._check_uboot = params['check_uboot'] self._cleanup_payload = params['cleanup_payload'] self._reboot_after = params['reboot_after'] self._uboot_only = params['uboot_only'] self._boot_only = params['boot_only'] self._jtag_hardware = params['jtag_hardware'] Example 8 Project: soccer-matlab Author: utra-robosoccer File: vrhand_vive_tracker.py License: BSD 2-Clause "Simplified" License 5 votes vote downvote up def getSerialOrNone(portname): try: return serial.Serial(port=portname,baudrate=115200,parity=serial.PARITY_ODD,stopbits=serial.STOPBITS_TWO,bytesize=serial.SEVENBITS) except: return None

Example 9 Project: soccer-matlab Author: utra-robosoccer File: hand.py License: BSD 2-Clause "Simplified" License 5 votes vote downvote up def getSerialOrNone(portname): try: return serial.Serial(port=portname,baudrate=115200,parity=serial.PARITY_ODD,stopbits=serial.STOPBITS_TWO,bytesize=serial.SEVENBITS) except: return None Example 10 Project: BatteryMonitor Author: simat File: bmscore.py License: GNU General Public License v2.0 5 votes vote downvote up def openbms(port='/dev/ttyUSB0'): ser = serial.Serial(port) # open serial port ser.timeout = 3 return ser

Example 11 Project: BatteryMonitor Author: simat File: bms.py License: GNU General Public License v2.0 5 votes vote downvote up def openbms(self,port): self.port = serial.Serial(port,timeout=2) # open serial port Example 12 Project: BatteryMonitor Author: simat File: piptest.py License: GNU General Public License v2.0 5 votes vote downvote up def openpip(port): openport = serial.Serial(port,baudrate=2400,timeout=1.0) # open serial port return openport

Example 13 Project: BatteryMonitor Author: simat File: pip.py License: GNU General Public License v2.0 5 votes vote downvote up def openpip(self,port): self.port = serial.Serial(port,baudrate=2400,timeout=1) # open serial port Example 14 Project: PyVESC Author: LiamBindle File: VESC.py License: Creative Commons Attribution 4.0 International 5 votes vote downvote up def init(self, serial_port, has_sensor=False, start_heartbeat=True, baudrate=115200, timeout=0.05): """ :param serial_port: Serial device to use for communication (i.e. "COM3" or "/dev/tty.usbmodem0") :param has_sensor: Whether or not the bldc motor is using a hall effect sensor :param start_heartbeat: Whether or not to automatically start the heartbeat thread that will keep commands alive. :param baudrate: baudrate for the serial communication. Shouldn't need to change this. :param timeout: timeout for the serial communication """

    if serial is None:
        raise ImportError("Need to install pyserial in order to use the VESCMotor class.")

    self.serial_port = serial.Serial(port=serial_port, baudrate=baudrate, timeout=timeout)
    if has_sensor:
        self.serial_port.write(encode(SetRotorPositionMode(SetRotorPositionMode.DISP_POS_OFF)))

    self.heart_beat_thread = threading.Thread(target=self._heartbeat_cmd_func)
    self._stop_heartbeat = threading.Event()

    if start_heartbeat:
        self.start_heartbeat()

    # check firmware version and set GetValue fields to old values if pre version 3.xx
    version = self.get_firmware_version()
    if int(version.split('.')[0]) < 3:
        GetValues.fields = pre_v3_33_fields

    # store message info for getting values so it doesn't need to calculate it every time
    msg = GetValues()
    self._get_values_msg = encode_request(msg)
    self._get_values_msg_expected_length = msg._full_msg_size 

Example 15 Project: PyVESC Author: LiamBindle File: get_values.py License: Creative Commons Attribution 4.0 International 5 votes vote downvote up def get_values_example(): with serial.Serial(serialport, baudrate=115200, timeout=0.05) as ser: try: # Optional: Turn on rotor position reading if an encoder is installed ser.write(pyvesc.encode(SetRotorPositionMode(SetRotorPositionMode.DISP_POS_OFF))) while True: # Set the ERPM of the VESC motor # Note: if you want to set the real RPM you can set a scalar # manually in setters.py # 12 poles and 19:1 gearbox would have a scalar of 1/228 ser.write(pyvesc.encode(SetRPM(10000)))

            # Request the current measurement from the vesc
            ser.write(pyvesc.encode_request(GetValues))

            # Check if there is enough data back for a measurement
            if ser.in_waiting > 61:
                (response, consumed) = pyvesc.decode(ser.read(61))

                # Print out the values
                try:
                    print(response.rpm)

                except:
                    # ToDo: Figure out how to isolate rotor position and other sensor data
                    #       in the incoming datastream
                    #try:
                    #    print(response.rotor_pos)
                    #except:
                    #    pass
                    pass

            time.sleep(0.1)

    except KeyboardInterrupt:
        # Turn Off the VESC
        ser.write(pyvesc.encode(SetCurrent(0))) 

Example 16 Project: py-sds011 Author: ikalchev File: init.py License: MIT License 5 votes vote downvote up def init(self, serial_port, baudrate=9600, timeout=2, use_query_mode=True): """Initialise and open serial port. """ self.ser = serial.Serial(port=serial_port, baudrate=baudrate, timeout=timeout) self.ser.flush() self.set_report_mode(active=not use_query_mode) Example 17 Project: ampy Author: scientifichackers File: pyboard.py License: MIT License 5 votes vote downvote up def init(self, device, baudrate=115200, user='micro', password='python', wait=0, rawdelay=0): global _rawdelay _rawdelay = rawdelay if device and device[0].isdigit() and device[-1].isdigit() and device.count('.') == 3: # device looks like an IP address self.serial = TelnetToSerial(device, user, password, read_timeout=10) else: import serial delayed = False for attempt in range(wait + 1): try: self.serial = serial.Serial(device, baudrate=baudrate, interCharTimeout=1) break except (OSError, IOError): # Py2 and Py3 have different errors if wait == 0: continue if attempt == 0: sys.stdout.write('Waiting {} seconds for pyboard '.format(wait)) delayed = True time.sleep(1) sys.stdout.write('.') sys.stdout.flush() else: if delayed: print('') raise PyboardError('failed to access ' + device) if delayed: print('') Example 18 Project: thingsboard-gateway Author: thingsboard File: custom_serial_connector.py License: Apache License 2.0 5 votes vote downvote up def __connect_to_devices(self): # Function for opening connection and connecting to devices for device in self.__devices: try: # Start error handler connection_start = time.time() if self.__devices[device].get("serial") is None
or self.__devices[device]["serial"] is None
or not self.__devices[device]["serial"].isOpen(): # Connect only if serial not available earlier or it is closed. self.__devices[device]["serial"] = None while self.__devices[device]["serial"] is None or not self.__devices[device]["serial"].isOpen(): # Try connect # connection to serial port with parameters from configuration file or default self.__devices[device]["serial"] = serial.Serial(port=self.__config.get('port', '/dev/ttyUSB0'), baudrate=self.__config.get('baudrate', 9600), bytesize=self.__config.get('bytesize', serial.EIGHTBITS), parity=self.__config.get('parity', serial.PARITY_NONE), stopbits=self.__config.get('stopbits', serial.STOPBITS_ONE), timeout=self.__config.get('timeout', 1), xonxoff=self.__config.get('xonxoff', False), rtscts=self.__config.get('rtscts', False), write_timeout=self.__config.get('write_timeout', None), dsrdtr=self.__config.get('dsrdtr', False), inter_byte_timeout=self.__config.get('inter_byte_timeout', None), exclusive=self.__config.get('exclusive', None)) time.sleep(.1) if time.time() - connection_start > 10: # Break connection try if it setting up for 10 seconds log.error("Connection refused per timeout for device %s", self.__devices[device]["device_config"].get("name")) break except serial.serialutil.SerialException: log.error("Port %s for device %s - not found", self.__config.get('port', '/dev/ttyUSB0'), device) except Exception as e: log.exception(e) else: # if no exception handled - add device and change connection state self.__gateway.add_device(self.__devices[device]["device_config"]["name"], {"connector": self}, self.__devices[device]["device_config"]["type"]) self.__connected = True Example 19 Project: thingsboard-gateway Author: thingsboard File: custom_serial_connector.py License: Apache License 2.0 5 votes vote downvote up def __connect_to_devices(self): # Function for opening connection and connecting to devices for device in self.__devices: try: # Start error handler connection_start = time.time() if self.__devices[device].get("serial") is None
or self.__devices[device]["serial"] is None
or not self.__devices[device]["serial"].isOpen(): # Connect only if serial not available earlier or it is closed. self.__devices[device]["serial"] = None while self.__devices[device]["serial"] is None or not self.__devices[device]["serial"].isOpen(): # Try connect # connection to serial port with parameters from configuration file or default self.__devices[device]["serial"] = serial.Serial(port=self.__config.get('port', '/dev/ttyUSB0'), baudrate=self.__config.get('baudrate', 9600), bytesize=self.__config.get('bytesize', serial.EIGHTBITS), parity=self.__config.get('parity', serial.PARITY_NONE), stopbits=self.__config.get('stopbits', serial.STOPBITS_ONE), timeout=self.__config.get('timeout', 1), xonxoff=self.__config.get('xonxoff', False), rtscts=self.__config.get('rtscts', False), write_timeout=self.__config.get('write_timeout', None), dsrdtr=self.__config.get('dsrdtr', False), inter_byte_timeout=self.__config.get('inter_byte_timeout', None), exclusive=self.__config.get('exclusive', None)) time.sleep(.1) if time.time() - connection_start > 10: # Break connection try if it setting up for 10 seconds log.error("Connection refused per timeout for device %s", self.__devices[device]["device_config"].get("name")) break except serial.serialutil.SerialException: log.error("Port %s for device %s - not found", self.__config.get('port', '/dev/ttyUSB0'), device) except Exception as e: log.exception(e) else: # if no exception handled - add device and change connection state self.__gateway.add_device(self.__devices[device]["device_config"]["name"], {"connector": self}, self.__devices[device]["device_config"]["type"]) self.__connected = True Example 20 Project: moler Author: nokia File: moler_serial_proxy.py License: BSD 3-Clause "New" or "Revised" License 5 votes vote downvote up def open(self): """ Take 'how to establish connection' info from constructor and open that connection.

    Return context manager to allow for:  with connection.open() as conn:
    """
    self._serial_connection = serial.Serial(port=self.port,
                                            baudrate=self.baudrate,
                                            stopbits=self.stopbits,
                                            parity=self.parity,
                                            timeout=self.timeout,
                                            xonxoff=self.xonxoff)
    return self 

Example 21 Project: moler Author: nokia File: test_serial_proxy.py License: BSD 3-Clause "New" or "Revised" License 5 votes vote downvote up def test_opening_ioserial_correctly_constructs_serial_connection(): from moler.util import moler_serial_proxy with mock.patch("moler.util.moler_serial_proxy.serial.Serial") as serial_conn: io = moler_serial_proxy.IOSerial(port="COM5") io.open() serial_conn.assert_called_once_with(port="COM5", baudrate=115200, stopbits=serial.STOPBITS_ONE, parity=serial.PARITY_NONE, timeout=2, xonxoff=1) Example 22 Project: moler Author: nokia File: test_serial_proxy.py License: BSD 3-Clause "New" or "Revised" License 5 votes vote downvote up def serial_connection_of_ioserial(): from serial import Serial with mock.patch("moler.util.moler_serial_proxy.serial.Serial") as serial_conn: # mocking class # serial_conn.return_value = mock.Mock(spec=Serial) # return value from Serial() is instance of Serial serial_conn.return_value = mock.Mock() # return value from Serial() is instance of Serial serial_conn.return_value.is_open = True serial_conn.return_value.read = lambda s: "" serial_conn.return_value.in_waiting = 0 serial_conn.return_value.close = mock.Mock() serial_conn.return_value.write = mock.Mock() yield serial_conn.return_value # returning instance that will be used by calling class Example 23 Project: ublox Author: Korving-F File: ubx.py License: MIT License 5 votes vote downvote up def init(self, dev=None): # pyserial 3.x has min requirement python2.7 # read() returns string in 2.7, bytes object otherwise if sys.version_info[0] < 3: if sys.version_info[1] < 7: raise ValueError('This library is based on pyserial v3.x. Python 2.7 or higher is required.') self._version = 2 self._ubox_synch = '\xb5b' else: self._version = 3 self._ubox_synch = ['b5', '62']

    if(dev):
        self.dev = dev
    else:
        self.dev = serial.Serial(timeout=1)

    try:
        if(self._dev.open):
            self.baudrate = dev.baudrate
    except AttributeError:
        print("Serial Port is closed; open before using.") 

Example 24 Project: ublox Author: Korving-F File: ubx.py License: MIT License 5 votes vote downvote up def dev(self, dev): x = dev.class.module + "." + dev.class.name supported = ["serial.serialcli.Serial", "serial.serialwin32.Serial", "serial.serialposix.Serial", "serial.serialjava.Serial"] if(x in supported): self._dev = dev else: print("This connection is not supported") Example 25 Project: ublox Author: Korving-F File: ubx.py License: MIT License 5 votes vote downvote up def baudrate(self): try: if(self._dev.open): return self._baudrate else: print("Port is closed.") except AttributeError: print("Serial connection has not been initialized or assigned a baudrate yet.") Example 26 Project: ublox Author: Korving-F File: ubx.py License: MIT License 5 votes vote downvote up def baudrate(self,baudrate): y = UbxMessage('06','00', msg_type="tx", rate=baudrate, version=self._version) try: if(self.dev.writable): if(self.dev.write(y.msg)): time.sleep(1) # Sleep to make sure buffer gets written! self._baudrate = baudrate self._dev.baudrate = baudrate

    except AttributeError:
        print("Serial connection has not been initialized or assigned a port yet.") 

Example 27 Project: OP_Manager Author: adwuard File: Midi.py License: MIT License 5 votes vote downvote up def init(self): self.stopFlag = False

    self.in_Midi_tool_screen_flag = False
    self.in_out_device_selector_flag = 0  # 0, 1, -1

    # Midi device search filter
    self.sysMidiFilterRemoveLst = ["Midi Through", "RtMidiIn Client", "RtMidiOut Client", "RtMidi", "Through"]
    # self.sysMidiFilterRemoveLst = []
    self.threads = []

    # Current Mounted Device
    self.currentInDevice = "Not Connected"
    self.currentOutDevice = "Not Connected"

    # Serial In out initialization
    # self.serialport = serial.Serial('/dev/serial0', 38400, serial.EIGHTBITS, serial.PARITY_NONE, serial.STOPBITS_ONE)  # /dev/ttyS0, ttyAMA0
    self.ser = serial.Serial(port="/dev/serial0", baudrate=38400, timeout=0)

    # Rtmidi USB Midi Initialization
    self.usbOut = rtmidi.MidiOut()
    self.usbIn = rtmidi.MidiIn()

    self.semitone_MinMax = (-7, 7)
    self.octave_MinMax = (-4, 4)
    self.octave = 0
    self.semiTone = 0 

Example 28 Project: OP_Manager Author: adwuard File: Midi.py License: MIT License 5 votes vote downvote up def read(self): """ Midi Serial Read.(In) :return: Midi message """ msg = [None, None, None] for i in range(len(msg)): raw_byte = self.ser.read() if not raw_byte: return byte_value = ord(raw_byte) if byte_value in [248, 250, 252]: return byte_value else: msg[i] = byte_value return msg Example 29 Project: OP_Manager Author: adwuard File: Midi.py License: MIT License 5 votes vote downvote up def write(self, message): """ Midi Serial write (Out) :param message: Midi Message [144, 60, 100] :return: N/A """ self.ser.write(message) Example 30 Project: Facedancer Author: usb-tools File: goodfet.py License: BSD 3-Clause "New" or "Revised" License 5 votes vote downvote up def GoodFETSerialPort(**kwargs): "Return a Serial port using default values possibly overriden by caller"

import serial

port = os.environ.get('GOODFET') or "/dev/ttyUSB0"
args = dict(port=port, baudrate=115200,
            parity=serial.PARITY_NONE, timeout=2)
args.update(kwargs)
return serial.Serial(**args) 
Clone this wiki locally