paulv
Posts: 564
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Adafruit DHT temp/humid sensor

Fri Nov 07, 2014 11:18 am

Hi danjperron,
A few months ago, I wanted to add support for a DHT22 (AM2303) sensor in my thermostat, to add relative humidity. It already uses three different DS18B20 sensors. I tried Joan's solution, but had to discard that because I'm already using RPi.GPIO in my program, and didn't want to modify my 5800 lines Python program to switch to her version of the GPIO drivers at this point.

I tried your solution, and really liked it. It's fast and accurate. However, my thermostat hardware is quite complicated, and I was short of the really General Purpose ports on my Pi. I did not want to give up an extra port to start using the SPI interface. I also ran into an issue where my test program using your code crashed with [b][code]OSError: [Errno 24] Too many open files[/code][/b] I could not find the problem and that with the extra GPIO port needed, made me abandon this solution.

So, for several months now, I have been using the Adafruit solution. That however, is very slow, most likely due to the "trial and error" matching it uses, and it regularly gives bad result, meaning values that are far off. In my code I try to account for those weaknesses, but the inaccuracy is bothering when you run an HVAC system with them.

So, a week ago, I went back to using your code, after having bitten the bullet about the required hardware changes to swap some GPIO ports around. To my dismay, I'm getting the same crashes due to the OS running out of files again. After some more soul searching and testing, I'm convinced there must be a "leak" in the spidev driver, maybe in combination with your code and my code since nobody else is reporting this problem. I'm using a thread that runs every 30 seconds and that reads the DHT22 three times with 2 seconds in between. It then averages the values, and moves on. So I'm intensively using the code.

It must be the spidev driver in combination with your code, because the thermostat has been running for months with the Adafruit solution. Even my simple test program that I used initially, just running a tight loop, crashes.

I wonder if you or anybody else can shed some light on this problem, because I cannot even remotely understand the spidev C code.

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

Re: Adafruit DHT temp/humid sensor

Fri Nov 07, 2014 12:06 pm

Hi paulv,

Good! You find a work around!

I won't be able to investigate before next year.
I just got a contract with my old employer. I didn't see him for 25 years.

But I will try to use one of my spare RPi and hook up a DHT22 and let it run.
I always ran the DHT22 code into a cron script and send information to a php script using shared memory.
I will try to run the application in an endless loop and see.

Daniel

ondrej1024
Posts: 171
Joined: Thu Dec 05, 2013 3:09 pm
Contact: Website

Re: Adafruit DHT temp/humid sensor

Fri Nov 07, 2014 5:13 pm

Hi paulv,

are you getting the crash you are reporting with danjperron Python or C code (from this topic)?
I am currently porting the C code into my own DHT22 library and will see if I am having similar issues. Will report back here shortly.

Ondrej
The Telegea.org project: https://www.telegea.org

paulv
Posts: 564
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Adafruit DHT temp/humid sensor

Fri Nov 07, 2014 8:11 pm

Hi Ondrej,

Yes, that's the correct reference. I am using the class version of the code from danjperron in a while loop with the bare minimum of code added, on an otherwise unused Pi with the latest updates.
I looked at your code and that looks promising. I will be looking forward to your porting results, and will be more than happy to test things out for you.

Danjperron,
Thanks for the reply. I wish I could be of more help, but C is not my thing, especially drivers. I hope somebody can find and fix the problem, it seems that a lot of people are using the DHT's and are struggling a bit.

Paulv

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

Re: Adafruit DHT temp/humid sensor

Sat Nov 08, 2014 1:18 am

Paulv,

You said that you are using a thread in your code to read the DHT22 using my code.

Did you modify my main() function to be a subfunction?

I could see a problem with the "pabort". Only the first pabort doesn't have the file stream open. Maybe you should modify the code to close the file before all pabort except the first one.

