Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
import sys
import os
# 1. Force pyqtgraph to use PyQt5 to prevent clashes with Visual Studio's background tools
os.environ["PYQTGRAPH_QT_LIB"] = "PyQt5"
from PyQt5.QtWidgets import QApplication
# 2. Instantiate QApplication IMMEDIATELY, before importing pyqtgraph or other UI elements
app = QApplication.instance()
if app is None:
app = QApplication(sys.argv)
# 3. Now it is safe to import the rest of your modules
import serial
import serial.tools.list_ports
import numpy as np
import pyqtgraph as pg
from PyQt5.QtWidgets import (QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QPushButton, QLabel, QComboBox, QInputDialog, QMessageBox)
from PyQt5.QtCore import QTimer
class UsbOscilloscope:
def __init__(self, port, baudrate=115200):
self.ser = serial.Serial(port, baudrate, timeout=1)
self.ser.read_all() # Clear buffer
def send_cmd(self, cmd):
self.ser.write((cmd + '\n').encode('ascii'))
return self.ser.readline().decode('ascii').strip()
def capture(self):
self.send_cmd("DAQ:ARM 0,0") # Arm: Rising Edge, Ch1
self.ser.write(b"DAQ:DATA?\n")
raw_data = self.ser.read(1024)
if len(raw_data) == 1024:
arr = np.frombuffer(raw_data, dtype=np.uint8)
return arr[0:512], arr[512:1024]
return None, None
def close(self):
if self.ser and self.ser.is_open:
self.ser.close()
class OscilloscopeGUI(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("FPGA Oscilloscope Control Panel")
self.resize(1100, 600)
self.scope = None
self.ch1_offset_cal = 0 # Software calibration offset
self.is_running = False
self.init_ui()
# Setup continuous update timer (e.g. 10 FPS)
self.timer = QTimer()
self.timer.timeout.connect(self.update_plot)
# Populate the COM ports on startup
self.refresh_ports()
def init_ui(self):
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QHBoxLayout(central_widget)
# --- LEFT PANEL: PLOT ---
pg.setConfigOption('background', 'k')
self.plot_widget = pg.PlotWidget(title="Live Waveform")
self.plot_widget.setYRange(0, 255)
self.plot_widget.showGrid(x=True, y=True, alpha=0.3)
self.ch1_line = self.plot_widget.plot(pen=pg.mkPen('y', width=2), name="CH1")
self.ch2_line = self.plot_widget.plot(pen=pg.mkPen('c', width=2), name="CH2")
main_layout.addWidget(self.plot_widget, stretch=3)
# --- RIGHT PANEL: CONTROLS ---
control_layout = QVBoxLayout()
# 1. Connection Controls
control_layout.addWidget(QLabel("<b>Connection:</b>"))
self.port_combo = QComboBox()
control_layout.addWidget(self.port_combo)
conn_btn_layout = QHBoxLayout()
self.btn_refresh = QPushButton("Refresh")
self.btn_refresh.clicked.connect(self.refresh_ports)
conn_btn_layout.addWidget(self.btn_refresh)
self.btn_connect = QPushButton("Connect")
self.btn_connect.clicked.connect(self.toggle_connection)
conn_btn_layout.addWidget(self.btn_connect)
control_layout.addLayout(conn_btn_layout)
control_layout.addSpacing(15)
# 2. Trigger Controls
control_layout.addWidget(QLabel("<b>Trigger Level (0-255):</b>"))
self.trig_combo = QComboBox()
self.trig_combo.addItems(["128 (Mid)", "64 (Low)", "192 (High)"])
self.trig_combo.currentIndexChanged.connect(self.update_trigger)
control_layout.addWidget(self.trig_combo)
# 3. Timebase Controls
control_layout.addWidget(QLabel("<b>Timebase:</b>"))
self.time_combo = QComboBox()
self.time_combo.addItems(["100 MSPS (Decim 0)", "1 MSPS (Decim 99)"])
self.time_combo.currentIndexChanged.connect(self.update_timebase)
control_layout.addWidget(self.time_combo)
# 4. Analog Frontend Controls
self.btn_set_offset = QPushButton("Set CH1 Offset (V)")
self.btn_set_offset.clicked.connect(self.set_analog_offset)
control_layout.addWidget(self.btn_set_offset)
control_layout.addSpacing(20)
# 5. Run / Stop / Calibrate
self.btn_run = QPushButton("RUN / STOP")
self.btn_run.setStyleSheet("background-color: gray; color: white; font-weight: bold;")
self.btn_run.clicked.connect(self.toggle_run)
control_layout.addWidget(self.btn_run)
self.btn_cal = QPushButton("Auto-Calibrate CH1 (0V)")
self.btn_cal.clicked.connect(self.calibrate_zero)
control_layout.addWidget(self.btn_cal)
control_layout.addStretch()
main_layout.addLayout(control_layout, stretch=1)
# Disable controls until connected
self.enable_controls(False)
# --- CONNECTION LOGIC ---
def refresh_ports(self):
self.port_combo.clear()
ports = serial.tools.list_ports.comports()
for port in ports:
# Add port description to view, but save the raw device name (e.g. 'COM3') as the data
self.port_combo.addItem(f"{port.device} - {port.description}", port.device)
def toggle_connection(self):
if self.scope is None:
# Attempt to connect
if self.port_combo.count() == 0:
QMessageBox.warning(self, "Warning", "No COM ports found!")
return
selected_port = self.port_combo.currentData()
try:
self.scope = UsbOscilloscope(selected_port)
self.btn_connect.setText("Disconnect")
self.port_combo.setEnabled(False)
self.btn_refresh.setEnabled(False)
self.enable_controls(True)
self.btn_run.setStyleSheet("background-color: green; color: white; font-weight: bold;")
# Send initial default configurations
self.update_trigger()
self.update_timebase()
except Exception as e:
QMessageBox.critical(self, "Connection Error", f"Failed to connect to {selected_port}.\n\nError: {str(e)}")
else:
# Disconnect
self.timer.stop()
self.is_running = False
self.scope.close()
self.scope = None
self.btn_connect.setText("Connect")
self.port_combo.setEnabled(True)
self.btn_refresh.setEnabled(True)
self.enable_controls(False)
self.btn_run.setStyleSheet("background-color: gray; color: white; font-weight: bold;")
def enable_controls(self, enabled):
self.trig_combo.setEnabled(enabled)
self.time_combo.setEnabled(enabled)
self.btn_set_offset.setEnabled(enabled)
self.btn_run.setEnabled(enabled)
self.btn_cal.setEnabled(enabled)
# --- BUTTON LOGIC ---
def update_trigger(self):
if self.scope:
val = self.trig_combo.currentText().split()[0]
print(self.scope.send_cmd(f"DAQ:TRIG:LEV {val}"))
def update_timebase(self):
if self.scope:
decim = "0" if "0" in self.time_combo.currentText() else "99"
print(self.scope.send_cmd(f"DAQ:TIMEBASE {decim}"))
def set_analog_offset(self):
val, ok = QInputDialog.getDouble(self, "Offset", "Enter CH1 Offset (-5.0 to 5.0 V):", 0.0, -5.0, 5.0, 2)
if ok and self.scope:
print(self.scope.send_cmd(f"CHAN1:OFFSET {val}"))
def toggle_run(self):
self.is_running = not self.is_running
if self.is_running:
self.btn_run.setStyleSheet("background-color: red; color: white; font-weight: bold;")
self.timer.start(100) # Update every 100ms (10 FPS)
else:
self.btn_run.setStyleSheet("background-color: green; color: white; font-weight: bold;")
self.timer.stop()
def update_plot(self):
ch1, ch2 = self.scope.capture()
if ch1 is not None:
# Apply software calibration offset to CH1
ch1_calibrated = np.clip(ch1.astype(int) + self.ch1_offset_cal, 0, 255)
self.ch1_line.setData(ch1_calibrated)
self.ch2_line.setData(ch2)
# --- CALIBRATION SEQUENCE ---
def calibrate_zero(self):
was_running = self.is_running
if was_running:
self.timer.stop()
msg = QMessageBox.information(self, "Calibration",
"Please disconnect any signals and SHORT Channel 1 to Ground.\n\nClick OK when ready.",
QMessageBox.Ok | QMessageBox.Cancel)
if msg == QMessageBox.Ok:
self.scope.send_cmd("CHAN1:OFFSET 0.0")
ch1, _ = self.scope.capture()
if ch1 is not None:
avg_val = np.mean(ch1)
self.ch1_offset_cal = 128 - avg_val
QMessageBox.information(self, "Success", f"Calibrated!\nDC Offset Error was: {self.ch1_offset_cal:.2f} ADC steps.")
if was_running:
self.timer.start(100)
if __name__ == '__main__':
# 4. Force pyqtgraph to initialize its environment
pg.setConfigOption('background', 'k')
# 5. Create and show the window
window = OscilloscopeGUI()
window.show()
# 6. Run the application loop
sys.exit(app.exec_())b5d2d36f5This file is pinned to the selected release. Download the original to open it in your design tool.