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.
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 += 1if 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.temperatureprevious_humidity = result.humiditycounter += 1rightnow = 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!"passtime.sleep(sleep_time)
When I run the script I get the following error: