1. 程式人生 > >python通過pyserial讀寫串列埠

python通過pyserial讀寫串列埠

轉自: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模組,用了下很方便,整理下常用功能

2,十六進位制顯示

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

在這裡定義了一個函式,如hexShow(argv),程式碼如下:

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

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

3,十六進位制傳送

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

1)'\x'+'aa'是不可以,涉及到轉義符反斜槓

2)'\\x'+'aa'和r'\x'+'aa'也不可以,這樣的列印結果雖然是\xaa,但賦給變數的值卻是'\\xaa'

 這裡用到decode函式,

  1. list='aabbccddee'
  2. hexer=list.decode("hex")  
  3. print  hexer  


需要注意一點,如果字串list的長度為奇數,則decode會報錯,可以按照實際情況,用字串的切片操作,在字串的開頭或結尾加一個'0'

假如在串列埠助手以十六進位制傳送字串"abc",那麼你在python中則這樣操作“self.l_serial.write(”\x61\x62\x63") ”

當然,還有另外一個方法:

  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 [email protected]

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 
  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 
  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 
  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 
  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

  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: 
  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

  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: 
  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: 

  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

  1. serial.SerialException  

Constants

parity: 
  1.     serial.PARITY_NONE  
  2. serial.PARITY_EVEN  
  3. serial.PARITY_ODD  
stopbits: 
  1. serial.STOPBITS_ONE  
  2. al.STOPBITS_TWO  
bytesize: 
  1.     serial.FIVEBITS  
  2. serial.SIXBITS  
  3. serial.SEVENBITS  
  4. serial.EIGHTBITS  

相關推薦

python通過pyserial串列

轉自:http://blog.csdn.net/xiaoxianerqq/article/details/50351632 一個python版串列埠工具的分享:http://bbs.csdn.net/topics/390535101 api說明文件:http://pyth

ros系統下通過pyserial模組實現串列通訊(Python

經過幾天的摸索終於實現了: 在ros系統下,訂閱Twist/cmd_vel 訊息,經過USB轉串列埠通訊,實現了通過燈帶實時反映小車(差速)執行狀態的功能。 通訊部分主要依賴pyserial模組的功能實現。 #!/usr/bin/env python #codi

串列的實現(一)

Windows開啟串列埠,讀寫串列埠,自動識別串列埠 該串列埠讀寫是採用非同步方式,即非阻塞模式進行讀寫串列埠 串列埠名形如: "COM3", "COM4", "COM22"等 其中COM1至COM9能成功開啟,但是COM10及以上開啟都是失敗的,需要特殊處理 及COM10

JavaDemo——java使用RXTX串列

對RXTX的介紹,copy自https://blog.csdn.net/u011728105/article/details/48085615RXTX RXTX是一個提供串列埠和並口通訊的開源java類庫,由該專案釋出的檔案均遵循LGPL協議。 RXTX專案提供了Wind

轉:Python通過pyserial控制串列操作

https://blog.csdn.net/lovelyaiq/article/details/48101487  你想通過串列埠讀寫資料,典型場景就是和一些硬體裝置打交道(比如一個機器人或感測器)。儘管你可以通過使用Python內建的I/O模組來完成這個任務,但對於序列通訊最好的選擇是使用 py

C++、Python文件、定位等操作

末尾 wid 字節 body log 大於 內容 app closed 一、C++文件流 1、文件流對象   C++中的文件流對象(fstream)是繼承自iostream的一個類,其關系如下: fstream可以用IO運算符(>>和<<)

通過file功能實現文件復制粘貼功能

文件屬性 復制 ring 數組 exist tro strong log [] 通過file讀寫功能實現文件復制粘貼功能 import java.io.*; public class Copy1M { public static void main(Str

[Python 3系列]文件

file文件路徑文件有兩個關鍵屬性:“文件名”和“路徑”。路徑指明了文件在計算機上的位置。在windows上,路徑書寫使用倒斜杠作為文件夾之間的分隔符。但在OS X和Linux上,使用正斜杠作為它們的路徑分隔符。如果想要程序運行在所有操作系統上,在編寫python腳本時,必須處理這兩種情況。如果將單個文件和路

python--文件

全部 例如 strip 描述符 等等 比較 可能 list 引入 文件讀寫 寫文件是最常見的IO操作。Python內置了讀寫文件的函數,用法和C是兼容的。 讀寫文件前,我們先必須了解一下,在磁盤上讀寫文件的功能都是由操作系統提供的,現代操作系統不允許普通的程序直接操作磁盤,

python文件

讀寫 python文件 文件讀寫 rip nes nbsp 一個 類型 read f=open(file,mod) str1=f.readline() //讀取一行的內容 str=f.readlines() //讀取剩余的全部內容 當mod設為“a+”使,無法讀取文件

python操作Excel(使用xlrd和xlrt)

bold 新建 例子 ref boolean 取整 設置 xfs .py 包下載地址:https://pypi.python.org/pypi/xlrd 導入 import xlrd 打開excel data = xlrd.open_workbook(‘demo.xl

python ConfigParser 配置

file logs 整型 csdn 文件的 設置 bsp 記得 列表 我們寫程序的時候一般都會寫程序包的時候,很少硬編碼寫在一起,這有個很好的配置文件包。 參考 ConfigParser 和 ConfigParser 的使用 一、ConfigParser 簡介 Con

python文件 - 文件r+ open實際表現

打開 而不是 imp 指定 tell int 文件打開 aid end 先說結論: 文件r+ open:   1. write()不能實現插入寫,它總是覆蓋寫或附加寫;   2. 如果文件一打開即write(),則從開頭覆蓋寫;   3. 如果文件一打開,用f.seek()

python文件-----csv的使用

imp index索引 lose 列表 年齡 size 一個 遍歷 數據 首先來看看原始的讀取: f= open(file,‘r‘) stat = f.readlines() print(stat) 輸出的結構是一個整體的列表。 [‘姓名,性別,年齡,愛好,人脈,學習

python 操作excel

exc python ng- gpo ati ref github -c div 【轉】http://wenqiang-china.github.io/2016/05/13/python-opetating-excel/python 操作excel讀寫

python文件操作

python文件讀寫 python基礎 對文件操作的流程:1、打開文件,得到文件句柄2、通過句柄對文件進行操作3、關閉文件我們拿/etc/passwd文件進行測試1、打開文件,"f"變量得到的是文件句柄>>> f = open("/tmp/passwd&

002-Go通過ioutil 文件

pos 讀寫 class 內容 log 讀取 () int 格式 1、讀取文件內容 package main import( "io/ioutil" "fmt" ) func main(){ b,err := ioutil.ReadFile("

使用Python對Access操作

microsoft win32com 更新 mov break 執行sql update 模塊 print 學習Python的過程中,我們會遇到Access的讀寫問題,這時我們可以利用win32.client模塊的COM組件訪問功能,通過ADODB操作Access的文件。

python-文件

r+ seek rec odi 版本 dir 是不是 see 文件讀寫 k in data: #判斷k是不是在文件裏f = open (‘ filename‘,encoding=‘utf-8‘) #打開文件 Python 2.7版本中是 File()print(‘rea

python 文件

truncate 只讀 err cat 讀取 圖片 就是 緩沖 png python文件讀寫是以open()函數的參數來決定是讀寫 open(file, mode=‘r‘, buffering=None, encoding=None, errors=None, newlin