简体   繁体   中英

Real time data logging with a DHT22 sensor on a RaspberryPi3

I've got a problem with a current project that aims to transmit data from a sensor to a platform in real time. It is a DHT22 sensor which is able to measure temperature and humidity. The idea was to save the data in a csv file and then send it to the platform using another script (sending the data from the csv file to the platform has always worked). The problem is that the data is stored in the csv file, but only in intervals of about 15 minutes and always in blocks of 800. The real-time aspect therefore does not come into play.

I used the following script to save the data as a csv file:

import time
import adafruit_dht
import board
 
dht = adafruit_dht.DHT22(board.D4)

with open("/home/pi/Desktop/temp_hum.csv", "a") as log:
    log.write("TEMP,HUM\n") # first row in the csv file
    
    while True:
        try:
            temperature = dht.temperature
            humidity = dht.humidity
            log.write("{:.1f},{}\n".format(temperature, humidity))
        except RuntimeError as error:
        # reading doesnt always work, no logging if error
            time.sleep(1)
            continue
        except Exception as error:
            dht.exit()
            raise error
    
        time.sleep(1)

As you can see, the data should be saved once per second, and error messages should not be saved. I was now wondering if it is at all possible to save the data in real time as a csv file or if there is a more suitable option for this. This is all done on a RaspberryPi3. Due to the fact that I know very little about programming, the scripts are mostly based on copy & paste and trial & error.

Thanks in advance.

The problem you are having is that you "write" to the file object but in the code you never flush it. So what you are writing stays in some buffer. Usually the flush happens automatically when the context that is created by with open() ends, but it never ends because you have an infinite loop inside there.

To fix this just surround every write individually by with open() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM