## Yet more DHT22 sensor code

danjperron
Posts: 3243
Joined: Thu Dec 27, 2012 4:05 am

### Re: Yet more DHT22 sensor code

Hum...

You should remove from the loop the GPIO setup and the sensor setup. This should be before the loop.

Code: Select all

    pi.set_mode(22,pigpio.OUTPUT)
pi.write(22,1)

s=DHT22.sensor(pi,2, LED=None, power=22)

Set the GPIO mode could start a DHT22 read out befor the s.trigger(), then you get garbage.

I don't think that you need to set the GPIO first! If you do please add a delay at least longer than the DHT22 response and not inside the loop.

Also GPIO2 is normally the I2C. Are you sure that the I2C is disabled. The best choice will be to select a GPIO not use for I2C or SPI.

time.sleep(30) will delay 30 seconds but the full cycle will be longer. You need to taking care of the code inside the loop.

Maybe the best way is to set the timer with time.time()

Code: Select all

target = time.time() + 30.0

while True:

while True:
#this is you loop to wait for 30 seconds
if target < time.time():
target = target + 30.0
break
time.sleep(0.01)



RhysJ
Posts: 2
Joined: Mon Oct 15, 2018 5:11 pm

### Re: Yet more DHT22 sensor code

Thanks Dan,
I followed your advice of taking the sensor setup outside of the loop and added the timer code you specified. It's been 5 days and the sensor hasn't crashed once! It appears that I don't need to set the GPIO for the power first, so i removed this from the code.

I also followed the pin numbering from Joans example code. The power pin in the example is GPIO8 which is an SPIO. After trying out other GPIOs it seems that the power reset will also work on non SPIO pins but not the I2C (I ended up using GPIO4 for the power).

I went a bit further in my code so that it runs constantly, saving humidity/temperature data to a file every 30 seconds and automatically generates a new file every day (based on an if statement comparing the initial date to the current date). The code will then generate and save a plot at the end of each day. To run the code below the user needs to have matplotlib installed and create a folder called 'HumidityData' in the '\home\pi' directory.

Code: Select all

####################################################################
#Import libraries
####################################################################
import time
from datetime import datetime
import pigpio
import DHT22
import os
import csv
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.dates import bytespdate2num

#define pigpio and DHT22 sensor
pi=pigpio.pi()
s=DHT22.sensor(pi,22, LED=None, power=4)

#set initial day and the sampling rate
Day=datetime.now().strftime("%d")
Interval = 30.0
target = time.time() + Interval

try:
while True:
#set the current day
NewDay = datetime.now().strftime("%d")

if int(NewDay)==int(Day):

#Read data from the DHT22 sensor
s.trigger()
time.sleep(0.2) # stops sensor spitting out jargon

humidity = '{:3.2f}'.format(s.humidity()/1.)
temperature = '{:3.2f}'.format(s.temperature()/1.)

#set up file saving
Date = datetime.now().strftime("%y:%m:%d") #formatted as year:month:day
Time = datetime.now().strftime("%H:%M:%S")

data = [Time,humidity,temperature]  #create list with all the parameters that are to be saved

Dir_name= '/home/pi/HumidityData'  #set file save directory. YOU MUST CREATE A FOLDER IN THE DIRECTORY CALLED 'HumudityData'.
Filename= '%s_Humidity_Recording' %Date  #set filename to include the date

# write data to file
with open(os.path.join(Dir_name,Filename + '.csv'), 'a') as file:
writer = csv.writer(file, delimiter=',')
writer.writerow(data)

# Ensure the sampling rate is correct
while True:
if target < time.time():
target = target + Interval
break
time.sleep(0.01)

else:
#If the date changes a plot will be produced for the previous days recording and the initial 'Day' will be updated to the current day

#plot data on same graph, different y axis
#set up the temperature plot
fig, ax1 = plt.subplots()
color = 'tab:red'
ax1.set_xlabel('Time')
ax1.set_ylabel('Temp (C)', color=color)
ax1.tick_params(axis='y', labelcolor=color)

#set up the humidity plot
ax2 = ax1.twinx()
color = 'tab:blue'
ax2.set_ylabel('Humidity (%)', color=color)
ax2.tick_params(axis='y', labelcolor=color)

#plot formatting
fig.tight_layout()
plt.title(Filename)
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))
plt.gcf().autofmt_xdate()

#save plot to same directory as .csv files. Don't automatically display the plot
plt.savefig(os.path.join(Dir_name,Filename + '.png'))
plt.close()

#reset the previous day to be the current day. This will allow loop to go back to the top of the if statement and start saving in a new file
Day=NewDay

time.sleep(0.1)

except KeyboardInterrupt:
#message to tell user that the python script has closed
print('Humidity sensor shut down')

finally:
#clear DHT22 sensor
s.cancel()