我正在尝试使用Python将来自2个传感器节点的数据写入CSV文件。在AT模式下,通过Xbee Series 1进行通信,2个传感器节点上的Xbee终端设备将数据传递给连接到我的计算机的Xbee协调器。然后这些数据必须写入CSV文件。传感器与Arduino相连。在
我目前面临的问题是,来自2个节点的传感器数据以这种方式写入CSV文件:
但是,我希望数据格式是:即将来自2个传感器节点的数据写入一个实例中的一行。在
我编写以下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)
请问我的代码哪里出错了?非常感谢大家!:)
我得到的印象是,你的困难来自于一个事实,即串行端口有两个交替的消息。当您有完整的数据时,您需要同步CSV write to be,同时存储来自第一条消息的部分数据。在
我强烈建议您检查所读数据的格式并报告错误。在
相关问题 更多 >
编程相关推荐