Code: Select all

  fd = open("/dev/spidev0.0", O_RDWR);
   if (fd < 0)
      pabort("can't open device");

   /*
    * spi mode
    */

        mode = 0;
   ret = ioctl(fd, SPI_IOC_WR_MODE, &mode);
   if (ret == -1)
     {
       close(fd);    //<---------------   add close
      pabort("can't set spi mode");
     }
   ret = ioctl(fd, SPI_IOC_RD_MODE, &mode);
   if (ret == -1)
    {
      close(fd);  //<------------------ add close
      pabort("can't get spi mode");
 }
Also it is possible the list all the open files of a process. You could just check after some time to see if the number of open files accumulates. It should list all open files.

Check this url , it will show you how to list all open files from a process.

http://www.cyberciti.biz/faq/howto-linu ... pen-files/

Code: Select all

 ps -C yourapplication -o pid=
ls -l /proc/yourapplicationpid/fd
If you modified my main() to a function in your thread, could you post the function.

Daniel

paulv
Posts: 564
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Adafruit DHT temp/humid sensor

Sat Nov 08, 2014 3:20 am

Hi Daniel,

Thank you for taking the time to look into this.
I have not had time to look and work with your suggestions, but you guessed right, I did modify your example and turn that into a class and a function that calls the class.
Here is my code:

Code: Select all

class dht22spi():
    '''
    Read a DHT22 sensor using SPI

    Author: Daniel Perron

    http://www.raspberrypi.org/forums/viewtopic.php?f=37&t=27215&p=591041#p591041
    uses the spidev import module for the DHT22 or AM2303 sensor
    '''
    def __init__(self, DeviceType="DHT22"):

        self.DHT22Type = (DeviceType == "DHT22")
        self.spi = spidev.SpiDev()
        self.speed = 500000
        self.spi.open(0,0)
        self.max_speed_hz=self.speed
        self.Bits = [128, 64, 32, 16, 8, 4, 2, 1]
        self.DHT22Reg = [0, 0, 0, 0, 0]

        # 10ms should be good enough to get a good snapshot with all data
        MaxBits = 0.010 * self.speed
        self.ArraySize = int(MaxBits / 8)
        self.TotalBits = self.ArraySize * 8
        self.D = bytearray(self.ArraySize)

        # set first 1.5 ms of the data to Low and the rest to High
        End = (0.0015 * self.speed) / 8

        for i in range(self.ArraySize):
            if i > End:
                self.D[i] = 255
            else:
                self.D[i] = 0

    def GetBit(self,index):
        byteIndex = index / 8
        if (self.Data[byteIndex] &  self.Bits[index % 8]) == 0:
            return False
        return True

    def GetNextDelay(self):
        if self.LastIndex  >= self.TotalBits:
            return 0
        Index = self.LastIndex
        LastBit = self.GetBit(Index)
        while Index < self.TotalBits:
            if not (self.GetBit(Index) == LastBit):
                Delta = Index - self.LastIndex
                Deltaus = Delta * 1000000 / self.speed
                self.LastIndex = Index
                return Deltaus
            Index += 1

  # this routine returns three values:
  #   Temperature , Humidity and a boolean flag to tell if the data is valid

    def Read(self):
        self.LastIndex = 0
        self.Data = list(self.D)
        self.spi.xfer2(self.Data)

        # first get rid off start
        self.GetNextDelay()
        # now get rid off wait
        self.GetNextDelay()
        # now get rid off Ack
        self.GetNextDelay()
        # and the the high Ack
        self.GetNextDelay()

        for Idx in range(5):
            self.DHT22Reg[Idx]=0
            for bitidx in range(8):
                # low parts
                self.GetNextDelay()

                # read High Parts
                delai = self.GetNextDelay()

                if delai < 12:
                    return [None, None, False]

                if delai > 80:
                    return [None, None, False]

                if delai > 43:
                    self.DHT22Reg[Idx] |= self.Bits[bitidx]

        # verify the checksum
        Checksum = 0;
        for Idx in range(4):
            Checksum += self.DHT22Reg[Idx]
        Checksum %= 256

        if Checksum == self.DHT22Reg[4]:
            if self.DHT22Type:
                Temp = ((self.DHT22Reg[2] & 127) * 256  + self.DHT22Reg[3]) / 10.0
                if (self.DHT22Reg[2] & 128) == 128:
                    Temp = -Temp
                Humidity = (self.DHT22Reg[0] * 256 + self.DHT22Reg[1]) / 10.0
            else:
                Temp = self.DHT22Reg[2]
                Humidity = self.DHT22Reg[0]
        else:
            return [None, None, False] # bad checksum
        return [Temp, Humidity, True]


