PySerial Documentation

3y ago
297 Views
28 Downloads
292.26 KB
63 Pages
Last View : 3d ago
Last Download : 3m ago
Upload by : Cade Thielen
Transcription

pySerial DocumentationRelease 3.4Chris LiechtiJul 02, 2018

Contents1.3334455Short introduction2.1 Opening serial ports .2.2 Configuring ports later2.3 Readline . . . . . . .2.4 Testing ports . . . . .77789pySerial API3.1 Classes . . . . . . . . . . . . .3.2 Exceptions . . . . . . . . . . .3.3 Constants . . . . . . . . . . . .3.4 Module functions and attributes3.5 Threading . . . . . . . . . . . .3.6 asyncio . . . . . . . . . . . . .111124252526294Tools4.1 serial.tools.list ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4.2 serial.tools.miniterm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3131335URL Handlers5.1 Overview . . .5.2 rfc2217://5.3 socket:// .5.4 loop:// . .5.5 hwgrep:// .5.6 spy:// . . .5.7 alt:// . . .5.8 Examples . . .373737383839394141236pySerial1.1 Overview . . .1.2 Features . . . .1.3 Requirements .1.4 Installation . .1.5 References . .1.6 Older VersionsExamples.43i

6.16.26.36.46.56.678Miniterm . . . . . . . . . . . . . . . . . . . .TCP/IP - serial bridge . . . . . . . . . . . . .Single-port TCP/IP - serial bridge (RFC 2217)Multi-port TCP/IP - serial bridge (RFC 2217) .wxPython examples . . . . . . . . . . . . . .Unit tests . . . . . . . . . . . . . . . . . . . .Appendix7.1 How To . . . . .7.2 FAQ . . . . . . .7.3 Related software7.4 License . . . . .434344454646.4949505050Indices and tables53Python Module Index55ii

pySerial Documentation, Release 3.4This module encapsulates the access for the serial port. It provides backends for Python running on Windows, OSX,Linux, BSD (possibly any POSIX compliant system) and IronPython. The module named “serial” automaticallyselects the appropriate backend.Other pages (online) project page on GitHub Download Page with releases This page, when viewed online is at https://pyserial.readthedocs.io/en/latest/ or s1

pySerial Documentation, Release 3.42Contents

CHAPTER1pySerial1.1 OverviewThis module encapsulates the access for the serial port. It provides backends for Python running on Windows, OSX,Linux, BSD (possibly any POSIX compliant system) and IronPython. The module named “serial” automaticallyselects the appropriate backend.It is released under a free software license, see LICENSE for more details.Copyright (C) 2001-2016 Chris Liechti cliechti(at)gmx.net Other pages (online) project page on GitHub Download Page with releases (PyPi) This page, when viewed online is at https://pyserial.readthedocs.io/en/latest/ or http://pythonhosted.org/pyserial/.1.2 Features Same class based interface on all supported platforms. Access to the port settings through Python properties. Support for different byte sizes, stop bits, parity and flow control with RTS/CTS and/or Xon/Xoff. Working with or without receive timeout. File like API with “read” and “write” (“readline” etc. also supported). The files in this package are 100% pure Python. The port is set up for binary transmission. No NULL byte stripping, CR-LF translation etc. (which are manytimes enabled for POSIX.) This makes this module universally useful.3

pySerial Documentation, Release 3.4 Compatible with io library RFC 2217 client (experimental), server provided in the examples.1.3 Requirements Python 2.7 or Python 3.4 and newer If running on Windows: Windows 7 or newer If running on Jython: “Java Communications” (JavaComm) or compatible extension for JavaFor older installations (older Python versions or older operating systems), see older versions below.1.4 InstallationThis installs a package that can be used from Python (import serial).To install for all users on the system, administrator rights (root) may be required.1.4.1 From PyPIpySerial can be installed from PyPI:python -m pip install pyserialUsing the python/python3 executable of the desired version (2.7/3.x).Developers also may be interested to get the source archive, because it contains examples, tests and the this documentation.1.4.2 From CondapySerial can be installed from Conda:conda install pyserialorconda install -c conda-forge pyserialCurrently the default conda channel will provide version 3.4 whereas the conda-forge channel provides the current 3.xversion.Conda: https://www.continuum.io/downloads1.4.3 From source (zip/tar.gz or checkout)Download the archive from http://pypi.python.org/pypi/pyserial or https://github.com/pyserial/pyserial/releases. Unpack the archive, enter the pyserial-x.y directory and run:python setup.py install4Chapter 1. pySerial

