12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- import tkinter as tk
- from tkinter import filedialog
- import csv
- import serial
- import time
- class SerialDataLogger:
- def __init__(self, root):
- self.root = root
- self.root.title("Serial Data Logger")
- self.serial_port = "COM1" # Change this to your serial port
- self.baud_rate = 115200 # Change this to match your device's baud rate
- self.is_logging = False
- self.sample_count = 0
- self.max_samples = 1000000
- self.sample_rate = 200
- self.data = []
- self.create_widgets()
- def create_widgets(self):
- self.start_button = tk.Button(self.root, text="Start", command=self.start_logging)
- self.start_button.pack()
- self.stop_button = tk.Button(self.root, text="Stop", command=self.stop_logging)
- self.stop_button.pack()
- self.save_button = tk.Button(self.root, text="Save", command=self.save_data)
- self.save_button.pack()
- def start_logging(self):
- self.is_logging = True
- self.sample_count = 0
- self.data = []
- try:
- self.serial_connection = serial.Serial(self.serial_port, self.baud_rate)
- self.root.after(0, self.read_serial_data)
- except serial.SerialException:
- print("Error: Unable to open serial port.")
- def stop_logging(self):
- self.is_logging = False
- if hasattr(self, 'serial_connection'):
- self.serial_connection.close()
- def read_serial_data(self):
- if self.is_logging:
- if self.sample_count < self.max_samples:
- try:
- raw_data = self.serial_connection.readline().decode().strip()
- timestamp = time.time()
- self.data.append((timestamp, raw_data))
- self.sample_count += 1
- except UnicodeDecodeError:
- print("Error decoding serial data.")
- else:
- self.stop_logging()
- self.root.after(int(1000 / self.sample_rate), self.read_serial_data)
- def save_data(self):
- if self.data:
- file_path = filedialog.asksaveasfilename(defaultextension=".csv")
- if file_path:
- with open(file_path, 'w', newline='') as csvfile:
- csv_writer = csv.writer(csvfile)
- csv_writer.writerow(["Timestamp", "Value"])
- csv_writer.writerows(self.data)
- print("Data saved to", file_path)
- else:
- print("No data to save.")
- if __name__ == "__main__":
- root = tk.Tk()
- app = SerialDataLogger(root)
- root.mainloop()
|