DHT 22 Temperature and Humidity measurement

Installing the Libraries

From the AdaFruit web site https://learn.adafruit.com/dht-humidity-sensing-on-raspberry-pi-with-gdocs-logging/software-install-updated

  1. git clone https://github.com/adafruit/Adafruit_Python_DHT.git
  2. cd Adafruit_Python_DHT
  3. sudo apt-get update
  4. sudo apt-get install build-essential python-dev python-openssl
  5. sudo python setup.py install


Wiring

DHT22 connectionsDHT 22 Schematic

DHT22 Wiring Back Side

Back Side DHT 22 Wiring

Testing

pi@raspberrypi ~ $ cd
pi@raspberrypi ~ $ ls
Adafruit_Python_DHT  Desktop  python  python_games  startvnc

pi@raspberrypi ~ $ cd Adafruit_Python_DHT/
pi@raspberrypi ~/Adafruit_Python_DHT $ ls

Adafruit_DHT           examples      README.md                   source
Adafruit_DHT.egg-info  ez_setup.py   setup.py
build                  ez_setup.pyc  setuptools-4.0.1-py2.7.egg
dist                   LICENSE       setuptools-4.0.1.zip

pi@raspberrypi ~/Adafruit_Python_DHT $ cd examples/
pi@raspberrypi ~/Adafruit_Python_DHT/examples $ ls

AdafruitDHT.py  google_spreadsheet.py  simpletest.py
pi@raspberrypi ~/Adafruit_Python_DHT/examples $ cat simpletest.py



#!/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.DHT22   # 22 is what I have.

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

# Example using a Raspberry Pi with DHT sensor
# connected to GPIO23.
#pin = 23        # Uncomment this for Pi and change the pin number to the pin you used when you wired it.

# 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!')
pi@raspberrypi ~/Adafruit_Python_DHT/examples $

Program on Pi to get the temperature and humidity


#! /usr/bin/python
import RPi.GPIO as GPIO import time import signal, os import sys import Adafruit_DHT # Catch a signal and set the gpio pins to default on forced exit def handler(signum, frame): # GPIO.output(ledPin, 0) GPIO.cleanup() os._exit(0) # In this case ^C signal.signal(signal.SIGINT, handler) # Set up parameters cycleTime = 300 # minutes ledTimeSleep = 1 sensor = 22 # sensor type pin = 23 # sensor data pin ledPin = 12 # heartbeat led # Loop forever while 1: #get the humidity and temperature. # print "get humidity\n" humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) #Send the info off to fibble execArg = "ssh -i /home/pi/.ssh/forhome deid@fibble.ca pi/testPi.py " + str(temperature) + "," + str(humidity) # Execute the ssh transfer os.system(execArg) # Flash the led every second # Reset the board and change to Broadcom numbering schema GPIO.cleanup() GPIO.setmode(GPIO.BCM) # set up pin to use GPIO.setup(ledPin, GPIO.OUT) #Loop switching on and off until time to get another temperature num = cycleTime / ledTimeSleep / 2 while num > 0: GPIO.output(ledPin, 1) time.sleep(ledTimeSleep) GPIO.output(ledPin, 0) time.sleep(ledTimeSleep) num = num - 1

# Set the gpio pins to default: GPIO.cleanup()

testPI.py


#! /usr/bin/python

import sys, time

localtime = time.localtime(time.time())

myTime = str("%d-%02d-%02d %02d:%02d" % (localtime[0],localtime[1],localtime[2],localtime[3],localtime[4]))
myDate = str("%d-%02d-%02d" % (localtime[0],localtime[1],localtime[2]))

Afile = open('/home/deid/pi/th-' + myDate , 'a')
Afile.write(myTime + "," +str(sys.argv[1]) + '\n')
Afile.close




Files Created


-rw-rw-r--  1 deid deid   11691 May 21 23:57 th-2016-05-21
-rw-rw-r--  1 deid deid   12132 May 22 23:57 th-2016-05-22
-rw-rw-r--  1 deid deid   10332 May 23 23:55 th-2016-05-23
-rw-rw-r--  1 deid deid   12168 May 24 23:55 th-2016-05-24
-rw-rw-r--  1 deid deid    9927 May 25 23:56 th-2016-05-25
-rw-rw-r--  1 deid deid   11826 May 26 23:56 th-2016-05-26
-rw-rw-r--  1 deid deid    7101 May 27 14:25 th-2016-05-27



Contents of a file

....


2016-05-27 13:39,22.1000003815,31.6000003815
2016-05-27 13:45,22.0,31.5
2016-05-27 13:50,22.0,31.6000003815
2016-05-27 13:55,21.8999996185,31.6000003815
2016-05-27 14:00,22.0,31.5
2016-05-27 14:05,22.0,31.5
2016-05-27 14:10,22.0,31.5
2016-05-27 14:15,22.0,31.5
2016-05-27 14:20,22.0,31.5
2016-05-27 14:25,21.8999996185,31.5