pySerial Documentation, Release 3.4Using the python/python3 executable of the desired version (2.7/3.x).1.4.4 PackagesThere are also packaged versions for some Linux distributions: Debian/Ubuntu: “python-serial”, “python3-serial” Fedora / RHEL / CentOS / EPEL: “pyserial” Arch Linux: “python-pyserial” Gentoo: “dev-python/pyserial”Note that some distributions may package an older version of pySerial. These packages are created and maintained bydevelopers working on these distributions.1.5 References Python: http://www.python.org/ Jython: http://www.jython.org/ IronPython: http://www.codeplex.com/IronPython1.6 Older VersionsOlder versions are still available on the current download page or the old download page. The last version of pySerial’s2.x series was 2.7, compatible with Python 2.3 and newer and partially with early Python 3.x versions.pySerial 1.21 is compatible with Python 2.0 on Windows, Linux and several un*x like systems, MacOSX and Jython.On Windows, releases older than 2.5 will depend on pywin32 (previously known as win32all). WinXP is supportedup to 3.0.1.1.5. References5

pySerial Documentation, Release 3.46Chapter 1. pySerial

CHAPTER2Short introduction2.1 Opening serial portsOpen port at “9600,8,N,1”, no timeout: import serialser serial.Serial('/dev/ttyUSB0') # open serial portprint(ser.name)# check which port was really usedser.write(b'hello')# write a stringser.close()# close portOpen named port at “19200,8,N,1”, 1s timeout: with serial.Serial('/dev/ttyS1', 19200, timeout 1) as ser:.x ser.read()# read one byte.s ser.read(10)# read up to ten bytes (timeout).line ser.readline()# read a '\n' terminated lineOpen port at “38400,8,E,1”, non blocking HW handshaking: ser serial.Serial('COM3', 38400, timeout 0,.parity serial.PARITY EVEN, rtscts 1) s ser.read(100)# read up to one hundred bytes.# or as much is in the buffer2.2 Configuring ports laterGet a Serial instance and configure/open it later: ser serial.Serial() ser.baudrate 19200(continues on next page)7

pySerial Documentation, Release 3.4(continued from previous page) ser.port 'COM1' serSerial id 0xa81c10, open False (port 'COM1', baudrate 19200, bytesize 8, parity 'N', stopbits 1, timeout None, xonxoff 0, rtscts 0) ser.open() ser.is openTrue ser.close() ser.is openFalseAlso supported with context manager:with serial.Serial() as ser:ser.baudrate 19200ser.port 'COM1'ser.open()ser.write(b'hello')2.3 ReadlineBe careful when using readline(). Do specify a timeout when opening the serial port otherwise it could blockforever if no newline character is received. Also note that readlines() only works with a timeout. readlines()depends on having a timeout and interprets that as EOF (end of file). It raises an exception if the port is not openedcorrectly.Do also have a look at the example files in the examples directory in the source distribution or online.Note: The eol parameter for readline() is no longer supported when pySerial is run with newer Python versions(V2.6 ) where the module io is available.2.3.1 EOLTo specify the EOL character for readline() or to use universal newline mode, it is advised to useio.TextIOWrapper:import serialimport ioser serial.serial for url('loop://', timeout 1)sio io.TextIOWrapper(io.BufferedRWPair(ser, ser))sio.write(unicode("hello\n"))sio.flush() # it is buffering. required to get the data out *now*hello sio.readline()print(hello unicode("hello\n"))8Chapter 2. Short introduction

