python通过pyserial读写串口

时间:2021-01-23 22:27:07

转自:http://blog.csdn.net/xiaoxianerqq/article/details/50351632


一个python版串口工具的分享:http://bbs.csdn.net/topics/390535101

api说明文档:http://pythonhosted.org/pyserial/pyserial_api.html

  因为有个需要用有源RFID搞资产管理的项目,需要用python读取读卡器的串口内容。于是装了pyserial模块,用了下很方便,整理下常用功能


一、

为了使用python操作串口,首先需要下载相关模块:

1. pyserial (http://pyserial.wiki.sourceforge.net/pySerial)

2. pywin32 (http://sourceforge.net/projects/pywin32/)

2,十六进制显示

十六进制显示的实质是把接收到的字符诸葛转换成其对应的ASCII码,然后将ASCII码值再转换成十六进制数显示出来,这样就可以显示特殊字符了。

在这里定义了一个函数,如hexShow(argv),代码如下:

[python]  view plain  copy
  1. import serial  
  2.   
  3. def hexShow(argv):  
  4.     result = ''  
  5.     hLen = len(argv)  
  6.     for i in xrange(hLen):  
  7.         hvol = ord(argv[i])  
  8.         hhex = '%02x'%hvol  
  9.         result += hhex+' '  
  10.     print 'hexShow:',result  
  11.   
  12. t = serial.Serial('com12',9600)  
  13. print t.portstr  
  14. strInput = raw_input('enter some words:')  
  15. n = t.write(strInput)  
  16. print n  
  17. str = t.read(n)  
  18. print str  
  19. hexShow(str)  

===================================================================================================================================


3,十六进制发送

十六进制发送实质是发送十六进制格式的字符串,如'\xaa','\x0b'。重点在于怎么样把一个字符串转换成十六进制的格式,有两个误区:

1)'\x'+'aa'是不可以,涉及到转义符反斜杠

2)'\\x'+'aa'和r'\x'+'aa'也不可以,这样的打印结果虽然是\xaa,但赋给变量的值却是'\\xaa'


 这里用到decode函数,

[python]  view plain  copy
  1. list='aabbccddee'  
  2. hexer=list.decode("hex")  
  3. print  hexer  


需要注意一点,如果字符串list的长度为奇数,则decode会报错,可以按照实际情况,用字符串的切片操作,在字符串的开头或结尾加一个'0'

 

