class - pyserial

最後更新: 202-12-11

 


安裝

python setup.py install

  • copying build/lib.linux-x86_64-2.6/serial/win32.py -> /usr/local/lib/python2.6/dist-packages/serial
  • byte-compiling /usr/local/lib/python2.6/dist-packages/serial/rfc2217.py to rfc2217.pyc
  • copying build/scripts-2.6/miniterm.py -> /usr/local/bin

Listing ports:

python -m serial.tools.list_ports

/dev/ttyS0
1 ports found

Port Example

USB: /dev/ttyUSB0

 

工具 - Miniterm

python -m serial.tools.miniterm <port name> -h

miniterm.py -h

usage:

miniterm.py [options] [port [baudrate]]  <-- default: 9600

  • --parity=PARITY       set parity, one of [N, E, O, S, M], default=N
  • --rtscts              enable RTS/CTS flow control (default off)
  • --xonxoff             enable software flow control (default off)
--- Miniterm on /dev/ttyUSB0: 9600,8,N,1 ---
--- Quit: Ctrl+]  |  Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---

 


Single-port TCP/IP - serial bridge

 

Usage:

rfc2217_server.py [options] port

Options:

  • --spy                             # 監視 in/out
  • -p SERIAL_PORT
  • -b BAUDRATE
  • -P TCP_PORT

code:

# Open port 0 at 9600,8,N,1s

>>> import serial
>>> ser = serial.Serial(0)  # open first serial port
>>> print ser.portstr       # check which port was really used
>>> tyte_to_write = 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()

在執行時更改 baudrate 及 port

>>> ser = serial.Serial()
>>> ser.baudrate = 19200
>>> ser.port = 0
>>> ser

Output:

Serial<id=0xa81c10, open=False>(port='COM1', baudrate=19200, bytesize=8,
parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)

測試 port 的 open 及 close:

>>> ser.open()
>>> ser.isOpen()
True
>>> ser.close()
>>> ser.isOpen()
False

 


non-blocking receiver

 

while True:
    data = ser.read(1)
    if len(data) > 0:
        print 'Got:', data

    sleep(0.5)
    print 'not blocked'

 


io.TextIOWrapper

 

# To specify the EOL character for readline() or to use universal newline mode

import serial
import io
ser = serial.serial_for_url('loop://', timeout=1)
sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser))

# 寫東西
sio.write(unicode("hello\n"))
sio.flush()

# 讀
hello = sio.readline()
print hello == unicode("hello\n")

# io Core tools for working with streams

http://docs.python.org/2/library/io.html

 


技巧

 

A delay after opening the port, before the first write(), is recommended in this situation.

E.g. a time.sleep(1)

 

 

附加檔案大小
enhancedserial.py_.txt2.12 KB

Creative Commons license icon Creative Commons license icon