使⽤Python3+PyQT5+Pyserial实现简单的串⼝⼯具⽅法练⼿项⽬,先上图
先实现⼀个简单的串⼝⼯具,为之后的上位机做准备
代码如下:
pyserial_demo.py
import sys
import serial
ls.list_ports
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtCore import QTimer
from ui_demo_1 import Ui_Form
class Pyqt5_Serial(QtWidgets.QWidget, Ui_Form):
def __init__(self):
super(Pyqt5_Serial, self).__init__()
self.setupUi(self)
self.init()
self.setWindowTitle("串⼝⼩助⼿")
self.ser = serial.Serial()
self.port_check()
# 接收数据和发送数据数⽬置零
self.data_num_received = 0
self.lineEdit.setText(str(self.data_num_received))
self.data_num_sended = 0
self.lineEdit_2.setText(str(self.data_num_sended))
def init(self):
# 串⼝检测按钮
self.s1__box_t(self.port_check)
# 串⼝信息显⽰
self.s1__box_t(self.port_imf)
# 打开串⼝按钮
self.open_t(self.port_open)
# 关闭串⼝按钮
self.close_t(self.port_close)
# 发送数据按钮
self.s3__send_t(self.data_send)
self.timer_send = QTimer()
self.timer_t(self.data_send)
self.timer_send_t(self.data_send_timer)
# 定时器接收数据
self.timer = QTimer(self)
self.t(self.data_receive)
# 清除发送窗⼝
self.s3__clear_t(self.send_data_clear)
# 清除接收窗⼝
self.s2__clear_ive_data_clear)
# 串⼝检测
def port_check(self):
# 检测所有存在的串⼝,将信息存储在字典中
self.Com_Dict = {}
port_list = ls.list_portsports())
self.s1__box_2.clear()
for port in port_list:
self.Com_Dict["%s" % port[0]] = "%s" % port[1]
self.s1__box_2.addItem(port[0])
if len(self.Com_Dict) == 0:
self.state_label.setText(" ⽆串⼝")
# 串⼝信息
def port_imf(self):
# 显⽰选定的串⼝的详细信息
imf_s = self.s1__box_2.currentText()
if imf_s != "":
self.state_label.setText(self.Com_Dict[self.s1__box_2.currentText()]) # 打开串⼝
def port_open(self):
self.ser.port = self.s1__box_2.currentText()
self.ser.baudrate = int(self.s1__box_3.currentText())
self.ser.bytesize = int(self.s1__box_4.currentText())
self.ser.stopbits = int(self.s1__box_6.currentText())
self.ser.parity = self.s1__box_5.currentText()
try:
self.ser.open()
except:
return None
# 打开串⼝接收定时器,周期为2ms
self.timer.start(2)
if self.ser.isOpen():
self.open_button.setEnabled(False)
self.close_button.setEnabled(True)
self.formGroupBox1.setTitle("串⼝状态(已开启)")
# 关闭串⼝
def port_close(self):
self.timer.stop()
self.timer_send.stop()
try:
self.ser.close()
except:
pass
self.open_button.setEnabled(True)
self.close_button.setEnabled(False)
self.lineEdit_3.setEnabled(True)
# 接收数据和发送数据数⽬置零
self.data_num_received = 0
self.lineEdit.setText(str(self.data_num_received))
self.data_num_sended = 0
self.lineEdit_2.setText(str(self.data_num_sended))
self.formGroupBox1.setTitle("串⼝状态(已关闭)")
# 发送数据
def data_send(self):
if self.ser.isOpen():
input_s = self.s3__PlainText()
if input_s != "":
100个python练手项目# ⾮空字符串
if self.hex_send.isChecked():
input_s = input_s.strip()
send_list = []
while input_s != '':
try:
num = int(input_s[0:2], 16)
except ValueError:
input_s = input_s[2:].strip()
send_list.append(num)
input_s = bytes(send_list)
else:
# ascii发送
input_s = (input_s + '\r\n').encode('utf-8')
num = self.ser.write(input_s)
self.data_num_sended += num
self.lineEdit_2.setText(str(self.data_num_sended))
else:
pass
# 接收数据
def data_receive(self):
try:
num = self.ser.inWaiting()
except:
self.port_close()
return None
if num > 0:
data = ad(num)
num = len(data)
# hex显⽰
if self.hex_receive.checkState():
out_s = ''
for i in range(0, len(data)):
out_s = out_s + '{:02X}'.format(data[i]) + ' '
self.s2__receive_text.insertPlainText(out_s)
else:
# 串⼝接收到的字符串为b'123',要转化成unicode字符串才能输出到窗⼝中去
self.s2__receive_text.insertPlainText(data.decode('iso-8859-1'))
# 统计接收字符的数量
self.data_num_received += num
self.lineEdit.setText(str(self.data_num_received))
# 获取到text光标
textCursor = self.s2__Cursor()
# 滚动到底部
# 设置光标到text中去
self.s2__receive_text.setTextCursor(textCursor)
else:
pass
# 定时发送数据
def data_send_timer(self):
if self.timer_send_cb.isChecked():
self.timer_send.start(int(self.()))
self.lineEdit_3.setEnabled(False)
else:
self.timer_send.stop()
self.lineEdit_3.setEnabled(True)
# 清除显⽰
def send_data_clear(self):
self.s3__send_text.setText("")
def receive_data_clear(self):
self.s2__receive_text.setText("")
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
myshow = Pyqt5_Serial()
myshow.show()
<_())
ui_demo_1.py
# Form implementation generated from reading ui file 'demo_1.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
self.formGroupBox = QtWidgets.QGroupBox(Form)
self.formGroupBox.setGeometry(QtCore.QRect(20, 20, 167, 301))
self.formGroupBox.setObjectName("formGroupBox")
self.formLayout = QtWidgets.QFormLayout(self.formGroupBox)
self.formLayout.setContentsMargins(10, 10, 10, 10)
self.formLayout.setSpacing(10)
self.formLayout.setObjectName("formLayout")
self.s1__lb_1 = QtWidgets.QLabel(self.formGroupBox)
self.s1__lb_1.setObjectName("s1__lb_1")
self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.s1__lb_1)
self.s1__box_1 = QtWidgets.QPushButton(self.formGroupBox)
self.s1__box_1.setAutoRepeatInterval(100)
self.s1__box_1.setDefault(True)
self.s1__box_1.setObjectName("s1__box_1")
self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.s1__box_1)
self.s1__lb_2 = QtWidgets.QLabel(self.formGroupBox)
self.s1__lb_2.setObjectName("s1__lb_2")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.s1__lb_2)
self.s1__box_2 = QtWidgets.QComboBox(self.formGroupBox)
self.s1__box_2.setObjectName("s1__box_2")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.s1__box_2)
self.s1__lb_3 = QtWidgets.QLabel(self.formGroupBox)
self.s1__lb_3.setObjectName("s1__lb_3")
self.formLayout.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.s1__lb_3)
self.s1__box_3 = QtWidgets.QComboBox(self.formGroupBox)
self.s1__box_3.setObjectName("s1__box_3")
self.s1__box_3.addItem("")
self.s1__box_3.addItem("")
self.s1__box_3.addItem("")
self.s1__box_3.addItem("")
self.s1__box_3.addItem("")
self.s1__box_3.addItem("")
self.s1__box_3.addItem("")
self.s1__box_3.addItem("")
self.s1__box_3.addItem("")
self.s1__box_3.addItem("")
self.s1__box_3.addItem("")
self.s1__box_3.addItem("")
self.formLayout.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.s1__box_3)
self.s1__lb_4 = QtWidgets.QLabel(self.formGroupBox)
self.s1__lb_4.setObjectName("s1__lb_4")
self.formLayout.setWidget(4, QtWidgets.QFormLayout.LabelRole, self.s1__lb_4)
self.s1__box_4 = QtWidgets.QComboBox(self.formGroupBox)
self.s1__box_4.setObjectName("s1__box_4")
self.s1__box_4.addItem("")
self.s1__box_4.addItem("")
self.s1__box_4.addItem("")
self.s1__box_4.addItem("")
self.formLayout.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.s1__box_4)
self.s1__lb_5 = QtWidgets.QLabel(self.formGroupBox)
self.s1__lb_5.setObjectName("s1__lb_5")
self.formLayout.setWidget(5, QtWidgets.QFormLayout.LabelRole, self.s1__lb_5)
self.s1__box_5 = QtWidgets.QComboBox(self.formGroupBox)
self.s1__box_5.setObjectName("s1__box_5")
self.s1__box_5.addItem("")
self.formLayout.setWidget(5, QtWidgets.QFormLayout.FieldRole, self.s1__box_5)
self.open_button = QtWidgets.QPushButton(self.formGroupBox)
self.open_button.setObjectName("open_button")
self.formLayout.setWidget(7, QtWidgets.QFormLayout.SpanningRole, self.open_button) self.close_button = QtWidgets.QPushButton(self.formGroupBox)
self.close_button.setObjectName("close_button")
self.formLayout.setWidget(8, QtWidgets.QFormLayout.SpanningRole, self.close_button) self.s1__lb_6 = QtWidgets.QLabel(self.formGroupBox)
self.s1__lb_6.setObjectName("s1__lb_6")
self.formLayout.setWidget(6, QtWidgets.QFormLayout.LabelRole, self.s1__lb_6)
self.s1__box_6 = QtWidgets.QComboBox(self.formGroupBox)
self.s1__box_6.setObjectName("s1__box_6")
self.state_label = QtWidgets.QLabel(self.formGroupBox)
self.state_label.setText("")
self.state_label.setTextFormat(QtCore.Qt.AutoText)
self.state_label.setScaledContents(True)
self.state_label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.state_label.setObjectName("state_label")
self.formLayout.setWidget(2, QtWidgets.QFormLayout.SpanningRole, self.state_label)
self.verticalGroupBox = QtWidgets.QGroupBox(Form)
self.verticalGroupBox.setGeometry(QtCore.QRect(210, 20, 401, 241))
self.verticalGroupBox.setObjectName("verticalGroupBox")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalGroupBox)
self.verticalLayout.setContentsMargins(10, 10, 10, 10)
self.verticalLayout.setObjectName("verticalLayout")
self.s2__receive_text = QtWidgets.QTextBrowser(self.verticalGroupBox)
self.s2__receive_text.setObjectName("s2__receive_text")
self.verticalLayout.addWidget(self.s2__receive_text)
self.verticalGroupBox_2 = QtWidgets.QGroupBox(Form)
self.verticalGroupBox_2.setGeometry(QtCore.QRect(210, 280, 401, 101))
self.verticalGroupBox_2.setObjectName("verticalGroupBox_2")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.verticalGroupBox_2)
self.verticalLayout_2.setContentsMargins(10, 10, 10, 10)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.s3__send_text = QtWidgets.QTextEdit(self.verticalGroupBox_2)
self.s3__send_text.setObjectName("s3__send_text")
self.verticalLayout_2.addWidget(self.s3__send_text)
self.s3__send_button = QtWidgets.QPushButton(Form)
self.s3__send_button.setGeometry(QtCore.QRect(620, 310, 61, 31))
self.s3__send_button.setObjectName("s3__send_button")
self.s3__clear_button = QtWidgets.QPushButton(Form)
self.s3__clear_button.setGeometry(QtCore.QRect(620, 350, 61, 31))
self.s3__clear_button.setObjectName("s3__clear_button")
self.formGroupBox1 = QtWidgets.QGroupBox(Form)
self.formGroupBox1.setGeometry(QtCore.QRect(20, 340, 171, 101))
self.formGroupBox1.setObjectName("formGroupBox1")
self.formLayout_2 = QtWidgets.QFormLayout(self.formGroupBox1)
self.formLayout_2.setContentsMargins(10, 10, 10, 10)
self.formLayout_2.setSpacing(10)
self.formLayout_2.setObjectName("formLayout_2")
self.label = QtWidgets.QLabel(self.formGroupBox1)
self.label.setObjectName("label")
self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.label)
self.label_2 = QtWidgets.QLabel(self.formGroupBox1)
self.label_2.setObjectName("label_2")
self.formLayout_2.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.label_2)
self.lineEdit = QtWidgets.QLineEdit(self.formGroupBox1)
self.lineEdit.setObjectName("lineEdit")
self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.lineEdit)
self.lineEdit_2 = QtWidgets.QLineEdit(self.formGroupBox1)
self.lineEdit_2.setObjectName("lineEdit_2")
self.formLayout_2.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.lineEdit_2)
self.hex_send = QtWidgets.QCheckBox(Form)
self.hex_send.setGeometry(QtCore.QRect(620, 280, 71, 16))
self.hex_send.setObjectName("hex_send")
self.hex_receive = QtWidgets.QCheckBox(Form)
self.hex_receive.setGeometry(QtCore.QRect(620, 40, 71, 16))
self.hex_receive.setObjectName("hex_receive")
self.s2__clear_button = QtWidgets.QPushButton(Form)
self.s2__clear_button.setGeometry(QtCore.QRect(620, 80, 61, 31))
self.s2__clear_button.setObjectName("s2__clear_button")
self.timer_send_cb = QtWidgets.QCheckBox(Form)
self.timer_send_cb.setGeometry(QtCore.QRect(260, 390, 71, 16))
self.timer_send_cb.setObjectName("timer_send_cb")
self.lineEdit_3 = QtWidgets.QLineEdit(Form)
self.lineEdit_3.setGeometry(QtCore.QRect(350, 390, 61, 20))
self.lineEdit_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lineEdit_3.setObjectName("lineEdit_3")
self.dw = QtWidgets.QLabel(Form)
self.dw.setGeometry(QtCore.QRect(420, 390, 54, 20))
self.dw.setObjectName("dw")
self.verticalGroupBox.raise_()
self.verticalGroupBox_2.raise_()
self.formGroupBox.raise_()
self.s3__send_button.raise_()
self.s3__clear_button.raise_()
self.formGroupBox.raise_()
self.hex_send.raise_()
self.hex_receive.raise_()
self.s2__clear_button.raise_()
self.timer_send_cb.raise_()
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论