Building A Remote Temperature and Humidity Sensor Web-Service Using A DHT22 Sensor and a Raspberry Pi 3B+

From Nearline Storage
Jump to navigation Jump to search
This is a photo of the Raspberry Pi 2 I use to make humidity and temperature readings from the DHT22 sensor that is attached to it available to other computers on my network. Since this is a Pi 2, and not a Pi 3 B+ as I describe in the write-up that follows, I had to add a USB wifi adapter to it so that it could connect to the wifi network in my home. The GPIO pin layout is also different on a Pi 2 vs a Pi 3.

Materials Required

  • Raspberry Pi 3B+ (Any Pi will do, as long as it has wifi for communications.)
  • Mini SD card, 8GB or larger (For this application there's no advantage to having an SD card that's any larger than the minimum requirement.)
  • DHT22/AM2302 temperature and humidity sensor (I assume that the 3-pin version of this sensor is being used here. There is also a 4-pin version available that may, or may not, require that a resistor be soldered in between two of the pins.)
If the DHT22 sensor does not come with jumper wires to connect it to the Pi included, then these must be ordered separately.
  • Block of wood for mounting (optional)
  • Small wood screws for mounting (optional)

Instructions

Here's an outline of the minimum steps required to get things running:

  • Set up the Raspberry Pi.
    • The linked instructions provide guidance on formatting the SD card using a program on Mac or Windows. See this tutorial for instructions on how to do the same thing on a Linux computer.
  • We will ultimately want to run the Pi as a headless system, i.e., without a keyboard or display attached, so set up ssh for remote access to a terminal.
  • Make sure that the Pi has a static IP address on the network, and even perhaps a hostname.
If the Pi is to be accessed remotely, it must have an IP address that is known. Associating that address with a hostname makes things even easier. Typically these would be things that would be configured through the DHCP and DNS settings on the local network router. The exact procedure for setting this up varies so I won't try to cover it here.
  • Enable the ssh service on the Pi, i.e., in a terminal session enter:
$ sudo systemctl start ssh
$ sudo systemctl enable ssh
  • Optional: set up SSL key-based login so that you don't have to enter the password every time.
  • With the Pi powered off, connect the DHT22 sensor.
There are three pins on the DHT22 sensor that must be connected to the GPIO pins on the Pi. Use the pinout command on the Pi to see a text-based diagram of the GPIO pin layout on the Pi.
  • Connect the "+" (power) pin on the DHT22 to one of the 5V pins on the Pi
  • Connect the "out" pin on the DHT22 to the GPIO2 pin, pin 3, on the Pi
  • Connect the "-" (ground) pin on the DHT22 to one of the GND pins on the Pi.
  • Power the Pi back on and add an entry for the DBUS file driver for the DHT22 sensor to /boot/config.txt:
dtoverlay=dht11,gpiopin=2
  • The gpiopin value used here must match the pin number that the data line of the sensor is connected to. In this example that's the GPIO2 pin.
  • Insert this line near the bottom of /boot/config.txt, immediately below the line that says "[all] and above the line that says "^M".
  • Reboot the Pi after making this change. There will now be a set of files in the /sys/bus/iio/devices/iio:device0 directory that contain information from the sensor.
  • Check the files that contain the temperature and humidity readings:
cat /sys/bus/iio/devices/iio\:device0/in_temp_input
cat /sys/bus/iio/devices/iio\:device0/in_humidityrelative_input
These commands should return a number that is 1000 X the temperature in degrees Celcius and 1000 X the relative humidity, as a percentage. They will also frequently return I/O errors. This simply means that the driver is busy fetching the updated values at the moment. Trying again a few seconds later should return the expected reading.
  • Create a web service on the Raspberry Pi that any computer on your network can query to get the current temperature and humidity.
    • Install a web server and the PHP scripting language.
sudo apt-get install php
This will install PHP and the Apache web server and their dependent packages.
  • Modify the web server's home page to turn it into the web service.
  • Delete or rename the file /var/www/html/index.html
  • Create a new file named /var/www/html/index.php with the following content:
    <?php
    
    // Get the tempurature and humidity data from the sensor and return those values in JSON format
    function getSensorReading() {
    
    	//  If we can't get a reading in 5 seconds, we'll return an empty string
    	$start = time();
    
    	//  Try to get readings from the sensor.  If there's any error, then these values will be empty
    	$temp = file_get_contents('/sys/bus/iio/devices/iio:device0/in_temp_input');
    	$humid = file_get_contents('/sys/bus/iio/devices/iio:device0/in_humidityrelative_input');
    
    	//  If there was an error, try again until we get a reading or until 5 seconds has elapsed
    	while ($temp == '' or $humid == '') {
    		if (time() - $start > 5) {
    			//  If 5 seconds has elapsed, then return an empty string
    			return '';
    		}
    		$temp = file_get_contents('/sys/bus/iio/devices/iio:device0/in_temp_input');
    		$humid = file_get_contents('/sys/bus/iio/devices/iio:device0/in_humidityrelative_input');
    	}
    
    	//  Convert temp to Fahrenheit
    	$temp = (intval($temp) / 1000 * 9 / 5) + 32;
    
    	//  Convert relative humdiity to proper scale
    	$humid = intval($humid) / 1000;
    
    	//  Return a JSON-like array containing the values
    	return [ 'temperature' => $temp, 'relativeHumidity' => $humid ];
    }
    
    //  The HTTP response ...
    header("Content-Type: application/json; charset=UTF-8");
    echo json_encode(getSensorReading());
    
    ?>
  • A web browser pointed at the IP address or hostname of the Pi should now display the temperature and humidity as a JSON string, like this:
{"temperature":70.88,"relativeHumidity":35.3}
  • Ta Da! This Raspberry Pi now provides a RESTful web service that can be used by any other computer in your network to obtain the current temperature and relative humidity from the DHT22 sensor.