def get_dht22():
    '''
    Function to read the temperature and humidity values from the DHT22.

    It uses the dht22spi class version.

    '''
    try:
        write_log("trace", "-get_dht22")
        write_log("debug", "-current_temp = {0}".format(current_temp))

        if DEBUG :
            start = time()

        i = 0
        avg_tmp = 0.0
        avg_hum = 0.0

        while (i < 3):
            try :
                dht22 = dht22spi("DHT22")
                value = dht22.Read()
            except Exception as e:
                e = format_exception(e)
                with open(exception_log, "a") as fout:
                    fout.write(e)
                write_log("error", "Exception in running dht22spi():\n{0}".format(e))
                mail_err_log()
                continue

            if value[2]:
                # there is a valid crc in the recording
                if TRACE :
                    print "temp ", value[0]
                    print "hum ", value[1]
                temp = value[0] + TMP_CORR
                avg_tmp = avg_tmp + temp

                hum = value[1]
                avg_hum = avg_hum + hum

                i += 1
            else:
                if DEBUG: write_log ("warning", "Bad crc from DHT22 sensor n={0}".format(i))
                # limit the number of tries
                if i > 6:
                    break

                # continue the loop but skip the bad readings
            # A little time to get a stable reading from the device
            sleep(2)

        # if there are no good temp readings, we might as well jump ship here.
        if (avg_tmp == 0.0):
            write_log ("error", "No good readings from the DHT22 sensor")
            return(current_temp, humidity) # previous global values

        temp = round(avg_tmp/(i), 1)
        hum = round(avg_hum/(i), 1)

        if DEBUG :
            delta = round((time() - start), 2)
            write_log("debug", "-new Temp={0}*C R_Hum.={1}% in {2} sec.".format(temp, hum, delta))
        else:
            write_log("trace", "-new Temp={0}*C R_Hum.={1}% ".format(temp, hum))

        return (temp, hum) # average and round the result to 1 decimal digit

    except Exception as e:
        e = format_exception(e)
        with open(exception_log, "a") as fout:
            fout.write(e)
        write_log("error", "Unexpected Exception in get_dht22() n={0} : \n{1}".format(i, e))
        subprocess.call(['logger "Unexpected Exception in get_dht22()"'], shell=True)
        mail_err_log()
        return (current_temp, humidity) # use the previous readings so we can continue

I've taken some statistical code pieces out to make it more clear to understand what I did.
Tomorrow I hope to look at your suggestions and I'll report back.

Paul
Last edited by paulv on Sat Nov 08, 2014 7:55 pm, edited 2 times in total.

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

Re: Adafruit DHT temp/humid sensor

Sat Nov 08, 2014 12:02 pm

In effect I think you are doing the following.

Code: Select all

#!/usr/bin/env python

import os
import time
import spidev

def fds():
   return os.listdir('/proc/self/fd')

class dht22spi():
   '''
   Snippet for testing.
   '''
   def __init__(self):

      self.spi = spidev.SpiDev()
      self.spi.open(0,0)


def get_dht22():
    '''
    Snippet for testing.
    '''
    dht22 = dht22spi()

while True:
   get_dht22()
   print(len(fds()))
If you run it you will see the problem.

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

Re: Adafruit DHT temp/humid sensor

Sat Nov 08, 2014 12:20 pm

Hi Paulv,

OK you are using my python code. oops!

Try Joan code it is the same thing but for python. At least it will show you which open files accumulates.

I had another thought this morning , I'm on EST time. You said that you create a thread to run this class.
It is possible that you create the thread every times you need to read the sensor and forget to kill the thread.

Maybe it should be wise to create a function to close the spidev handle if you are using multiple thread.

def Close(self):
self.spi.close()

And add the atexit behavior

import atexit
atexit.register(self.Close);

