安裝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è)參考,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
