简体   繁体   中英

Clear serial buffer before acquiring data

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.

Snapshot of issue

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()
  1. If new process red this data, perhaps the old one didn't. This is a problem in a previous program, which should ensure it received all data (by waiting for the EOFError or '\0') before closing connection.
  2. In a new process I would skip the lines until some unique marker spotted (for example, start streaming your csv from '\n' (and quote all the '\n' in a streamed content to be '\n').

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM