-
Notifications
You must be signed in to change notification settings - Fork 109
/
pyserial_demo.py
198 lines (169 loc) · 6.55 KB
/
pyserial_demo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import sys
import serial
import serial.tools.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_1.clicked.connect(self.port_check)
# 串口信息显示
self.s1__box_2.currentTextChanged.connect(self.port_imf)
# 打开串口按钮
self.open_button.clicked.connect(self.port_open)
# 关闭串口按钮
self.close_button.clicked.connect(self.port_close)
# 发送数据按钮
self.s3__send_button.clicked.connect(self.data_send)
# 定时发送数据
self.timer_send = QTimer()
self.timer_send.timeout.connect(self.data_send)
self.timer_send_cb.stateChanged.connect(self.data_send_timer)
# 定时器接收数据
self.timer = QTimer(self)
self.timer.timeout.connect(self.data_receive)
# 清除发送窗口
self.s3__clear_button.clicked.connect(self.send_data_clear)
# 清除接收窗口
self.s2__clear_button.clicked.connect(self.receive_data_clear)
# 串口检测
def port_check(self):
# 检测所有存在的串口,将信息存储在字典中
self.Com_Dict = {}
port_list = list(serial.tools.list_ports.comports())
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:
QMessageBox.critical(self, "Port Error", "此串口不能被打开!")
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__send_text.toPlainText()
if input_s != "":
# 非空字符串
if self.hex_send.isChecked():
# hex发送
input_s = input_s.strip()
send_list = []
while input_s != '':
try:
num = int(input_s[0:2], 16)
except ValueError:
QMessageBox.critical(self, 'wrong data', '请输入十六进制数据,以空格分开!')
return None
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 = self.ser.read(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__receive_text.textCursor()
# 滚动到底部
textCursor.movePosition(textCursor.End)
# 设置光标到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.lineEdit_3.text()))
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()
sys.exit(app.exec_())