I didn't test the code so maybe my atexit.register is not exactly ok. We have to check if the spi was opened before closing it.

Daniel

paulv
Posts: 564
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Adafruit DHT temp/humid sensor

Sat Nov 08, 2014 12:36 pm

Hi Joan,
That was an eye opener indeed!
Just for those following the discussion, Joans code produced this:

Code: Select all

['0', '1', '2', '3', '4']
['0', '1', '2', '3', '4', '5']
['0', '1', '2', '3', '4', '5', '6']
['0', '1', '2', '3', '4', '5', '6', '7']
['0', '1', '2', '3', '4', '5', '6', '7', '8']
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13']
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15']
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16']
After adding a close:

Code: Select all

          self.spi = spidev.SpiDev()
          self.spi.open(0,0)
          self.spi.close()
, I got this:

Code: Select all

['0', '1', '2', '3']
['0', '1', '2', '3']
['0', '1', '2', '3']
['0', '1', '2', '3']
['0', '1', '2', '3']
['0', '1', '2', '3']
['0', '1', '2', '3']
['0', '1', '2', '3']
['0', '1', '2', '3']
['0', '1', '2', '3']
['0', '1', '2', '3']
['0', '1', '2', '3']
['0', '1', '2', '3']
Obviously (now :o ), is that most likely the majority of users call this code from cron as a self contained module. When it executes and finishes, the close is automatic.
When you run it from within a program, as I do, you need to add the close statement.

Daniel, I use a separate thread to run the hardware in a tight loop, and do the housekeeping in the main code. The thread will call the temperature readings and control the HVAC. This thread gets started and never stops.

Now I need to figure out where I need to put the spi.close() statement. I quickly tried to add it just before the return of the Class but that didn't work.
Thanks for the help so far!

ondrej1024
Posts: 171
Joined: Thu Dec 05, 2013 3:09 pm
Contact: Website

Re: Adafruit DHT temp/humid sensor

Sat Nov 08, 2014 12:54 pm

Hi paulv,
I think it's important to understand what are the files/devices your program opens (and which seem to be increasing over time).
So just run your program and then get the list of open files with the "lsof" command, e.g.

Code: Select all

lsof | grep <your_program_name>
Depending of what you get there, it should give you some hint of what are the files/devices that remain open. You can run the "lsof" command also when you get the crash and you will see what are all those open files that caused the issue.

Ondrej
The Telegea.org project: https://www.telegea.org

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

Re: Adafruit DHT temp/humid sensor

Sat Nov 08, 2014 1:14 pm

As danjperron suggests just add a close method to the class and call it before the end of the calling function.

This sort of idea.

Code: Select all

#!/usr/bin/env python

import os
import time
import spidev

def fds():
   return os.listdir('/proc/self/fd')

class dht22spi():
   '''
   Snippet for testing.
   '''
   def __init__(self):

      self.spi = spidev.SpiDev()
      self.spi.open(0,0)

   # add close method
   def close(self):
      self.spi.close()


def get_dht22():
    '''
    Snippet for testing.
    '''
    dht22 = dht22spi()
    # add call to close before the get_dht22 function returns
    dht22.close()

while True:
   get_dht22()
   print(len(fds()))

paulv
Posts: 564
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Adafruit DHT temp/humid sensor

Sat Nov 08, 2014 2:17 pm

Problem solved!

Joan, Daniel and Ondrej, thank you very much.
You solved the problem for me, and I learned a couple of things in the process.
Excellent example of the power of this forum.
Last edited by paulv on Sat Nov 08, 2014 9:17 pm, edited 1 time in total.

paulv
Posts: 564
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Adafruit DHT temp/humid sensor

Sat Nov 08, 2014 8:28 pm

To follow-up on the issue that we had, I'd like to elaborate a bit on what was suggested to me to track the open file issue.
I was unaware of the method you can use to track open file issues, so let me show you how to do this, using the example above.

With the "run-away" file opening problem, this is what the process shows by using:

Code: Select all

