Hi, the following Arduino code registers data from two sensors and sends it, together with time, and sends it, correctly, to the corresponding serial port:
´´´
void setup() {
Serial.begin(9600);
}
void loop() {
float time = micros() /1e6;
int sensorValue1 = analogRead(A0);
int sensorValue2 = analogRead(A1);
delay(100);
Serial.print(time);
Serial.print(", “);
Serial.print(sensorValue1);
Serial.print(”, ");
Serial.print(sensorValue2);
}
´´´
While the arduino access to the serial port is closed, i run the following Python code (in Python 3.9.9):
´´´
import serial
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import csv
SERIAL_PORT=“/dev/cu.usbserial-10”
BAUD_RATE = 9600
ser = serial.Serial(SERIAL_PORT, BAUD_RATE)
x_vals =
sensorValue1_data=
sensorValue2_data=
def read_and_process_data():
line = ser.readline().decode(“utf-8”).strip()
sensorValues = line.split(", ")
x_vals.append(float(sensorValues[0]))
sensorValue1_data.append(int(sensorValues[1]),base=10)
sensorValue2_data.append(int(sensorValues[2]),base=10)
print(f"Time: {sensorValues[0]}, Sensor1: {sensorValues[1]}, Sensor2: {sensorValues[2]}")
def update_plot(frame):
read_and_process_data()
plt.cla()
plt.plot(x_vals, sensorValue1_data, label = “Sensor1”)
plt.plot(x_vals, sensorValue2_data, label = “Sensor2”)
plt.xlabel(“Time”)
plt.ylabel(“Sensor Values”)
plt.legend()
def on_close(event):
with open(“ard_data.csv”,“w”,newline=“”) as csvfile:
writer = csv.writer(csvfile)
writer.writerow([“Time”, “Sensor1”, “Sensor2”])
for x,s1,s2 in zip(x_vals, sensorValue1_data, sensorValue2_data):
writer.writerow([x,s1,s2])
fig, ax = plt.subplots()
fig.canvas.mpl_connect(“close_event”, on_close)
ani = FuncAnimation(fig, update_plot, interval=10)
plt.show()
´´´
This code is supposed to, by reading the adequate serial port, fractionate the data according to the sensors it came from, append them to lists corresponding to each parameter in consideration in order to make a real plot of them and save the records into a csv file.
Although the csv file is generated, it only has the parameters labels. As for the live plot and data from sensors, non is working. Specifically, I get a frozen / blank matplolib frame as well as the following message in the Visual Studio Code Terminal:
´´´
UserWarning: frames=None which we can infer the length of, did not pass an explicit save_count and passed cache_frame_data=True. To avoid a possibly unbounded cache, frame data caching has been disabled. To suppress this warning either pass cache_frame_data=False
or save_count=MAX_FRAMES
.
ani = FuncAnimation(fig, update_plot, interval=10)
´´´
I would appreciate very much help on how to get this project work…Thank you all.