(Python)PyQT5编写51单片机的取模机和上位机

上学期的一个课程设计要求做一个8x8x8光立方的上位机,一时不知怎么写,上学期太懒了,好久没写程序的缘故,关于PyQT5的运用也是之前用过一点皮毛,所以也忘的差不多了,所以在网上参考一些前辈写的,在此记录一下,以观后效之用。

首先得声明一下:这是我从网上的前辈拿来的程序,并非我个人所写。

取模器

  • pattern.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
# -*- coding: utf-8 -*-
class Pattern:
def __init__(self, page=8, row=8, column=8):
self.page = page
self.row = row
self.column = column
self.init_data()
def init_data(self):
self.data = []
self.page_flag = []
self.row_flag = []
self.column_flag = []
for i in range(0, self.page):
page_data = []
self.page_flag.append(0)
a_row_flag = []
for i in range(0, self.row):
a_row_flag.append(0)
a_column_flag = []
for j in range(0, self.column):
a_column_flag.append(0)
page_data.append(0)
self.column_flag.append(a_column_flag)
self.row_flag.append(a_row_flag)
self.data.append(page_data)
def __str__(self):
return self.format(format='hex')
def __repr__(self):
return '<Pattern Object %dx%dx%d>' % (self.page, self.row, self.column)
def set(self, page, row, column, value):
self.data[page][row * 8 + column] = value
for bit in self.data[page]:
self.page_flag[page] = bit
if bit == 0:
break
start = self.column * row
end = start + self.column
for bit in self.data[page][start:end]:
self.row_flag[page][row] = bit
if bit == 0:
break
start = column
step = self.column
end = start + step * self.row
for bit in self.data[page][start:end:step]:
self.column_flag[page][column] = bit
if bit == 0:
break
def set_row(self, page, row, value):
for i in range(0, self.column):
self.set(page, row, i, value)
def set_column(self, page, column, value):
for i in range(self.row):
self.set(page, i, column, value)
def set_page(self, page, value):
for i in range(self.row * self.column):
self.data[page][i] = value
self.page_flag[page] = value
for i in range(self.row):
self.row_flag[page][i] = value
for i in range(self.column):
self.column_flag[page][i] = value
def set_all(self, value):
for i in range(0, self.page):
self.set_page(i, value)
def zip(self):
zipped_data = []
for row in range(self.row):
for page in range(self.page):
column_sum = 0
for column in range(self.column):
bit = self.data[page][row * self.column + column]
if bit:
column_sum += 2**column
zipped_data.append(column_sum)
return zipped_data
def unzip(self, zipped_data):
unzipped_data = []
zipped_data_t = []
for p in range(self.page):
p_data_t = []
for pt in zipped_data:
p_data_t.append(pt[p])
zipped_data_t.append(p_data_t)
for p in zipped_data_t:
page = []
for r in p:
c = list(bin(r)[2:].zfill(8))
cint = []
for i in c[::-1]:
cint.append(int(i))
page.extend(cint)
unzipped_data.append(page)
return unzipped_data
def format(self, format='hex', sep=', ', beautify=True):
data = self.zip()
data_str = []
if format == 'dec':
for i in data:
data_str.append(str(i))
elif format == 'hex':
for i in data:
data_str.append('0x%.2X' % i)
else:
raise ValueError("No such format '%s'" % format)
if beautify:
data_beauty = []
for i in range(0, self.row):
start = self.page * i
end = start + 8
a_row = sep.join(data_str[start:end])
data_beauty.append(a_row)
data_beauty_str = ',\n'.join(data_beauty)
return data_beauty_str
else:
return sep.join(data_str)
def restore(self, text):
text = text.split(',\n')
self.page = len(text)
zipped_data = []
for p in text:
rows = p.split(', ')
self.row = len(rows)
rows = [int(i, 0) for i in rows]
zipped_data.append(rows)
unzipped_data = self.unzip(zipped_data)
self.init_data()
for page in range(self.page):
for row in range(self.row):
for column in range(self.column):
index = self.column * row + column
new_bit = unzipped_data[page][index]
if new_bit:
self.set(page, row, column, 1)
else:
self.set(page, row, column, 0)
if __name__ == '__main__':
p = Pattern(8, 8, 8)
# print(p.page_flag)
# print(p.row_flag)
# print(p.column_flag)
# for i in range(8):
# p.set_column(0, i, 1)
# p.set(0, i, 0, 0)
# print(p.format('dec'))
# print(p.page_flag)
# print(p.row_flag)
# print(p.column_flag)
hex_text = """0xFF, 0x01, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0x01, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0x01, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0x01, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0x01, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0x01, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00"""
# p.restore(dec_text)
p.restore(hex_text)
print(p.data)
print(p.page_flag)
print(p.row_flag)
print(p.column_flag)
  • patternflow.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import (
QMainWindow, QDesktopWidget, QApplication, QWidget,
QVBoxLayout, QHBoxLayout, QGridLayout,
QPushButton, QComboBox, QTextEdit, QCheckBox
)
from PyQt5.QtCore import QCoreApplication, Qt
from PyQt5.QtGui import QGuiApplication
from pattern import Pattern
class PatternFlow(QWidget):
def __init__(self, page=8, row=8, column=8):
super().__init__()
self.page = page
self.row = row
self.column = column
self.pt = Pattern()
self.format = 'dec'
self.cb = QGuiApplication.clipboard()
matrixs = self.matrixs(8)
console = self.console()
main_layout = QVBoxLayout()
main_layout.addLayout(matrixs)
main_layout.addStretch(1)
main_layout.addLayout(console)
self.setLayout(main_layout)
self.center_windows()
self.setWindowTitle('PatternFlow')
self.resize(800, 400)
self.show()
def console(self):
format_cbo = QComboBox()
format_cbo.addItem('Dec')
format_cbo.addItem('Hex')
format_cbo.activated[str].connect(self.set_format)
self.code_text = QTextEdit()
copy_btn = QPushButton('Copy')
copy_btn.setToolTip('Copy the pattern code to the clipboard')
copy_btn.clicked.connect(self.copy_to_clipboard)
reset_btn = QPushButton('Reset')
reset_btn.setToolTip('Reset all bit to 0')
reset_btn.clicked.connect(self.reset)
setall_btn = QPushButton('Set All')
setall_btn.setToolTip('Set all bit to 1')
setall_btn.clicked.connect(self.setall)
restore_btn = QPushButton('Restore')
restore_btn.clicked.connect(self.restore)
restore_btn.setToolTip('Restore pattern from code')
quit_btn = QPushButton('Quit')
quit_btn.clicked.connect(QCoreApplication.instance().quit)
console = QGridLayout()
console.addWidget(self.code_text, 0, 0, 6, 4)
console.setColumnStretch(0, 1)
console.addWidget(format_cbo, 0, 6)
console.addWidget(copy_btn, 1, 6)
console.addWidget(reset_btn, 3, 6)
console.addWidget(setall_btn, 2, 6)
console.addWidget(restore_btn, 4, 6)
console.addWidget(quit_btn, 5, 6)
return console
def reset(self):
self.pt.init_data()
self.mapto_btn()
self.code_text.clear()
def setall(self):
for i in range(self.page):
self.pt.set_page(i, 1)
self.mapto_btn()
self.gen_result()
def copy_to_clipboard(self):
text = self.code_text.toPlainText()
self.cb.setText(text)
def matrixs(self, page):
self.bit_btns = []
matrixs = QGridLayout()
for page in range(8):
matrix = QGridLayout()
matrix.setSpacing(2)
set_page = QPushButton()
set_page.setFixedSize(16, 16)
set_page.setToolTip('set_page(%d' % page)
set_page.setStyleSheet(
'QPushButton {background-color: #fff; border: 1px solid #ccc; border-radius: 4px}'
'QPushButton:open {background-color: #666; border: 1px solid #ccc}'
)
set_page.clicked.connect(self.set_page)
matrix.addWidget(set_page, 0, 0)
for row in range(8):
set_row = QPushButton()
set_row.setFixedSize(16, 16)
set_row.setToolTip('set_row(%d, %d)' % (page, row))
set_row.setStyleSheet(
'QPushButton {background-color: #fff; border: 1px solid #ccc; border-radius: 4px}'
'QPushButton:open {background-color: #aaa}'
)
set_row.clicked.connect(self.set_row)
matrix.addWidget(set_row, row + 1, 0)
for column in range(8):
set_column = QPushButton()
set_column.setFixedSize(16, 16)
set_column.setToolTip('set_column(%d, %d)' % (page, column))
set_column.setStyleSheet(
'QPushButton {background-color: #fff; border: 1px solid #ccc; border-radius: 4px}'
'QPushButton:open {background-color: #aaa}'
)
set_column.clicked.connect(self.set_column)
matrix.addWidget(set_column, 0, column + 1)
btn_page = []
for row in range(8):
for column in range(8):
name = 'set_bit(%d, %d, %d)' % (page, row, column)
bit_btn = QPushButton()
bit_btn.setToolTip(name)
bit_btn.setFixedSize(16, 16)
bit_btn.setCheckable(True)
bit_btn.setStyleSheet(
'QPushButton {background: #ddd; border: none; margin: 0px; padding: 0px}'
'QPushButton:checked {background-color: #2c9e4b; border: none}'
)
bit_btn.clicked[bool].connect(self.set_bit)
btn_page.append(bit_btn)
matrix.addWidget(bit_btn, row + 1, column + 1)
self.bit_btns.append(btn_page)
matrixs.addLayout(matrix, page / 4, page % 4)
return matrixs
def mapto_code(self):
for page in range(self.page):
for row in range(self.row):
for column in range(self.column):
bit_btn = self.bit_btns[page][self.column * row + column]
if bit_btn.isChecked():
self.pt.set(page, row, column, 1)
else:
self.pt.set(page, row, column, 0)
def mapto_btn(self):
for page in range(self.page):
for row in range(self.row):
for column in range(self.column):
bit_btn = self.bit_btns[page][self.column * row + column]
bit = self.pt.data[page][self.column * row + column]
if bit == 1:
bit_btn.setChecked(True)
else:
bit_btn.setChecked(False)
def restore(self):
text = self.code_text.toPlainText()
if text:
try:
self.pt.restore(text)
self.mapto_btn()
except (ValueError, IndexError):
pass
def set_format(self, text):
self.format = text.lower()
self.gen_result()
def gen_result(self):
self.code_text.setText(self.pt.format(self.format))
def set_page(self, state):
sender = self.sender()
page = sender.toolTip().strip('set_page(').strip(')')
page = int(page)
if self.pt.page_flag[page] == 0:
self.pt.set_page(page, 1)
for bit_btn in self.bit_btns[page]:
bit_btn.setChecked(True)
else:
self.pt.set_page(page, 0)
for bit_btn in self.bit_btns[page]:
bit_btn.setChecked(False)
self.gen_result()
def set_row(self, state):
sender = self.sender()
text = sender.toolTip().strip('set_row(').strip(')').split(', ')
page = int(text[0])
row = int(text[1])
start = self.column * row
end = start + self.column
if self.pt.row_flag[page][row]:
self.pt.set_row(page, row, 0)
for bit_btn in self.bit_btns[page][start:end]:
bit_btn.setChecked(False)
else:
self.pt.set_row(page, row, 1)
for bit_btn in self.bit_btns[page][start:end]:
bit_btn.setChecked(True)
self.gen_result()
def set_column(self, state):
sender = self.sender()
text = sender.toolTip().strip('set_column(').strip(')').split(', ')
page = int(text[0])
column = int(text[1])
start = column
step = self.column
end = start + step * self.row
if self.pt.column_flag[page][column]:
self.pt.set_column(page, column, 0)
for bit_btn in self.bit_btns[page][start:end:step]:
bit_btn.setChecked(False)
else:
self.pt.set_column(page, column, 1)
for bit_btn in self.bit_btns[page][start:end:step]:
bit_btn.setChecked(True)
self.gen_result()
def set_bit(self, pressed):
sender = self.sender()
text = sender.toolTip().strip('set_bit(').strip(')').split(', ')
page = int(text[0])
row = int(text[1])
column = int(text[2])
if pressed:
self.pt.set(page, row, column, 1)
else:
self.pt.set(page, row, column, 0)
self.gen_result()
def center_windows(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
if __name__ == '__main__':
app = QApplication(sys.argv)
pf = PatternFlow()
sys.exit(app.exec_())

取模器的代码来源一个网上的前辈分享的Github

上位机

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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# -*- coding: utf-8 -*-
import sys
import serial
import threading
import binascii
from PyQt5 import QtCore, QtGui, QtWidgets
import serial.tools.list_ports
class Ui_MainWindow(object):
ser = serial.Serial()
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(579, 369)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(10, 10, 141, 311))
self.groupBox.setObjectName("groupBox")
self.label = QtWidgets.QLabel(self.groupBox)
self.label.setGeometry(QtCore.QRect(10, 20, 31, 16))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.groupBox)
self.label_2.setGeometry(QtCore.QRect(10, 50, 41, 16))
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.groupBox)
self.label_3.setGeometry(QtCore.QRect(10, 110, 41, 16))
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(self.groupBox)
self.label_4.setGeometry(QtCore.QRect(10, 80, 41, 16))
self.label_4.setObjectName("label_4")
self.label_5 = QtWidgets.QLabel(self.groupBox)
self.label_5.setGeometry(QtCore.QRect(10, 140, 41, 16))
self.label_5.setObjectName("label_5")
self.comboBox_4 = QtWidgets.QComboBox(self.groupBox)
self.comboBox_4.setGeometry(QtCore.QRect(60, 20, 71, 22))
self.comboBox_4.setObjectName("comboBox_4")
self.comboBox_4.addItem("")
self.comboBox_4.addItem("")
self.comboBox_4.addItem("")
self.comboBox_4.addItem("")
self.comboBox_4.addItem("")
self.comboBox_4.addItem("")
self.comboBox_4.addItem("")
self.comboBox_4.addItem("")
self.comboBox_4.addItem("")
self.comboBox_4.addItem("")
self.lineEdit_3 = QtWidgets.QLineEdit(self.groupBox)
self.lineEdit_3.setGeometry(QtCore.QRect(60, 50, 71, 20))
self.lineEdit_3.setObjectName("lineEdit_3")
self.comboBox = QtWidgets.QComboBox(self.groupBox)
self.comboBox.setGeometry(QtCore.QRect(60, 80, 71, 22))
self.comboBox.setObjectName("comboBox")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox_2 = QtWidgets.QComboBox(self.groupBox)
self.comboBox_2.setGeometry(QtCore.QRect(60, 110, 71, 22))
self.comboBox_2.setObjectName("comboBox_2")
self.comboBox_2.addItem("")
self.comboBox_2.addItem("")
self.comboBox_2.addItem("")
self.comboBox_2.addItem("")
self.comboBox_2.addItem("")
self.comboBox_3 = QtWidgets.QComboBox(self.groupBox)
self.comboBox_3.setGeometry(QtCore.QRect(60, 140, 71, 22))
self.comboBox_3.setObjectName("comboBox_3")
self.comboBox_3.addItem("")
self.comboBox_3.addItem("")
self.comboBox_3.addItem("")
self.pushButton = QtWidgets.QPushButton(self.groupBox)
self.pushButton.setGeometry(QtCore.QRect(10, 240, 51, 23))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.groupBox)
self.pushButton_2.setGeometry(QtCore.QRect(80, 240, 51, 23))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.groupBox)
self.pushButton_3.setGeometry(QtCore.QRect(40, 200, 61, 23))
self.pushButton_3.setObjectName("pushButton_3")
self.label_11 = QtWidgets.QLabel(self.groupBox)
self.label_11.setGeometry(QtCore.QRect(10, 170, 41, 16))
self.label_11.setObjectName("label_11")
self.label_12 = QtWidgets.QLabel(self.groupBox)
self.label_12.setGeometry(QtCore.QRect(70, 170, 54, 16))
font = QtGui.QFont()
font.setFamily("Aharoni")
font.setBold(True)
font.setWeight(75)
self.label_12.setFont(font)
self.label_12.setObjectName("label_12")
self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox_2.setGeometry(QtCore.QRect(160, 10, 411, 181))
self.groupBox_2.setObjectName("groupBox_2")
self.textBrowser = QtWidgets.QTextBrowser(self.groupBox_2)
self.textBrowser.setGeometry(QtCore.QRect(10, 20, 391, 151))
self.textBrowser.setObjectName("textBrowser")
self.groupBox_3 = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox_3.setGeometry(QtCore.QRect(160, 200, 261, 121))
self.groupBox_3.setObjectName("groupBox_3")
self.textEdit = QtWidgets.QTextEdit(self.groupBox_3)
self.textEdit.setGeometry(QtCore.QRect(10, 20, 241, 91))
self.textEdit.setObjectName("textEdit")
self.checkBox = QtWidgets.QCheckBox(self.centralwidget)
self.checkBox.setGeometry(QtCore.QRect(430, 210, 61, 16))
self.checkBox.setObjectName("checkBox")
self.checkBox_2 = QtWidgets.QCheckBox(self.centralwidget)
self.checkBox_2.setGeometry(QtCore.QRect(500, 210, 61, 20))
self.checkBox_2.setObjectName("checkBox_2")
self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_4.setGeometry(QtCore.QRect(430, 240, 61, 23))
self.pushButton_4.setObjectName("pushButton_4")
self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_5.setGeometry(QtCore.QRect(430, 280, 61, 23))
self.pushButton_5.setObjectName("pushButton_5")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 579, 23))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
MainWindow.setFixedSize(MainWindow.width(), MainWindow.height());
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Serial_gui"))
self.groupBox.setTitle(_translate("MainWindow", "串口设置"))
self.label.setText(_translate("MainWindow", "串 口"))
self.label_2.setText(_translate("MainWindow", "波特率"))
self.label_3.setText(_translate("MainWindow", "校验位"))
self.label_4.setText(_translate("MainWindow", "数据位"))
self.label_5.setText(_translate("MainWindow", "停止位"))
self.lineEdit_3.setText(_translate("MainWindow", "9600"))
self.comboBox.setItemText(0, _translate("MainWindow", "8"))
self.comboBox.setItemText(1, _translate("MainWindow", "7"))
self.comboBox.setItemText(2, _translate("MainWindow", "6"))
self.comboBox.setItemText(3, _translate("MainWindow", "5"))
self.comboBox_2.setItemText(0, _translate("MainWindow", "N"))
self.comboBox_2.setItemText(1, _translate("MainWindow", "E"))
self.comboBox_2.setItemText(2, _translate("MainWindow", "O"))
self.comboBox_2.setItemText(3, _translate("MainWindow", "M"))
self.comboBox_2.setItemText(4, _translate("MainWindow", "S"))
self.comboBox_3.setItemText(0, _translate("MainWindow", "1"))
self.comboBox_3.setItemText(1, _translate("MainWindow", "1.5"))
self.comboBox_3.setItemText(2, _translate("MainWindow", "2"))
self.comboBox_4.setItemText(0, _translate("MainWindow", "COM1"))
self.comboBox_4.setItemText(1, _translate("MainWindow", "COM2"))
self.comboBox_4.setItemText(2, _translate("MainWindow", "COM3"))
self.comboBox_4.setItemText(3, _translate("MainWindow", "COM4"))
self.comboBox_4.setItemText(4, _translate("MainWindow", "COM5"))
self.comboBox_4.setItemText(5, _translate("MainWindow", "COM6"))
self.comboBox_4.setItemText(6, _translate("MainWindow", "COM7"))
self.comboBox_4.setItemText(7, _translate("MainWindow", "COM8"))
self.comboBox_4.setItemText(8, _translate("MainWindow", "COM9"))
self.comboBox_4.setItemText(9, _translate("MainWindow", "COM10"))
self.pushButton.setText(_translate("MainWindow", "打开"))
self.pushButton.clicked.connect(self.port_open)
self.pushButton_2.setText(_translate("MainWindow", "关闭"))
self.pushButton_2.clicked.connect(self.port_close)
self.pushButton_3.setText(_translate("MainWindow", "检测串口"))
self.pushButton_3.clicked.connect(self.port_cheak)
self.label_11.setText(_translate("MainWindow", "状 态:"))
self.label_12.setText(_translate("MainWindow", "串口状态"))
self.groupBox_2.setTitle(_translate("MainWindow", "接收区"))
self.groupBox_3.setTitle(_translate("MainWindow", "发送区"))
self.checkBox.setText(_translate("MainWindow", "Hex显示"))
self.checkBox_2.setText(_translate("MainWindow", "Hex发送"))
self.pushButton_4.setText(_translate("MainWindow", "清除"))
self.pushButton_4.clicked.connect(self.clean_data)
self.pushButton_5.setText(_translate("MainWindow", "发送"))
self.pushButton_5.clicked.connect(self.send_data)
def port_open(self):
self.ser.port = self.comboBox_4.currentText()
self.ser.baudrate = int(self.lineEdit_3.text())
self.ser.bytesize = int(self.comboBox.currentText())
self.ser.stopbits = int(self.comboBox_3.currentText())
self.ser.parity = self.comboBox_2.currentText()
self.ser.open()
if(self.ser.isOpen()):
self.pushButton.setEnabled(False)
self.label_12.setText("打开成功")
self.t1 = threading.Thread(target=self.receive_data)
self.t1.setDaemon(True)
self.t1.start()
else:
self.label_12.setText("打开失败")
def port_close(self):
self.ser.close()
if(self.ser.isOpen()):
self.label_12.setText("关闭失败")
else:
self.pushButton.setEnabled(True)
self.label_12.setText("关闭成功")
def send_data(self):
if(self.ser.isOpen()):
if(self.checkBox_2.isChecked()):
self.ser.write(binascii.a2b_hex(self.textEdit.toPlainText()))
else:
self.ser.write(self.textEdit.toPlainText().encode('utf-8'))
self.label_12.setText("发送成功")
# self.ser.flushOutput()
else:
self.label_12.setText("发送失败")
def receive_data(self):
print("The receive_data threading is start")
res_data = ''
num = 0
while (self.ser.isOpen()):
size = self.ser.inWaiting()
if size:
res_data = self.ser.read_all()
if(self.checkBox.isChecked()):
self.textBrowser.append(binascii.b2a_hex(res_data).decode())
else:
self.textBrowser.append(res_data.decode())
self.textBrowser.moveCursor(QtGui.QTextCursor.End)
self.ser.flushInput()
num +=1
self.label_12.setText("接收:"+str(num))
def clean_data(self):
self.textBrowser.setText("")
self.label_12.setText("接收清空")
def port_cheak(self):
Com_List=[]
port_list = list(serial.tools.list_ports.comports())
self.comboBox_4.clear()
for port in port_list:
Com_List.append(port[0])
self.comboBox_4.addItem(port[0])
if(len(Com_List) == 0):
self.label_12.setText("没串口")
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())

这是从一个CSDN前辈写的拿来用的,一些日子我也忘记了从哪里来的了…但是灯只能亮前三排…总之非常感谢前辈的分享~

---------------本文终---------------

文章作者:刘俊

最后更新:2019年02月22日 - 11:02

许可协议: 转载请保留原文链接及作者。