class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 480)
self.MainWindow = MainWindow
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.widget = QtWidgets.QWidget(self.centralwidget)
self.widget.setGeometry(QtCore.QRect(0, 442, 800, 35))
self.widget.setObjectName("widget")
self.widget_2 = QtWidgets.QWidget(self.centralwidget)
self.widget_2.setGeometry(QtCore.QRect(0, 0, 800, 71))
self.widget_2.setObjectName("widget_2")
# Create a QLabel to hold the background image
self.background_label = QtWidgets.QLabel(MainWindow)
self.background_label.setGeometry(0, 0, MainWindow.width(), MainWindow.height())
self.background_label.lower() # Ensure the label is behind all other widgets
self.MainScreen_widget = QtWidgets.QWidget(self.centralwidget)
self.MainScreen_widget.setGeometry(QtCore.QRect(7, 5, 786, 61))
self.MainScreen_widget.setStyleSheet("QWidget {\n"
"\n"
" background-color: rgb(85, 107, 122); /* Semi-transparent background */\n"
" border: 2px solid rgba(255, 255, 255, 1); /* Semi-transparent border */\n"
" border-radius: 10px; /* Rounded corners */\n"
"}\n"
"")
self.MainScreen_widget.setObjectName("MainScreen_widget")
self.modeSelect_Button = QtWidgets.QPushButton(self.MainScreen_widget)
self.modeSelect_Button.setGeometry(QtCore.QRect(333, 10, 81, 23))
self.modeSelect_Button.setObjectName("modeSelect_Button")
self.widgetSelect_Button = QtWidgets.QPushButton(self.MainScreen_widget)
self.widgetSelect_Button.setGeometry(QtCore.QRect(305, 30, 141, 27))
self.widgetSelect_Button.setObjectName("widgetSelect_Button")
# Create a stacked widget to hold screens
self.stackedWidget = QtWidgets.QStackedWidget(self.centralwidget)
self.stackedWidget.setGeometry(QtCore.QRect(0, 72, 800, 340))
self.stackedWidget.setObjectName("stackedWidget")
# Initialize the modes and widgets dictionary
self.modes = {
"mode 1": [
("widget 1", mode_1_widget_1),
("widget 2", mode_1_widget_2),
("widget 3", mode_1_widget_3),
("widget 4", mode_1_widget_4)
],
"mode 2": [
("widget 1", mode_2_widget_1),
("widget 2", mode_2_widget_2),
("widget 3", mode_2_widget_3),
],
"mode 3": [
("widget 1", mode_3_widget_1)
]
}
# # Initial settings
self.mode_index = 0
self.widget_index = 0
self.current_widget = None
# Load the initial widget
self.loadWidget()
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def changeWidget(self):
"""Change the widget within the current mode."""
mode = list(self.modes.keys())[self.mode_index]
self.last_selected[mode] = (self.last_selected[mode] + 1) % len(self.modes[mode])
self.loadWidget()
def changeMode(self):
"""Change the mode and update the widget."""
self.mode_index = (self.mode_index + 1) % len(self.modes)
self.loadWidget()
def loadWidget(self):
"""Load the widget corresponding to the current mode and widget index."""
mode = list(self.modes.keys())[self.mode_index]
widget_index = self.last_selected[mode]
widget_class = self.modes[mode][widget_index][1]
if self.current_widget:
self.stackedWidget.removeWidget(self.current_widget)
self.stackedWidget.addWidget(self.current_widget)
self.stackedWidget.setCurrentWidget(self.current_widget)
# Update the text on the widget button
self.widgetSelect_Button.setText(self.modes[mode][widget_index][0])
# Update the text on the mode button
self.modeSelect_Button.setText(mode)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.modeSelect_Button.setText(_translate("MainWindow", ""))
self.widgetSelect_Button.setText(_translate("MainWindow", ""))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
for example mode_1_widget_1 code to receive the data and plotting via serial comm and it’s similar for the all mode_1, mode_2, mode_3 widgets:
class Ui_mode_1_Widget_1(object):
def setupUi(self, mode_1_Widget_1):
mode_1_Widget_1.setObjectName("mode_1_Widget_1")
mode_1_Widget_1.resize(800, 340)
mode_1_Widget_1.setStyleSheet("background-color:transparent;\n"
"")
self.data_1_widget = QtWidgets.QWidget(mode_1_Widget_1)
self.data_1_widget.setGeometry(QtCore.QRect(30, 30, 768, 200))
font = QtGui.QFont()
font.setPointSize(10)
self.data_1_widget.setFont(font)
self.data_1_widget.setStyleSheet("background-color: transparent;")
self.data_1_widget.setObjectName("data_1_widget")
self.data_1_Label = QtWidgets.QLabel(mode_1_Widget_1)
self.data_1_Label.setGeometry(QtCore.QRect(4, 120, 23, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.data_1_Label.setFont(font)
self.data_1_Label.setStyleSheet("color:rgb(50, 255, 14);\n"
"background-color:none")
self.data_1_Label.setText("")
self.data_1_Label.setAlignment(QtCore.Qt.AlignCenter)
self.data_1_Label.setObjectName("data_1_Label")
self.retranslateUi(mode_1_Widget_1)
QtCore.QMetaObject.connectSlotsByName(mode_1_Widget_1)
# Create PlotWidgets for each channel
self.plot_widgets = {
"R1": PlotWidget(mode_1_Widget_1)
}
# Set geometry for each PlotWidget based on the provided positions
for channel, plot_widget in self.plot_widgets.items():
plot_widget.setBackground(None)
# Additional features
plot_widget.hideAxis('left')
plot_widget.hideAxis('bottom')
plot_widget.setMouseEnabled(x=False, y=False) # Disable zooming
plot_widget.setStyleSheet("background-color: transparent;")
if channel.startswith("R"):
if channel == "R1":
plot_widget.setGeometry(QtCore.QRect(30, 30, 768, 200))
else:
# Handle other channel names if needed
pass
plot_widget.setObjectName(channel + "_widget")
def retranslateUi(self, mode_1_Widget_1):
_translate = QtCore.QCoreApplication.translate
mode_1_Widget_1.setWindowTitle(_translate("mode_1_Widget_1", "Form"))
self.data_1_Label.setText(_translate("mode_1_Widget_1", "R1"))
class mode_1_Widget_1(QtWidgets.QWidget, Ui_mode_1_Widget_1):
def __init__(self):
super().__init__()
self.setupUi(self)
# Initialize analog data dictionary
self.analog_data = {channel: [] for channel in self.plot_widgets.keys()}
# Initialize serial communication
self.serial_connected = False
self.init_serial()
# Start receiving analog data
self.start_analog_reception()
def init_serial(self):
try:
self.ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1) # Adjust the port and baud rate accordingly
time.sleep(2) # Wait for the serial connection to initialize
self.serial_connected = True
except serial.SerialException:
print("SerialException: Could not open serial port")
self.serial_connected = False
def start_analog_reception(self):
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.update_analog_plot)
self.timer.start(100) # Update every 100 ms
self.analog_thread = threading.Thread(target=self.receive_analog_data)
self.analog_thread.daemon = True
self.analog_thread.start()
def update_analog_plot(self):
for channel, plot_widget in self.plot_widgets.items():
if self.analog_data[channel]:
num_points = len(self.analog_data[channel])
x = np.linspace(0, num_points - 1, num_points) # Adjust x array length
analog_values = self.analog_data[channel][::-1]
# Ensure the length of analog_values matches the length of x
analog_values = analog_values[:len(x)]
plot_widget.plot(x, analog_values, clear=True, pen=mkPen(color='g', width=1)) # Plot as a continuous line
else:
# If no data received, plot a single thin line
plot_widget.plot([0], [0], clear=True, pen=mkPen(color='g', width=1)) # Plot a single thin line
def receive_analog_data(self):
while True:
if not self.serial_connected:
# If the serial connection is not established, append '0'
for channel in self.analog_data.keys():
self.analog_data[channel].append(0)
if len(self.analog_data[channel]) > 3000: # Keep only the latest 2000 data points
self.analog_data[channel].pop(0)
time.sleep(1) # Wait for a second before trying again
self.init_serial() # Try to reconnect the serial port
continue
try:
line = self.ser.readline().strip()
if line:
try:
analog_value = int(line.decode('utf-8'))
for channel in self.analog_data.keys():
self.analog_data[channel].append(analog_value)
if len(self.analog_data[channel]) > 3000: # Keep only the latest 2000 data points
self.analog_data[channel].pop(0)
except UnicodeDecodeError:
# Handle UnicodeDecodeError gracefully
print("UnicodeDecodeError: Invalid byte received")
else:
# If no value received, append "0" to all channels
for channel in self.analog_data.keys():
self.analog_data[channel].append(0)
if len(self.analog_data[channel]) > 3000: # Keep only the latest 2000 data points
self.analog_data[channel].pop(0)
except serial.SerialException:
print("SerialException: Issue with the serial connection")
self.serial_connected = False # Mark serial connection as disconnected
except ValueError:
print("ValueError: Unable to convert data to integer")
continue
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = mode_1_Widget_1()
mainWin.show()
sys.exit(app.exec_())
I’m using this PyQt5 code on the Raspberry Pi 4. When I run the code, I receive and plot analog values on the plot_widget via serial communication. If I change the mode or widget, and then attach the respective widget using the stackedWidget method, I face issues with receiving and plotting the data on the plot_widget and delayed in overall response. This is leading to hanging conditions and slow the overall performance like user interface, or an inability to get the analog value from the serial communication. I analysed the RAM memory and found that it’s only taking up to 40-50% on that occasion. Can anyone please help me to resolve these issues