Hello there. I am trying to do a project in which I record analog pressure data from the Arduino Mega in real time and save it to excel using python with the openpyxl library. The Arduino sends data at a fast rate in the serial monitor but compared to the output of the python script, it is lagging behind by a large margin (By lagging, I mean that even when the water source is off, it is still logging pressure from when the water source was on). What can I possibly do in the python script or Arduino program to get a fast sampling rate and record it in real time without lag?
Arduino code:
const float OffSet = 0.475 ; // adjust this value
int analog = A0;
float avgV = 0.0;
float V=0;
float P;
void setup()
{
Serial.begin(115200); // open serial port, set the baud rate to 9600 bps
pinMode(analog, INPUT);
}
void loop()
{
//Connect sensor to Analog 0
V = analogRead(analog) * 5.00 / 1024; //Sensor output voltage
P = (V - OffSet) * 250; //Calculate water pressure
// Serial.print("Voltage:");
// Serial.print(V, 3);
// Serial.println("V");
//Serial.print(" Pressure:");
Serial.println(P, 1);
//Serial.print(" KPa");
//Serial.println();
delay(10); //debugging purposes
}
Python code:
import serial
import openpyxl
from datetime import datetime
import os
ser = serial.Serial(port='COM7', baudrate=115200, timeout=None)
file_name = "Datasetpressure.xlsx"
# Check if file exists, if not create a new one with headers
if not os.path.exists(file_name):
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Pressure Data"
ws.append(["Timestamp", "Pressure (kPA)"]) # Add header row
wb.save(file_name)
else:
wb = openpyxl.load_workbook(file_name)
ws = wb.active
try:
print("Recording data... Press Ctrl+C to stop.")
while True:
if ser.in_waiting > 0:
line = ser.readline().decode('utf-8').strip()
try:
flow_rate = float(line)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
ws.append([timestamp, flow_rate])
wb.save(file_name)
print(f"{timestamp} - Pressure: {flow_rate} kPa")
except ValueError:
print(f"Invalid data received: {line}")
except KeyboardInterrupt:
print("\nStopping data recording...")
finally:
ser.close()
wb.save(file_name)
print(f"Data saved to {file_name}.")