Python 串口通信的實現(xiàn)
串口通信是指外設和計算機間,通過數(shù)據(jù)信號線 、地線、控制線等,按位進行傳輸數(shù)據(jù)的一種通訊方式。這種通信方式使用的數(shù)據(jù)線少,在遠距離通信中可以節(jié)約通信成本,但其傳輸速度比并行傳輸?shù)?。串口是計算機上一種非常通用的設備通信協(xié)議。pyserial模塊封裝了python對串口的訪問,為多平臺的使用提供了統(tǒng)一的接口。
安裝:
pip3 install pyserial
測試:
兩個CH340 (TTL轉串口模塊)接入到PC串口上,通過Python進行數(shù)據(jù)交互:

簡單串口程序實現(xiàn):
import serial #導入模塊
try:
#端口,GNU / Linux上的/ dev / ttyUSB0 等 或 Windows上的 COM3 等
portx="COM3"
#波特率,標準值之一:50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
bps=115200
#超時設置,None:永遠等待操作,0為立即返回請求結果,其他值為等待超時時間(單位為秒)
timex=5
# 打開串口,并得到串口對象
ser=serial.Serial(portx,bps,timeout=timex)
# 寫數(shù)據(jù)
result=ser.write("我是東小東".encode("gbk"))
print("寫總字節(jié)數(shù):",result)
ser.close()#關閉串口
except Exception as e:
print("---異常---:",e)
獲取可用串口列表:
import serial #導入模塊
import serial.tools.list_ports
port_list = list(serial.tools.list_ports.comports())
print(port_list)
if len(port_list) == 0:
print('無可用串口')
else:
for i in range(0,len(port_list)):
print(port_list[i])
十六進制處理:
import serial #導入模塊
try:
portx="COM3"
bps=115200
#超時設置,None:永遠等待操作,0為立即返回請求結果,其他值為等待超時時間(單位為秒)
timex=None
ser=serial.Serial(portx,bps,timeout=timex)
print("串口詳情參數(shù):", ser)
#十六進制的發(fā)送
result=ser.write(chr(0x06).encode("utf-8"))#寫數(shù)據(jù)
print("寫總字節(jié)數(shù):",result)
#十六進制的讀取
print(ser.read().hex())#讀一個字節(jié)
print("---------------")
ser.close()#關閉串口
except Exception as e:
print("---異常---:",e)
其他細節(jié)補充:
import serial #導入模塊
try:
#端口,GNU / Linux上的/ dev / ttyUSB0 等 或 Windows上的 COM3 等
portx="COM3"
#波特率,標準值之一:50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
bps=115200
#超時設置,None:永遠等待操作,0為立即返回請求結果,其他值為等待超時時間(單位為秒)
timex=5
# 打開串口,并得到串口對象
ser=serial.Serial(portx,bps,timeout=timex)
print("串口詳情參數(shù):", ser)
print(ser.port)#獲取到當前打開的串口名
print(ser.baudrate)#獲取波特率
result=ser.write("我是東小東".encode("gbk"))#寫數(shù)據(jù)
print("寫總字節(jié)數(shù):",result)
#print(ser.read())#讀一個字節(jié)
# print(ser.read(10).decode("gbk"))#讀十個字節(jié)
#print(ser.readline().decode("gbk"))#讀一行
#print(ser.readlines())#讀取多行,返回列表,必須匹配超時(timeout)使用
#print(ser.in_waiting)#獲取輸入緩沖區(qū)的剩余字節(jié)數(shù)
#print(ser.out_waiting)#獲取輸出緩沖區(qū)的字節(jié)數(shù)
#循環(huán)接收數(shù)據(jù),此為死循環(huán),可用線程實現(xiàn)
while True:
if ser.in_waiting:
str=ser.read(ser.in_waiting ).decode("gbk")
if(str=="exit"):#退出標志
break
else:
print("收到數(shù)據(jù):",str)
print("---------------")
ser.close()#關閉串口
except Exception as e:
print("---異常---:",e)
部分封裝:
其中讀數(shù)據(jù)的封裝方法并不是很好用,使用的話又得循環(huán)接收,這樣反而更加復雜了
import serial #導入模塊
import threading
STRGLO="" #讀取的數(shù)據(jù)
BOOL=True #讀取標志位
#讀數(shù)代碼本體實現(xiàn)
def ReadData(ser):
global STRGLO,BOOL
# 循環(huán)接收數(shù)據(jù),此為死循環(huán),可用線程實現(xiàn)
while BOOL:
if ser.in_waiting:
STRGLO = ser.read(ser.in_waiting).decode("gbk")
print(STRGLO)
#打開串口
# 端口,GNU / Linux上的/ dev / ttyUSB0 等 或 Windows上的 COM3 等
# 波特率,標準值之一:50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
# 超時設置,None:永遠等待操作,0為立即返回請求結果,其他值為等待超時時間(單位為秒)
def DOpenPort(portx,bps,timeout):
ret=False
try:
# 打開串口,并得到串口對象
ser = serial.Serial(portx, bps, timeout=timeout)
#判斷是否打開成功
if(ser.is_open):
ret=True
threading.Thread(target=ReadData, args=(ser,)).start()
except Exception as e:
print("---異常---:", e)
return ser,ret
#關閉串口
def DColsePort(ser):
global BOOL
BOOL=False
ser.close()
#寫數(shù)據(jù)
def DWritePort(ser,text):
result = ser.write(text.encode("gbk")) # 寫數(shù)據(jù)
return result
#讀數(shù)據(jù)
def DReadPort():
global STRGLO
str=STRGLO
STRGLO=""#清空當次讀取
return str
if __name__=="__main__":
ser,ret=DOpenPort("COM6",115200,None)
if(ret==True):#判斷串口是否成功打開
count=DWritePort(ser,"我是東小東,哈哈")
print("寫入字節(jié)數(shù):",count)
#DReadPort() #讀串口數(shù)據(jù)
#DColsePort(ser) #關閉串口
查看所有串口
import serial.tools.list_ports
port_list = list(serial.tools.list_ports.comports())
if len(port_list) == 0:
print('找不到串口')
else:
for i in range(0,len(port_list)):
print(port_list[i])
參考:
https://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.open
以上就是Python 串口通信的實現(xiàn)的詳細內容,更多關于python 串口通信的資料請關注腳本之家其它相關文章!
相關文章
Pythony運維入門之Socket網(wǎng)絡編程詳解
這篇文章主要介紹了Pythony運維入門之Socket網(wǎng)絡編程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04
python數(shù)學建模是加深Numpy和Pandas學習
這篇文章主要介紹了python數(shù)學建模是加深Numpy和Pandas學習,緊接上一篇學習內容展開Numpy更多相關內容,需要的小伙伴可以參考一下2022-07-07
使用pycallgraph分析python代碼函數(shù)調用流程以及框架解析
這篇文章主要介紹了使用pycallgraph分析python代碼函數(shù)調用流程以及框架解析,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03

