如何为使用 PySerial 收集的数据添加时间戳并导出到 csv?

How to timestamp data collected using PySerial and export to csv?

我正在尝试从多个设备收集串行数据、时间戳并将其导出到 .csv 文件。我想为每个设备编写单独的模块,以便它们 return 将数据发送到主模块,并在其中完成对 csv 的所有写入。

以下程序将日期和时间写入 csv,而不是从设备模块 return 编辑的数据。

import time
import csv
from threading import Thread
import fio2

def Csv_creator():
    my_file = open('test_csv.csv', 'w+')

    with my_file:
        new_file = csv.writer(my_file)

def Timestamp():
    date_now = time.strftime('%d/%m/%y')
    time_now = time.strftime('%H:%M:%S')
    return [date_now,time_now]


def Write_loop():
    Csv_creator()
    fio2.Initialize()

    while True:
        with open('test_csv.csv', 'a') as f:
            [date_now,time_now] = Timestamp()
            fio2_data = fio2.Reader()
            print fio2_data
            to_write = [date_now,time_now,fio2_data]
            csv_file = csv.writer(f)
            csv_file.writerow(to_write)     

t = Thread(target=Write_loop)
t.daemon = True
t.start()

raw_input("Press any key to stop \n")

设备模块如下图。它自己运行良好,但我很难将其设为 return 值并将其写入 csv 文件。

import serial

ser = serial.Serial("COM6",
                    baudrate=2400,
                    bytesize=serial.EIGHTBITS,
                    parity =serial.PARITY_ODD,
                    timeout=1,
                    writeTimeout =1)


def Initialize():
    global ser
    try:
        ser.isOpen()
        print("\n Serial is open")
    except: 
        print ("Error: serial Not Open")

def Reader():
    global ser
    if (ser.isOpen()):

        try:                    
            x = ser.readline().decode()
            x = (x)
            return x
        except:
            return "unable to print"
    else: 
        return "cannot open serial port"

与其在循环中每次都打开文件,我建议将其移到外部:

with open('test_csv.csv', 'a') as f:
    csv_file = csv.writer(f)

    while True:
        date_now, time_now = Timestamp()
        fio2_data = fio2.Reader()
        csv_file.writerow([date_now, time_now, fio2_data])

我明白了。我不得不删除一些与十进制值相关的垃圾字母。首先,我将接收到的数据更改为字符串并替换了垃圾字母。以下是我的更改方式:

[date_now,time_now] = Timestamp()
fio2_data = str(fio2.Reader()).replace("\r\n","")
fio2_data = fio2_data.replace("\x000","")
write_list = [date_now,time_now,fio2_data]