I have attached a DHT-22 weather sensor to my rev 1 raspberry pi after a fresh install of a recent install of debian.

Following the instructions from https://www.youtube.com/watch?v=IHTnU1T8ETk I installed the pipgio and got this to work using sudo python.

import os
import pigpio
pi = pigpio.pi()
import DHT22
s = DHT22.sensor(pi, 4)
print('{:3.2f}'.format(s.humidity() / 1.)) => 48.60
print('{:3.2f}'.format(s.temperature() / 1.)) => 27.50

Great! What I expected. This code when I put in a file called mypio.py in the same folder as PIGPIO I get this response:


I'm sure it's my not understanding what python is doing but surely I would have found a post on Google about it. I'm unsure which github repo has the canonical version of this library, but no fruitful yield of my searches yet. Help me understand the difference between running it in the python console and the file itself, thx, sam

  • Did you start the deamon? Jul 29 '15 at 14:06
  • Yes, sudo pigpio and the lock file is /var/run/pigpio.pid with the date I started this a.m.
    – sam452
    Jul 29 '15 at 14:23
  • There should be a delay after the trigger, perhaps a time.sleep(0.2), so try import time and add a short delay. If you are not reading in a while loop it's probably best to s.cancel() and pi.stop() as well at the end of the program to release resources. Don't run the script with sudo. Only the daemon needs starting with sudo.
    – joan
    Jul 29 '15 at 14:46
  • Yes, that seems to help. I did not add a time.sleep(0.2) to before the humidity call and it responded as before. I did add it to before the temperature call and it worked. Aside from some sort of "Error in atexit._run_exitfuncs:" which will be a separate question, I'd appreciate if you would put it in an answer.
    – sam452
    Jul 29 '15 at 16:24

You need to have a short delay after triggering a DHT22 reading to allow the returned data to be received and processed.

A reading is triggered by holding the output line low for about 20ms. When the line is released (left to float) the DHT22 will return a reading.

DHT22 trigger and data

The data is returned as a preamble followed by the 40 data bits (two bytes for temperature, two bytes for humidity, plus one byte checksum. In all they take about 4ms to transmit.

DHT22 data bits

You need to allow time for the script to process the returned data.

In practice a delay of 0.2 seconds between trigger and reading the returned temperature and humidity seems sufficient.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.