亚洲精品久久久久久第一页-人妻少妇精彩视品一区二区三区-91国产自拍免费视频-免费一级a在线播放视频正片-少妇天天日天天射天天爽-国产大屁股喷水视频在线观看-操美女骚穴抽插性爱视频-亚洲 欧美 中文字幕 丝袜-成人免费无码片在线观看

python串口通信的接收與發(fā)送 python串口發(fā)送十六進(jìn)制數(shù)


python串口通信的接收與發(fā)送 python串口發(fā)送十六進(jìn)制數(shù)

文章插圖
1、這節(jié)課我們來(lái)實(shí)現(xiàn)串口的寫(xiě)入與接收,同樣查看pyserial的在線(xiàn)文檔,查看數(shù)據(jù)的寫(xiě)入與發(fā)送 。
2、Write方法,文檔中表明,寫(xiě)的方法只能寫(xiě)bytes,所以我們?cè)赾om.py,增加兩個(gè)函數(shù)用來(lái)寫(xiě)數(shù)據(jù):
def comwritebytes(self,b):
wlen=self.com.write(b)
return wlen
def comwritestring(self,b):
wlen=self.com.write(b.encode(“utf-8”))
return wlen
一個(gè)用來(lái)直接發(fā)送bytes數(shù)據(jù),另一個(gè)將string數(shù)據(jù)轉(zhuǎn)為bytes再發(fā)送,接著我們需要更新下主界面:
增加一個(gè)line edite命名為txt_send,一個(gè)checkbox命名為cb_send,一個(gè)發(fā)送與接收按鈕,分別命名為btn_send、btn_receive.
我們串口發(fā)送的代碼已經(jīng)完成了,那么我們將功能增加到界面中來(lái) 。
1、在界面中發(fā)送string類(lèi)型的數(shù)據(jù),先更新最新的界面代碼,在cmd中輸入指令:pyuic5 -o uart.py uart.ui
接著在uartform.py中增加代碼:
def WriteData(self):
try:
msg=self.new.txt_send.text()
cbcheck=self.new.cb_send.checkState()
if cbcheck:
pass
else:
self.com.comwritestring(msg)
except Exception as e:
self.ShowBox(str(e))
當(dāng)cb_send沒(méi)有被選中的時(shí)候,也就是默認(rèn)發(fā)送string類(lèi)型,如果我要發(fā)送hex數(shù)據(jù),如:01 ff 00 12這類(lèi)數(shù)據(jù)的時(shí)候呢?
我們來(lái)實(shí)現(xiàn)一個(gè)將hex數(shù)據(jù)轉(zhuǎn)為bytes的代碼:
def HexToBytes(self):
bl=[]
try:
text=self.new.txt_send.text()
slist=text.split(” “)
for e in slist:
b=int(e,16)
bl.append(b)
except Exception as e:
self.ShowBox(str(e))
return bl
將發(fā)送代碼更新為:
def WriteData(self):
try:
slen=0
msg=self.new.txt_send.text()
cbcheck=self.new.cb_send.checkState()
if cbcheck:
bl=self.HexToBytes()
slen=self.com.comwritebytes(bl)
else:
slen=self.com.comwritestring(msg)
self.ShowMsg(“發(fā)送數(shù)據(jù)長(zhǎng)度”+str(slen))
except Exception as e:
self.ShowBox(str(e))
將函數(shù)綁定到按鈕:
self.new.btn_send.clicked.connect(self.WriteData)
運(yùn)行一下,不打開(kāi)串口發(fā)送,提示錯(cuò)誤:
打開(kāi)串口發(fā)送string:
勾選hex,發(fā)送:
提示數(shù)據(jù)格式錯(cuò)誤,接著我們更改數(shù)據(jù)格式后發(fā)送:
到此為止,串口的數(shù)據(jù)發(fā)送我們已經(jīng)完成,下一節(jié)課將實(shí)現(xiàn)串口接收數(shù)據(jù) 。


    以上關(guān)于本文的內(nèi)容,僅作參考!溫馨提示:如遇健康、疾病相關(guān)的問(wèn)題,請(qǐng)您及時(shí)就醫(yī)或請(qǐng)專(zhuān)業(yè)人士給予相關(guān)指導(dǎo)!

    「愛(ài)刨根生活網(wǎng)」www.malaban59.cn小編還為您精選了以下內(nèi)容,希望對(duì)您有所幫助: