1. 程式人生 > >轉:Python通過pyserial控制串列埠操作

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

https://blog.csdn.net/lovelyaiq/article/details/48101487

 你想通過串列埠讀寫資料,典型場景就是和一些硬體裝置打交道(比如一個機器人或感測器)。儘管你可以通過使用Python內建的I/O模組來完成這個任務,但對於序列通訊最好的選擇是使用 pySerial包 。 這個包的使用非常簡單,先安裝pySerial,使用類似下面這樣的程式碼就能很容易的開啟一個串列埠:

一、用python操作串列埠,首先需要下載相關模組:

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

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

    import serial
    ser = serial . Serial('/dev/tty.usbmodem641', # Device name varies
                          baudrate = 9600,
                          bytesize = 8,
                          parity = 'N',
                          stopbits = 1)

裝置名對於不同的裝置和作業系統是不一樣的。 比如,在Windows系統上,你可以使用0,1等表示的一個裝置來開啟通訊端”COM0”和”COM1”。 一旦埠開啟,那就可以使用read() , readline() 和 write() 函式讀寫資料了。

二,十六進位制顯示

       十六進位制顯示的實質是把接收到的字元轉換成其對應的ASCII碼,然後將ASCII碼值再轉換成十六進位制數顯示出來,這樣就可以顯示特殊字元了。在這裡定義了一個函式,如hexShow(argv),程式碼如下:

[python] view plain copy

import serial  

 
def hexShow(argv):  
    result = ''  
    hLen = len(argv)  
    for i in xrange(hLen):  
        hvol = ord(argv[i])  
        hhex = '%02x'%hvol  
        result += hhex+' '  
    print 'hexShow:',result  
 
t = serial.Serial('com12',9600)  
print t.portstr  
strInput = raw_input('enter some words:')  
n = t.write(strInput)  
print n  
str = t.read(n)  
print str  
hexShow(str)

3,十六進位制傳送

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

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

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

 這裡用到decode函式,

[python] view plain copy

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

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

 

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

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


[python] view plain copy


strSerial = "abc"  
strHex = binascii.b2a_hex(strSerial)  
#print strHex  
strhex = strHex.decode("hex")  
#print strhex  
self.l_serial.write(strhex);  


Short introduction
Open port 0 at "9600,8,N,1", no timeout
[text] view plain copy

    >>> 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
[text] view plain copy

    >>> 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
[text] view plain copy

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

Parameters for the Serial class
[text] view plain copy

    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:
[text] view plain copy

    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
[text] view plain copy

    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:
[text] view plain copy

    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:

[text] view plain copy

    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
[text] view plain copy

    serial.SerialException  


Constants
parity:
[text] view plain copy

        serial.PARITY_NONE  
    serial.PARITY_EVEN  
    serial.PARITY_ODD  

stopbits:
[text] view plain copy

    serial.STOPBITS_ONE  
    al.STOPBITS_TWO  

bytesize:
[text] view plain copy

        serial.FIVEBITS  
    serial.SIXBITS  
    serial.SEVENBITS  
    serial.EIGHTBITS  
---------------------
作者:TiRan_Yang
來源:CSDN
原文:https://blog.csdn.net/lovelyaiq/article/details/48101487
版權宣告:本文為博主原創文章,轉載請附上博文連結!