You are on page 1of 3

import matplotlib.

pyplot as plt

import serial

import time

# Function to receive and plot data

def receive_and_plot(serial_port, ax, values, timestamps, plot_interval):

start_time = time.time()

while time.time() - start_time < 5: # Run for 5 seconds initially

try:

data = serial_port.readline().decode('utf-8').strip()

if data:

value = int(data)

values.append(value)

timestamps.append(time.time() - start_time)

ax.clear()

ax.plot(timestamps, values, marker='o', linestyle='-')

ax.set_xlabel('Time (s)')

ax.set_ylabel('Value')

plt.pause(plot_interval)

except ValueError:

pass

# Clear the plot and reset data after 5 seconds

ax.clear()

values.clear()
timestamps.clear()

start_time = time.time()

while True: # Continue plotting after serial reset

try:

data = serial_port.readline().decode('utf-8').strip()

if data:

value = int(data)

values.append(value)

timestamps.append(time.time() - start_time)

ax.clear()

ax.plot(timestamps, values, marker='o', linestyle='-')

ax.set_xlabel('Time (s)')

ax.set_ylabel('Value')

plt.pause(plot_interval)

except ValueError:

pass

# Create a serial connection to Arduino

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

# Create a figure and axis for the plot

fig, ax = plt.subplots()

values = []

timestamps = []
plot_interval = 0.1 # 100ms interval

# Start receiving and plotting data

receive_and_plot(serial_port, ax, values, timestamps, plot_interval)

plt.show() # Display the plot

You might also like