如何在 Python 中訪問序列埠 (RS232)?


要訪問 Python 中的序列埠,請使用 pyserial 模組,這是適用於 Win32、OSX、Linux、BSD、Jython、IronPython 的 Python 序列埠擴充套件。

讓我們看看它的功能 -

  • 透過 Python 屬性訪問埠設定。
  • 支援不同位元組大小、停止位、奇偶校驗和使用 RTS/CTS 和/或 Xon/Xoff 的流控制。
  • 使用或不使用接收超時。
  • 此軟體包中的檔案是 100% 純 Python。
  • 埠已設定為二進位制傳輸。不剝離空位元組、轉換 CR-LF 等。

要安裝 pyserial,請使用 pip

pip install pyserial

首先匯入所需的庫。

import time import serial

然後,配置序列埠連線。

ser = serial.Serial( port='Enter Port', baudrate=9600, parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_TWO, bytesize=serial.SEVENBITS )

使用 input() 獲取鍵盤輸入

input = 1 while 1: # get keyboard input input = input(">> ") if input == 'exit': ser.close() exit()

如果輸入不等於 exit,則使用 write() 將字元傳送到裝置

else: ser.write(input + '\r\n') out = ''

在讀取輸出之前等待一秒鐘。

time.sleep(1) while ser.inWaiting() > 0: out += ser.read(1) if out != '': print ">>" + out

更新於: 2022-09-20

21000+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

馬上開始
廣告
© . All rights reserved.