如何使用 python 将传感器数据输出保存到 excel

how to save sensor data output into excel using python

我目前正在使用 raspberry pi 并使用 DHT11 每秒读取温度和湿度值。我必须将这些值实时保存到数据库中。这是我每秒显示传感器数据的代码,我不知道如何在 excel.

中保存 data/result
import RPi.GPIO as GPIO
import dht11
import time
import datetime
import os


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

instance = dht11.DHT11(pin=dht11_pin)

    while True:

        cnt += 1
        if cnt%limit_sec == 0 or cnt == 1:

            result = instance.read()
            if result.is_valid():

                if previous_temperature != result.temperature or previous_humidity != result.humidity:

                    previous_temperature = result.temperature
                    previous_humidity = result.humidity

                    counter += 1
                    rightnow = datetime.datetime.now()

                    if result.humidity>=40:
                        print(str(counter)+". Last valid input: " )
                        print("Date: " + rightnow.strftime("%d/%m/%Y"))
                        print("Time: " + rightnow.strftime("%H:%M:%S"))
                        print("Status: Your plant is on the good condition.")
                        print("Temperature: %d C" % result.temperature)
                        print("Humidity: %d %%" % result.humidity)
                        print("*******************************************")


                    else:
                        print(str(counter)+". Last valid input: " )
                        print("Date: " + rightnow.strftime("%d/%m/%Y"))
                        print("Time: " + rightnow.strftime("%H:%M:%S"))
                        print("Status: Your plant is on the bad condition. Please open the water supply.")
                        print("Temperature: %d C" % result.temperature)
                        print("Humidity: %d %%" % result.humidity)
                        print("*******************************************")

            else:
                print "Invalid result!"
                pass

        time.sleep(sleep_time)

首先是 import csv 模块然后使用 with open('file_name.csv', 'w', newline='') as csvfile:

writer = csv.DictWriter(csvfile, fieldnames=field_names) field_names 只是您列

的键值

writer.writerow( {'Date': 'Date', 'Time': 'Time', 'Status': 'Status', 'Temperature': 'Temperature', 'Humidity': 'Humidity'}) 为您的 excel 文件写 header

writer.writerow( {'Date': rightnow.strftime("%d/%m/%Y"), 'Time': rightnow.strftime("%H:%M:%S"), 'Status': status, 'Temperature':result.temperature, 'Humidity': result.humidity}) 根据 field_names

中的键值将数据写入您的 csv 文件

完整代码:

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


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

instance = dht11.DHT11(pin=dht11_pin)
with open('file_name.csv', 'w', newline='') as csvfile:
    field_names = ['Date', 'Time', 'Status', 'Temperature', 'Humidity']
    writer = csv.DictWriter(csvfile, fieldnames=field_names)
    writer.writerow(
        {'Date': 'Date', 'Time': 'Time',
         'Status': 'Status', 'Temperature': 'Temperature', 'Humidity': 'Humidity'})

    while True:

        cnt += 1
        if cnt%limit_sec == 0 or cnt == 1:

            result = instance.read()
            if result.is_valid():

                if previous_temperature != result.temperature or previous_humidity != result.humidity:

                    previous_temperature = result.temperature
                    previous_humidity = result.humidity

                    counter += 1
                    rightnow = datetime.datetime.now()

                    if result.humidity>=40:
                        status = 'Your plant is on the good condition.'
                        print(str(counter)+". Last valid input: " )
                        print("Date: " + rightnow.strftime("%d/%m/%Y"))
                        print("Time: " + rightnow.strftime("%H:%M:%S"))
                        print("Status: Your plant is on the good condition.")
                        print("Temperature: %d C" % result.temperature)
                        print("Humidity: %d %%" % result.humidity)
                        print("*******************************************")


                    else:
                        status = 'Your plant is on the bad condition. Please open the water supply.'
                        print(str(counter)+". Last valid input: " )
                        print("Date: " + rightnow.strftime("%d/%m/%Y"))
                        print("Time: " + rightnow.strftime("%H:%M:%S"))
                        print("Status: Your plant is on the bad condition. Please open the water supply.")
                        print("Temperature: %d C" % result.temperature)
                        print("Humidity: %d %%" % result.humidity)
                        print("*******************************************")
                    writer.writerow(
                        {'Date': rightnow.strftime("%d/%m/%Y"), 'Time': rightnow.strftime("%H:%M:%S"),
                         'Status': status, 'Temperature':result.temperature, 'Humidity': result.humidity})
            else:
                print "Invalid result!"
                pass

        time.sleep(sleep_time)

第一个 writer.writerow 是你 header 和 field_names 只是用作将数据填充到特定列的键

存储你的 status = '' 并将其放入 writer.writerow()