mattg31
Posts: 79
Joined: Fri Jan 05, 2018 9:55 pm

DHT22 AM2302 problems

Wed Apr 18, 2018 2:27 am

Hello,
I have read countless forum posts, and spent hours trying to figure this out and cannot seem to get my DH22 AM2302 temperature/humidity sensor to work. Can someone familiar with this please have a look at my setup? I must be missing something simple? I have tried two different sensors thinking one was damaged.

Here is my connections:https://imagebin.ca/v/3yl8DleaaQ1Y
--I followed the adafruit tutorial (several times) and have run the example code "simpletest.py" and am getting the printout "'Failed to get reading. Try again!"

Code: Select all

#!/usr/bin/python

# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import Adafruit_DHT

# Sensor should be set to Adafruit_DHT.DHT11,
# Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
sensor = Adafruit_DHT.2302

# Example using a Beaglebone Black with DHT sensor
# connected to pin P8_11.
#pin = 'P8_11'

# Example using a Raspberry Pi with DHT sensor
# connected to GPIO23.
pin = 4

# Try to grab a sensor reading.  Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

# Note that sometimes you won't get a reading and
# the results will be null (because Linux can't
# guarantee the timing of calls to read the sensor).
# If this happens try again!
if humidity is not None and temperature is not None:
    print('Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temperature, humidity))
else:
    print('Failed to get reading. Try again!')
--I tried the pigpio tutorial that @joan posted in several locations, but this is also not working. depending on what code I follow I am getting either 999.99 for a temperature or I am getting various error messages.

Code: Select all

#!/usr/bin/env python

# 2014-07-11 DHT22.py

import time
import atexit

import pigpio

class sensor:
   """
   A class to read relative humidity and temperature from the
   DHT22 sensor.  The sensor is also known as the AM2302.

   The sensor can be powered from the Pi 3V3 or the Pi 5V rail.

   Powering from the 3V3 rail is simpler and safer.  You may need
   to power from 5V if the sensor is connected via a long cable.

   For 3V3 operation connect pin 1 to 3V3 and pin 4 to ground.

   Connect pin 2 to a gpio.

   For 5V operation connect pin 1 to 5V and pin 4 to ground.

   The following pin 2 connection works for me.  Use at YOUR OWN RISK.

   5V--5K_resistor--+--10K_resistor--Ground
                    |
   DHT22 pin 2 -----+
                    |
   gpio ------------+
   """

   def __init__(self, pi, gpio, LED=None, power=None):
      """
      Instantiate with the Pi and gpio to which the DHT22 output
      pin is connected.

      Optionally a LED may be specified.  This will be blinked for
      each successful reading.

      Optionally a gpio used to power the sensor may be specified.
      This gpio will be set high to power the sensor.  If the sensor
      locks it will be power cycled to restart the readings.

      Taking readings more often than about once every two seconds will
      eventually cause the DHT22 to hang.  A 3 second interval seems OK.
      """

      self.pi = pi
      self.gpio = gpio
      self.LED = LED
      self.power = power

      if power is not None:
         pi.write(power, 1) # Switch sensor on.
         time.sleep(2)

      self.powered = True

      self.cb = None

      atexit.register(self.cancel)

      self.bad_CS = 0 # Bad checksum count.
      self.bad_SM = 0 # Short message count.
      self.bad_MM = 0 # Missing message count.
      self.bad_SR = 0 # Sensor reset count.

      # Power cycle if timeout > MAX_TIMEOUTS.
      self.no_response = 0
      self.MAX_NO_RESPONSE = 2

      self.rhum = -999
      self.temp = -999

      self.tov = None

      self.high_tick = 0
      self.bit = 40

      pi.set_pull_up_down(gpio, pigpio.PUD_OFF)

      pi.set_watchdog(gpio, 0) # Kill any watchdogs.

      self.cb = pi.callback(gpio, pigpio.EITHER_EDGE, self._cb)

   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.high_tick, tick)

      if level == 0:

         # Edge length determines if bit is 1 or 0.

         if diff >= 50:
            val = 1
            if diff >= 200: # Bad bit?
               self.CS = 256 # Force bad checksum.
         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:

               # 40th bit received.

               self.pi.set_watchdog(self.gpio, 0)

               self.no_response = 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

                  self.tov = time.time()

                  if self.LED is not None:
                     self.pi.write(self.LED, 0)

               else:

                  self.bad_CS += 1

         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.high_tick = tick
         if diff > 250000:
            self.bit = -2
            self.hH = 0
            self.hL = 0
            self.tH = 0
            self.tL = 0
            self.CS = 0

      else: # level == pigpio.TIMEOUT:
         self.pi.set_watchdog(self.gpio, 0)
         if self.bit < 8:       # Too few data bits received.
            self.bad_MM += 1    # Bump missing message count.
            self.no_response += 1
            if self.no_response > self.MAX_NO_RESPONSE:
               self.no_response = 0
               self.bad_SR += 1 # Bump sensor reset count.
               if self.power is not None:
                  self.powered = False
                  self.pi.write(self.power, 0)
                  time.sleep(2)
                  self.pi.write(self.power, 1)
                  time.sleep(2)
                  self.powered = True
         elif self.bit < 39:    # Short message receieved.
            self.bad_SM += 1    # Bump short message count.
            self.no_response = 0

         else:                  # Full message received.
            self.no_response = 0

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

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

   def staleness(self):
      """Return time since measurement made."""
      if self.tov is not None:
         return time.time() - self.tov
      else:
         return -999

   def bad_checksum(self):
      """Return count of messages received with bad checksums."""
      return self.bad_CS

   def short_message(self):
      """Return count of short messages."""
      return self.bad_SM

   def missing_message(self):
      """Return count of missing messages."""
      return self.bad_MM

   def sensor_resets(self):
      """Return count of power cycles because of sensor hangs."""
      return self.bad_SR

   def trigger(self):
      """Trigger a new relative humidity and temperature reading."""
      if self.powered:
         if self.LED is not None:
            self.pi.write(self.LED, 1)

         self.pi.write(self.gpio, pigpio.LOW)
         time.sleep(0.017) # 17 ms
         self.pi.set_mode(self.gpio, pigpio.INPUT)
         self.pi.set_watchdog(self.gpio, 200)

   def cancel(self):
      """Cancel the DHT22 sensor."""

      self.pi.set_watchdog(self.gpio, 0)

      if self.cb != None:
         self.cb.cancel()
         self.cb = None