pySerial Documentation, Release 3.42.4 Testing ports2.4.1 Listing portspython -m serial.tools.list ports will print a list of available ports. It is also possible to add a regexpas first argument and the list will only include entries that matched.Note: The enumeration may not work on all operating systems. It may be incomplete, list unavailable ports or maylack detailed descriptions of the ports.2.4.2 Accessing portspySerial includes a small console based terminal program called serial.tools.miniterm. It can be started with python-m serial.tools.miniterm port name (use option -h to get a listing of all options).2.4. Testing ports9

pySerial Documentation, Release 3.410Chapter 2. Short introduction

CHAPTER3pySerial API3.1 Classes3.1.1 Native portsclass serial.Serialinit (port None, baudrate 9600, bytesize EIGHTBITS, parity PARITY NONE, stopbits STOPBITS ONE, timeout None, xonxoff False, rtscts False, write timeout None,dsrdtr False, inter byte timeout None, exclusive None)Parameters port – Device name or None. baudrate (int) – Baud rate such as 9600 or 115200 etc. bytesize – Number of data bits.SEVENBITS, EIGHTBITSPossible values:FIVEBITS, SIXBITS, parity – Enable parity checking. Possible values: PARITY NONE, PARITY EVEN ,PARITY ODD PARITY MARK, PARITY SPACE stopbits – Number of stop bits.Possible values:STOPBITS ONE POINT FIVE, STOPBITS TWOSTOPBITS ONE, timeout (float) – Set a read timeout value. xonxoff (bool) – Enable software flow control. rtscts (bool) – Enable hardware (RTS/CTS) flow control. dsrdtr (bool) – Enable hardware (DSR/DTR) flow control. write timeout (float) – Set a write timeout value. inter byte timeout (float) – Inter-character timeout, None to disable (default).11

pySerial Documentation, Release 3.4 exclusive (bool) – Set exclusive access mode (POSIX only). A port cannot be openedin exclusive access mode if it is already open in exclusive access mode.Raises ValueError – Will be raised when parameter are out of range, e.g. baud rate, data bits. SerialException – In case the device can not be found or can not be configured.The port is immediately opened on object creation, when a port is given. It is not opened when port isNone and a successive call to open() is required.port is a device name: depending on operating system. e.g. /dev/ttyUSB0 on GNU/Linux or COM3 onWindows.The parameter baudrate can be one of the standard values: 50, 75, 110, 134, 150, 200, 300, 600, 1200,1800, 2400, 4800, 9600, 19200, 38400, 57600, 115200. These are well supported on all platforms.Standard values above 115200, such as: 230400, 460800, 500000, 576000, 921600, 1000000, 1152000,1500000, 2000000, 2500000, 3000000, 3500000, 4000000 also work on many platforms and devices.Non-standard values are also supported on some platforms (GNU/Linux, MAC OSX Tiger, Windows).Though, even on these platforms some serial ports may reject non-standard values.Possible values for the parameter timeout which controls the behavior of read(): timeout None: wait forever / until requested number of bytes are received timeout 0: non-blocking mode, return immediately in any case, returning zero or more, up tothe requested number of bytes timeout x: set timeout to x seconds (float allowed) returns immediately when the requestednumber of bytes are available, otherwise wait until the timeout expires and return all bytes that werereceived until then.write() is blocking by default, unless write timeout is set. For possible values refer to the list fortimeout above.Note that enabling both flow control methods (xonxoff and rtscts) together may not be supported. It iscommon to use one of the methods at once, not both.dsrdtr is not supported by all platforms (silently ignored). Setting it to None has the effect that its statefollows rtscts.Also consider using the function serial for url() instead of creating Serial instances directly.Changed in version 2.5: dsrdtr now defaults to False (instead of None)Changed in version 3.0: numbers as port argument are no longer supportedNew in version 3.3: exclusive flagopen()Open port. The state of rts and dtr is applied.Note: Some OS and/or drivers may activate RTS and or DTR automatically, as soon as the port is opened.There may be a glitch on RTS/DTR when rts or dtr are set differently from their default value (True /active).Note: For compatibility reasons, no error is reported when applying rts or dtr fails on POSIX due toEINVAL (22) or ENOTTY (25).12Chapter 3. pySerial API