pi@TestRig ~ $ sudo ls -l /proc/28037/fd
total 0
lrwx------ 1 pi pi 64 Nov  8 14:06 0 -> /dev/pts/2
lrwx------ 1 pi pi 64 Nov  8 14:06 1 -> /dev/pts/2
lrwx------ 1 pi pi 64 Nov  8 14:06 2 -> /dev/pts/2
lrwx------ 1 pi pi 64 Nov  8 14:06 3 -> /dev/spidev0.0
lrwx------ 1 pi pi 64 Nov  8 14:06 4 -> /dev/spidev0.0
lrwx------ 1 pi pi 64 Nov  8 14:06 5 -> /dev/spidev0.0
lrwx------ 1 pi pi 64 Nov  8 14:06 6 -> /dev/spidev0.0
lrwx------ 1 pi pi 64 Nov  8 14:06 7 -> /dev/spidev0.0
lrwx------ 1 pi pi 64 Nov  8 14:06 8 -> /dev/spidev0.0
lrwx------ 1 pi pi 64 Nov  8 14:06 9 -> /dev/spidev0.0
28037 was the process number I got from running

Code: Select all

ps ax
The above listing clearly shows an ever increasing number of filehandlers for /dev/spidev0.0, which is the spi module called by the value = dht22.Read() statement in the Python code of get_dht22().
When the now added dht22.Close() statement is invoked to close the Read, the same command now shows :

Code: Select all

pi@TestRig ~ $ sudo ls -l /proc/28452/fd
total 0
lrwx------ 1 pi pi 64 Nov  8 14:15 0 -> /dev/pts/2
lrwx------ 1 pi pi 64 Nov  8 14:15 1 -> /dev/pts/2
lrwx------ 1 pi pi 64 Nov  8 14:15 2 -> /dev/pts/2
lrwx------ 1 pi pi 64 Nov  8 14:20 3 -> /dev/spidev0.0
(It took me a while to even catch the last line)
This code piece was added in the Class:

Code: Select all

    # This is needed to close the Class after the read,
    # to avoid running out of files
    # invoked by get_dht22()
    def Close(self):
        self.spi.close()
And the Close was added in get_spi22() as follows

Code: Select all

            dht22 = dht22spi("DHT22")
            value = dht22.Read()
            # close the read before the get_dht22 function returns again
            dht22.Close()
I hope this will help some other clueless soul, as I was a few hours ago.

ondrej1024
Posts: 171
Joined: Thu Dec 05, 2013 3:09 pm
Contact: Website

Re: Adafruit DHT temp/humid sensor

Tue Nov 11, 2014 1:06 pm

Hi there,

I am glad to announce an important update to the DHTlib C library for reading the family of DHT sensors. It now supports reading the DHT sensors via the SPI interface. I was able to integrate this functionality thanks to danjperron's contributions in this thread. Not only did he come up with the idea of using SPI but also provided the C code which I ported into my library. I hope you don't mind Daniel, I gave you credit on the project page, of course. ;)

Communication over SPI works very reliable and should be the preferred solution in a user land program (as opposed to GPIO communication, which all other existing implementations use).

So please find the update on GitHub:
https://github.com/ondrej1024/foxg20/tree/master/dhtlib

Any feedback, comments, suggestions, (bug reports :? ) are very welcome.
Have fun, Ondrej
The Telegea.org project: https://www.telegea.org

paulv
Posts: 564
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Adafruit DHT temp/humid sensor

Tue Nov 11, 2014 2:26 pm

