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

时间:2018-07-28 05:00:25

标签: python github raspberry-pi3 sensor soil

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

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)

1 个答案:

答案 0 :(得分:1)

第一件事是使用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文件写标题

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将是您的标题,而field_names仅用作将数据填充到垂直列的键

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