Certainly! Below is the revised code for a PyQt application that controls a Keithley instrument with GPIB interface to set voltages for specific durations and record the measurements in an Excel file. I've added a few improvements, like more clear variable naming, and I've provided the ability to parse CSV-style input from the QLineEdit widgets.
Please note that you'd need to have the PyVISA, PyQt5, pandas, and openpyxl packages installed, and also ensure your GPIB interface is correctly set up with the required drivers installed:
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QVBoxLayout, QPushButton, QLineEdit, QLabel
)
import pyvisa
import pandas as pd
from datetime import datetime
import time
class KeithleyControlGUI(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
self.setup_instrument()
def setup_instrument(self):
# Set up GPIB communication with the Keithley instrument
self.rm = pyvisa.ResourceManager()
try:
self.instrument = self.rm.open_resource('GPIB0::1::INSTR')
self.instrument.write("*RST") # Reset instrument to known state
self.instrument.write("SOUR:FUNC VOLT") # Set to voltage source mode
except pyvisa.VisaIOError as e:
self.show_error(f"Could not open resource: {str(e)}")
def initUI(self):
self.setGeometry(200, 200, 500, 300)
self.setWindowTitle('Keithley Control')
self.voltages_input = QLineEdit(self)
self.voltages_input.move(20, 50)
self.voltages_input_label = QLabel("Voltages (comma separated, V):", self)
self.voltages_input_label.move(20, 30)
self.durations_input = QLineEdit(self)
self.durations_input.move(260, 50)
self.durations_input_label = QLabel("Durations (comma separated, s):", self)
self.durations_input_label.move(260, 30)
self.start_button = QPushButton('Start Sequence', self)
self.start_button.move(200, 100)
self.start_button.clicked.connect(self.start_sequence)
self.data = []
self.show()
def start_sequence(self):
try:
voltages_str = self.voltages_input.text()
durations_str = self.durations_input.text()
voltages = list(map(float, voltages_str.split(',')))
durations = list(map(float, durations_str.split(',')))
if len(voltages) != len(durations):
raise ValueError("Number of voltages must match number of durations.")
self.run_sequence(voltages, durations)
self.save_data_to_excel()
except Exception as e:
self.show_error(f"Error during sequence execution: {str(e)}")
def run_sequence(self, voltages, durations):
self.data = [] # Reset data list
for voltage, duration in zip(voltages, durations):
self.instrument.write(f"SOUR:VOLT {voltage}")
time_end = time.time() + duration
while time.time() < time_end:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
measured_voltage = self.instrument.query("MEAS:VOLT?")
measured_current = self.instrument.query("MEAS:CURR?")
self.data.append({
"Timestamp": timestamp,
"Set Voltage (V)": voltage,
"Measured Voltage (V)": measured_voltage,
"Measured Current (A)": measured_current
})
time.sleep(0.1) # Small delay to limit the query rate
def save_data_to_excel(self):
df = pd.DataFrame(self.data)
filename = f"Keithley_Measurements_{datetime.now().strftime('%Y%m%d%H%M%S')}.xlsx"
df.to_excel(filename, index=False)
self.show_info(f"Data saved to {filename}")
def show_error(self, message):
error_dialog = QtWidgets.QErrorMessage(self)
error_dialog.showMessage(message)
def show_info(self, message):
info_dialog = QtWidgets.QMessageBox(self)
info_dialog.setText(message)
info_dialog.exec_()
def main():
app = QApplication(sys.argv)
main_window = KeithleyControlGUI()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Remember to test this code carefully. The instrument I/O operations (self.instrument.query, write, etc.) need to match your specific instrument's SCPI commands (consult its manual for details). The sleep delay between queries in run_sequence should be tuned based on your actual system's performance and the instrument's response time. The show_error function is used to display any errors encountered during the operation of the GUI.
The code assumes that the Keithley instrument is ready to accept SCPI command sequences for setting voltages and querying measurements. Adjustments might be required based on your particular Keithley model's SCPI command syntax and capabilities.