I am trying to create a pyqtgraph that updates real time based on the values it receives from a pyserial connection. Currently I have two files: one that reads data from a pyserial connection and emits a signal when two values have changed, and a second file that interprets the signal and displays the two changed values. For some reason the values that are read from the pyserial connection are not being emitted to the second file. Pushing the start QPushButton starts the thread. I referenced this post but I can't figure out why there is an issue with the signal so any advice would be appreciated. Thanks ahead of time!
Here is the first file:
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.")
Here is the second file:
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)