Hi Ondrej,
This looks really good and well documented. As soon as I have finished my post about the DHT devices (http://www.raspberrypi.org/forums/viewt ... 63#p638763) I'll spend some time working with your code to see if there are any changes in the part I'm describing. If there are, I'll update them, to get a good reference for the device.
After that, I will start to work with your code and try to write a Python wrapper around it. If you already have one, please publish so we can all use that to start from.

Thanks,
Paul

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

Re: Adafruit DHT temp/humid sensor

Tue Nov 11, 2014 2:31 pm

Great ! Use my code.

I put it on public domain for that reason.


B.T.W. I got some other ideas to read the DHT22 but they will on the burner for now. This imply using a small cpu.

1- Use a pic12F1840 and interface the DHT22 with the I2C bus. I did a lot of I2C interface with that chip and it will be easy.

2- Use the Pic again but with the serial interface. Simpler.

3- This is the far fetch one. Since the 1 wire works very well, I should be able to emulate the 1 wire protocol using a PIC processor and return the temperature and humidity and made the RPI think it is talking to two DS18B20s.
For the temperature the probe will be 28-000000000000 and for humidity the probe will be 28-000000000001. This way it will be possible to have more than one DHT22 just by changin the id. The cpu will have free pin than it could be use to select the ID.

These methods will only use a cheap cpu , less than $2, and it could be programmed by the Raspberry Pi.


Presently I use my multi IO board to do what I want. I'm using RS-485, it could have the sensor 1200 meter away.
Sorry the document is in french.
https://docs.google.com/document/d/1JIR ... sp=sharing


Daniel
Last edited by danjperron on Tue Nov 11, 2014 3:06 pm, edited 2 times in total.

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

Re: Adafruit DHT temp/humid sensor

Tue Nov 11, 2014 2:34 pm

ondrej1024 wrote:Hi there,

I am glad to announce an important update to the DHTlib C library for reading the family of DHT sensors. It now supports reading the DHT sensors via the SPI interface. I was able to integrate this functionality thanks to danjperron's contributions in this thread. Not only did he come up with the idea of using SPI but also provided the C code which I ported into my library. I hope you don't mind Daniel, I gave you credit on the project page, of course. ;)

Communication over SPI works very reliable and should be the preferred solution in a user land program (as opposed to GPIO communication, which all other existing implementations use).

So please find the update on GitHub:
https://github.com/ondrej1024/foxg20/tree/master/dhtlib

Any feedback, comments, suggestions, (bug reports :? ) are very welcome.
Have fun, Ondrej
How reliable is very reliable? How many error free readings have you taken?

Over a million readings over 34 days with 11 errors. http://www.raspberrypi.org/forums/viewt ... 11#p605211

An advantage of my method is that any user gpio may be used and more than one sensor may be connected.

ondrej1024
Posts: 171
Joined: Thu Dec 05, 2013 3:09 pm
Contact: Website

Re: Adafruit DHT temp/humid sensor

Tue Nov 11, 2014 3:08 pm

Hi joan,

For me GPIO mode works really unreliable (about 80% of success rate). But since you have achieved much better results with your code I guess there is room for improvement. I will look at your implementation to see if there are any substantial differences.

I am still testing SPI mode (just a few thousand iterations so far, reading every 2s) but I haven't seen any error yet. Need to leave this running some more, of course. However, just from looking at the theory behind it, I think the GPIO method must be much more dependant on system load. Another big advantage I found is that with a (rather big) TP-LINK TL-WN722N wlan usb stick connected to the RPi, the communication with the sensor via GPIO does not work at all. I guess that's a problem with the rather flaky RPi power supply. But using the SPI method also solves this problem for me.

I agree that GPIO mode is more flexible if you want to choose the pin, of course. That's why I am supporting both GPIO and SPI methods in DHTlib, so the user can choose.

Ondrej
The Telegea.org project: https://www.telegea.org

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

Re: Adafruit DHT temp/humid sensor

Tue Nov 11, 2014 3:47 pm

ondrej1024 wrote:Hi joan,

For me GPIO mode works really unreliable (about 80% of success rate). But since you have achieved much better results with your code I guess there is room for improvement. I will look at your implementation to see if there are any substantial differences.

I am still testing SPI mode (just a few thousand iterations so far, reading every 2s) but I haven't seen any error yet. Need to leave this running some more, of course. However, just from looking at the theory behind it, I think the GPIO method must be much more dependant on system load. Another big advantage I found is that with a (rather big) TP-LINK TL-WN722N wlan usb stick connected to the RPi, the communication with the sensor via GPIO does not work at all. I guess that's a problem with the rather flaky RPi power supply. But using the SPI method also solves this problem for me.

