1、这节课我们来实现串口的写入与接收,同样查看pyserial的在线文档,查看数据的写入与发送。

2、write方法,文档中表明,写的方法只能写bytes,所以我们在com.py,增加两个函数用来写数据:

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

一个用来直接发送bytes数据,另一个将string数据转为bytes再发送,接着我们需要更新下主界面:

增加一个line edite命名为txt_send,一个checkbox命名为cb_send,一个发送与接收按钮,分别命名为btn_send、btn_receive.

我们串口发送的代码已经完成了,那么我们将功能增加到界面中来。

1、在界面中发送string类型的数据,先更新最新的界面代码,在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))

当cb_send没有被选中的时候,也就是默认发送string类型,如果我要发送hex数据,如:01 ff 00 12这类数据的时候呢?

我们来实现一个将hex数据转为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

将发送代码更新为:

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(“发送数据长度”+str(slen))

except exception as e:

self.showbox(str(e))

将函数绑定到按钮:
self.new.btn_send.clicked.connect(self.writedata)

运行一下,不打开串口发送,提示错误:

打开串口发送string:

勾选hex,发送:

提示数据格式错误,接着我们更改数据格式后发送:

到此为止,串口的数据发送我们已经完成,下一节课将实现串口接收数据。