在Python中单行写入传感器数据

2024-09-28 01:24:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python将来自2个传感器节点的数据写入CSV文件。在AT模式下,通过Xbee Series 1进行通信,2个传感器节点上的Xbee终端设备将数据传递给连接到我的计算机的Xbee协调器。然后这些数据必须写入CSV文件。传感器与Arduino相连。在

我目前面临的问题是,来自2个节点的传感器数据以这种方式写入CSV文件:

The yellow area represents a block of data coming in from the 2 sensor nodes, split into 2 rows at the time 10:48:16 (HH:MM:SS). The green area represents the next block of data in the next second.

但是,我希望数据格式是:即将来自2个传感器节点的数据写入一个实例中的一行。在

One row of data contains data from 2 sensor nodes.

我编写以下CSV文件的Python代码是:

import serial
import time
import csv

# Arduino
arduino = serial.Serial('COM11', 9600, timeout=1)

time.sleep(3) # wait for Arduino to initialize

while True:
    for datastring in arduino:
        datastring = datastring.strip()  # removes whitespaces and newline char

        if datastring:
            datasplit = datastring.split(',')  # Splits line of txt -> array of strings composed of EA individual sensor data
            field1 = datasplit[0]
            field2 = datasplit[1]
            field3 = datasplit[2]

            with open('testing1.csv', 'ab') as csvfile: # 'ab' to remove newline char after each print
                field1 = field1.replace('\n',"")
                sensor_fields = [field1, field2, field3, time.strftime("%H%M%S")]
                writer = csv.writer(csvfile)
                writer.writerow(sensor_fields)

请问我的代码哪里出错了?非常感谢大家!:)


Tags: 文件ofcsv数据import节点time传感器
1条回答
网友
1楼 · 发布于 2024-09-28 01:24:13

我得到的印象是,你的困难来自于一个事实,即串行端口有两个交替的消息。当您有完整的数据时,您需要同步CSV write to be,同时存储来自第一条消息的部分数据。在

import serial
import time
import csv

arduino = serial.Serial('COM11', 9600, timeout=1)

time.sleep(3)

with open('testing1.csv', 'ab') as csvfile:
    writer = csv.writer(csvfile)

    data = []
    while True:

        for datastring in arduino:

            # one should really put some error checking and reporting on the input data
            # as it is coming from an uncontrolled external source
            fields = datastring.strip().split(',')
            fields[0] = fields[0].replace('\n', '')

            # We need to store first set of fields until the second set has been read.
            # first set is tagged '665b'
            # The list data is being used as storage and to indicate that the first line has been read
            if fields[0] == '665b':
                data = fields

            # check if we have complete data from both sensors and write out if so.
            # and ignore if alternating data is out of sync (i.e. first time round)
            elif len(data) == 3 and fields[0] != '665b': 
                writer.writerow(data + fields + [time.strftime("%H%M%S")])
                data = []

我强烈建议您检查所读数据的格式并报告错误。在

相关问题 更多 >

    热门问题