wonx
Posts: 22
Joined: Tue Aug 07, 2012 11:00 am
Location: Barcelona

Re: Yet more DHT22 sensor code

Sun Feb 08, 2015 10:56 pm

Oh :(

So it's probably physically broken, for some reason. I'll probably try buying another sensor (any advice?). Or perhaps I could dissasemble the dht22 sensor from inside the case and try to plug it directly the raspberry.

Anyway, thank you for your time and effort. You've been very helpful :)

Massi
Posts: 1691
Joined: Fri May 02, 2014 1:52 pm
Location: Italy

Re: Yet more DHT22 sensor code

Mon Feb 09, 2015 8:37 am

Did you use raspi internal pullup for dataline? you are using bulk DHT22, am i wrong?

danjperron
Posts: 3392
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: Yet more DHT22 sensor code

Mon Feb 09, 2015 12:39 pm

@wonx I had to point out that I let the DHT22 running all night and it froze around 2:30 am.

Image

It was without the pull-up. I just put a 4K7 and I will see.


I do have another system , with the resistor, and it is working fine for a long time.

Daniel

RaspberryLove
Posts: 4
Joined: Fri Feb 20, 2015 11:40 pm

Re: Yet more DHT22 sensor code

Fri Feb 20, 2015 11:52 pm

I installed pigpio as explained on its homepage under downloads. Assuming the unzipped files were only temporary, I removed all of it after running make install. Then I figured that I probably need all these files, since the tests - such as ./x_pigpio_if refer to the current directory. So where do you guys put the archive, what directory is a reasonable choice?

User avatar
joan
Posts: 14196
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: Yet more DHT22 sensor code

Sat Feb 21, 2015 11:06 am

RaspberryLove wrote:I installed pigpio as explained on its homepage under downloads. Assuming the unzipped files were only temporary, I removed all of it after running make install. Then I figured that I probably need all these files, since the tests - such as ./x_pigpio_if refer to the current directory. So where do you guys put the archive, what directory is a reasonable choice?
Debian creates a Downloads directory under your home directory and downloads default to going there. That seems a reasonable place.

RaspberryLove
Posts: 4
Joined: Fri Feb 20, 2015 11:40 pm

Re: Yet more DHT22 sensor code

Sun Feb 22, 2015 2:56 pm

Hi again,
I was trying to run pigpio (the __main__ code in DHT22.py) with python3.
However, I got an error that pigpio module was missing (import pigpio at the beginning of the file).
So I looked for where it is for python 2.7 and just copied it to the equivalent python 3 directory.
And this time python3 DHT22.py did run well (except for a minor difference: the formatting looks odd, it is not truncating decimal numbers and sometimes prints all the available (15 or something) decimal positions after the comma). However, I was wondering if this is the way it is supposed to be run with python 3, I mean the copying pigpio.py from one directory to the other? Or may I be running into some errors or unexpected behavior in the future, when using pigpio in python 3?
Thanks a lot in advance

User avatar
joan
Posts: 14196
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: Yet more DHT22 sensor code

Sun Feb 22, 2015 3:03 pm

RaspberryLove wrote:Hi again,
I was trying to run pigpio (the __main__ code in DHT22.py) with python3.
However, I got an error that pigpio module was missing (import pigpio at the beginning of the file).
So I looked for where it is for python 2.7 and just copied it to the equivalent python 3 directory.
And this time python3 DHT22.py did run well (except for a minor difference: the formatting looks odd, it is not truncating decimal numbers and sometimes prints all the available (15 or something) decimal positions after the comma). However, I was wondering if this is the way it is supposed to be run with python 3, I mean the copying pigpio.py from one directory to the other? Or may I be running into some errors or unexpected behavior in the future, when using pigpio in python 3?
Thanks a lot in advance
Because of the way Python works you have to compile the module for each variant of Python you want to use. You can't just copy the byte code from one version to another.

You need to do the following in the PIGPIO directory:

Code: Select all

sudo python2 setup.py install # install for Python 2

sudo python3 setup.py install # install for Python 3

RaspberryLove
Posts: 4
Joined: Fri Feb 20, 2015 11:40 pm

Re: Yet more DHT22 sensor code

Sun Feb 22, 2015 4:10 pm

joan wrote:
RaspberryLove wrote: Because of the way Python works you have to compile the module for each variant of Python you want to use. You can't just copy the byte code from one version to another.
Got it. Though I copied only the py-file, not the pyc-file. After reading your reply, I checked and saw that - right where I dropped the py-file - python created a directory __pycache__ with a pyc file in it.
Nevertheless, I will revert this and do it the way you described, with the setup.py file. Thanks!

thesky2101
Posts: 1
Joined: Fri Mar 06, 2015 6:30 am

Re: Yet more DHT22 sensor code

Fri Mar 06, 2015 6:34 am

Hi could you help? I need to produce a warning when the Humidity reaches above certain level but i already configure the buzzer but i dont know how to call the humidity value into the if statement. Could you help me?

danjperron
Posts: 3392
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: Yet more DHT22 sensor code

Fri Mar 06, 2015 11:37 am

Hi thesky2101,

The first thing to know is what is your code?

The best way is to set a target value and compare to the current one.

Code: Select all

humidityTarget = 40

if  hm_dht22 > humidityTarget :
   humidityAlarm()
The humidityAlarm function could be a mail via google or a GPIO output.

Daniel

Massi
Posts: 1691
Joined: Fri May 02, 2014 1:52 pm
Location: Italy

Re: Yet more DHT22 sensor code

Fri Mar 13, 2015 1:41 pm

Hello,
i modified a little joan's script to get a version:
- for single reading and not continuous (no "numberb of timeout", only IF timeout) because i use it in this way :)
- the connection to pigpiod is managed by the class itself and not outside
- i hate the time.sleep to wait for the end of the reading, so i added a method for that..
- for long cables setups, it may be useful the possibility to modify the threshold used to understand if a bit is 1 or 0, so i added a dedicated var

