21.python經過pyserial讀寫串口--2013-06-02

    由於有個須要用有源RFID搞資產管理的項目,須要用python讀取讀卡器的串口內容。因而裝了pyserial模塊,用了下很方便,整理下經常使用功能 php


1、

爲了使用python操做串口,首先須要下載相關模塊:

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

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

2,十六進制顯示 shell

十六進制顯示的實質是把接收到的字符諸葛轉換成其對應的ASCII碼,而後將ASCII碼值再轉換成十六進制數顯示出來,這樣就能夠顯示特殊字符了。 windows

在這裏定義了一個函數,如hexShow(argv),代碼以下: app

[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,十六進制發送 ide

十六進制發送實質是發送十六進制格式的字符串,如'\xaa','\x0b'。重點在於怎麼樣把一個字符串轉換成十六進制的格式,有兩個誤區: svn

1)'\x'+'aa'是不能夠,涉及到轉義符反斜槓 函數

2)'\\x'+'aa'和r'\x'+'aa'也不能夠,這樣的打印結果雖然是\xaa,但賦給變量的值倒是'\\xaa' ui


 這裏用到decode函數, this

[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
>>> 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", 1s 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
>>> ser
Serial<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 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

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 created
baudrate=9600,          # baud rate
bytesize=EIGHTBITS,     # number of databits
parity=PARITY_NONE,     # enable parity checking
stopbits=STOPBITS_ONE,  # number of stopbits
timeout=None,           # set a timeout value, None for waiting forever
xonxoff=0,              # enable software flow control
rtscts=0,               # enable RTS/CTS flow control
interCharTimeout=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 forever
timeout=0               # non-blocking mode (return immediately on read)
timeout=x               # set timeout to x seconds (float allowed)

Methods of Serial instances

open()                  # open port
close()                 # close port immediately
setBaudrate(baudrate)   # change baud rate on an open port
inWaiting()             # return the number of chars in the receive buffer
read(size=1)            # read "size" characters
write(s)                # write the string s to the port
flushInput()            # flush input buffer, discarding all it's contents
flushOutput()           # flush output buffer, abort output
sendBreak()             # send break condition
setRTS(level=1)         # set RTS line to specified logic level
setDTR(level=1)         # set DTR line to specified logic level
getCTS()                # return the state of the CTS line
getDSR()                # return the state of the DSR line
getRI()                 # return the state of the RI line
getCD()                 # return the state of the CD line

Attributes of Serial instances

Read Only:
portstr                 # device name
BAUDRATES               # list of valid baudrates
BYTESIZES               # list of valid byte sizes
PARITIES                # list of valid parities
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:

port                    # port name/number as set by the user
baudrate                # current baud rate setting
bytesize                # byte size in bits
parity                  # parity setting
stopbits                # stop bit with (1,2)
timeout                 # timeout setting
xonxoff                 # if Xon/Xoff flow control is enabled
rtscts                  # if hardware flow control is enabled

Exceptions

serial.SerialException

Constants

parity:
serial.PARITY_NONE
serial.PARITY_EVEN
serial.PARITY_ODD
stopbits:
serial.STOPBITS_ONE
serial.STOPBITS_TWO
bytesize:
serial.FIVEBITS
serial.SIXBITS
serial.SEVENBITS
serial.EIGHTBITS
相關文章
相關標籤/搜索