2

I'm currently working with raspberry pi and using DHT11 to read temperature and humidity values every second. I have to save these values into a database in real time. here's my code that showing sensor data every second, I don't know how to save the data/result in 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)
aizack
  • 59
  • 1
  • 6

1 Answers1

1

first thing is to import csv module then use with open('file_name.csv', 'w', newline='') as csvfile:

writer = csv.DictWriter(csvfile, fieldnames=field_names) field_names are just key value for your column

writer.writerow( {'Date': 'Date', 'Time': 'Time', 'Status': 'Status', 'Temperature': 'Temperature', 'Humidity': 'Humidity'}) write header for your excel file

writer.writerow( {'Date': rightnow.strftime("%d/%m/%Y"), 'Time': rightnow.strftime("%H:%M:%S"), 'Status': status, 'Temperature':result.temperature, 'Humidity': result.humidity}) write data in your csv file as per the key values in field_names

full code:

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)

where first writer.writerow will be you header and field_names are just used as key to fill you data to perticular column

store your status = '' and put it in writer.writerow() etc.

Nihal
  • 5,262
  • 7
  • 23
  • 41
  • you can ask new question and share its link in this comment, so i can get better understanding of the problem. by the looks of error, it is an indentation problem. – Nihal Jul 30 '18 at 05:37
  • in that question just include the line where error lies. there is no need to include `while True:` loop. – Nihal Jul 30 '18 at 06:37
  • Okay, thanks. This is the link https://stackoverflow.com/questions/51588592/how-to-deal-with-this-eror-indentationerror-unexpected-indent – aizack Jul 30 '18 at 07:04
  • you should insert lines from import to csv.writer as well – Nihal Jul 30 '18 at 07:30
  • if you don't mind even if full code is long post it in your question. – Nihal Jul 30 '18 at 07:41
  • you can add this: I'm currently working with raspberry pi and using DHT11 to read temperature and humidity values every second. I have to save these values into a database in real time. here's my code that showing sensor data every second – Nihal Jul 30 '18 at 08:19
  • it work, thanks you. I already upload the entire coding at https://stackoverflow.com/questions/51588592/how-to-deal-with-indentationerror-unexpected-indent. – aizack Jul 30 '18 at 08:22
  • can you help me with this problem https://stackoverflow.com/questions/51606283/how-to-save-sensor-data-output-into-microsoft-access-using-python?noredirect=1#comment90182523_51606283 – aizack Jul 31 '18 at 09:13