if __name__ == "__main__":

   import time

   import pigpio

   import DHT22

   # Intervals of about 2 seconds or less will eventually hang the DHT22.
   INTERVAL=3

   pi = pigpio.pi()

   s = DHT22.sensor(pi, 4, LED=16, power=8)

   r = 0

   next_reading = time.time()

   while True:

      r += 1

      s.trigger()

      time.sleep(0.2)

      print("{} {} {} {:3.2f} {} {} {} {}".format(
         r, s.humidity(), s.temperature(), s.staleness(),
         s.bad_checksum(), s.short_message(), s.missing_message(),
         s.sensor_resets()))

      next_reading += INTERVAL

      time.sleep(next_reading-time.time()) # Overall INTERVAL second polling.

   s.cancel()

   pi.stop()

I have tried with no resistor, 4.7K, and 10K. All with the same results. As mentioned above I also tried a second sensor.

I am ready to give up, but thought I would see if someone has had similar issues.

Lastly, is there a sensor that is a little more user (inexperienced user) friendly for the raspberry pi?

Any help is appreciated!

Thanks!

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

Re: DHT22 AM2302 problems

Wed Apr 18, 2018 4:35 am

It would be helpful to have a photo of your sensor and a link to where it was purchased. It may not be the model you think it is (the most likely reason for not being able to get a reading).

Another useful diagnostic would be a photo of how you have connected it to the Pi. That would let us verify the GPIO and power supply being used.

