簡體   English   中英

在獲取數據之前清除串行緩沖區

[英]Clear serial buffer before acquiring data

我在 python 中創建了一個簡短的腳本,它從 Arduino 讀取傳入的串行數據並將其寫入 CSV 文件。 我在 Arduino 程序中創建了標題(數據標簽),它們作為第一個字符串值傳遞並分配為列標題。 然而,由於某種原因,數據頭前面有一小部分數據,我認為這些數據是 USB 串行緩沖區中的舊數據。 無論如何我可以告訴 python 等到舊數據被清除並且 Arduino 已重置串行連接?

代碼如下所示,任何幫助將不勝感激。

問題快照

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. 如果新進程將這些數據變紅,那么舊進程可能不會。 這是以前程序中的一個問題,它應該確保在關閉連接之前它接收到所有數據(通過等待 EOFError 或 '\0')。
  2. 在一個新過程中,我會跳過這些行,直到發現一些獨特的標記(例如,開始從 '\n' 流式傳輸您的 csv (並將流式傳輸內容中的所有 '\n' 引用為 '\n')。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM