[英]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.我在 python 中创建了一个简短的脚本,它从 Arduino 读取传入的串行数据并将其写入 CSV 文件。 I've created headers (data labels) in the Arduino program which are passed as the first string values and assigned as the column headers.
我在 Arduino 程序中创建了标题(数据标签),它们作为第一个字符串值传递并分配为列标题。 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.
然而,由于某种原因,数据头前面有一小部分数据,我认为这些数据是 USB 串行缓冲区中的旧数据。 Is there anyway I can tell python to wait until the old data is cleared and the Arduino has reset the serial connection?
无论如何我可以告诉 python 等到旧数据被清除并且 Arduino 已重置串行连接?
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.