轉:神奇的python(六)之python的串列埠操作(pyserial)
阿新 • • 發佈:2018-11-15
https://blog.csdn.net/qq_14997473/article/details/80875722:Python學習筆記——串列埠配置以及傳送資料
https://blog.csdn.net/ubuntu14/article/details/75335106:python實現串列埠自動觸發工作
簡介:最近專案突然要使用python串列埠操作,這不,查資料,翻文件,是時候寫一份串列埠操作的簡要用法,
以後有時間可以使用pyqt再寫個介面,弄個串列埠除錯終端。
(1) 安裝pyserial庫
pip install pyserial
(2) pyserial庫常用函式介紹
serial = serial.Serial(‘COM1’, 115200) 開啟COM1並設定波特率為115200,COM1只適用於Windows serial = serial.Serial(‘/dev/ttyS0’, 115200) 開啟/dev/ttyS0並設定波特率為115200, 只適用於Linux print serial .portstr 能看到第一個串列埠的標識 serial .write(“hello”) 往串口裡面寫資料 serial .close() 關閉serial 表示的串列埠 serial .open() 開啟串列埠 data = serial .read(num) 讀num個字元 data= serial .readline() 讀一行資料,以/n結束,要是沒有/n就一直讀,阻塞。 serial .baudrate = 9600 設定波特率 print serial 可檢視當前串列埠的狀態資訊 serial .isOpen() 當前串列埠是否已經開啟 serial.inWaiting() 判斷當前接收的資料 serial.flushInput() 清除輸入緩衝區資料 serial.flushOutput() 中止當前輸出並清除輸出緩衝區資料 --------------------- 作者:識荒者 來源:CSDN 原文:https://blog.csdn.net/absinjun/article/details/81407790版權宣告:本文為博主原創文章,轉載請附上博文連結!
(3) 例項: 獲取從其他串列埠傳送來的資料並回顯
#!/usr/bin/python
# coding=UTF-8
import serial
###################################################
#
# 功 能: 將接收到的資料已hex顯示
# 參 數: 串列埠接受到的資料
# 返 回: 轉換後的資料
#
###################################################
def hexshow(data):
hex_data = '' hLen = len(data)
for i in xrange(hLen):
hvol = ord(data[i])
hhex = '%02x' % hvol
hex_data += hhex+' '
print 'hexshow:', hex_data
###################################################
#
# 功 能: 將需要傳送的字串以hex形式傳送
# 參 數: 待發送的資料
# 返 回: 轉換後的資料
#
###################################################
def hexsend(string_data=''):
hex_data = string_data.decode("hex")
return hex_data
if __name__ == '__main__':
serial = serial.Serial('/dev/ttyS0', 115200)
print serial
if serial.isOpen():
print("open success")
else:
print("open failed")
try:
while True:
count = serial.inWaiting()
if count > 0:
data = serial.read(count)
if data != b'':
print("receive:", data)
serial.write(data)
else:
serial.write(hexsend(data))
except KeyboardInterrupt:
if serial != None:
serial.close() --------------------- 作者:識荒者 來源:CSDN 原文:https://blog.csdn.net/absinjun/article/details/81407790 版權宣告:本文為博主原創文章,轉載請附上博文連結!