I use it in this way:

Code: Select all

from sensors import dht22
import time

s = dht22.DHT22(25) #set up sensor on gpio 25
s.trigger() #start reading

print s.waitReading() #print us taken for the reading to end
if s.errorMessage() is not False: #error check
	print(s.errorMessage())
else: #results
	print('Temp: {:0.1f}'.format(s.temperature() / 1.))
	print('Humidity: {:0.1f}'.format(s.humidity() / 1.))

s.cancel()
the core is 100% joan :)

Bye

Code: Select all

#!/usr/bin/env python3 
#coding=utf-8

import time
import pigpio

class DHT22:
	"""
	A class to read relative humidity and temperature from the DHT22 sensor.
	"""
	def __init__(self, gpio):
		"""
		Instantiate with the gpio to which the DHT22 output pin is connected.
		"""
		self.pi = pigpio.pi()
		self.gpio = gpio
		self.edgeLen = 50 #configuring edgeLen var to understand bits. in us
		self.readOver = False #local var to understand when we are over with data from sensor
		self.timeStart = False #start reading tick
		self.rhum = None
		self.temp = None
		self.tick = 0
		self.bit = -2
		self.hH = 0
		self.hL = 0
		self.tH = 0
		self.tL = 0
		self.CS = 0
		self.pi.set_pull_up_down(gpio, pigpio.PUD_OFF)
		self.error = False				

	def _cb(self, gpio, level, tick):
		"""
		Accumulate the 40 data bits.  Format into 5 bytes, humidity high,
		humidity low, temperature high, temperature low, checksum.
		"""
		diff = pigpio.tickDiff(self.tick, tick)
		if level == 0:
			# edge length determines if bit is 1 or 0
			if diff >= self.edgeLen:
				val = 1
			else:
				val = 0
			if self.bit >= 40: # message complete
				self.bit = 40
			elif self.bit >= 32: # in checksum byte
				self.CS  = (self.CS<<1)  + val
				if self.bit == 39:
					# 40 bits received
					self.pi.set_watchdog(self.gpio, 0)
					total = self.hH + self.hL + self.tH + self.tL
					if (total & 255) == self.CS: # is checksum ok
						self.rhum = ((self.hH<<8) + self.hL) * 0.1
						if self.tH & 128: # negative temperature
							mult = -0.1
							self.tH = self.tH & 127
						else:
							mult = 0.1
						self.temp = ((self.tH<<8) + self.tL) * mult
					else:
						self.error = "Bad checksum"
			elif self.bit >=24: # in temp low byte
				self.tL = (self.tL<<1) + val
			elif self.bit >=16: # in temp high byte
				self.tH = (self.tH<<1) + val
			elif self.bit >= 8: # in humidity low byte
				self.hL = (self.hL<<1) + val
			elif self.bit >= 0: # in humidity high byte
				self.hH = (self.hH<<1) + val
			else:				# header bits
				pass
			self.bit += 1
		elif level == 1:
			self.tick = tick
			if self.bit >= 40: # message complete
				self.readOver = True
		else: #level == pigpio.TIMEOUT:
			#time out if less than 40 bits received
			loggerInfo.info("Signal timeout")
			self.pi.set_watchdog(self.gpio, 0)
			self.error = "Timeout"
			
	def errorMessage(self):
		"""Return error message."""
		return self.error

	def temperature(self):
		"""Return current temperature."""
		return self.temp

	def humidity(self):
		"""Return current relative humidity."""
		return self.rhum

	def trigger(self):
		"""Trigger a new relative humidity and temperature reading."""
		self.pi.set_mode(self.gpio, pigpio.OUTPUT)
		self.pi.write(self.gpio, pigpio.LOW)
		time.sleep(0.018)
		self.timeStart = self.pi.get_current_tick() #start time!
		self.pi.set_mode(self.gpio, pigpio.INPUT)
		self.cb = self.pi.callback(self.gpio, pigpio.EITHER_EDGE, self._cb)
		self.pi.set_watchdog(self.gpio, 200)
		
	def waitReading(self):
		"""Wait for the reading to end and return microseconds taken for it."""
		while self.readOver is not True and self.error is False: #reading ends if 40bits received or error message
			pass
		readTime = pigpio.tickDiff(self.timeStart, self.pi.get_current_tick())
		return readTime

	def cancel(self):
		"""Cancel the DHT22 sensor."""
		self.cb.cancel()
		self.pi.stop()
