You are on page 1of 3

import tkinter as tk

from tkinter import ttk

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

import matplotlib.pyplot as plt

import serial

from datetime import datetime

import time

# Initialize tkinter window

root = tk.Tk()

root.title("Serial Data Plotter")

# Create a figure and axis for plotting

fig, ax = plt.subplots()

ax.set_xlabel("Time")

ax.set_ylabel("Value")

# Create a canvas for matplotlib and add it to the tkinter window

canvas = FigureCanvasTkAgg(fig, master=root)

canvas_widget = canvas.get_tk_widget()

canvas_widget.pack()

# Initialize serial communication with Arduino

ser = serial.Serial('COM1', 9600) # Replace 'COM1' with your Arduino's port


# Initialize variables for data and timestamps

data = []

timestamps = []

# Function to update the plot

def update_plot():

global data, timestamps

# Read data from Arduino and append it to the lists

try:

serial_data = ser.readline().decode('utf-8').strip()

value = float(serial_data)

data.append(value)

timestamps.append(datetime.now().strftime('%H:%M:%S'))

except ValueError:

pass

# Clear the plot and start a new one after 20 seconds

if len(data) > 200: # Assuming 100ms interval, this is equivalent to 20 seconds

data.clear()

timestamps.clear()

ax.clear()

ax.plot(timestamps, data, label="Sensor Data")

ax.legend()
ax.set_xlabel("Time")

ax.set_ylabel("Value")

ax.set_title("Arduino Serial Data")

# Annotate data points

for i, txt in enumerate(data):

ax.annotate(txt, (timestamps[i], data[i]))

canvas.draw()

root.after(100, update_plot) # Update plot every 100ms

# Start updating the plot

update_plot()

# Run tkinter main loop

root.mainloop()

# Close the serial connection when the program exits

ser.close()

You might also like