0

I am using minimalmodbus to communicate via Modbus RS-485. The code is reading 4 registers every 6 seconds. Then, every minute the average for each variable is saved in a csv file. The goal is to have the time series data every minute, but from time to time I loose 1 minute of the data because the sleep time between readings is not the same in every step of the loop.

I have tried to adjust the time by resting the time it takes the process to be completed, but its hard to tune it.

Any idea how to improve it or any suggestion about a different way to do it in order to save data exactly every minute?

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')

Below is the data I am getting with the actual code

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

There is a small jump at 18:11 hrs.

HuHu
  • 25
  • 6
  • 18:10:59 is one second before 18:11, and then there is 18:12... For me it looks ok where is the jump??? – mguijarr May 06 '19 at 08:07
  • Yes, it is 1 sec before 18:11. This second that I am kind of loosing is showing up every 40 min, sometimes 1 hr. The best way to have the series is by keeping the readings stable at 00 seconds all the time. The problem is that my data is increasing the seconds all the time. Also when I read the data by using only the hr:m, there is 1 minute missing from time to time. – HuHu May 06 '19 at 08:33

0 Answers0