Last edited by Massi on Fri Mar 13, 2015 7:44 pm, edited 1 time in total.

danjperron
Posts: 3392
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: Yet more DHT22 sensor code

Fri Mar 13, 2015 3:35 pm

Well pattagghiu you stripped away the thing I like the most about Joan's code. The possibility to power off/on the sensor when it's hang!

The only way that I'm able the get the DTH22 sensor not hanging was my SPI method.

Because eventually it will hang.

Daniel

User avatar
joan
Posts: 14196
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: Yet more DHT22 sensor code

Fri Mar 13, 2015 4:06 pm

danjperron wrote: ...
The only way that I'm able the get the DTH22 sensor not hanging was my SPI method.

Because eventually it will hang.

Daniel
I wish someone could explain the root cause. If it is true to say that SPI never hangs then that surely must be to do with the triggering of the read. The actual reception of the data bits surely can't be an issue.

danjperron
Posts: 3392
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: Yet more DHT22 sensor code

Fri Mar 13, 2015 4:40 pm

It could be that the SPI will hang eventually but I did run it for 3 month without any problem.

I switched to your code because I need the SPI but the system will hang after one day or two. But with your way to power the sensor to restart it, the problem was solved and I never use the SPI again to read the DHT 22 sensor.

I must say that to be able to restart the sensor is for me the best approach anyway.

Daniel

