Python module for Serial Communication -- pyserial

Source: Internet
Author: User
Pyserialoverview

This module encapsulates the access for the serial port. it provides backends for python running on Windows, Linux, BSD (possibly any POSIX compliant system), Jython and ironpython (. net and mono ). the module named "serial" automatically selects the appropriate
Backend.

It is released under a free software license, see license.txt
More details.
(C) 2001-2008 Chris liechti cliechti@gmx.net

The project page on SourceForge and here is the SVN
Repository and the download page.
The homepage is on http://pyserial.sf.net/

Features
  • Same class based interface on all supported platforms
  • Access to the port settings through Python 2.2 + properties
  • Port numbering starts at zero, no need to know the port name in the user program
  • Port string (device name) can be specified if access through numbering is inappropriate
  • Support for different bytesizes, stopbits, 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. they depend on non standard but common packages on Windows (pywin32) and Jython (javacomm ). POSIX (Linux, BSD) uses only modules from the standard Python distribution)
  • The port is set up for binary transmission. No Null Byte stripping, CR-LF translation etc. (which are allowed times enabled for POSIX.) This makes this module universally useful.

Requirements

  • Python 2.2 or newer
  • Pywin32 extensions on Windows
  • "Java Communications" (javacomm) or compatible extension for Java/Jython

Installation

From Source

Extract files from the archive, open a shell/console in that directory and let distutils do the rest:
Python setup. py install

The files get installed in the "lib/Site-packages" directory.

Easy_install

An egg is available from the python package index: http://pypi.python.org/pypi/pyserial
Easy_install pyserial

Windows Installer

There is also a Windows Installer for end users. It is located in the download page
Developers may be interested to get the source archive, because it contains examples and the readme.

Short Introduction

Open Port 0 at "9600,8, N, 1", no timeout

>>> import serial>>> ser = serial.Serial(0)  # open first serial port>>> print ser.portstr       # check which port was really used>>> ser.write("hello")      # write a string>>> ser.close()             # close port

Open named port at "19200,8, N, 1", 1 s timeout

>>> ser = serial.Serial('/dev/ttyS1', 19200, timeout=1)>>> x = ser.read()          # read one byte>>> s = ser.read(10)        # read up to ten bytes (timeout)>>> line = ser.readline()   # read a '\n' terminated line>>> ser.close()

Open second port at "38400,8, E, 1", Non Blocking HW HandShaking

>>> ser = serial.Serial(1, 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 buffer

Get a serial instance and configure/open it later

>>> ser = serial.Serial()>>> ser.baudrate = 19200>>> ser.port = 0>>> serSerial<id=0xa81c10, open=False>(port='COM1', baudrate=19200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)>>> ser.open()>>> ser.isOpen()True>>> ser.close()>>> ser.isOpen()False

Be carefully when using "readline ". do specify a timeout when opening the serial port otherwise it cocould block forever if no newline character is wrongly ed. 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 opened correctly.
Do also have a look at the example files in the examples directory in the source distribution or online.

Examples

Please look in the SVN Repository. There is an example directory where you can find a simple terminal and more.
Http://pyserial.svn.sourceforge.net/viewvc/pyserial/trunk/pyserial/examples/

Parameters for the serial class
ser = serial.Serial(port=None,              # number of device, numbering starts at# zero. if everything fails, the user# can specify a device string, note# that this isn't portable anymore# if no port is specified an unconfigured# an closed serial port object is createdbaudrate=9600,          # baud ratebytesize=EIGHTBITS,     # number of databitsparity=PARITY_NONE,     # enable parity checkingstopbits=STOPBITS_ONE,  # number of stopbitstimeout=None,           # set a timeout value, None for waiting foreverxonxoff=0,              # enable software flow controlrtscts=0,               # enable RTS/CTS flow controlinterCharTimeout=None   # Inter-character timeout, None to disable)

The port is immediately opened on object creation, if a port is given. It is not opened if port is None.
Options for read timeout:

timeout=None            # wait forevertimeout=0               # non-blocking mode (return immediately on read)timeout=x               # set timeout to x seconds (float allowed)

Methods of Serial instances

open()                  # open portclose()                 # close port immediatelysetBaudrate(baudrate)   # change baud rate on an open portinWaiting()             # return the number of chars in the receive bufferread(size=1)            # read "size" characterswrite(s)                # write the string s to the portflushInput()            # flush input buffer, discarding all it's contentsflushOutput()           # flush output buffer, abort outputsendBreak()             # send break conditionsetRTS(level=1)         # set RTS line to specified logic levelsetDTR(level=1)         # set DTR line to specified logic levelgetCTS()                # return the state of the CTS linegetDSR()                # return the state of the DSR linegetRI()                 # return the state of the RI linegetCD()                 # return the state of the CD line

Attributes of Serial instances

Read Only:

portstr                 # device nameBAUDRATES               # list of valid baudratesBYTESIZES               # list of valid byte sizesPARITIES                # list of valid paritiesSTOPBITS                # list of valid stop bit widths

New values can be assigned to the following attributes, the port will be reconfigured, even if it's opened at that time:

port                    # port name/number as set by the userbaudrate                # current baud rate settingbytesize                # byte size in bitsparity                  # parity settingstopbits                # stop bit with (1,2)timeout                 # timeout settingxonxoff                 # if Xon/Xoff flow control is enabledrtscts                  # if hardware flow control is enabled

Exceptions

serial.SerialException

Constants

Parity:

    serial.PARITY_NONEserial.PARITY_EVENserial.PARITY_ODD

Stopbits:

    serial.STOPBITS_ONEserial.STOPBITS_TWO

Bytesize:

    serial.FIVEBITSserial.SIXBITSserial.SEVENBITSserial.EIGHTBITS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.