I agree that GPIO mode is more flexible if you want to choose the pin, of course. That's why I am supporting both GPIO and SPI methods in DHTlib, so the user can choose.

Ondrej
80% is pretty impressive. I had a feeling that 50% success was pretty good for any of the busy-spin solutions.

I found that polling every 2 seconds eventually caused the sensor to hang which is why I'd poll every 3 seconds by default.

It would be interesting to see the SPI success reading stats for an extended run.

paulv
Posts: 564
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Adafruit DHT temp/humid sensor

Fri Nov 14, 2014 12:18 pm

Ondrej,
I tried your code and used the same methods I described in another post (http://www.raspberrypi.org/forums/viewt ... &t=91326&p) to verify. Because you use the same principle as Daniel, the scope shows no issues with timings. Your code is very well documented and complete, so a good addition the the SPI method of dealing with the DHT type sensors especially if you're working in C. Or you can modify your example to use that with a Python wrapper, which is what I did to test things out.
Good job!
Paul

ondrej1024
Posts: 171
Joined: Thu Dec 05, 2013 3:09 pm
Contact: Website

Re: Adafruit DHT temp/humid sensor

Fri Nov 14, 2014 1:20 pm

Hi Paul,

thanks for the feedback. I'm glad to hear things are working as expected.
While the Python class Daniel and you wrote is very handy for scripting type implementations, the DHTlib C library aims at C programs which want to add DHT sensor reading capability. I've also tried to implement this library with no dependencies on a specific hardware, so it can be run on any Linux system with GPIO and SPI support. Porting to some other board than RPi is just a matter of recompiling the code.
There are still some things to do, need to add the DHT11 support for SPI mode and make sure the sensor is not read too often (less than 2s) even if the user tries to do that. Hope to get an update out in the next few days.

Ondrej
The Telegea.org project: https://www.telegea.org

ondrej1024
Posts: 171
Joined: Thu Dec 05, 2013 3:09 pm
Contact: Website

Re: Adafruit DHT temp/humid sensor

Fri Nov 14, 2014 2:02 pm

Hi joan,

regarding reliability, I have been running a test for the last few days and reading the DHT22 sensor every 2s with the SPI method. Approaching 100.000 reads, there has not been a single failure so far. And, surprisingly, the sensor never got into a state where it didn't respond any more.
I won't wait for a million reads. I guess I have seen enough and I am satisfied with the stability of this method.
Ondrej
The Telegea.org project: https://www.telegea.org

paulv
Posts: 564
Joined: Tue Jan 15, 2013 12:10 pm
Location: Netherlands

Re: Adafruit DHT temp/humid sensor

Fri Nov 14, 2014 2:08 pm

Ondrej, all kudo's need to go to Daniel (danjperron) who implemented the SPI-method, wrote all the code and was gracious enough to post it.
I'm just a curious hobbyist.
I liked the principle and the method he used, and merely tried to understand it. It is so reliable (have yet to see a check sum error), that I wanted to learn more about it before I implemented it in my own application. During the fact finding and learning I documented my findings for others to use and learn from because forums die if there's only one-way-traffic.

Paul

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

Re: Adafruit DHT temp/humid sensor

Fri Nov 14, 2014 2:10 pm

ondrej1024 wrote:Hi joan,

regarding reliability, I have been running a test for the last few days and reading the DHT22 sensor every 2s with the SPI method. Approaching 100.000 reads, there has not been a single failure so far. And, surprisingly, the sensor never got into a state where it didn't respond any more.
I won't wait for a million reads. I guess I have seen enough and I am satisfied with the stability of this method.
Ondrej
That's good. I did have my method running for a week once before it hung at 2 second intervals.

mkhalil85
Posts: 3
Joined: Wed Feb 25, 2015 11:01 am

Re: Adafruit DHT temp/humid sensor

Thu Feb 26, 2015 9:29 am

Hi ,

Can anybody just tell me how i can put my DHT-11 sensor current reading on my web page.I already prepare a graph using dygraph but now i only want o show my digital output on the web sever.like on HTTP\\190.168.0.1\temp.html

Thanks in advance

Return to “Automation, sensing and robotics”