User avatar
joan
Posts: 14196
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: Yet more DHT22 sensor code

Fri Mar 13, 2015 4:46 pm

danjperron wrote:It could be that the SPI will hang eventually but I did run it for 3 month without any problem.

I switched to your code because I need the SPI but the system will hang after one day or two. But with your way to power the sensor to restart it, the problem was solved and I never use the SPI again to read the DHT 22 sensor.

I must say that to be able to restart the sensor is for me the best approach anyway.

Daniel
After a month of working without problems I hoped I wouldn't have to look at the DHT22 ever again. At least now I have a couple of Pis doing nothing. I reckon I'll solder a DHT22 to a piece of board and leave it running permanently somewhere.

Massi
Posts: 1691
Joined: Fri May 02, 2014 1:52 pm
Location: Italy

Re: Yet more DHT22 sensor code

Fri Mar 13, 2015 7:43 pm

danjperron wrote:Well pattagghiu you stripped away the thing I like the most about Joan's code. The possibility to power off/on the sensor when it's hang!

The only way that I'm able the get the DTH22 sensor not hanging was my SPI method.

Because eventually it will hang.

Daniel
saying the truth, i never used that part.
My DHT22 never hang so for me it's a nonsense wasting a gpio to power it
If i have to say everything, none of my dht22 ever hang..

brownleeb
Posts: 3
Joined: Sun Oct 12, 2014 8:37 pm

Re: Yet more DHT22 sensor code

Tue Jun 16, 2015 5:11 pm

For those watching this forum, Gordon has some pretty good code in a recent release of wiringPi.
viewtopic.php?p=775023#p775023

RaspberryLove
Posts: 4
Joined: Fri Feb 20, 2015 11:40 pm

Re: Yet more DHT22 sensor code

Sat Feb 20, 2016 9:39 pm

Hi Joan, hi Daniel,

I was setting up the DHT22 sensor again and now was wondering how to wire it.
You guys say you always connect a pull-up resistor to the data pin.
However, this is not mentioned in the comments of DHT22.py for the 3V3 setup, whereas it is explicitly mentioned for th 5V supply.
I didn't pay too much attention to this when wiring and did not use any pull-up, used the 3V3 supply. And at least I did not get any read errors.
So I was wondering what is the proper way of wiring the sensor. Can you briefly comment on that? Thanks a lot in advance!

Best regards
Paul

danjperron
Posts: 3392
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: Yet more DHT22 sensor code

Sat Feb 20, 2016 9:56 pm

Yes you could get lucky and it works.

Like everything in electronics specification needs to be follow. It doesn't mean that it won't work if you go outside the specification.

But that doesn't mean that another DHT22 will work. The pullup resistor is there for the transistion between the output mode and the input mode to have a good signal rise.

I will still suggest to put the pullup resistor.

http://raspberrypi.stackexchange.com/qu ... ity-sensor

Massi
Posts: 1691
Joined: Fri May 02, 2014 1:52 pm
Location: Italy

Re: Yet more DHT22 sensor code

Sun Feb 21, 2016 8:55 am

RaspberryLove wrote:Hi Joan, hi Daniel,

I was setting up the DHT22 sensor again and now was wondering how to wire it.
You guys say you always connect a pull-up resistor to the data pin.
However, this is not mentioned in the comments of DHT22.py for the 3V3 setup, whereas it is explicitly mentioned for th 5V supply.
I didn't pay too much attention to this when wiring and did not use any pull-up, used the 3V3 supply. And at least I did not get any read errors.
So I was wondering what is the proper way of wiring the sensor. Can you briefly comment on that? Thanks a lot in advance!

Best regards
Paul
it depends if you have the "bulk" sensor (4 pin) or a built board with the sensor (commonly, 3 pin, the pullup and a capacitor on power line)
If you have the bulk sensor, the pullup is _required_ by the datasheet.
The sensor can be powered (within specs) by the 3.3v line or by the 5v line (if the sensor is quite far from the raspi, 5v is required)

