简体   繁体   English

将 DHT11 传感器中的值保存到 CSV 文件

[英]Save Values from a DHT11 Sensor to a CSV file

I am working with a RBPI4B and have installed the dht11 sensor.我正在使用 RBPI4B 并安装了 dht11 传感器。 The code that I am using is working fine with the dht library and get the results.我正在使用的代码在 dht 库中运行良好并获得了结果。 I need to save the output values to a csv under a /temp folder.我需要将 output 值保存到 /temp 文件夹下的 csv 中。 Can you please help me?你能帮我么? I would like to save it to a data.csv file, with: date, time, tempc, tempf, humidty (columns)我想将其保存到 data.csv 文件中,其中包含:日期、时间、tempc、tempf、湿度(列)

import RPi.GPIO as GPIO
import dht11
import time
import datetime

# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

# read data using pin 14
instance = dht11.DHT11(pin=17)

while True:
        result = instance.read()
        if result.is_valid():
                print("Last valid input: " + str(datetime.datetime.now()))
                print("Temperature: %d C" % result.temperature)
                print("Temperature: %d F" % ((result.temperature * 9/5)+32))
                print("Humidity: %d %%" % result.humidity)
time.sleep(1)

You will have to use python's file writer to read and write to files您将不得不使用 python 的文件编写器来读取和写入文件

with open('data.csv','w') as file:

    while True:
            result = instance.read()
            if result.is_valid():
                file.write("{:s},{:d},{:f},{:d}\n".format(
                    str(datetime.datetime.now()),
                    result.temperature,
                    ((result.temperature * 9/5)+32),
                    result.humidity
                ))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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