I've created a short script in python which reads incoming serial data from an Arduino and writes it to a CSV file. I've created headers (data labels) in the Arduino program which are passed as the first string values and assigned as the column headers. However, for some reason the data headers are preceded by a small collection of data which I assume is old data in the USB serial buffer. Is there anyway I can tell python to wait until the old data is cleared and the Arduino has reset the serial connection?
Code is shown below, any help would be appreciated.
import serial
from datetime import datetime
import time
import pandas as pd
import random
a = input("Enter a:")
b = input("Enter b:")
c = input("Enter c:")
d = input("Enter d:")
fileName= a + "-" + b + "-" + c + "-" + d + ".csv" #name of the CSV file generated
arduino_port = "COM7"
baud = 115200
print_labels = False
file = open(fileName, "w", newline="")
print("Created file")
ser = serial.Serial(arduino_port, baud)
print("Connected to Arduino port:" + arduino_port)
line = 0 #start at 0 because our header is 0 (not real data)
while True:
getData = (ser.readline().decode())
data=getData[0:][:-1]
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
time.sleep(1)
if data
if line == 0:
print(data)
file = open(fileName, "a", newline="")
file.write(data + "\n") #write data with a newline
line = line+1
else:
print(data + "," + dt_string)
file = open(fileName, "a", newline="")
file.write(data + "," + dt_string + "\n") #write data with a newline
line = line+1
print("Data collection complete!")
file.close()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.