technion
Posts: 239
Joined: Sun Dec 02, 2012 9:49 am

Adafruit DHT temp/humid sensor

Fri Dec 28, 2012 2:30 am

Hey guys,

I have an AM2032 I'm looking to run.

Using the Adafruit_DHT_Driver, I keep seeing garbage come out:

sudo ./Adafruit_DHT.dist 2302 25
Using pin #25
Data (39): 0x3 0x5a 0x1 0xdf 0x1d

What it never seems to show, is a temperature or a humidity.
Advice appreciate.

User avatar
malakai
Posts: 1382
Joined: Sat Sep 15, 2012 10:35 am
Contact: Website

Re: Adafruit DHT temp/humid sensor

Fri Dec 28, 2012 2:41 am

where did the .dist come from after the file?

This is my output

./Adafruit_DHT 22 4
Using pin #4
Data (40): 0x1 0xd 0x1 0x9 0x18
Temp = 26.5 *C, Hum = 26.9 %
http://www.raspians.com - always looking for content feel free to ask to have it posted. Or sign up and message me to become a contributor to the site. Raspians is not affiliated with the Raspberry Pi Foundation. (RPi's + You = Raspians)

technion
Posts: 239
Joined: Sun Dec 02, 2012 9:49 am

Re: Adafruit DHT temp/humid sensor

Fri Dec 28, 2012 3:31 am

malakai wrote:where did the .dist come from after the file?
I kept a copy of the original file as .dist before I tried messing with the source code and recompiling to try and fix it.

technion
Posts: 239
Joined: Sun Dec 02, 2012 9:49 am

Re: Adafruit DHT temp/humid sensor

Fri Dec 28, 2012 4:32 am

Definitely looks like a code issue. I found a reference in the last post here:
http://www.raspberrypi.org/phpBB3/viewt ... ht#p221775

I've pasted a patch below which basically says "if the checksum fails, divide by two rather than erroring". I've run continuously with this config and it hasn't failed yet.

Code: Select all

