Python使用pyserial進(jìn)行串口通信的實(shí)例
更新時(shí)間:2019年07月02日 10:41:15 作者:kingokay
今天小編就為大家分享一篇Python使用pyserial進(jìn)行串口通信的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
安裝pyserial
pip install pyserial
查看可用的端口
# coding:utf-8 import serial.tools.list_ports plist = list(serial.tools.list_ports.comports()) if len(plist) <= 0: print("沒(méi)有發(fā)現(xiàn)端口!") else: plist_0 = list(plist[0]) serialName = plist_0[0] serialFd = serial.Serial(serialName, 9600, timeout=60) print("可用端口名>>>", serialFd.name)
所發(fā)十六進(jìn)制需轉(zhuǎn)換為以下格式
# 所發(fā)十六進(jìn)制字符串010591F50000F104 cmd = [0x01, 0x05, 0x91, 0xF5, 0x00, 0x00, 0xF1, 0x04]
串口通信
Windows下端口為COM*, Ubuntu下為/dev/ttyS0 import serial class Ser(object): def __init__(self): # 打開(kāi)端口 self.port = serial.Serial(port='COM4', baudrate=9600, bytesize=8, parity='E', stopbits=1, timeout=2) # 發(fā)送指令的完整流程 def send_cmd(self, cmd): self.port.write(cmd) response = self.port.readall() response = self.convert_hex(response) return response # 轉(zhuǎn)成16進(jìn)制的函數(shù) def convert_hex(self, string): res = [] result = [] for item in string: res.append(item) for i in res: result.append(hex(i)) return result
以上這篇Python使用pyserial進(jìn)行串口通信的實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python 調(diào)用 C++ 傳遞numpy 數(shù)據(jù)詳情
這篇文章主要介紹了Python 調(diào)用 C++ 傳遞numpy 數(shù)據(jù)詳情,文章主要分為兩部分,c++代碼和python代碼,代碼分享詳細(xì),需要的小伙伴可以參考一下,希望對(duì)你有所幫助2022-03-03Python中subprocess.run()執(zhí)行命令、檢查狀態(tài)與結(jié)果處理深入理解
這篇文章主要介紹了Python中subprocess.run()執(zhí)行命令、檢查狀態(tài)與結(jié)果處理的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2025-04-04