假如在串口助手以十六进制发送字符串"abc",那么你在python中则这样操作“self.l_serial.write(”\x61\x62\x63") ”

当然,还有另外一个方法:

[python]  view plain  copy
  1. strSerial = "abc"  
  2. strHex = binascii.b2a_hex(strSerial)  
  3. #print strHex  
  4. strhex = strHex.decode("hex")  
  5. #print strhex  
  6. self.l_serial.write(strhex);  

同样可以达到相同目的。

那么,串口方面的就整理完了


Overview

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  for 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 many 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 
[text]  view plain  copy
  1. >>> import serial  
  2. >>> ser = serial.Serial(0)  # open first serial port  
  3. >>> print ser.portstr       # check which port was really used  
  4. >>> ser.write("hello")      # write a string  
  5. >>> ser.close()             # close port  
Open named port at "19200,8,N,1", 1s timeout 
[text]  view plain  copy
  1. >>> ser = serial.Serial('/dev/ttyS1', 19200, timeout=1)  
  2. >>> x = ser.read()          # read one byte  
  3. >>> s = ser.read(10)        # read up to ten bytes (timeout)  
  4. >>> line = ser.readline()   # read a '\n' terminated line  
  5. >>> ser.close()  
Open second port at "38400,8,E,1", non blocking HW handshaking 
[text]  view plain  copy
  1. >>> ser = serial.Serial(1, 38400, timeout=0,  
  2. ...                     parity=serial.PARITY_EVEN, rtscts=1)  
  3. >>> s = ser.read(100)       # read up to one hundred bytes  
  4. ...                         # or as much is in the buffer  
Get a Serial instance and configure/open it later 
[text]  view plain  copy
  1. >>> ser = serial.Serial()  
  2. >>> ser.baudrate = 19200  
  3. >>> ser.port = 0  
  4. >>> ser  
  5. Serial<id=0xa81c10, open=False>(port='COM1', baudrate=19200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)  
  6. >>> ser.open()  
  7. >>> ser.isOpen()  
  8. True  
  9. >>> ser.close()  
  10. >>> ser.isOpen()  
  11. False  
Be carefully when using "readline". Do specify a timeout when opening the serial port otherwise it could block forever 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 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

[text]  view plain  copy
  1. ser = serial.Serial(  
  2. port=None,              # number of device, numbering starts at  
  3. # zero. if everything fails, the user  
  4. # can specify a device string, note  
  5. # that this isn't portable anymore  
  6. # if no port is specified an unconfigured  
  7. # an closed serial port object is created  
  8. baudrate=9600,          # baud rate  
  9. bytesize=EIGHTBITS,     # number of databits  
  10. parity=PARITY_NONE,     # enable parity checking  
  11. stopbits=STOPBITS_ONE,  # number of stopbits  
  12. timeout=None,           # set a timeout value, None for waiting forever  
  13. xonxoff=0,              # enable software flow control  
  14. rtscts=0,               # enable RTS/CTS flow control  
  15. interCharTimeout=None   # Inter-character timeout, None to disable  
  16. )  
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: 
[text]  view plain  copy
  1. timeout=None            # wait forever  
  2. timeout=0               # non-blocking mode (return immediately on read)  
  3. timeout=x               # set timeout to x seconds (float allowed)  

Methods of Serial instances

[text]  view plain  copy
  1. open()                  # open port  
  2. close()                 # close port immediately  
  3. setBaudrate(baudrate)   # change baud rate on an open port  
  4. inWaiting()             # return the number of chars in the receive buffer  
  5. read(size=1)            # read "size" characters  
  6. write(s)                # write the string s to the port  
  7. flushInput()            # flush input buffer, discarding all it's contents  
  8. flushOutput()           # flush output buffer, abort output  
  9. sendBreak()             # send break condition  
  10. setRTS(level=1)         # set RTS line to specified logic level  
  11. setDTR(level=1)         # set DTR line to specified logic level  
  12. getCTS()                # return the state of the CTS line  
  13. getDSR()                # return the state of the DSR line  
  14. getRI()                 # return the state of the RI line  
  15. getCD()                 # return the state of the CD line  

Attributes of Serial instances

Read Only: 
[text]  view plain  copy
  1. portstr                 # device name  
  2. BAUDRATES               # list of valid baudrates  
  3. BYTESIZES               # list of valid byte sizes  
  4. PARITIES                # list of valid parities  
  5. STOPBITS                # 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: 

[text]  view plain  copy
  1. port                    # port name/number as set by the user  
  2. baudrate                # current baud rate setting  
  3. bytesize                # byte size in bits  
  4. parity                  # parity setting  
  5. stopbits                # stop bit with (1,2)  
  6. timeout                 # timeout setting  
  7. xonxoff                 # if Xon/Xoff flow control is enabled  
  8. rtscts                  # if hardware flow control is enabled  

Exceptions

[text]  view plain  copy
  1. serial.SerialException  

Constants

parity: 
[text]  view plain  copy
  1.     serial.PARITY_NONE  
  2. serial.PARITY_EVEN  
  3. serial.PARITY_ODD  
stopbits: 
[text]  view plain  copy
  1. serial.STOPBITS_ONE  
  2. al.STOPBITS_TWO  
bytesize: 
[text]  view plain  copy
  1.     serial.FIVEBITS  
  2. serial.SIXBITS  
  3. serial.SEVENBITS  
  4. serial.EIGHTBITS