Creating a complete BGA rework machine control system with an Arduino Mega and a Python GUI is a complex task that involves both embedded programming and desktop application development. Below, I will outline a solution with detailed code for both the Arduino firmware and the Python GUI. This solution will include the features you requested, but please note that this is a starting point, and you may need to refine it based on your specific hardware and requirements.
Arduino Firmware (C++)
The Arduino firmware will handle temperature control using PID, manage temperature profiles, and communicate with the Python GUI over USB. We'll use the MAX6675 library for thermocouple readings, the PID_v1 library for PID control, and EEPROM to store profiles.
Libraries Required
MAX6675 (for thermocouples)
PID_v1 (for PID control)
EEPROM (included in Arduino IDE, for storing profiles)
Install these libraries via the Arduino Library Manager.
Arduino Code
#include <max6675.h>
#include <PID_v1.h>
#include <EEPROM.h>
// Pin definitions for MAX6675
#define TOP_THERMO_CS 10
#define BOT1_THERMO_CS 9
#define BOT2_THERMO_CS 8
#define THERMO_SO 12
#define THERMO_SCK 13
// Pin definitions for heaters (PWM pins)
#define TOP_HEATER_PIN 3
#define BOT1_HEATER_PIN 5
#define BOT2_HEATER_PIN 6
// Profile structure
#define MAX_SEGMENTS 8
#define MAX_PROFILES 5
struct ProfileSegment {
float targetTemp;
unsigned long duration; // in seconds
};
struct TemperatureProfile {
ProfileSegment segments[MAX_SEGMENTS];
int numSegments;
};
TemperatureProfile topProfiles[MAX_PROFILES];
TemperatureProfile botProfiles[MAX_PROFILES];
// PID variables
double topTemp, bot1Temp, bot2Temp;
double topSetpoint, bot1Setpoint, bot2Setpoint;
double topOutput, bot1Output, bot2Output;
// PID tuning parameters
double topKp = 2, topKi = 0.5, topKd = 1;
double bot1Kp = 2, bot1Ki = 0.5, bot1Kd = 1;
double bot2Kp = 2, bot2Ki = 0.5, bot2Kd = 1;
// PID objects
PID topPID(&topTemp, &topOutput, &topSetpoint, topKp, topKi, topKd, DIRECT);
PID bot1PID(&bot1Temp, &bot1Output, &bot1Setpoint, bot1Kp, bot1Ki, bot1Kd, DIRECT);
PID bot2PID(&bot2Temp, &bot2Output, &bot2Setpoint, bot2Kp, bot2Ki, bot2Kd, DIRECT);
// MAX6675 objects
MAX6675 topThermo(THERMO_SCK, TOP_THERMO_CS, THERMO_SO);
MAX6675 bot1Thermo(THERMO_SCK, BOT1_THERMO_CS, THERMO_SO);
MAX6675 bot2Thermo(THERMO_SCK, BOT2_THERMO_CS, THERMO_SO);
// State variables
bool isRunning = false;
int currentProfile = 0;
unsigned long segmentStartTime = 0;
int currentSegment = 0;
void setup() {
Serial.begin(115200);
// Initialize heater pins
pinMode(TOP_HEATER_PIN, OUTPUT);
pinMode(BOT1_HEATER_PIN, OUTPUT);
pinMode(BOT2_HEATER_PIN, OUTPUT);
// Initialize PID
topPID.SetMode(AUTOMATIC);
bot1PID.SetMode(AUTOMATIC);
bot2PID.SetMode(AUTOMATIC);
topPID.SetOutputLimits(0, 255);
bot1PID.SetOutputLimits(0, 255);
bot2PID.SetOutputLimits(0, 255);
// Load profiles from EEPROM
loadProfiles();
}
void loop() {
// Read temperatures
topTemp = topThermo.readCelsius();
bot1Temp = bot1Thermo.readCelsius();
bot2Temp = bot2Thermo.readCelsius();
// Send temperature data to PC
sendTemperatureData();
// Handle serial commands
handleSerialCommands();
// Run profile if active
if (isRunning) {
runProfile();
}
// Update PID
topPID.Compute();
bot1PID.Compute();
bot2PID.Compute();
// Apply PID output to heaters
analogWrite(TOP_HEATER_PIN, topOutput);
analogWrite(BOT1_HEATER_PIN, bot1Output);
analogWrite(BOT2_HEATER_PIN, bot2Output);
}
void runProfile() {
unsigned long currentTime = millis() / 1000; // Convert to seconds
unsigned long elapsedTime = currentTime - segmentStartTime;
if (currentSegment < topProfiles[currentProfile].numSegments) {
topSetpoint = topProfiles[currentProfile].segments[currentSegment].targetTemp;
bot1Setpoint = botProfiles[currentProfile].segments[currentSegment].targetTemp;
bot2Setpoint = botProfiles[currentProfile].segments[currentSegment].targetTemp;
if (elapsedTime >= topProfiles[currentProfile].segments[currentSegment].duration) {
currentSegment++;
segmentStartTime = currentTime;
}
} else {
// Profile complete
isRunning = false;
analogWrite(TOP_HEATER_PIN, 0);
analogWrite(BOT1_HEATER_PIN, 0);
analogWrite(BOT2_HEATER_PIN, 0);
}
}
void sendTemperatureData() {
Serial.print("TEMP,");
Serial.print(topTemp);
Serial.print(",");
Serial.print(bot1Temp);
Serial.print(",");
Serial.print(bot2Temp);
Serial.println();
}
void handleSerialCommands() {
if (Serial.available() > 0) {
String command = Serial.readStringUntil('\n');
if (command.startsWith("START,")) {
currentProfile = command.substring(6).toInt();
isRunning = true;
currentSegment = 0;
segmentStartTime = millis() / 1000;
} else if (command.startsWith("STOP")) {
isRunning = false;
} else if (command.startsWith("PROFILE,")) {
parseProfile(command);
} else if (command.startsWith("PID,")) {
parsePID(command);
}
}
}
void parseProfile(String command) {
// Format: PROFILE,profileNum,isTop,segmentNum,targetTemp,duration
int profileNum = command.substring(8, command.indexOf(',', 8)).toInt();
bool isTop = command.substring(command.indexOf(',', 8) + 1, command.indexOf(',', command.indexOf(',', 8) + 1)).toInt();
int segmentNum = command.substring(command.indexOf(',', command.indexOf(',', 8) + 1) + 1, command.indexOf(',', command.indexOf(',', command.indexOf(',', 8) + 1) + 1)).toInt();
float targetTemp = command.substring(command.indexOf(',', command.indexOf(',', command.indexOf(',', 8) + 1) + 1) + 1, command.indexOf(',', command.indexOf(',', command.indexOf(',', command.indexOf(',', 8) + 1) + 1) + 1)).toFloat();
unsigned long duration = command.substring(command.indexOf(',', command.indexOf(',', command.indexOf(',', command.indexOf(',', 8) + 1) + 1) + 1) + 1).toInt();
if (isTop) {
topProfiles[profileNum].segments[segmentNum].targetTemp = targetTemp;
topProfiles[profileNum].segments[segmentNum].duration = duration;
topProfiles[profileNum].numSegments = max(topProfiles[profileNum].numSegments, segmentNum + 1);
} else {
botProfiles[profileNum].segments[segmentNum].targetTemp = targetTemp;
botProfiles[profileNum].segments[segmentNum].duration = duration;
botProfiles[profileNum].numSegments = max(botProfiles[profileNum].numSegments, segmentNum + 1);
}
saveProfiles();
}
void parsePID(String command) {
// Format: PID,heater,Kp,Ki,Kd
int heater = command.substring(4, command.indexOf(',', 4)).toInt();
float Kp = command.substring(command.indexOf(',', 4) + 1, command.indexOf(',', command.indexOf(',', 4) + 1)).toFloat();
float Ki = command.substring(command.indexOf(',', command.indexOf(',', 4) + 1) + 1, command.indexOf(',', command.indexOf(',', command.indexOf(',', 4) + 1) + 1)).toFloat();
float Kd = command.substring(command.indexOf(',', command.indexOf(',', command.indexOf(',', 4) + 1) + 1) + 1).toFloat();
if (heater == 0) { // Top heater
topKp = Kp; topKi = Ki; topKd = Kd;
topPID.SetTunings(topKp, topKi, topKd);
} else if (heater == 1) { // Bottom heater 1
bot1Kp = Kp; bot1Ki = Ki; bot1Kd = Kd;
bot1PID.SetTunings(bot1Kp, bot1Ki, bot1Kd);
} else if (heater == 2) { // Bottom heater 2
bot2Kp = Kp; bot2Ki = Ki; bot2Kd = Kd;
bot2PID.SetTunings(bot2Kp, bot2Ki, bot2Kd);
}
}
void saveProfiles() {
int addr = 0;
for (int i = 0; i < MAX_PROFILES; i++) {
EEPROM.put(addr, topProfiles[i]);
addr += sizeof(TemperatureProfile);
EEPROM.put(addr, botProfiles[i]);
addr += sizeof(TemperatureProfile);
}
}
void loadProfiles() {
int addr = 0;
for (int i = 0; i < MAX_PROFILES; i++) {
EEPROM.get(addr, topProfiles[i]);
addr += sizeof(TemperatureProfile);
EEPROM.get(addr, botProfiles[i]);
addr += sizeof(TemperatureProfile);
}
}
Python GUI (Python)
The Python GUI will communicate with the Arduino over USB, allowing you to send profiles, edit PID parameters, autotune PID, and plot temperatures in real-time. We'll use tkinter for the GUI, pyserial for serial communication, and matplotlib for plotting.
Libraries Required
pyserial
matplotlib
tkinter (included with Python)
Install the required libraries using pip:
pip install pyserial matplotlib
Python Code
import tkinter as tk
from tkinter import ttk
import serial
import serial.tools.list_ports
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import threading
import time
class BGAReworkGUI:
def __init__(self, root):
self.root = root
self.root.title("BGA Rework Station Control")
self.serial_port = None
self.temperatures = {'top': [], 'bot1': [], 'bot2': []}
self.times = []
self.create_gui()
self.start_plotting()
def create_gui(self):
# Serial port selection
self.port_label = ttk.Label(self.root, text="Select Serial Port:")
self.port_label.grid(row=0, column=0, padx=5, pady=5)
self.port_combobox = ttk.Combobox(self.root, values=self.get_serial_ports())
self.port_combobox.grid(row=0, column=1, padx=5, pady=5)
self.connect_button = ttk.Button(self.root, text="Connect", command=self.connect_serial)
self.connect_button.grid(row=0, column=2, padx=5, pady=5)
# Profile selection
self.profile_label = ttk.Label(self.root, text="Select Profile:")
self.profile_label.grid(row=1, column=0, padx=5, pady=5)
self.profile_combobox = ttk.Combobox(self.root, values=[str(i) for i in range(5)])
self.profile_combobox.grid(row=1, column=1, padx=5, pady=5)
self.start_button = ttk.Button(self.root, text="Start Profile", command=self.start_profile)
self.start_button.grid(row=1, column=2, padx=5, pady=5)
self.stop_button = ttk.Button(self.root, text="Stop", command=self.stop_profile)
self.stop_button.grid(row=1, column=3, padx=5, pady=5)
# Profile editor
self.profile_frame = ttk.LabelFrame(self.root, text="Profile Editor")
self.profile_frame.grid(row=2, column=0, columnspan=4, padx=5, pady=5, sticky="ew")
self.profile_entries = []
for i in range(8):
ttk.Label(self.profile_frame, text=f"Segment {i+1}:").grid(row=i, column=0, padx=5, pady=2)
top_temp = ttk.Entry(self.profile_frame, width=10)
top_temp.grid(row=i, column=1, padx=5, pady=2)
bot_temp = ttk.Entry(self.profile_frame, width=10)
bot_temp.grid(row=i, column=2, padx=5, pady=2)
duration = ttk.Entry(self.profile_frame, width=10)
duration.grid(row=i, column=3, padx=5, pady=2)
self.profile_entries.append((top_temp, bot_temp, duration))
self.save_profile_button = ttk.Button(self.profile_frame, text="Save Profile", command=self.save_profile)
self.save_profile_button.grid(row=8, column=0, columnspan=4, padx=5, pady=5)
# PID tuning
self.pid_frame = ttk.LabelFrame(self.root, text="PID Tuning")
self.pid_frame.grid(row=3, column=0, columnspan=4, padx=5, pady=5, sticky="ew")
self.pid_entries = []
for i, heater in enumerate(["Top", "Bottom 1", "Bottom 2"]):
ttk.Label(self.pid_frame, text=f"{heater} Kp:").grid(row=i, column=0, padx=5, pady=2)
kp = ttk.Entry(self.pid_frame, width=10)
kp.grid(row=i, column=1, padx=5, pady=2)
ttk.Label(self.pid_frame, text=f"{heater} Ki:").grid(row=i, column=2, padx=5, pady=2)
ki = ttk.Entry(self.pid_frame, width=10)
ki.grid(row=i, column=3, padx=5, pady=2)
ttk.Label(self.pid_frame, text=f"{heater} Kd:").grid(row=i, column=4, padx=5, pady=2)
kd = ttk.Entry(self.pid_frame, width=10)
kd.grid(row=i, column=5, padx=5, pady=2)
self.pid_entries.append((kp, ki, kd))
self.save_pid_button = ttk.Button(self.pid_frame, text="Save PID", command=self.save_pid)
self.save_pid_button.grid(row=3, column=0, columnspan=6, padx=5, pady=5)
# Plot
self.fig, self.ax = plt.subplots()
self.canvas = FigureCanvasTkAgg(self.fig, master=self.root)
self.canvas.get_tk_widget().grid(row=0, column=4, rowspan=4, padx=5, pady=5)
def get_serial_ports(self):
ports = serial.tools.list_ports.comports()
return [port.device for port in ports]
def connect_serial(self):
port = self.port_combobox.get()
if port:
try:
self.serial_port = serial.Serial(port, 115200, timeout=1)
self.connect_button.config(text="Disconnect", command=self.disconnect_serial)
threading.Thread(target=self.read_serial, daemon=True).start()
except Exception as e:
print(f"Error connecting to serial port: {e}")
def disconnect_serial(self):
if self.serial_port:
self.serial_port.close()
self.serial_port = None
self.connect_button.config(text="Connect", command=self.connect_serial)
def read_serial(self):
while self.serial_port and self.serial_port.is_open:
try:
line = self.serial_port.readline().decode().strip()
if line.startswith("TEMP,"):
temps = line.split(",")[1:]
if len(temps) == 3:
self.temperatures['top'].append(float(temps[0]))
self.temperatures['bot1'].append(float(temps[1]))
self.temperatures['bot2'].append(float(temps[2]))
self.times.append(time.time())
if len(self.times) > 100: # Limit data points
self.temperatures['top'].pop(0)
self.temperatures['bot1'].pop(0)
self.temperatures['bot2'].pop(0)
self.times.pop(0)
except Exception as e:
print(f"Error reading serial: {e}")
def start_plotting(self):
def update_plot():
if self.times:
self.ax.clear()
self.ax.plot(self.times, self.temperatures['top'], label='Top')
self.ax.plot(self.times, self.temperatures['bot1'], label='Bottom 1')
self.ax.plot(self.times, self.temperatures['bot2'], label='Bottom 2')
self.ax.legend()
self.ax.set_xlabel("Time (s)")
self.ax.set_ylabel("Temperature (°C)")
self.canvas.draw()
self.root.after(1000, update_plot)
update_plot()
def start_profile(self):
if self.serial_port:
profile_num = self.profile_combobox.get()
self.serial_port.write(f"START,{profile_num}\n".encode())
def stop_profile(self):
if self.serial_port:
self.serial_port.write("STOP\n".encode())
def save_profile(self):
if self.serial_port:
profile_num = self.profile_combobox.get()
for i, (top_temp, bot_temp, duration) in enumerate(self.profile_entries):
if top_temp.get() and duration.get():
self.serial_port.write(f"PROFILE,{profile_num},1,{i},{top_temp.get()},{duration.get()}\n".encode())
if bot_temp.get() and duration.get():
self.serial_port.write(f"PROFILE,{profile_num},0,{i},{bot_temp.get()},{duration.get()}\n".encode())
def save_pid(self):
if self.serial_port:
for i, (kp, ki, kd) in enumerate(self.pid_entries):
if kp.get() and ki.get() and kd.get():
self.serial_port.write(f"PID,{i},{kp.get()},{ki.get()},{kd.get()}\n".encode())
if __name__ == "__main__":
root = tk.Tk()
app = BGAReworkGUI(root)
root.mainloop()
Notes and Considerations
-
Hardware Setup:
- Ensure your MAX6675 modules are correctly wired to the Arduino Mega.
- Use appropriate MOSFETs or SSRs to control the heaters, as Arduino pins cannot directly drive high-power loads.
- Test the thermocouples and heaters individually before integrating them into the system.
-
PID Autotuning:
- The provided code does not include PID autotuning. You can implement this using the
PID_AutoTune_v0 library for Arduino, but it requires careful integration and testing. Autotuning typically involves running a step response test and analyzing the system's behavior.
-
Safety:
- BGA rework involves high temperatures, so implement safety features like temperature limits, emergency stop, and thermal runaway protection.
- Test the system thoroughly in a controlled environment before using it on actual BGA chips.
-
EEPROM Storage:
- The EEPROM on the Arduino Mega has limited write cycles (about 100,000 per address). Consider using an external EEPROM or SD card for more robust storage if frequent profile updates are expected.
-
GUI Enhancements:
- The Python GUI can be enhanced with features like profile loading from files, more detailed plotting options, and error handling.
-
Communication Protocol:
- The serial communication protocol is simple (comma-separated values). For a more robust system, consider using a more structured protocol like JSON or a binary format.
This code provides a foundation for your BGA rework station. You may need to adjust it based on your specific hardware, performance requirements, and safety considerations.