samplecsv_taker.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import tkinter as tk
  2. from tkinter import filedialog
  3. import csv
  4. import serial
  5. import time
  6. class SerialDataLogger:
  7. def __init__(self, root):
  8. self.root = root
  9. self.root.title("Serial Data Logger")
  10. self.serial_port = "COM1" # Change this to your serial port
  11. self.baud_rate = 115200 # Change this to match your device's baud rate
  12. self.is_logging = False
  13. self.sample_count = 0
  14. self.max_samples = 1000000
  15. self.sample_rate = 200
  16. self.data = []
  17. self.create_widgets()
  18. def create_widgets(self):
  19. self.start_button = tk.Button(self.root, text="Start", command=self.start_logging)
  20. self.start_button.pack()
  21. self.stop_button = tk.Button(self.root, text="Stop", command=self.stop_logging)
  22. self.stop_button.pack()
  23. self.save_button = tk.Button(self.root, text="Save", command=self.save_data)
  24. self.save_button.pack()
  25. def start_logging(self):
  26. self.is_logging = True
  27. self.sample_count = 0
  28. self.data = []
  29. try:
  30. self.serial_connection = serial.Serial(self.serial_port, self.baud_rate)
  31. self.root.after(0, self.read_serial_data)
  32. except serial.SerialException:
  33. print("Error: Unable to open serial port.")
  34. def stop_logging(self):
  35. self.is_logging = False
  36. if hasattr(self, 'serial_connection'):
  37. self.serial_connection.close()
  38. def read_serial_data(self):
  39. if self.is_logging:
  40. if self.sample_count < self.max_samples:
  41. try:
  42. raw_data = self.serial_connection.readline().decode().strip()
  43. timestamp = time.time()
  44. self.data.append((timestamp, raw_data))
  45. self.sample_count += 1
  46. except UnicodeDecodeError:
  47. print("Error decoding serial data.")
  48. else:
  49. self.stop_logging()
  50. self.root.after(int(1000 / self.sample_rate), self.read_serial_data)
  51. def save_data(self):
  52. if self.data:
  53. file_path = filedialog.asksaveasfilename(defaultextension=".csv")
  54. if file_path:
  55. with open(file_path, 'w', newline='') as csvfile:
  56. csv_writer = csv.writer(csvfile)
  57. csv_writer.writerow(["Timestamp", "Value"])
  58. csv_writer.writerows(self.data)
  59. print("Data saved to", file_path)
  60. else:
  61. print("No data to save.")
  62. if __name__ == "__main__":
  63. root = tk.Tk()
  64. app = SerialDataLogger(root)
  65. root.mainloop()