pySerial Documentation, Release 3.4close()Close port immediately.del ()Destructor, close port when serial port instance is freed.The following methods may raise SerialException when applied to a closed port.read(size 1)Parameters size – Number of bytes to read.Returns Bytes read from the port.Return type bytesRead size bytes from the serial port. If a timeout is set it may return less characters as requested. With notimeout it will block until the requested number of bytes is read.Changed in version 2.5: Returns an instance of bytes when available (Python 2.6 and newer) and strotherwise.read until(expected LF, size None)Parameters expected – The byte string to search for. size – Number of bytes to read.Returns Bytes read from the port.Return type bytesRead until an expected sequence is found (‘\n’ by default), the size is exceeded or until timeout occurs. Ifa timeout is set it may return less characters as requested. With no timeout it will block until the requestednumber of bytes is read.Changed in version 2.5: Returns an instance of bytes when available (Python 2.6 and newer) and strotherwise.write(data)Parameters data – Data to send.Returns Number of bytes written.Return type intRaises SerialTimeoutException – In case a write timeout is configured for the port andthe time is exceeded.Write the bytes data to the port. This should be of type bytes (or compatible such as bytearray ormemoryview). Unicode strings must be encoded (e.g. 'hello'.encode('utf-8').Changed in version 2.5: Accepts instances of bytes and bytearray when available (Python 2.6 and newer)and str otherwise.Changed in version 2.5: Write returned None in previous versions.flush()Flush of file like objects. In this case, wait until all data is written.in waitingGetter Get the number of bytes in the input bufferType int3.1. Classes13

pySerial Documentation, Release 3.4Return the number of bytes in the receive buffer.Changed in version 3.0: changed to property from inWaiting()out waitingGetter Get the number of bytes in the output bufferType intPlatform PosixPlatform WindowsReturn the number of bytes in the output buffer.Changed in version 2.7: (Posix support added)Changed in version 3.0: changed to property from outWaiting()reset input buffer()Flush input buffer, discarding all its contents.Changed in version 3.0: renamed from flushInput()reset output buffer()Clear output buffer, aborting the current output and discarding all that is in the buffer.Note, for some USB serial adapters, this may only flush the buffer of the OS and not all the data that maybe present in the USB part.Changed in version 3.0: renamed from flushOutput()send break(duration 0.25)Parameters duration (float) – Time to activate the BREAK condition.Send break condition. Timed, returns to idle state after given duration.break conditionGetter Get the current BREAK stateSetter Control the BREAK stateType boolWhen set to True activate BREAK condition, else disable. Controls TXD. When active, no transmittingis possible.rtsSetter Set the state of the RTS lineGetter Return the state of the RTS lineType boolSet RTS line to specified logic level. It is possible to assign this value before opening the serial port, thenthe value is applied upon open() (with restrictions, see open()).dtrSetter Set the state of the DTR lineGetter Return the state of the DTR lineType bool14Chapter 3. pySerial API

pySerial Documentation, Release 3.4Set DTR line to specified logic level. It is possible to assign this value before opening the serial port, thenthe value is applied upon open() (with restrictions, see open()).Read-only attributes:nameGetter Device name.Type strNew in version 2.5.ctsGetter Get the state of the CTS lineType boolReturn the state of the CTS line.dsrGetter Get the state of the DSR lineType boolReturn the state of the DSR line.riGetter Get the state of the RI lineType boolReturn the state of the RI line.cdGetter Get the state of the CD lineType boolReturn the state of the CD lineis openGetter Get the state of the serial port, whether it’s open.Type boolNew values can be assigned to the following attributes (properties), the port will be reconfigured, even if it’sopened at that time:portType strRead or write port. When the port is already open, it will be closed and reopened with the new setting.baudrateGetter Get current baud rateSetter Set new baud rateType intRead or write current baud rate setting.bytesize3.1. Classes15

pySerial Documentation, Release 3.4Getter Get current byte sizeSetter Set new byte size. Possible values: FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITSType intRead or write current data byte size setting.parityGetter Get current parity settingSetter Set new parity mode.Possible values:PARITY ODD PARITY MARK, PARITY SPACEPARITY NONE, PARITY EVEN ,Read or write current parity setting.stopbitsGetter Get current stop bit settingSetter Set new stop bit setting.PossibleSTOPBITS ONE POINT FIVE, STOPBITS TWOvalues:STOPBITS ONE,Read or write current stop bit width setting.timeoutGetter Get current read timeout settingSetter Set read timeoutType float (seconds)Read or write current read timeout setting.write timeoutGetter Get current write timeout settingSetter Set write timeoutType float (seconds)Read or write current write timeout setting.Changed in version 3.0: renamed from writeTimeoutinter byte timeoutGetter Get current inter byte timeout settingSetter Disable (None) or enable the inter byte timeoutType float or NoneRead or write current inter byte timeout setting.Changed in version 3.0: renamed from interCharTimeoutxonxoffGetter Get current software flow control settingSetter Enable or disable software flow controlType boolRead or write current software flow control rate setting.rtscts16Chapter 3. pySerial API

pySerial Documentation, Release 3.4Getter Get current hardware flow control settingSetter Enable or disable hardware flow controlType boolRead or write current hardware flow control setting.dsrdtrGetter

2.x series was2.7, compatible with Python 2.3 and newer and partially with early Python 3.x versions. pySerial1.21is compatible with Python 2.0 on Windows, Linux and several un*x like systems, MacOSX and Jython. On Windows, releases older than 2.5 will depend onpywin32(previously known as win32all). WinXP is supported up to 3.0.1. 1.5. References 5

Related Documents:

Installing pySerial into Python Installations This is just a description of how I have managed to get pySerial into the Blender Game Engine and the standalone Pyzo python environments. It is certainly not a guide on how you get pySerial into every python installation. Having said that, chances are this method will work for other python installations.

library. The pyserial library is really useful, but I wanted to do most of my programming in Python. So, I will not be making yet another tutorial for using the pyserial library with Arduino. We will be using the py1rmata and keyboard libraries instead. I will walk you through installing the necessary Python libraries and setting up your Arduino.

While traditional documentation cannot survive the demands of modern development , abandoning documentation altogether equally unviable. An ongoing, automated processes folds modern documentation into the DevOps framework and prevents documentation from becoming a bottleneck to rapid releases. Just as traditional documentation slipstreamed into

The technical documentation for Boeing aircraft model. CSTA/CAMI Workshop #3: Technical Documentation 5 The volumes of documentation make it easy to understand how documentation problems . align company task cards with the aircraft maintenance manual (Rankin, 2008).

Excellent documentation supports excellent care. 4 Documentation Tip Card: General Documentation Tips Dep ar tm e n t o f V et e r a n s Af f a i rs , Al ed a E . L u tz V AMC Cl i n ic a l Do c um e nt a t io n Imp ro v em e n t P r o g ra m Acute vs. Chronic. It’s important to document conditions as Acute or Chronic, or even an

Clinical Documentation Improvement Clinical Documentation Improvement www.aapc.com 1 Introduction Clinical documentation improvement is a prevailing topic in the health care industry. Clinical documentation is the catalyst for coding, billing, and auditing, and is the con-duit for (and provides evidence of) the quality and conti-

terminology in coding (ICD-9-CM) And CPT also Lack of sufficient documentation or no documentation to support the healthcare claim/charges Documentation and charges did not meet medical necessity Documentation that is conflicting, contrasting, or ambiguous Documentation is nonspecific Reimbursements systems are “CODE .

target language effectively, independently and creatively, so that they have a solid basis from which to progress to A Level or employment. Engaging and popular topics . Our specification includes both familiar and new topics that you have told us you like and that motivate your students. Manageable content . Our content has been structured across five themes. This flexible programme of study .