在Python中以单行编写传感器数据

时间:2018-01-15 03:01:54

标签: python csv

我正在尝试使用Python将来自2个传感器节点的数据写入CSV文件。通过Xbee系列1在AT模式下进行通信,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)

请问我的代码在哪里出错了?非常感谢你们! :)

1 个答案:

答案 0 :(得分:0)

我的印象是,您的困难来自于串行端口有两条交替的消息。您需要将CSV写入同步为具有完整数据,同时存储来自第一条消息的部分数据。

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 = []

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