Temperature and humidity sensor

To control the heating, the Pi needs to know temperature and humidity, this is possible by using the combined sensor DHT22. I got my unit from Adafruit here. It comes with the required 4.7K – 10K resistor, to be used as a pullup from the data pin to VCC. How the wiring on the breadboard works you can see depicted further below.

Initially I wanted to interface the DHT22 temperature and humidity sensor with perl. After some time it became obvious that perl on the Pi is not fast enough to read successfully from the sensor.

At that point I decided to use the great C-code from Adafruit (available on Github) and simply embed it into my perl script. A very useful tutorial from Adafruit is available here.

The picture below shows how the wiring looks like on the breadboard
Temp/Hum Sensor

This is how this translates into the Fritzing breadboard view
Temp/Hum Fritzing

The script calls the Adafruit C-code with the parameters 22 (for the sensor type) and 4 (which is the GPIO pin to be used). As even this code is not able to perform a successful measurement at every run I created a small loop to ensure that the logging only happens when the values have been extracted successfully. You may also notice the counter variable in the code, this variable can be used to track how many loops are required until a successful measurement could be taken. In practice the values are between 2 and 5 loops, maximum I noticed so far was 11.

#!/usr/bin/perl

# logfile handling
sub logging {

  my $logfile = "/appco.de/log/appco.de.log";

  if ( ! open LOG, ">>", $logfile ) {
    die "Kann Logdatei nicht anlegen: $!";
  }

  my ($sekunden, $minuten, $stunde, $tag, $monat, $jahr) = localtime;
  my $echtes_jahr = $jahr + 1900;
  my $echter_monat = $monat + 1;
  printf LOG "%s.%02s.%02s %02s:%02s:%02s %s\n", $echtes_jahr, $echter_monat, $tag, $stunde, $minuten, $sekunden, $_[0];
  close LOG;

}

my $bin = './Adafruit_DHT 22 4';
my $check = 0;
my $counter = 0;

#run until a temperature and humidity value has been logged
while ($check == 0){
  # run the C program
  $result2 = `$bin`;

  # extract the strings
  my @array = split("\n", $result2);

  $counter = $counter + 1;

  # logging only if the string is not empty
  if ($array[2] ne "") {
    &logging ("$array[2]");
    &logging ("$counter");
    $check = 1;
  }
}

One thought on “Temperature and humidity sensor

  1. Pingback: Raspberry Pi and sensors | appco.de

Leave a Reply

Your email address will not be published. Required fields are marked *