I'll modify the code to start temperature plotting only when a profile begins and add the target profile visualization. Here are the updated sections:
Updated Python GUI - Modified Sections
import sys
import struct
import time
import threading
from datetime import datetime
from collections import deque
import serial
import serial.tools.list_ports
import numpy as np
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import pyqtgraph as pg
# ... (keep all the protocol constants and classes as before)
class TemperaturePlot(pg.PlotWidget):
def __init__(self):
super().__init__()
self.setLabel('left', 'Temperature', '°C')
self.setLabel('bottom', 'Time', 's')
self.showGrid(x=True, y=True)
# Data storage
self.max_points = 3600 # Increased for longer profiles
self.time_data = deque(maxlen=self.max_points)
self.temp_top = deque(maxlen=self.max_points)
self.temp_bot1 = deque(maxlen=self.max_points)
self.temp_bot2 = deque(maxlen=self.max_points)
# Plot lines for actual temperatures
self.line_top = self.plot(pen=pg.mkPen('r', width=2), name='Top Actual')
self.line_bot1 = self.plot(pen=pg.mkPen('g', width=2), name='Bottom 1 Actual')
self.line_bot2 = self.plot(pen=pg.mkPen('b', width=2), name='Bottom 2 Actual')
# Plot lines for target temperatures (setpoints)
self.line_target_top = self.plot(pen=pg.mkPen('r', width=1, style=Qt.DashLine), name='Top Target')
self.line_target_bot = self.plot(pen=pg.mkPen('orange', width=1, style=Qt.DashLine), name='Bottom Target')
self.addLegend()
# Profile plotting data
self.profile_time_data = []
self.profile_temp_data = []
self.profile_line = None
# Control variables
self.is_recording = False
self.start_time = None
self.current_profile = None
def start_recording(self, profile=None):
"""Start recording temperature data and plot profile if provided"""
self.clear_data()
self.is_recording = True
self.start_time = time.time()
self.current_profile = profile
if profile:
self.plot_profile_preview(profile)
def stop_recording(self):
"""Stop recording temperature data"""
self.is_recording = False
self.start_time = None
self.current_profile = None
def clear_data(self):
"""Clear all plot data"""
self.time_data.clear()
self.temp_top.clear()
self.temp_bot1.clear()
self.temp_bot2.clear()
# Clear plots
self.line_top.setData([], [])
self.line_bot1.setData([], [])
self.line_bot2.setData([], [])
self.line_target_top.setData([], [])
self.line_target_bot.setData([], [])
# Remove profile line if exists
if self.profile_line is not None:
self.removeItem(self.profile_line)
self.profile_line = None
def plot_profile_preview(self, profile):
"""Plot the target temperature profile"""
if not profile or not profile.segments:
return
# Generate profile data
time_data = [0]
temp_data = [25] # Start at room temperature
current_time = 0
current_temp = 25
for segment in profile.segments:
# Ramp phase
if segment.ramp_rate != 0:
ramp_time = abs((segment.target_temp - current_temp) / segment.ramp_rate)
# Add intermediate points for smooth ramping
steps = max(10, int(ramp_time))
for i in range(1, steps + 1):
t = current_time + (ramp_time * i / steps)
temp = current_temp + (segment.target_temp - current_temp) * i / steps
time_data.append(t)
temp_data.append(temp)
current_time += ramp_time
else:
# Instant jump to target temperature
time_data.append(current_time)
temp_data.append(segment.target_temp)
# Soak phase
current_time += segment.soak_time
time_data.append(current_time)
temp_data.append(segment.target_temp)
current_temp = segment.target_temp
# Plot profile line
if self.profile_line is not None:
self.removeItem(self.profile_line)
self.profile_line = self.plot(time_data, temp_data,
pen=pg.mkPen('yellow', width=2, style=Qt.DashLine),
name='Target Profile')
# Store for reference
self.profile_time_data = time_data
self.profile_temp_data = temp_data
def update_data(self, top, bot1, bot2, setpoint_top=None, setpoint_bot1=None, setpoint_bot2=None):
"""Update temperature data - only record if recording is active"""
if not self.is_recording or self.start_time is None:
return
current_time = time.time() - self.start_time
self.time_data.append(current_time)
self.temp_top.append(top)
self.temp_bot1.append(bot1)
self.temp_bot2.append(bot2)
# Update actual temperature lines
self.line_top.setData(list(self.time_data), list(self.temp_top))
self.line_bot1.setData(list(self.time_data), list(self.temp_bot1))
self.line_bot2.setData(list(self.time_data), list(self.temp_bot2))
# Update setpoint lines if provided
if setpoint_top is not None:
# Create setpoint data arrays matching time data
setpoint_times = list(self.time_data)
setpoint_top_data = [setpoint_top] * len(setpoint_times)
setpoint_bot_data = [setpoint_bot1 if setpoint_bot1 is not None else setpoint_bot2] * len(setpoint_times)
self.line_target_top.setData(setpoint_times, setpoint_top_data)
self.line_target_bot.setData(setpoint_times, setpoint_bot_data)
class SerialWorker(QThread):
temperature_update = pyqtSignal(float, float, float)
connection_lost = pyqtSignal()
status_update = pyqtSignal(dict)
setpoint_update = pyqtSignal(float, float, float) # New signal for setpoints
def __init__(self):
super().__init__()
self.serial_port = None
self.running = False
def connect_port(self, port, baud=115200):
try:
self.serial_port = serial.Serial(port, baud, timeout=1)
self.running = True
return True
except:
return False
def disconnect(self):
self.running = False
if self.serial_port:
self.serial_port.close()
def run(self):
while self.running:
try:
if self.serial_port and self.serial_port.is_open:
# Request temperature
self.send_command(CMD_GET_TEMP, b'')
response = self.read_response()
if response and response['cmd'] == CMD_GET_TEMP:
temps = struct.unpack('fff', response['data'])
self.temperature_update.emit(*temps)
# Request status
self.send_command(CMD_GET_STATUS, b'')
response = self.read_response()
if response and response['cmd'] == CMD_GET_STATUS:
if len(response['data']) >= 13: # Updated to include setpoints
status = {
'running': bool(response['data'][0]),
'segment': response['data'][1]
}
# Extract setpoints (assuming they're sent as floats)
setpoints = struct.unpack('fff', response['data'][2:14])
self.setpoint_update.emit(*setpoints)
self.status_update.emit(status)
time.sleep(0.5)
except:
self.connection_lost.emit()
self.running = False
# ... (keep all other SerialWorker methods as before)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.serial_worker = SerialWorker()
self.serial_worker.temperature_update.connect(self.update_temperature)
self.serial_worker.connection_lost.connect(self.handle_connection_lost)
self.serial_worker.status_update.connect(self.update_status)
self.serial_worker.setpoint_update.connect(self.update_setpoints) # New connection
self.current_setpoints = (25, 25, 25) # Store current setpoints
self.init_ui()
def init_ui(self):
self.setWindowTitle("BGA Rework Station Control")
self.setGeometry(100, 100, 1200, 800)
# Central widget
central_widget = QWidget()
self.setCentralWidget(central_widget)
# Main layout
main_layout = QVBoxLayout(central_widget)
# Connection bar (same as before)
conn_layout = QHBoxLayout()
self.port_combo = QComboBox()
self.refresh_ports()
conn_layout.addWidget(QLabel("Port:"))
conn_layout.addWidget(self.port_combo)
self.refresh_btn = QPushButton("Refresh")
self.refresh_btn.clicked.connect(self.refresh_ports)
conn_layout.addWidget(self.refresh_btn)
self.connect_btn = QPushButton("Connect")
self.connect_btn.clicked.connect(self.toggle_connection)
conn_layout.addWidget(self.connect_btn)
self.status_label = QLabel("Disconnected")
self.status_label.setStyleSheet("color: red")
conn_layout.addWidget(self.status_label)
# Profile status indicator
self.profile_status_label = QLabel("Profile: Stopped")
self.profile_status_label.setStyleSheet("color: gray; font-weight: bold")
conn_layout.addWidget(self.profile_status_label)
conn_layout.addStretch()
main_layout.addLayout(conn_layout)
# Tab widget
self.tabs = QTabWidget()
# Temperature monitoring tab
temp_tab = QWidget()
temp_layout = QVBoxLayout(temp_tab)
# Current temperatures display
temp_display_layout = QHBoxLayout()
self.temp_top_label = QLabel("Top: --°C")
self.temp_top_label.setStyleSheet("font-size: 20px; font-weight: bold")
temp_display_layout.addWidget(self.temp_top_label)
self.temp_bot1_label = QLabel("Bot1: --°C")
self.temp_bot1_label.setStyleSheet("font-size: 20px; font-weight: bold")
temp_display_layout.addWidget(self.temp_bot1_label)
self.temp_bot2_label = QLabel("Bot2: --°C")
self.temp_bot2_label.setStyleSheet("font-size: 20px; font-weight: bold")
temp_display_layout.addWidget(self.temp_bot2_label)
temp_display_layout.addStretch()
temp_layout.addLayout(temp_display_layout)
# Setpoint display
setpoint_layout = QHBoxLayout()
self.setpoint_top_label = QLabel("Target Top: --°C")
self.setpoint_top_label.setStyleSheet("font-size: 14px; color: red")
setpoint_layout.addWidget(self.setpoint_top_label)
self.setpoint_bot1_label = QLabel("Target Bot1: --°C")
self.setpoint_bot1_label.setStyleSheet("font-size: 14px; color: green")
setpoint_layout.addWidget(self.setpoint_bot1_label)
self.setpoint_bot2_label = QLabel("Target Bot2: --°C")
self.setpoint_bot2_label.setStyleSheet("font-size: 14px; color: blue")
setpoint_layout.addWidget(self.setpoint_bot2_label)
setpoint_layout.addStretch()
temp_layout.addLayout(setpoint_layout)
# Temperature plot
self.temp_plot = TemperaturePlot()
temp_layout.addWidget(self.temp_plot)
# Control buttons
control_layout = QHBoxLayout()
self.profile_combo = QComboBox()
self.profile_combo.addItems([f"Profile {i+1}" for i in range(10)])
control_layout.addWidget(QLabel("Profile:"))
control_layout.addWidget(self.profile_combo)
self.start_btn = QPushButton("Start Profile")
self.start_btn.clicked.connect(self.start_profile)
self.start_btn.setStyleSheet("QPushButton { background-color: green; color: white; font-weight: bold; }")
control_layout.addWidget(self.start_btn)
self.stop_btn = QPushButton("Stop")
self.stop_btn.clicked.connect(self.stop_profile)
self.stop_btn.setStyleSheet("QPushButton { background-color: red; color: white; font-weight: bold; }")
self.stop_btn.setEnabled(False)
control_layout.addWidget(self.stop_btn)
# Clear plot button
self.clear_plot_btn = QPushButton("Clear Plot")
self.clear_plot_btn.clicked.connect(self.clear_plot)
control_layout.addWidget(self.clear_plot_btn)
control_layout.addStretch()
temp_layout.addLayout(control_layout)
self.tabs.addTab(temp_tab, "Temperature Monitor")
# Profile editor tab (same as before)
self.profile_editor = ProfileEditor()
self.tabs.addTab(self.profile_editor, "Profile Editor")
# PID tuning tab (same as before)
self.pid_tuner = PIDTuner(self.serial_worker)
self.tabs.addTab(self.pid_tuner, "PID Tuning")
# Manual control tab (same as before)
manual_tab = QWidget()
manual_layout = QVBoxLayout(manual_tab)
manual_grid = QGridLayout()
self.manual_top = QDoubleSpinBox()
self.manual_top.setRange(0, 300)
self.manual_top.setValue(25)
manual_grid.addWidget(QLabel("Top Setpoint:"), 0, 0)
manual_grid.addWidget(self.manual_top, 0, 1)
self.manual_bot1 = QDoubleSpinBox()
self.manual_bot1.setRange(0, 300)
self.manual_bot1.setValue(25)
manual_grid.addWidget(QLabel("Bottom 1 Setpoint:"), 1, 0)
manual_grid.addWidget(self.manual_bot1, 1, 1)
self.manual_bot2 = QDoubleSpinBox()
self.manual_bot2.setRange(0, 300)
self.manual_bot2.setValue(25)
manual_grid.addWidget(QLabel("Bottom 2 Setpoint:"), 2, 0)
manual_grid.addWidget(self.manual_bot2, 2, 1)
manual_layout.addLayout(manual_grid)
self.manual_apply_btn = QPushButton("Apply Setpoints")
self.manual_apply_btn.clicked.connect(self.apply_manual_setpoints)
manual_layout.addWidget(self.manual_apply_btn)
manual_layout.addStretch()
self.tabs.addTab(manual_tab, "Manual Control")
main_layout.addWidget(self.tabs)
# Menu bar (same as before)
menubar = self.menuBar()
file_menu = menubar.addMenu('File')
save_profile_action = QAction('Save Profile', self)
save_profile_action.triggered.connect(self.save_profile)
file_menu.addAction(save_profile_action)
load_profile_action = QAction('Load Profile', self)
load_profile_action.triggered.connect(self.load_profile)
file_menu.addAction(load_profile_action)
# ... (keep refresh_ports, toggle_connection, handle_connection_lost as before)
def update_temperature(self, top, bot1, bot2):
self.temp_top_label.setText(f"Top: {top:.1f}°C")
self.temp_bot1_label.setText(f"Bot1: {bot1:.1f}°C")
self.temp_bot2_label.setText(f"Bot2: {bot2:.1f}°C")
# Update plot with current setpoints
self.temp_plot.update_data(top, bot1, bot2,
self.current_setpoints[0],
self.current_setpoints[1],
self.current_setpoints[2])
def update_setpoints(self, top, bot1, bot2):
"""Update current setpoint display"""
self.current_setpoints = (top, bot1, bot2)
self.setpoint_top_label.setText(f"Target Top: {top:.1f}°C")
self.setpoint_bot1_label.setText(f"Target Bot1: {bot1:.1f}°C")
self.setpoint_bot2_label.setText(f"Target Bot2: {bot2:.1f}°C")
def update_status(self, status):
if status['running']:
self.start_btn.setEnabled(False)
self.stop_btn.setEnabled(True)
self.profile_status_label.setText(f"Profile: Running (Segment {status['segment'] + 1})")
self.profile_status_label.setStyleSheet("color: green; font-weight: bold")
else:
self.start_btn.setEnabled(True)
self.stop_btn.setEnabled(False)
self.profile_status_label.setText("Profile: Stopped")
self.profile_status_label.setStyleSheet("color: gray; font-weight: bold")
def start_profile(self):
if not self.serial_worker.running:
QMessageBox.warning(self, "Not Connected",
"Please connect to the device first")
return
# Get the current profile from the editor
profile = self.profile_editor.get_profile()
profile_index = self.profile_combo.currentIndex()
# Start temperature recording with profile preview
self.temp_plot.start_recording(profile)
# Send profile to Arduino and start it
self.serial_worker.set_profile(profile_index, profile)
time.sleep(0.1) # Give time for the profile to be saved
# Start the profile
self.serial_worker.start_profile(profile_index)
QMessageBox.information(self, "Profile Started",
f"Temperature profile '{profile.name}' has been started.\n"
f"Temperature logging is now active.")
def stop_profile(self):
self.serial_worker.stop_profile()
self.temp_plot.stop_recording()
QMessageBox.information(self, "Profile Stopped",
"Temperature profile has been stopped.\n"
"Temperature logging is now inactive.")
def clear_plot(self):
"""Clear the temperature plot"""
self.temp_plot.clear_data()
QMessageBox.information(self, "Plot Cleared", "Temperature plot has been cleared.")
# ... (keep all other methods as before: apply_manual_setpoints, save_profile, load_profile, etc.)
# ... (keep all other classes and the main function as before)
Updated Arduino Sketch - Modified Status Response
// In the sendStatus() function, modify to include setpoints:
void sendStatus() {
Serial.write(START_BYTE);
Serial.write(CMD_GET_STATUS);
Serial.write(14); // Increased size to include setpoints
Serial.write(profileRunning ? 0x01 : 0x00);
Serial.write(currentSegment);
// Send current setpoints as floats
Serial.write((byte*)&setpoint_top, 4);
Serial.write((byte*)&setpoint_bot1, 4);
Serial.write((byte*)&setpoint_bot2, 4);
Serial.write(END_BYTE);
}
Key Changes Made:
-
Temperature Plot Control:
- Plot only starts recording when a profile is started
- Added
start_recording() and stop_recording() methods
- Added
clear_data() method to clear the plot
-
Profile Visualization:
- Added
plot_profile_preview() to show the target temperature profile
- Profile is plotted as a yellow dashed line when starting
- Shows the complete temperature curve including ramp and soak phases
-
Enhanced UI:
- Added setpoint display labels showing current target temperatures
- Added profile status indicator showing running state and current segment
- Added "Clear Plot" button for manual plot clearing
- Improved visual feedback with colored buttons and status labels
-
Real-time Setpoint Tracking:
- Added setpoint updates from Arduino
- Current setpoints are displayed and used in plotting
- Target lines show current setpoints vs. profile preview
-
Better User Experience:
- Clear indication when profile starts/stops
- Visual separation between actual temperatures and targets
- Profile preview helps users verify their temperature curves before starting
Now the system will only start plotting when you begin a temperature profile, and you'll see both your target profile curve and the actual temperature readings in real-time!