diff --git a/Adafruit_DHT_Driver/Adafruit_DHT.c b/Adafruit_DHT_Driver/Adafruit_DHT.c
index 9d1746b..49e8c74 100644
--- a/Adafruit_DHT_Driver/Adafruit_DHT.c
+++ b/Adafruit_DHT_Driver/Adafruit_DHT.c
@@ -126,8 +126,8 @@ int readDHT(int type, int pin) {

   printf("Data (%d): 0x%x 0x%x 0x%x 0x%x 0x%x\n", j, data[0], data[1], data[2], data[3], data[4]);

-  if ((j >= 39) &&
-      (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) {
+  if ((j >= 39)) {
+     // (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) {
      // yay!
      if (type == DHT11)
        printf("Temp = %d *C, Hum = %d \%\n", data[2], data[0]);
@@ -139,6 +139,13 @@ int readDHT(int type, int pin) {
        f = (data[2] & 0x7F)* 256 + data[3];
         f /= 10.0;
         if (data[2] & 0x80)  f *= -1;
+
+       if ((data[4] != ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) {
+               printf("Applying hack\n");
+               h /= 2;
+               f /= 2;
+       }
+
        printf("Temp =  %.1f *C, Hum = %.1f \%\n", f, h);
     }
     return 1;

technion
Posts: 239
Joined: Sun Dec 02, 2012 9:49 am

Re: Adafruit DHT temp/humid sensor

Fri Dec 28, 2012 5:12 am

On a side note, how does this make sense? With that sleep commented, surely this would pretty much always end up breaking at 1000? It's a recent change according to git.

Code: Select all

while ( bcm2835_gpio_lev(pin) == laststate) {
        counter++;
        //nanosleep(1);         // overclocking might change this?
        if (counter == 1000)
          break;
    }

User avatar
malakai
Posts: 1382
Joined: Sat Sep 15, 2012 10:35 am
Contact: Website

Re: Adafruit DHT temp/humid sensor

Fri Dec 28, 2012 5:27 am

It was just a way to control the timing if you go too fast which I haven't played with it doesn't go well.

The break just breaks out of the loop to continue with the code. I think the tutorial talks about having to wait 2 seconds and it appears sleep and overclocking changes the timing I don't think a counter is affected by overclock settings is my guess.
http://www.raspians.com - always looking for content feel free to ask to have it posted. Or sign up and message me to become a contributor to the site. Raspians is not affiliated with the Raspberry Pi Foundation. (RPi's + You = Raspians)

technion
Posts: 239
Joined: Sun Dec 02, 2012 9:49 am

Re: Adafruit DHT temp/humid sensor

Fri Jan 04, 2013 3:07 am

Hey guys,

Just to update this thread, I've found that, overtime, the library discussed just didn't seem reliable, or something I could fix.

I found a few recommendations to a wiringPi based dht11.c floating around, and although that's not my sensor, I've been able to adapt it to my sensor based on the logic in the Adafruit driver.

It seems working quite well - I just want to run it for a few days to be comfortable before I release it.

technion
Posts: 239
Joined: Sun Dec 02, 2012 9:49 am

Re: Adafruit DHT temp/humid sensor

Sun Jan 06, 2013 9:58 am

Further update.

The deeper I looked at my, nearly 100% reliable code, the more it looks identical to the Adafruit code. The difference therefore, I believe, is in the difference between the bcm library that the Adafruit code backs into, and the wiringPi library that the original dht11.c used.

p4trykx
Posts: 127
Joined: Wed Jan 11, 2012 2:55 pm

Re: Adafruit DHT temp/humid sensor

Sun Jan 06, 2013 11:15 pm

How did your test go?
On my raspi I get an error once every 10 reads. I used the code from Adafruit and from dht11.c

technion
Posts: 239
Joined: Sun Dec 02, 2012 9:49 am

Re: Adafruit DHT temp/humid sensor

Mon Jan 07, 2013 3:03 am

p4trykx wrote:How did your test go?
On my raspi I get an error once every 10 reads. I used the code from Adafruit and from dht11.c
After running both for nearly a day, I'm getting about 90% junk with the Adafruit code (again, I will blame the BCM library here) and about 90% reliable data with the dht11.c.

My version can be found here:
https://github.com/technion/lol_dht22

Just ensure you hard code the GPIO PIN number correctly in the .c file before compiling.

p4trykx
Posts: 127
Joined: Wed Jan 11, 2012 2:55 pm

Re: Adafruit DHT temp/humid sensor

Tue Jan 08, 2013 10:48 am

I think that the main problem is that Linux is not a real time operating system and I think that nothing can be done. Maybe the process is sometimes interrupted and we get bad data.
Maybe RT Linux kernel will be available for Raspi sometimes.

The WiringPi might have some better microseconds nanoseconds sleep functions than system ones.

p4trykx
Posts: 127
Joined: Wed Jan 11, 2012 2:55 pm

Re: Adafruit DHT temp/humid sensor

Tue Jan 08, 2013 1:41 pm

Just tried running the process with higher priority and from brief testing I get more good data. But the improvement is rather marginal.
Also overclocking Raspi to 900Mhz seems to have a good effect.

first login as root

Code: Select all

sudo su
and then

Code: Select all

nice -n -20 ./sht11
Note than -20 is the highest priority and 10 is the normal priority. Them smaller the number the higher priority.

technion
Posts: 239
Joined: Sun Dec 02, 2012 9:49 am

Re: Adafruit DHT temp/humid sensor

Wed Jan 09, 2013 5:55 am

p4trykx wrote:
The WiringPi might have some better microseconds nanoseconds sleep functions than system ones.
I thought that would have to be false.

However, in the code, is the below. The implementation is actually surprisingly long.

Code: Select all

/*
 * delayMicroseconds:
 *      This is somewhat intersting. It seems that on the Pi, a single call
 *      to nanosleep takes some 80 to 130 microseconds anyway, so while
 *      obeying the standards (may take longer), it's not always what we
 *      want!
 *
 *      So what I'll do now is if the delay is less than 100uS we'll do it
 *      in a hard loop, watching a built-in counter on the ARM chip. This is
 *      somewhat sub-optimal in that it uses 100% CPU, something not an issue
 *      in a microcontroller, but under a multi-tasking, multi-user OS, it's
 *      wastefull, however we've no real choice )-:
 *
 *      Plan B: It seems all might not be well with that plan, so changing it
 *      to use gettimeofday () and poll on that instead...
 *********************************************************************************
 */

p4trykx
Posts: 127
Joined: Wed Jan 11, 2012 2:55 pm

Re: Adafruit DHT temp/humid sensor

Thu Jan 10, 2013 1:28 am

I found this code
https://github.com/technion/lol_dht22
And it work rather well I tried to raise the priority of the process but I really can't see a clean difference. Where I run this program and have an endless loop in it I get 1 error ever 10-15 reads.
Once I even got 50 good read in a row ;-)

This is my modification in main()

Code: Select all

if (piHiPri(20) == 0)
  {
     printf("Priority set \n");
  }

  while (1)
  {
    read_dht22_dat();
    delay(1000); // wait 1sec to refresh
  }

WiringPi has a function millis() which return miliseconds sice start the execution time for the critical section varies by 1 milisecond but there is no correlation to good or bad data.

I also found a thread about a logic analyzer http://www.raspberrypi.org/phpBB3/viewt ... =37&t=7696
It stops all interrupts and gets sort of real time system but this kind of trick requires the program to be a kernel module so it's a bit of overkill. Eventually I get good data from DHT22 after 2-3 at worse. And temperature and humidity don;t change that much.

There is also one blogpost about the timings of DHT22 which are not so precise as stated in the datasheet(by the way this datasheet does not look very professional ).
http://blog.ringerc.id.au/2012/01/using ... ht-22.html

User avatar
Sarge
Posts: 34
Joined: Sun Jan 13, 2013 4:57 pm

Re: Adafruit DHT temp/humid sensor

Sun Mar 10, 2013 1:51 am

hi guys,

i can't add anything to your discussion of timings but i have been following the discussion around humidity sensors and have tried two (freetronics DHT22 & am2302 styles).

i got the reference for the first from Mark's blog post:
http://www.wolfe.id.au/2012/12/22/raspb ... struction/

but after receiving and hooking it up, i've found that performance is less than optimal. long story short, i'm getting 50 - 60% good reads with the Adafruit_DHT driver and 70 - 80% accurate reads with the dht22 driver referred to early by technion. so i agree that the dht22 driver with the wiringPi library is nominally better.

it shouldn't be a big deal for the application, but i'd be interested if anyone is getting better performance :lol:

User avatar
Mariuspe
Posts: 27
Joined: Thu Mar 14, 2013 5:55 pm

Re: Adafruit DHT temp/humid sensor

Thu Mar 14, 2013 6:00 pm

I have noticed that my DHT22 with Adafruit DHT drivers works without any issues when Motion (computer vision) is not started and starts giving trash data when Motion is running. I am suspecting that this is due to the processor load and program not being able to read sensor quickly enough. But that is just a guess... Any ideas how to fix that?

p4trykx
Posts: 127
Joined: Wed Jan 11, 2012 2:55 pm

Re: Adafruit DHT temp/humid sensor

Thu Mar 14, 2013 7:57 pm

you could run the sensor code with higher priority

Code: Select all

sudo nice -20 ./dht22

User avatar
Mariuspe
Posts: 27
Joined: Thu Mar 14, 2013 5:55 pm

Re: Adafruit DHT temp/humid sensor

Fri Mar 15, 2013 10:37 am

no luck unfortunately:
[email protected]:/Adafruit-Raspberry-Pi-Python-Code/Adafruit_DHT_Driver# nice -20 ./Adafruit_DHT 2302 4
Using pin #4
Data (32): 0x2 0x7e 0x3 0x97 0x0

And immediately after stopping Motion process:
[email protected]:~# /etc/init.d/motion stop
[ ok ] Stopping motion detection daemon: motion.
[email protected]:~# cd /Adafruit-Raspberry-Pi-Python-Code/Adafruit_DHT_Driver
[email protected]:/Adafruit-Raspberry-Pi-Python-Code/Adafruit_DHT_Driver# nice -20 sudo ./Adafruit_DHT 2302 4
Using pin #4
Data (40): 0x1 0x39 0x0 0xd7 0x11
Temp = 21.5 *C, Hum = 31.3 %

What is interesting, that Motion was using no more than 50% of the processor...

p4trykx wrote:you could run the sensor code with higher priority

Code: Select all

sudo nice -20 ./dht22

p4trykx
Posts: 127
Joined: Wed Jan 11, 2012 2:55 pm

Re: Adafruit DHT temp/humid sensor

Fri Mar 15, 2013 2:56 pm

Does your code in ./dht22 run just once? I remember that when there is only one call in the program it almost always fails but when I put a while loop in the main function I got success ~80% of the time. Not sure why but I suspected some scheduling issues.
Put a while loop and read the sensor until you get a good answer.

There might be a problem that the USB driver in the kernel has even higher priority than -20.

rickman90
Posts: 4
Joined: Mon May 06, 2013 9:43 pm

Re: Adafruit DHT temp/humid sensor

Wed Jul 31, 2013 6:59 pm

Just found this old topic. I'm resurrecting it because I'm having a bunch of trouble with what seems like a simple thing. The sensor works fine, except of course when I have a USB webcam with motion running, but the biggest problem is trying to get the python script which calls the c script to run in crontab or as an init.d service. It only runs when I manually type it in! I've tried every combo of putting full paths, keeping the python script and the Adafruit_DHT script together, using sudo crontab -e and using the noip example of creating a init.d service to no avail.

Before I even try to hassle with getting it to run while motion is running I need to get it to run on its own. For some reason it's not working for me, so I'm wondering if there's a way to release a gpio pin from needing sudo to access it on the Pi?

User avatar
Mariuspe
Posts: 27
Joined: Thu Mar 14, 2013 5:55 pm

Re: Adafruit DHT temp/humid sensor

Wed Jul 31, 2013 7:28 pm

rickman90 wrote:Just found this old topic. I'm resurrecting it because I'm having a bunch of trouble with what seems like a simple thing. The sensor works fine, except of course when I have a USB webcam with motion running, but the biggest problem is trying to get the python script which calls the c script to run in crontab or as an init.d service. It only runs when I manually type it in! I've tried every combo of putting full paths, keeping the python script and the Adafruit_DHT script together, using sudo crontab -e and using the noip example of creating a init.d service to no avail.

Before I even try to hassle with getting it to run while motion is running I need to get it to run on its own. For some reason it's not working for me, so I'm wondering if there's a way to release a gpio pin from needing sudo to access it on the Pi?
What error do you get in crontab?

rickman90
Posts: 4
Joined: Mon May 06, 2013 9:43 pm

Re: Adafruit DHT temp/humid sensor

Thu Aug 01, 2013 12:07 pm

I'm not sure. I've checked /var/log/syslog and the entries appear the same as other scripts I have running in crontab (non-sudo). In fact, using top I can see that it tries to run each time (I set it to 1 minute)... The c and python script that calls it (and posts to a google spreadsheet) all run fine when I directly type them in, it just won't run on its own...

User avatar
Mariuspe
Posts: 27
Joined: Thu Mar 14, 2013 5:55 pm

Re: Adafruit DHT temp/humid sensor

Thu Aug 01, 2013 12:26 pm

rickman90 wrote:I'm not sure. I've checked /var/log/syslog and the entries appear the same as other scripts I have running in crontab (non-sudo). In fact, using top I can see that it tries to run each time (I set it to 1 minute)... The c and python script that calls it (and posts to a google spreadsheet) all run fine when I directly type them in, it just won't run on its own...
when I have same sort of issues with crontab first of all I am putting my email address in to get notified when and why it fails and secondly make sure that commands in my script have paths. I.e. shutdown -r now works directly, but in crontab it works only with /sbin/shutdown -r now. Hopefully this will help you.

p4trykx
Posts: 127
Joined: Wed Jan 11, 2012 2:55 pm

Re: Adafruit DHT temp/humid sensor

Fri Aug 02, 2013 7:28 pm

here is my code
It's in /home/pi/dht22A/
I run it with cron. Here is a part of my crontab

Code: Select all

*/10 *  * * *   root    /home/pi/dht22A/Adafruit_DHT_googledocs.ex.py

Code: Select all

#!/usr/bin/python

import subprocess
import re
import sys
import time
import datetime
import gspread

# ===========================================================================
# Google Account Details
# ===========================================================================

# Account details for google docs
email       = 'xxxxxxxxxxx'
password    = 'xxxxxxxxxx'
spreadsheet = 'xxxxxxxxxxxxx'

# ===========================================================================
# Example Code
# ===========================================================================


# Login with your Google account
try:
  gc = gspread.login(email, password)
except:
  print "Unable to log in.  Check your email address/password"
  sys.exit()

# Open a worksheet from your spreadsheet using the filename
try:
  worksheet = gc.open(spreadsheet).sheet1
  # Alternatively, open a spreadsheet using the spreadsheet's key
  # worksheet = gc.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE')
except:
  print "Unable to open the spreadsheet.  Check your filename: %s" % spreadsheet
  sys.exit()

# Continuously append data
while(True):
  # Run the DHT program to get the humidity and temperature readings!

  output = subprocess.check_output(["/home/pi/dht22A/Adafruit_DHT", "2302", "17"]);
  print output
  matches = re.search("Temp =\s+([0-9.]+)", output)
  if (not matches):
	time.sleep(3)
	continue
  temp = float(matches.group(1))
  
  # search for humidity printout
  matches = re.search("Hum =\s+([0-9.]+)", output)
  if (not matches):
	time.sleep(3)
	continue
  humidity = float(matches.group(1))

  print "Temperature: %.1f C" % temp
  print "Humidity:    %.1f %%" % humidity
 
  # Append the data in the spreadsheet, including a timestamp
  try:
    values = [datetime.datetime.now(), temp, humidity, 'dht22']
    worksheet.append_row(values)
  except:
    print "Unable to append data.  Check your connection?"
  sys.exit()

  # Wait 30 seconds before continuing
  print "Wrote a row to %s" % spreadsheet
  break 
#sys.exit() 
#time.sleep(600)

#Odczyt dht11

# Continuously append data
while(True):
  # Run the DHT program to get the humidity and temperature readings!

  output = subprocess.check_output(["/home/pi/dht22A/Adafruit_DHT", "11", "17"]);
  print output
  matches = re.search("Temp =\s+([0-9.]+)", output)
  if (not matches):
        time.sleep(3)
        continue
  temp1 = float(matches.group(1))

  # search for humidity printout
  matches = re.search("Hum =\s+([0-9.]+)", output)
  if (not matches):
        time.sleep(3)
        continue
  humidity1 = float(matches.group(1))

  print "Temperature: %.1f C" % temp
  print "Humidity:    %.1f %%" % humidity

  # Append the data in the spreadsheet, including a timestamp
  try:
    values = [datetime.datetime.now(), temp, humidity, '', temp1, humidity1]
    worksheet.append_row(values)
  except:
    print "Unable to append data.  Check your connection?"
#    sys.exit()

  # Wait 30 seconds before continuing
  print "Wrote a row to %s" % spreadsheet
  sys.exit()




scanpat
Posts: 1
Joined: Fri Aug 09, 2013 8:07 pm

Re: Adafruit DHT temp/humid sensor

Fri Aug 09, 2013 8:16 pm

I have the same trouble : when motion process is started adafruit_dht code doesnt work.

Do you know how to fix it ?
(I have try with nice -n -20 without success)

Do you know another lib/code to handle dht without adafruit code ?

Return to “Automation, sensing and robotics”