DaHai8
Posts: 55
Joined: Fri Jul 31, 2015 9:21 am

Re: Yet more DHT22 sensor code

Sat Jul 22, 2017 6:43 am

First, I want to thank joan for this code!
I was busting my brain trying to figure out why some old python code I found wouldn't work on the Pi 3. It worked fine on the Pi2, but just returned errors on the Pi3. I guess the Pi3 was too fast or something?
Anyway, it works and returns valid results....IF...I divide the values by 25!
Temperature= 768c / 25 = 30.72
Humidity=896% / 25 = 35.84
So unless I'm sitting on the Sun (it is very HOT here outside), there's is something very strange going on.
The divided values are in line with my indoor thermometer and the old values I got on the Pi 2.
And if I place my hand on the sensor, the Temperature and Humidity does go up (and back down when I remove my hand). So I'm pretty sure I didn't do anything stupid like poll the wrong GPIO port.
Power: Pin1 (3V3)
Ground: Pin6 (Ground)
Data: Pin7 (GPIO4)

Code: Select all

pi = pigpio.pi()
s = DHT22.sensor(pi, 4, LED=None, power=None)
Any ideas what's causing this? (Kelvin or Rankine doesn't match either)

Thanks!

zenonmb
Posts: 8
Joined: Wed Mar 18, 2015 10:56 am

Re: Yet more DHT22 sensor code

Mon Nov 06, 2017 8:24 pm

Guys,

I am using the sensor with Adafruit driver and reading the sensor is very instable, so want to use another one . I see here there are options, but not sure where to get it.
Can anyone point me to the right direction?
Regards,

martin

User avatar
joan
Posts: 14196
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: Yet more DHT22 sensor code

Mon Nov 06, 2017 8:35 pm

pigpio should be most reliable.


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

Re: Yet more DHT22 sensor code

Mon Oct 15, 2018 5:22 pm

Hi there,
I've been reading through this thread as i'm having trouble with my DHT22 sensor hanging.
I'm trying to save a timestamp, temperature and humidity to a file every 30 seconds but after some random time the sensor will start spitting out -999 for each data point.
I've stated what pins i'm using below. Can someone look at my code to see where i'm going wrong?
Thanks!

Pin 1: GPIO22
Pin 2: Data - GPIO2 (Pull up resistor of 4.7k)
Pin 3: NC
Pin 4: Ground

Code: Select all

####################################################################
#Importing libraries
####################################################################
import time
import csv
from datetime import datetime
import os
import pigpio
import DHT22
#######################################################################

pi=pigpio.pi()

try:
    while True:      
        
        #Read data from DHT22 sensor and display on LCD
        pi.set_mode(22,pigpio.OUTPUT)
        pi.write(22,1)

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

        s.trigger()
        time.sleep(0.5) # stops sensor spitting out jargon
        h = '{:3.2f}'.format(s.humidity()/1.)
        t = '{:3.2f}'.format(s.temperature()/1.)
            
        #set up file saving
        Date = datetime.now().strftime("%y:%m:%d")
        Time = datetime.now().strftime("%H:%M:%S")
        Dir_name= '/home/pi/HumidityData' #set file save directory 
        Filename= '%s_Lab_Recording' %Date #set filename (date dependent)
        data = [Time,h,t] #create list with all the parameters that are to be saved
            
        with open(os.path.join(Dir_name,Filename + '.csv'), 'a') as file:
            writer = csv.writer(file, delimiter=',')
            writer.writerow(data)
            
        time.sleep(30) # defines how often data is sampled. -0.2 seconds compensates for the time.sleep(0.2) in the above while loop 
                
except KeyboardInterrupt:
        
        #message to tell user that the python script has successfully closed
        print('Humidity sensor shut down')

finally:
    #clear all raspberry pi GPIO pins and turn off LED and LCD  
    s.cancel()
    

Return to “Automation, sensing and robotics”