I've made an application with pyside2 (qml).
The purpose is to read and present the values comming from an arduino to a chart.
The data is send every second over the serial connection to the pc.
To achieve this I had to create an QThread for not freezing up the UI. Used explenation here.
In the UI I've a button to start/pause the app.
The application is almost working as expected: Only when I pause the app and say after a minute or so I resume the app (QThread) I got a lot of data gathered from the Arduino when this should not be happening.
I expect as long as the thread is "pausing" it won't read data that I don't need.
How do I fix it so it won't read the data when the thread in on "pause" ?
main.py
from PySide2.QtCore import Signal, Slot, QObject, QThread
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtWidgets import QApplication
class Worker(QThread):
data = Signal(object)
def __init__(self, ctrl):
QThread.__init__(self)
self.ctrl = ctrl
def run(self):
while True:
while self.ctrl["running"]:
self.data.emit(arduino.read_arduino())
else:
time.sleep(0)
if self.ctrl["break"]:
break
class MainWindow(QObject):
def __init__(self):
QObject.__init__(self)
self.thread = QThread()
self.ctrl = {"break": False, "running": True}
self.worker = Worker(self.ctrl)
@Slot()
def start_measurement(self):
if not self.thread.isRunning():
self.worker.moveToThread(self.thread)
self.thread.started.connect(self.worker.run)
self.worker.data.connect(self.handle_arduino_raw_data)
self.thread.start()
else:
self.ctrl["running"] = True
if self.ctrl["running"] = True:
self.ctrl["running"] = False
@Slot(str)
def handle_arduino_raw_data(self, data):
# handle the data received from the arduino
arduino.py
def read_arduino(self):
raw_data = self.ser.readline().decode('utf-8').rstrip()
return raw_data