Getting Started with pySerial
pySerial is a Python API module to access the serial port. pySerial provides a uniform API across multiple operating systems, including Windows, Linux, and BSD. This article explains how to use the pySerial API to access a serial port.
Installation
The following procedure installs pySerial in GNU/Linux
Systems. pyserial
installs a package serial
and can be used from
python.
import serial
Download pyserial from http://pypi.python.org/pypi/pyserial. Extract the archive file and run:
python setup.py install
for Python 3.x:
python3 setup.py install
From the Python Package Index
Alternative installation method
pip pyserial
or
easy_install -U pyserial
Using pySerial API
For using this package in python, we have to import a module called
serial
. Enter in to python Interpreter by running the command python
user~$ python
Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import serial # It imports all the methods used inside serial module
>>>
Opening a Serial Port
Create a Serial Object using Serial()
:
>>> import serial
>>> ser = serial.Serial('/dev/ttyUSB0')
>>> ser.portstr
'/dev/ttyUSB0'
>>> ser
Serial<id=0x7fe78c12b9d0, open=True>(port='/dev/ttyUSB0', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=False, rtscts=False, dsrdtr=False)
>>>
-
The opened serial port is
/dev/ttyUSB0
-
You can see the serial object was created with default baudrate 9600.
-
Which has 8 bit mask, no parity is None and 1 stop bit
-
Timeout is 0
-
Software flow control off (xonxoff = false)
-
Hardware flow control off (rtscts = False, dsrdtr = False)
Examples to Change serial attributes
We can change the properties of the serial port at any time after opening the port.
-
dir(ser)
will show all attributes for theser
object -
help(serial.Serial)
will show the man page for serial API’s
>>> dir(ser)
['BAUDRATES', 'BYTESIZES', 'PARITIES', 'STOPBITS','_IOBase__closed', '_SETTINGS',
'__abstractmethods__', '__class__', '__del__', '__delattr__', '__dict__', '__doc__',
'__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__',
'__iter__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__',
'_abc_cache', '_abc_negative_cache', '_abc_negative_cache_version', '_abc_registry', '
_baudrate', '_bytesize', '_checkClosed', '_checkReadable', '_checkSeekable',
'_checkWritable', '_dsrdtr', '_interCharTimeout', '_isOpen', '_parity', '_port',
'_reconfigurePort', '_rtscts', '_stopbits', '_timeout', '_unsupported', '_writeTimeout',
'_xonxoff', 'applySettingsDict', 'baudrate', 'bytesize', 'close', 'closed',
'drainOutput', 'dsrdtr', 'fd', 'fileno', 'flowControl', 'flush', 'flushInput',
'flushOutput', 'getBaudrate', 'getByteSize', 'getCD', 'getCTS', 'getDSR',
'getDsrDtr', 'getInterCharTimeout', 'getParity', 'getPort', 'getRI', 'getRtsCts',
'getSettingsDict', 'getStopbits', 'getSupportedBaudrates', 'getSupportedByteSizes',
'getSupportedParities', 'getSupportedStopbits', 'getTimeout', 'getWriteTimeout',
'getXonXoff', 'inWaiting', 'interCharTimeout', 'isOpen', 'isatty', 'makeDeviceName',
'name', 'next', 'nonblocking', 'open', 'parity', 'port', 'portstr', 'read', 'readable',
'readall', 'readinto', 'readline', 'readlines', 'rtscts', 'seek', 'seekable', 'sendBreak',
'setBaudrate', 'setBreak', 'setByteSize', 'setDTR', 'setDsrDtr', 'setInterCharTimeout',
'setParity', 'setPort', 'setRTS', 'setRtsCts', 'setStopbits', 'setTimeout', 'setWriteTimeout',
'setXonXoff', 'stopbits', 'tell', 'timeout', 'truncate', 'writable', 'write',
'writeTimeout', 'writelines', 'xonxoff']
>>> ser.timeout = 1
>>> ser.baudrate = 115200
>>> ser.port = '/dev/ttyUSB1'
>>> ser.xonxoff=True
-
You can see the modifed serial attributes by using
ser
. -
Like wise you can modify all the attributes as per the requirement
>>> ser
Serial<id=0x7f1eea35a9d0, open=True>(port='/dev/ttyUSB1', baudrate=115200,
bytesize=8, parity='N', stopbits=1, timeout=1, xonxoff=True, rtscts=False, dsrdtr=False)
>>>
Writing Data
-
write(data)
will write the string data to the port and returns no. of bytes sent.
>>> ser.write('+++')
3
>>>
Reading Data
Reading of data is possible by using
-
read(size)
will read data from serial port -
A time out can be set, so that within that time if no characters are received,
read()
will return an empty string. If timout isNone
,read()
won’t return until it receives the no. of bytes specified as argument.
>>> ser.timeout = 1
>>> ser.read(1)
''
>>> ser.timeout = None
>>> ser.read(1)
|
-
readline(size)
will read a line until it sees a EOL(end of line \n) character. -
It also read up to the size of bytes.
-
Suppose the serial device sending a data \r\nSerial Upload\r\n
>>> ser.readline() # return the string when it sees new line character or EOL
'\r\n'
>>> ser.readline() # return the string when it sees new line character or EOL
'Serial Upload\r\n'
>>> ser.readline() # looks for new line character (serial port is blocked) Since time out is None
|
-
readlines()
, will return all lines received within the specified time out. -
The
size
argument is ignored. -
Consider the same string used in
readline()
\r\nSerial Upload\r\n
>>> ser.timeout = 1
>>> ser.readlines() # It will return only the no of bytes read within the specified timeout.
['', 'Ser']
>>>
Closing the Serial Port
After finishing read and write operation. We have to prperly close the serial port.
-
close()
will close the serial port immediately.
>>> ser.close()
>>>
Concluding Notes
Hope this article will help you to kick start using serial API to test your devices which is using serial port.
Get in touch with us at sales@zilogic.com for commercial Embedded Linux related services.