Python 串口通信的實現(xiàn)
串口通信是指外設(shè)和計算機(jī)間,通過數(shù)據(jù)信號線 、地線、控制線等,按位進(jìn)行傳輸數(shù)據(jù)的一種通訊方式。這種通信方式使用的數(shù)據(jù)線少,在遠(yuǎn)距離通信中可以節(jié)約通信成本,但其傳輸速度比并行傳輸?shù)?。串口是計算機(jī)上一種非常通用的設(shè)備通信協(xié)議。pyserial模塊封裝了python對串口的訪問,為多平臺的使用提供了統(tǒng)一的接口。
安裝:
pip3 install pyserial
測試:
兩個CH340 (TTL轉(zhuǎn)串口模塊)接入到PC串口上,通過Python進(jìn)行數(shù)據(jù)交互:
簡單串口程序?qū)崿F(xiàn):
import serial #導(dǎo)入模塊try: #端口,GNU / Linux上的/ dev / ttyUSB0 等 或 Windows上的 COM3 等 portx='COM3' #波特率,標(biāo)準(zhǔn)值之一:50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200 bps=115200 #超時設(shè)置,None:永遠(yuǎn)等待操作,0為立即返回請求結(jié)果,其他值為等待超時時間(單位為秒) timex=5 # 打開串口,并得到串口對象 ser=serial.Serial(portx,bps,timeout=timex) # 寫數(shù)據(jù) result=ser.write('我是東小東'.encode('gbk')) print('寫總字節(jié)數(shù):',result) ser.close()#關(guān)閉串口except Exception as e: print('---異常---:',e)
獲取可用串口列表:
import serial #導(dǎo)入模塊import serial.tools.list_portsport_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])
十六進(jìn)制處理:
import serial #導(dǎo)入模塊try: portx='COM3' bps=115200 #超時設(shè)置,None:永遠(yuǎn)等待操作,0為立即返回請求結(jié)果,其他值為等待超時時間(單位為秒) timex=None ser=serial.Serial(portx,bps,timeout=timex) print('串口詳情參數(shù):', ser) #十六進(jìn)制的發(fā)送 result=ser.write(chr(0x06).encode('utf-8'))#寫數(shù)據(jù) print('寫總字節(jié)數(shù):',result) #十六進(jìn)制的讀取 print(ser.read().hex())#讀一個字節(jié) print('---------------') ser.close()#關(guān)閉串口except Exception as e: print('---異常---:',e)
其他細(xì)節(jié)補(bǔ)充:
import serial #導(dǎo)入模塊try: #端口,GNU / Linux上的/ dev / ttyUSB0 等 或 Windows上的 COM3 等 portx='COM3' #波特率,標(biāo)準(zhǔn)值之一:50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200 bps=115200 #超時設(shè)置,None:永遠(yuǎn)等待操作,0為立即返回請求結(jié)果,其他值為等待超時時間(單位為秒) timex=5 # 打開串口,并得到串口對象 ser=serial.Serial(portx,bps,timeout=timex) print('串口詳情參數(shù):', ser) print(ser.port)#獲取到當(dāng)前打開的串口名 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'):#退出標(biāo)志 break else:print('收到數(shù)據(jù):',str) print('---------------') ser.close()#關(guān)閉串口except Exception as e: print('---異常---:',e)
部分封裝:
其中讀數(shù)據(jù)的封裝方法并不是很好用,使用的話又得循環(huán)接收,這樣反而更加復(fù)雜了
import serial #導(dǎo)入模塊import threadingSTRGLO='' #讀取的數(shù)據(jù)BOOL=True #讀取標(biāo)志位#讀數(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 等# 波特率,標(biāo)準(zhǔn)值之一:50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200# 超時設(shè)置,None:永遠(yuǎn)等待操作,0為立即返回請求結(jié)果,其他值為等待超時時間(單位為秒)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#關(guān)閉串口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=''#清空當(dāng)次讀取 return strif __name__=='__main__': ser,ret=DOpenPort('COM6',115200,None) if(ret==True):#判斷串口是否成功打開 count=DWritePort(ser,'我是東小東,哈哈') print('寫入字節(jié)數(shù):',count) #DReadPort() #讀串口數(shù)據(jù) #DColsePort(ser) #關(guān)閉串口
查看所有串口
import serial.tools.list_portsport_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)的詳細(xì)內(nèi)容,更多關(guān)于python 串口通信的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. python 如何在 Matplotlib 中繪制垂直線2. bootstrap select2 動態(tài)從后臺Ajax動態(tài)獲取數(shù)據(jù)的代碼3. ASP常用日期格式化函數(shù) FormatDate()4. python中@contextmanager實例用法5. html中的form不提交(排除)某些input 原創(chuàng)6. CSS3中Transition屬性詳解以及示例分享7. js select支持手動輸入功能實現(xiàn)代碼8. 如何通過python實現(xiàn)IOU計算代碼實例9. 開發(fā)效率翻倍的Web API使用技巧10. vue使用moment如何將時間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時間格式
