我正在尝试创建一个 pyqtgraph,它根据它从 pyserial 连接接收到的值实时更新。目前我有两个文件:一个从 pyserial 连接读取数据并在两个值发生更改时发出信号,另一个文件解释信号并显示两个更改的值。由于某种原因,从 pyserial 连接读取的值不会发送到第二个文件。按下启动 QPushButton 启动线程。我引用了这篇文章,但我无法弄清楚为什么信号存在问题,所以任何建议都将不胜感激。提前谢谢!
这是第一个文件:
class PortCommunication(QThread):
# Define signal for thread communication
data_changed = pyqtSignal(float, float)
def run(self):
try:
# Define port settings
with serial.Serial(
port = "COM4",
baudrate = 9600,
bytesize = 8,
parity = serial.PARITY_NONE,
stopbits = 1,
timeout = 1,
) as self.ser:
count = 0
# test only 10 iterations
while count < 10:
count += 1
self.ser.write(b"ADC0\r\n")
# Get device output (should be ['#,#,#'])
output = self.ser.read(size=20)
decoded_output = (output.decode('utf-8'))
# Turn the decoded_output from string to list
final_list = decoded_output.strip().split(',')
# Torque is the first number in the ['#', '#', '#']
torque = float(final_list[0])
speed = float(final_list[1])
# Emit torque and speed signal
#print(torque, speed)
self.data_changed.emit(torque, speed)
time.sleep(3)
except serial.serialutil.SerialException:
print("Couldn't open port.")
这是第二个文件:
class MainWidget(QtGui.QWidget):
def __init__ (self):
super(MainWidget, self).__init__()
self.initializeSpace()
def initializeSpace(self):
# Create and define buttons that will control the thread
self.start = QtGui.QPushButton("Start")
self.start.clicked.connect(self.startEvent)
self.stop = QtGui.QPushButton("Stop")
# Create Layout
self.layout = QtGui.QGridLayout()
# Add widgets to layout
self.layout.addWidget(self.start, 0, 0)
self.layout.addWidget(self.stop, 1, 0)
# Set layout
self.setLayout(self.layout)
def startEvent(self):
# Create a thread
self.thread = PortCommunication()
self.thread.start()
# Connect signals & slots
self.thread.data_changed.connect(self.display_data)
def display_data(self, torque, speed):
print(torque, speed)