ARDUINO 10
Tue Jan 09 2024 00:01:09 GMT+0000 (Coordinated Universal Time)
Saved by
@马丽
import serial
import matplotlib.pyplot as plt
# Establish serial connection
ser = serial.Serial('COM5', 921600) # Replace 'COM3' with your port
plt.ion() # Turn on interactive mode for live plotting
voltage_data = []
current_data = []
power_data = []
fig, axs = plt.subplots(3, 1)
# Initialize empty plots
lines = [ax.plot([], [], label=label)[0] for ax, label in zip(axs, ['Voltage (V)', 'Current (A)', 'Power (W)'])]
for ax in axs:
ax.legend()
plt.show(block=False) # Ensure non-blocking plot
while True:
# Read data from serial port
arduino_data = ser.readline().decode().strip()
if arduino_data:
data_values = arduino_data.split(',')
if len(data_values) >= 3: # Check for at least 3 values
try:
voltage = float(data_values[0])
current = float(data_values[1])
power = float(data_values[2])
voltage_data.append(voltage)
current_data.append(current)
power_data.append(power)
lines[0].set_data(range(len(voltage_data)), voltage_data)
lines[1].set_data(range(len(current_data)), current_data)
lines[2].set_data(range(len(power_data)), power_data)
for ax in axs:
ax.relim()
ax.autoscale_view()
plt.draw()
plt.pause(0.01) # Update plot every 0.01 seconds
except ValueError as e:
print(f"Error: {e}. Invalid data format received: {arduino_data}")
else:
print(f"Incomplete data received: {arduino_data}")
else:
print("No data received from Arduino")
# Close serial connection
ser.close()
content_copyCOPY
Comments