我正在使用Minimummodbus通过Modbus RS-485进行通信。该代码每6秒读取4个寄存器。然后,每分钟将每个变量的平均值保存在一个csv文件中。目标是每分钟获取一次时间序列数据,但是我不时地丢失1分钟的数据,因为读数的睡眠时间在循环的每个步骤中都不相同。
我试图通过等待完成过程所需的时间来调整时间,但是很难对其进行调整。
有什么想法可以改进它,或者有任何建议以其他方式做到这一点,以便每分钟精确地保存数据?
def collect_data():
try:
register_3204 = instr.read_registers(3203,4,3)
register_3208 = instr.read_registers(3207,4,3)
register_3220 = instr.read_registers(3219,4,3)
register_3224 = instr.read_registers(3223,4,3)
EaImport = convert_64bit(register_3204)
EaExport = convert_64bit(register_3208)
ErImport = convert_64bit(register_3220)
ErExport = convert_64bit(register_3224)
data=[EaImport,EaExport,ErImport,ErExport]
except IOError:
print("Failed to read from instrument")
return (data)
startt = time.time()
with open('/iEM_test/iEM3155.csv', 'a', buffering=0) as file:
while True:
average = np.hstack([0])
for i in range(10):
data=(collect_data())
data1=np.hstack([data[0], data[1], data[2], data[3]])
average = average + data1
stopt= time.time()
sleeptime = 6-(stopt-startt) - 0.000925925926
time.sleep(sleeptime)
startt = time.time()
average1=average/10
dt= datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
data=[dt,str(average1[0]),str(average1[1]),str(average1[2]),str(average1[3])]
data_str=",".join(data)
file.write(data_str + '\n')
以下是我通过实际代码获取的数据
5/5/2019 18:08:59 37.8401 4.407 13.0227 43.797
5/5/2019 18:09:59 37.8532 4.4073 13.0277 43.797
5/5/2019 18:10:59 37.856 4.408 13.029 43.797
5/5/2019 18:12:00 37.8599 4.408 13.0292 43.7976
5/5/2019 18:13:00 37.8824 4.408 13.03 43.798
5/5/2019 18:14:00 37.9075 4.408 13.03 43.79877
在18:11时有一个小跳跃。