Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

import tkinter as tk

from tkinter import ttk

import serial

import matplotlib.pyplot as plt

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

import threading

import time

# Arduino serial port (adjust as needed)

arduino_port = '/dev/ttyACM0'

baud_rate = 9600

# Initialize lists to store data

time_values = []

data_values = []

# Create a function to read data from Arduino

def read_data():

with serial.Serial(arduino_port, baud_rate, timeout=1) as ser:

ser.flush()

start_time = time.time()

while time.time() - start_time < 5:

try:

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

if line:
current_time = time.time() - start_time

time_values.append(current_time)

data_values.append(float(line))

except ValueError:

pass

time.sleep(0.1) # Read data every 100ms

# Create a function to update the plot

def update_plot():

plt.plot(time_values, data_values, '-o')

plt.xlabel('Time (s)')

plt.ylabel('Data Value')

plt.title('Arduino Data Plot')

canvas.draw()

# Create the Tkinter GUI

root = tk.Tk()

root.title('Arduino Data Plot')

frame = ttk.Frame(root)

frame.pack()

# Create a Matplotlib figure

fig, ax = plt.subplots(figsize=(6, 4))

canvas = FigureCanvasTkAgg(fig, master=frame)


canvas_widget = canvas.get_tk_widget()

canvas_widget.pack()

# Create a thread to read data from Arduino

data_thread = threading.Thread(target=read_data)

data_thread.start()

# Update the plot every 100ms

update_interval = 100

root.after(update_interval, update_plot)

root.mainloop()

You might also like