mattg31
Posts: 79
Joined: Fri Jan 05, 2018 9:55 pm

Re: DHT22 AM2302 problems

Wed Apr 18, 2018 9:27 am

Thanks for the reply.
The sensor I purchased is here: https://www.digikey.ca/product-detail/e ... ND/5356714
Here is a picture of the back of my received sensor: https://imagebin.ca/v/3ynFE7VNO1Uw
Here is a picture of of how I have the connections to the pi: https://imagebin.ca/v/3yl8DleaaQ1Y

It is a raspberry pi 3 model B, and I have tried a 4.7K resistor, 10k resistor, and no resistor at all.

Thanks again for the reply, and assistance, much appreciated.

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

Re: DHT22 AM2302 problems

Wed Apr 18, 2018 9:40 am

Everything you have written appears to be correct.

The datasheet suggests a 1k pull-up but I would have thought a 4k7 would have worked.

GPIO4 is also used for the 1-wire bus by default if enabled (the AM2302 is not 1-wire bus compatible). It is worth checking that there is no mention of 1-wire in /boot/config.txt - anything starting w1 should be commented out.

The other thing I would do is run up piscope and capture the transaction (if any).

http://abyz.me.uk/rpi/pigpio/piscope.html

Alternatively use http://abyz.me.uk/rpi/pigpio/examples.h ... monitor_py to capture the traffic on GPIO4.

Both will show what is going on and if the device is responding to reading triggers.

mattg31
Posts: 79
Joined: Fri Jan 05, 2018 9:55 pm

Re: DHT22 AM2302 problems

Wed Apr 18, 2018 10:03 am

Yes I feel like I have triple checked all of my connections, not sure why it is giving me so much trouble.

I will try your suggestions when I am in front of my pi later today and let you know what the piscope shows.

thanks again

mattg31
Posts: 79
Joined: Fri Jan 05, 2018 9:55 pm

Re: DHT22 AM2302 problems

Sat Apr 21, 2018 10:19 pm

joan wrote:
Wed Apr 18, 2018 9:40 am
The other thing I would do is run up piscope and capture the transaction (if any).

http://abyz.me.uk/rpi/pigpio/piscope.html

Alternatively use http://abyz.me.uk/rpi/pigpio/examples.h ... monitor_py to capture the traffic on GPIO4.

Both will show what is going on and if the device is responding to reading triggers.
Hi @joan
I have connected the piscope, and there is definitely activity on GPIO 4. I have no idea what I'm doing wrong, but as you can see in the screen shot, I am still not getting any temperature readings.

screenshot:
https://imgur.com/a/SvzyaX0

mattg31
Posts: 79
Joined: Fri Jan 05, 2018 9:55 pm

Re: DHT22 AM2302 problems

Sat Apr 21, 2018 10:24 pm

Update, I disconnected the DHT22 from GPIO 4 and the piscope is still showing signal transfers?

Any ideas?

Edit:
I connected the DHT22 to GPIO 23 and now it's working? I have done this a few days ago and it wasn't working on any GPIO. So weird.
The only thing I can think of that is different, is that I am running piscope at the same time.

Also, I tried taking a measurement several times and was successful, but did not see any data transfer on the piscope? (Except GPIO 4, which is connected to nothing)

sbm
Posts: 2
Joined: Thu Oct 11, 2018 8:15 am

Re: DHT22 AM2302 problems

Thu Nov 15, 2018 4:11 am

mattg31 wrote:
Sat Apr 21, 2018 10:24 pm
Update, I disconnected the DHT22 from GPIO 4 and the piscope is still showing signal transfers?

Any ideas?

Edit:
I connected the DHT22 to GPIO 23 and now it's working? I have done this a few days ago and it wasn't working on any GPIO. So weird.
The only thing I can think of that is different, is that I am running piscope at the same time.

Also, I tried taking a measurement several times and was successful, but did not see any data transfer on the piscope? (Except GPIO 4, which is connected to nothing)
The above option of changing PIN works reliably.

Return to “Automation, sensing and robotics”