Web Display


Temperature Humidity Graph

And the Code



<html><head><title>Temperature and Humidity Chart</title>
</head>
<body>
<!-- Set up the canvases for the temperature and humidity -->
<canvas id="temperature" width="576" height="300" style="border:1px solid #000000; position:absolute; left:430px; top:20px">
Your browser does not support the HTML5 canvas tag.
</canvas>

<canvas id="humidity" width="576" height="300" style="border:1px solid #000000; position:absolute; left:430px; top:380px">
Your browser does not support the HTML5 canvas tag.
</canvas>

<form method="post" action="th0.php">
Date: <input type="text" name=date>
</form>

<?php
// See if there is a date from the form and it is correct format.  If so use it.
$myDate = date('Y-m-d');
if ($formDate = $_POST['date']) {
  if(preg_match("/^\d{4}-\d{2}-\d{2}/", $formDate)) {
    $myDate = $formDate;
  }
}

// Open the desired file.  Defaults to todays file.    
if ($INP = fopen ("/home/deid/pi/th-. $myDate, 'r')) {

  // Get and display the last 5 values
  $pos = -2;
  for ($i = 4; $i >= 0; $i--) {
    while ($t != "\n") {
      fseek($INP, $pos, SEEK_END);
      $t = fgetc($INP);
      $pos = $pos - 1;
    }
    $t = "";
  }
  echo "<b>Most Recent 5 Readings</b><br>";
  echo "<table border=\"1\" style=\"font-size:large; font-style:oblique;\">";
  echo "<tr><td>Time</td><td>Temperature</td><td>Humidity</td></tr>";
  while(!feof($INP)){
    $line = fgets($INP);
    if ($line) { 
      list($time , $temp, $humidity) = explode(",", $line);
      echo "<tr><td>$time</td><td>. round($temp,2) . "</td><td>. round($humidity,2) . "</td></tr>";
    }
  }
  echo "</table></big></b><p>";
  
//  Seek back to the beginning and get and display all the values.
  fseek($INP,0);
  
  echo "<b>All $myDate Readings</b><br>";
  echo "<table border=\"1\">";
  echo "<tr><td>Time</td><td>Temperature</td><td>Humidity</td></tr>";
  while (!feof($INP)) {
    if ($line = fgets($INP)) {
      list($time , $temp, $humidity) = explode(",", $line);
      echo "<tr><td>$time</td><td>. round($temp,2) . "</td><td>. round($humidity,2) . "</td></tr>";

// Put temperature and humidity into arrays for plotting      
      $temps[] = $temp;
      $humiditys[] = $humidity;
    }
  }
  echo "</table>";
} else {
  exit;
}

?>

<script>
// Figure out where the canvases are in Javascript
var c = document.getElementById("temperature");
var t = c.getContext("2d");

var c = document.getElementById("humidity");
var h = c.getContext("2d");
</script>

<?php
// Calculate the temperature and humidity max/min and scale to fill the canvas.
$maxt = round(max($temps), 2);
$mint = round(min($temps), 2);
$scalet = 300 / ($maxt - $mint);

$maxh = round(max($humiditys), 2);
$minh = round(min($humiditys), 2);
$scaleh = 300 / ($maxh - $minh);

// Write the temperature and humidity scale values.
echo '<p style="position:absolute; left:395px; top:0px">';
echo $maxt;
echo '</p>';
echo '<p style="position:absolute; left:395px; top:295px">';
echo $mint;

echo '<p style="position:absolute; left:395px; top:360px">';
echo $maxh;
echo '</p>';
echo '<p style="position:absolute; left:395px; top:660px">';
echo $minh;

?>

<script>
// Create the Javascript to display the temperature graph.

// Initialize the coordinates.
var x = 0;
var y = 300
t.moveTo(x, y);

<?php
foreach ($temps as $t) {
  $t =  round(300 - ($t - $mint) * $scalet, 0);
  echo "t.lineTo(x,$t);t.stroke();x=x+2;";
}
?>
</script>

<!-- Position the temperature title and display it. -->
<p style="position:absolute; left:640px; top:315px"">
<b>Temperature</b>
</p>

<script>
// Create the Javascript to display the humidity graph.
// Initialize the coordinates.
x = 0;
y = 300
h.moveTo(x, y);

<?php
foreach ($humiditys as $t) {
  $t =  round(300 - ($t - $minh) * $scaleh, 0);
  echo "h.lineTo(x,$t);h.stroke();x=x+2;";
}
?>
</script>

<!-- Position the humidity title and display it. -->
<p style="position:absolute; left:640px; top:670px"">
<b>Humidity</b>
</p>

</body></html>








....