Difference between revisions of "Building A Remote Temperature and Humidity Sensor Web-Service Using A DHT22 Sensor and a Raspberry Pi 3B+"
Jump to navigation
Jump to search
m |
m |
||
Line 134: | Line 134: | ||
:#Select <code>Finish</code> from the main configuration menu. | :#Select <code>Finish</code> from the main configuration menu. | ||
:#Answer <code>Yes</code> to the question, “Would you like to reboot now?” and the system will reboot. | :#Answer <code>Yes</code> to the question, “Would you like to reboot now?” and the system will reboot. | ||
− | :The file systems are once again read/write. | + | :The file systems are once again read/write. System changes that are made will be written to the SD card. |
__NOTOC__ | __NOTOC__ | ||
[[Category:Raspberry Pi]] | [[Category:Raspberry Pi]] | ||
[[Category:Linux]] | [[Category:Linux]] |
Revision as of 03:03, 22 January 2020
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.
Additional Configuration Tasks
These tasks probably should be carried out to complete the system configuration but are not directly pertinent to the creation of the web service.
- Securing the system.
- The default configuration has the system automatically logging on the "pi" userid into a desktop environment. This isn't good security and, since we'll be running this system as headless, without a display or keyboard, we really don't need to waste resources running X windows anyway. Therefore the simplest option is to turn the desktop (X windows) off altogether:
- In a terminal session run the command
sudo raspi-config
. - Select option
3 Boot Options
. - Select option
B1 Desktop / CLI
- Select option
B1 Console
- In a terminal session run the command
- At the next sytem reboot it will come up with a simple text-based console login on the main display. Of course, since we're running headless and don't have any display connected to the Pi, we won't see this.
- Protecting the SD card from corruption.
- On small systems like the Raspberry Pi it is not unheard of for the SD card they boot from to become corrupted during normal system operations, rendering the system unbootable. Small PC board-based systems can be a bit sensitive to power glitches, unplugging the power cord before shutting down completely, failed disk writes, etc. This is why full image backups of the SD cards used in systems like this are highly recommended. Another way to reduce this risk is to make the file systems stored on the SD card read only. When this is done the system uses filesystem memory overlays to hold any disk changes while it's running, allowing it to operate normally until it shuts down. When shutdown occurs the changes stored in the overlay memory are lost. The next time the system boots up it comes up in the state that was originally stored on the SD card when it was made read-only. Any changes made during the last boot, be they good changes or bad changes, are gone. For the type of system we made in this project that is no problem as there is no dynamic data that matters that's being stored locally on the SD card.
- It used to be an involved process to turn on or off this sort of filesystem overlay configuration on a Raspberry Pi. If you search the internet you'll find any number of complex sets of instructions on how to do it. Fortunately, however, this configuration has now been built into the Raspian OS that runs on the Raspberry Pi and overlay configuration is simple to enable and disable.
- To enable filesystem memory overlays:
- In a terminal session run the command
sudo raspi-config
. - Select option
7 Advanced Options
- Select option
AB Overlay FS
- Answer
Yes
to the question, “Would you like the overlay file system to be enabled?” and then wait while the system generates the necessary files. (This is only done once, the first time you enable overlays.) - Answer
Ok
to the message “The overlay file system is enabled.” - Answer
Yes
to the question, “Would you like the boot partition to be write protected?” - Answer
Ok
to the message “The boot partition is read-only.” - Select
Finish
from the main configuration menu. - Answer
Yes
to the question, “Would you like to reboot now?” and the system will reboot.
- In a terminal session run the command
- The system will restart, and can be used in exactly the same manner as it was prior to the change. It's just that any system changes made now will be wiped out when the system next reboots.
- Reversing this process and making the filesystem read/write again is done in exactly the same manner, using the
raspi-config
tool. There will be two reboots required during the process:
- In a terminal session run the command
sudo raspi-config
. - Select option
7 Advanced Options
- Select option
AB Overlay FS
- Answer
No
to the question, “Would you like the overlay file system to be enabled?” - Answer
Ok
to the message “The overlay file system is disabled.” - Answer
Ok
to the message “The boot partition is currently read-only. This cannot be changed while an overlay file system is enabled.” - Select
Finish
from the main configuration menu. - Answer
Yes
to the question, “Would you like to reboot now?” and the system will reboot. - After the reboot is complete, run the
sudo raspi-config
command again in a terminal session. - Select option
7 Advanced Options
- Select option
AB Overlay FS
- Answer
No
to the question, “Would you like the overlay file system to be enabled?” - Answer
Ok
to the message “The overlay file system is disabled.” - Answer
No
to the question, “Would you like the boot partition to be write protected?” - Answer
Ok
to the message “The boot partition is writable.” - Select
Finish
from the main configuration menu. - Answer
Yes
to the question, “Would you like to reboot now?” and the system will reboot.
- In a terminal session run the command
- The file systems are once again read/write. System changes that are made will be written to the SD card.