网站首页 文章专栏 Python 串口
Python 串口
创建于:2021-07-04 08:48:12 更新于:2024-12-04 08:26:09 羽瀚尘 719
Python Python

python 串口

2021 更新 2

  • 清空缓冲区
    写入或者读出,调用 flush 确保完成
    ser.flush()

  • 获得接收缓冲区字符数

    count = ser.inWaiting()
    
    • 清空接收缓冲区
      python ser.flushInput()
  • 及时关闭串口

    try:
    main()
    except KeyboardInterrupt:
    if ser != None:
        ser.close()
    
    • 列出可用串口
      python import serial.tools.list_ports plist = list(serial.tools.list_ports.comports()) if len(plist) <= 0: print("没有发现端口!") else: plist_0 = list(plist[0]) serialName = plist_0[0] serialFd = serial.Serial(serialName, 9600, timeout=60) print("可用端口名>>>", serialFd.name)
  • 程序退出回调

https://learnku.com/docs/pymotw/atexit-program-shutdown-callbacks/3458
atexit — 程序关闭时回调

  • mock 串口
import pty
import os
import select
 
def mkpty():
    master1, slave = pty.openpty()
    slaveName1 = os.ttyname(slave)
    master2, slave = pty.openpty()
    slaveName2 = os.ttyname(slave)
    print '\nslave device names: ', slaveName1, slaveName2
    return master1, master2
 
if __name__ == "__main__":
    master1, master2 = mkpty()
    while True:
        rl, wl, el = select.select([master1, master2], [], [], 1)
        for master in rl:
            data = os.read(master, 128)
            print "read %d data." %len(data)
            if master == master1:
                os.write(master2, data)
            else:
                os.write(master1, data)