Introduction: Raspberry PI and DHT22 Temperature and Humidity Logger With LAMP and Email Warnings

This is an Raspberry Pi based temperature and humidity logger that uses 2 (works also with 1) Adafruit DHT22 sensors for measurements. You might have seen similar kind of instructions before, but this one has a twist. It doesn't just read temperature and humidity from sensors, but it stores data to MySql database and provides means to read that temperature data with any web enabled device (computer, phone, tablet) web browser. This logger also allows you to set limits for temperatures and is able to send email if sensor temperature drops below set limit...this neat feature can be for example used to alarm when it is time to set heating on in your house / carage / greenhouse / you name it.

To complete this instructable, you will need following:

- Raspberry PI (I used Raspberry PI 1 model B+, but should be doable with other models as well)

- Power supply for the pi. (I used old Nokia microusb telephone charger which gives about 880mA)

- SD memory card. Note that you might need adapter. (I used 8Gb and had 4.1Gb available after installing everything)

- Ethernet cable or USB wlan dongle that is supported by Raspberry Pi (google can help with this)

- DHT22 sensor/s and 4.7 kOhm resistors. Instructable supports 2 sensors, but can be done with 1. https://www.adafruit.com/products/385

- Cables and breakout for connection https://www.adafruit.com/products/914

- Computer where you set up the SD card for the raspberry PI and from where you can connect and do the configurations. (NOTE: this instruction uses PC)

- Optional: Breadboard. Test assembly is easier to be created on this, than by connecting wires directly to sensors: http://thepihut.com/products/raspberry-pi-breadbo...

Internet connection is also require in location where you are going to set the raspberry logger. Either via ethernet or wlan dongle.

Keyboard + display are needed as well while installing and configuring the Wheezy OS. But once installations are finished, network is up and SSH enabled, it is possible to use connect raspberry pi remotely from PC and keyboard + display can be put aside.

Step 1: Sensor and RPI Assembly

NOTE- Assembly image updated 19.11.2015. There was error in last edition. -NOTE

Create assembly as instructed in attached image. Image instructs how you can connect two DHT22's to the Raspberry Pi, but if you have only one available just ignore another one and add one.

Notable here is that you can connect sensors to any GPIO you like. I had mine connected in GPIO22 and GPIO23. Both sensors also need +3.3Volts and ground. Resistor is set between +3.3V line and GPIO line.

When assembly is ready, prepare SD card and go to next step.

Step 2: OS for the RPI (Debian Wheezy)

Get the Wheezy image from here to your computer https://www.raspberrypi.org/downloads/raspbian/htt...

And get also Win32 Disk Imager http://sourceforge.net/projects/win32diskimager/

Start Win32 Disk Imager and set the location of the downloaded Wheezy image (.img file) to "Image File". Select the drive where your SD card is and select "Write".

Imager asks to Confirm Overwrite. Double check that drive is correct and select "Yes". Wait for write to finish. When Disk Imager informs that write is completed and successful press "OK", close the Disk Imager and eject the SD card from computer.

Place the card to your Raspberry Pi and go to next step.

Step 3: Setting Up Raspberry Pi

Set SD card (that has the Wheezy) to Raspberry Pi and power it up by plugging the power supply to Raspberry Pi's micro-usb. (Remember to attach keyboard and display before you insert power supply).

Rasperry Pi starts to boot up and shortly you will see configuration tool (image above).

In configuration tool, do the following:

1. Expand the file system

2. Change your password and give new password to Raspberry Pi

3. Make sure that Raspberry Pi boots to console by selecting option 1, console.

4. This is optional, but it is advised that you set up locale information correctly. If you want to change internationalization options e.g. keyboard layout, timezone.

5. Don't do anything

6. Don't do anything

7. Don't do anything

8. Open advanced options

8.1 Select A4 SSH and enable it. This allows you to connect to RPI with SSH from your computer. This way you don't need display or keyboard on RPI to use it

8.2 A2 has option to change hostname, however I have used default raspberrypi, you can do the same

Finally go to "Finish" and restart RPI by accepting "would you like to reboot now?" If you selected No to this reboot question RPI can be booted from command prompt by typing

sudo reboot

Note also that by typing

sudo raspi-config

will get you back to this configuration tool…in case you want to change something later.

When RPI boots up you will be asked for raspberry pi login information. Give user name and password. By default username is pi and password is what you have given during setup in configuration tool

Configuration is now ready. Next step is to check how it can be connected remotely from PC.

Step 4: Connect Your Raspberry Pi From PC Part 1

Raspberry Pi is now configured and booted up. You should be able connect it via PuTTY from your PC now. PuTTY can be downloaded from http://www.chiark.greenend.org.uk/~sgtatham/putty...

When you start up the PuTTY you will notice that Host name or IP is required in order to connect to your Raspberry PI. To obtain the Raspberry Pi's IP address. Type the following to Raspberry Pi and press enter

Ifconfig

This will list you network adapters and information from them (check image). If you are connected with Ethernet (like I was at this point) you should see inet addr:xxx.xxx.xxx.xxx in eth0. by typing this inet address to PuTTY's host name line you should be able to connect Raspberry Pi remotely.

Note that if you don't want to connect via ethernet but want to use WLAN instead read next section to see how to setup WLAN, otherwise skip it and continue with how to connect with PuTTY.

Step 5: Optional: Wlan Configuration to Raspberry Pi

If you want to connect your Raspberry Pi via WLAN, you need to set wlan ssid and password to configuration so that Raspberry Pi can connect it.To start, type following and press enter.

sudo nano /etc/network/interfaces

This opens up interfaces file that should already have configurations. Check taha there is "auto wlan0" in this file. Should be there by default.

Press ctrl-x to exit (save if you did changes with "Y").

Now add the actual network settings. Type following and press enter.

sudo nano /etc/wpa_supplicant/wpa_supplicant.conf

Add network section and configurations to the end of the file (check above image for reference):

Network={

ssid="yourssid"

psk="passwordtoyourwlan"

}

Save with Ctrl+X and select "Y" to confirm save.

Now restart Raspberry Pi. Type following and press enter.

sudo reboot

Once booted up and logged in, type following and press enter.

Ifconfig

You should now see that also wlan0 has inet addr available.

Step 6: Connect Your Raspberry Pi From PC Part 2

Now the IP (ethernet or wlan) address is known. You can now connect via PuTTY from your windows desktop. To do so, open putty, type in IP address and port 22 and select open.

Say yes to security alert and command line opens up in PuTTY.

Type in login name and password and now you should be in pi's command prompt. This means that you can now disconnect keyboard and display from Raspberry Pi and do all the rest of the steps from your pc via PuTTY. To shutdown pi (just in case when disconnecting keyboard and display) type following and press enter.

sudo shutdown -h now

Raspberry Pi will shut down. Once you have disconnected keyboard and display disconnect power supply and put it back in to boot up the Raspberry Pi. Wait for a moment (so Raspberry Pi boots up) and then try to connect again via PuTTY, if everything works like it should you should be now able to login...if you get timeout at first, wait for a moment and try again.

NOTE: IP address can change if your routers DHCP gives new IP address to the Raspberry Pi during bootup / reset and therefore you should know the new IP in order to connect again via PuTTY.

To avoid this problem, you have option to set in static ip address for the Raspberry Pi…there is few guides how to do that. E.g. try this http://www.modmypi.com/blog/tutorial-how-to-give-...

Or then you can do like I did (if your router allows it), add address reservation to Raspberry Pi's wlan adapter MAC address in router configurations. I have tplink router so i added MAC address and reserved currently assigned IP address for it. For this trick, you need both, IP address and MAC. Againy type following and press enter.

ifconfig

Take note from hwaddr (this is the Mac and inet addr which is the IP)Then create address reservation to your DHCP / address reseravtion list. Check your routers user guide to see how this can be done in your own router. I have TPLink so Address Reservation looks exactly like in attached image.

Now everything is set up and we can get to the fun part.

Step 7: Installing DHT22 Sensor Libraries

Start by updating and upgrading the Raspberry Pi. Type following and press enter.

sudo apt-get update

This updates software sources then type following and press enter.

sudo apt-get upgrade

This updates to everything to latest version. If prompted to continue press "Y".

When these are finished, it is time to install Adafruit Python code. You will need this code in order to get readings from DHT22 sensors. This will also allow you to test that your assembly works in first place.

At first, get compiler and python library. For that type following and press enter

sudo apt-get install build-essential python-dev python-openssl

Then, make sure that you are in folder where you want to install the Adafruit code, by default i would suggest /home/. For that type following and press enter.

cd /home/pi


Now clone the git repository. Type following and press enter.

git clone https://github.com/adafruit/Adafruit_Python_DHT.g...

Go to folder.Type following and press enter.

cd Adafruit_Python_DHT


And finally install the Adafruit library. Type following and press enter.

sudo python setup.py install

Then it is time to test your assembly...

Step 8: Testing the DHT22's

Now that installation is completed you can test the connected sensor/s and see that you get reading from them. Go to folder where you cloned the Adafruit_Python_DHT and then to examples folder. Type following and press enter.

cd /home/pi/Adafruit_Python_DHT/examples

You remember the gpio/s where you plugged the sensor/s? Good, then type sudo ./AdafruitDHT.py and press enter. I had gpio 22 and 23 so I tested with

sudo ./AdafruitDHT.py 22 22

sudo ./AdafruitDHT.py 22 23

If your sensor and assembly is ok, you should get back temperature and humidity from the sensor/s. Like seen in attached image.

NOTE:

If you see "Failed to get reading. Try again!", then try again few times.

If still nothing, re-check that you typed in the right GPIO.

If gpio is for sure right, check your assembly again. E.g. DHT22 gets power, ground and resistor is connected correctly.

If all above are right, try to connect your sensor to another GPIO and see if you get reading from that

If nothing from above works, it is always possible that your DHT22 is broken. :(

Libraries for DHT22 sensors are now installed and you can get the readings from sensor/s. Time to set up database for holding that data.

Step 9: Setting Up the MySql for Storing the Temperature Data

Get Mysql and required addons for it. To do that type following and press enter.

sudo apt-get install mysql-server python-mysqldb

During the installation you will be asked for the password for ROOT user, set what you want and remember it for later use.

After password is set and installation completed. It is time to set up the actual database and tables for storing the data. This need to be done in mysql console. To get into console type in the following and press enter.

mysql -u root -p -h localhost

Enter password you set during the installation and then you should be in MySql console (check reference image)

In MySQL console

First, create database called temperatures. Type following and press enter.

CREATE DATABASE temperatures;

Select the created database by typing following and pressing enter.

USE temperatures;

Next you need to create database user and grant access to database . (Change password to something else if you like).To do that type in the following lines separately and after each press enter (check reference image 2).

CREATE USER 'logger'@'localhost' IDENTIFIED BY 'password';

GRANT ALL PRIVILEGES ON temperatures.* TO 'logger'@'localhost';

FLUSH PRIVILEGES;

Now the user has been created and privileges added. Time to change user from root to this new logger. Log out by typing following and pressing enter.

quit

And log back in with this new user by typing following and pressing enter

mysql -u logger -p -h localhost

And give password that you assigned after IDENTIFIED BY when creating the user (by default it was password).

Now it is time t ocreate two tables. Temperaturedata for storing sensor information and time of measurement and also mailsendlog that holds information when temperature limit trigged mail warnings have been sent. Mailsendlog is used in code to check when last warning was sent and it has been restricted that limit warning can be sent once in every 2 hours / sensor. This restriction is required so that mailbox is not flooded in cases where measurements are done frequently, e.g. every minute. However there is little exception when this check is ignored and that is in cases when temperature increases or decreases 5 degrees between measurements. Think of the case when you are logging home temperature via this logger and there is suddenly 5 degree drop in temperature between measurements, it would be nice to get information about that even if 2 hours have not passed yet.

Some warnings, like sensor cannot be read, or database insert failed are send every time when they occur and are not logged to table. These warning indicate that there is something wrong with Raspberry Pi or sensors and should be checked.

To start creating tables, type in the following and press enter.

USE temperatures;

Create first table with columns dateandtime, sensor, temperature and humidity. To do that type in the following and press enter.

CREATE TABLE temperaturedata (dateandtime DATETIME, sensor VARCHAR(32), temperature DOUBLE, humidity DOUBLE);

Create second table with columns dateandtime, triggedsensor, triggedlimit and lasttemperature. To do that type in the following and press enter.

CREATE TABLE mailsendlog (mailsendtime DATETIME, triggedsensor VARCHAR(32), triggedlimit VARCHAR(10), lasttemperature VARCHAR(10));

You can confim, that empty sets are present by typing in the following and pressing enter.

SELECT * FROM mailsendlog;

SELECT * FROM temperaturedata;

If tables exist, you should see "Empty Set (0.00 sec)"

Database and tables are now setup, exit the MySql console by typing in the following and pressing enter.

quit

Then restart mysql to changes take effect. To do that type in the following and press enter

sudo /etc/init.d/mysql restart

Thats it, mysql and database is ready. Next thing is to download the DHT22-TemperatureLogger for reading sensors, and inserting data to these new tables.

Step 10: Set Up the Temperature Logger Code

TemperatureLogger Python code can also be found from github, just like the Adafruit DHT22 codes.

NOTE: If this is first time you are doing this, you can skip to "Setting up" few lines below. But if you already have done this step earlier and now there is fixes in github that is wanted on your setup as well, you need to re-clone the code. Unfortunately you cannot update the folder/content, it need to be removed and cloned again. For doing so, backup configurations json file, backup also SQL backups from DHT22-TemperatureLogger/Backups folder, then remove DHT-TemperatureLogger folder. To remove the folder make sure you are on the folder that contains DHT22-TemperatureLogger. e.g. type:

cd /home/pi

and remove the folder by typing

sudo rm -r DHT22-TemperatureLogger/

Now you can re-clone from GIT and reset the configurations with the steps mentioned below. Notable is that if there were changes also to configurations json file (e.g. new configurations), you cannot copy the backed up old file back as is.

Setting up.

Make sure that you are in folder where you want to install the DHT22-TemperatureLogger, by default i would suggest /home/pi/. Type in the folder and press enter.

cd /home/pi

Now clone git repository by typing

git clone https://github.com/jjpFin/DHT22-TemperatureLogger

Type

ls

and press enter. And you should see that TemperatureLogger is unpacked to new DHT22-TemperatureLogger folder (image attached). Now to get this to work with Adafruit code and your MySql database that was just created, some configurations are needed. Start by editing the settings. To do this go to DHT22-TemperatureLogger folder by typing following and pressing enter

cd /home/pi/DHT22-TemperatureLogger

Now open config.json in editor. Type in the following and press enter.

sudo nano config.json

Configuration file opens up in editor (reference image attached).

Start going through the configurations and make them match your configurations.

MYSQL: Change mysql part to match what was created in mysql creation phase.

SENSORS: Set names for your sensors, e.g. outside, inside, livingroom, kitchen and so on. Where that sensor is going to be located or how you want to name it in log. Note that if you have only one sensor attached, then you set name for sensor1 and can leave sensor 2 as is.

TRIGGERLIMITS: Set triggerlimits. These are limits for triggering email warnings. E.g. if sensor1lowlimit is 0 and temperature on that location drops below 0, you will receive warning to email address that you assign later.

HUMIDITYTRIGGERS: Set trigger limits for humidity. These limits works exactly like temperature limits, but send warnings if humidity received from sensor doesn't fit between the limits

SENSORGPIOS: Sensor gpios. What is the gpio where your dht22 is connected. Once again, if only 1 sensor attached, 2nd can be ignored

MAILINFO: This is for sending those email warnings. (I created new gmail just for this purpose) NOTE CURRENTLY ONLY GMAIL IS SUPPORTED

Senderaddress: This is shown in receivers inbox as sender

Receiveraddress: Where do you want to sent these warnings

Username: username for sender email

Password: password for sender email

subjectMessage: Can be changed if you want to, this is subject of the sended email in normal case

subjectWarning: This can also be changed, this is sended in case that warning is triggered (e.g. temperature is below triggerlimit)

SENSORTYPE: Keep this as 22 with dht22 sensor, this is here in case that i will later add support for other sensors as well

SENSORAMOUNT: How many sensors you have connected. 1 or 2. (more than 2 isn't supported currently, maybe later)

SQLBACKUPBATH: SQL dump is taken every night at 5 am as backup, so this is the directory where that dump is written. Change this to folder where you want those dumps to be written. Every dump is automatically created to own datetime folder in this directory. Note that this folder isn't automatically backed up to any location. You need to copy it manually every now and then.

ADAFRUITPATH: This is the path where Adafruit_Python_DHT was downloaded from Git in beginning. By default it was /home/pi/Adafruit_Python_DHT/ Script AdafruitDHT.py This is important as it is used to get readings from each connected sensor.

SQLBACKUPDUMP: This is for defining if and when sql dump is taken for backup.

BackupDumpEnabled: y means enabled, anything else means it is disabled.

BackupHour: Any value from 0 to 23. Dump is taken daily, but you can define at what time by setting hour

CONNECTIONCHECK: Used to define if connection check is done weekly (reports weekly averages from sensors, this is done in order that you can be sure that logger is up and running even though warnings haven't been sent recently)

ConnectionCheckEnabled: y means enabled, anything else means it is disabled.

ConnectionCheckDay: Any value from 0-6 representing days from monday to sunday. Day of the week connection check is sended.

ConnectionCheckHour: Any value from 0 to 23. Represents hour of the selected day when check is sended.

Once settings are set, press Ctrl+x and save when prompted with "Y".

Now test that readings are written to database correctly In DHT22-TemperatureLogger folder, type following and press enter.

python DHT22logger.py

If everything goes as planned, Raspberry executes the python script, gets readings from sensor/s and writes them to database. If you cant see any errors, all seems to be working. Now check database that data is inserted. Go to mysql console by typing following and pressing enter.

mysql -u logger -p -h localhost

And log in with your password. In mysql console type following and press enter.

use temperatures;

And then type (and press enter)

select * from temperaturedata;

And check that readings were saved to table (reference image)

If everything seems to be in order and you can see the readings, exit mysql by typing following and pressing enter

quit

Note that mailsendlog table is empty at this point as no warning mails have been send. However, if you have only one sensor attached, but in configs sensor amount setting is more than 1, you will get email indicating that sensor couldn't be read. These kind of warnings are send always if they occur and are not logged.

Step 11: Automatical Sensor Reading

Now that temperature logger seem to be working, you probably want to take measurements automatically every n minutes all the time when Raspberry is powered on. To do so add timed event to crontab scheduler

Type following and press enter.

crontab -e

And add the following line at the end of the file (check reference image). This will run the script every 15 minutes.

*/15 * * * * python /home/pi/DHT22-TemperatureLogger/DHT22logger.py

More information about setting the crontab job can be found from here http://www.thesitewizard.com/general/set-cron-job...

Quit and save with Ctrl+x and select "Y" when prompted

Wait for 15-20 minute (or reduce time to wait less) and check that new inserts are done to mysql table. If yes, everything is now set up…and logger is working automatically and inserting data to MySql & sending mails.

Next thing thing is to set up LAMP (Linux, Apache, MySQL, PHP) and serve MySql information to web page. This way you can check the current readings with any web enabled device.

Step 12: LAMP (Linux, Apache, MySQL, PHP) and Data to Web Page

First type in

sudo apt-get update

to update again. After update finished. Install apache2 web-server (and addons) so that you can serve temperaturelogger web page to client.

sudo apt-get install apache2 php5 libapache2-mod-php5 php5-mysql php5-cli -y

After install finished restart apache server by typing

sudo /etc/init.d/apache2 restart

Now the web server is ready and can serve your first web-page.

On your PC web-browser type in the IP address of the raspberrypi and you shdould see the index page. (same as in attached picture)

Good, now change html page to PHP and get data for the page from temperatures database. Go to location from where the index.html page is served. Type

cd /var/www/html/

Note: location used to be /var/www/ but has since changed to /var/www/html/

Check that you are in correct folder and actually have the index.html in this folder by typing

ls

You should see that there is index.html in this page (attached reference image 2)

Create the index.php page and copy following code section to it. Type in.

sudo nano index.php

Editor opens up. Copy the code from attached index.php.txt file to the editor. Remember to change settings to match your MySql settings. And you can also change how many hours backwards temperatures are seen in web page by editing $hours variable.

When ready Exit with Ctrl+X and save with "Y" when prompted

Now remove the index.html, so that next time page is loaded index.php is used by typing

sudo rm index.html

Then once again, on your PC web-browser type in the IP address of the raspberrypi and you should see the page, but this time with temperature information from your MySql database (attached image as reference).

Good, you are almost finished. Last thing to do is installing dynamic DNS so that you can connect this page with www. instead of IP.

Step 13: Installing Dynamic DNS

As dynamic DNS I have been using no-ip as it is free to use and quite simple to set up. To use this, first you need to create account to No-Ip. Go to www.noip.com and sign up. NOTE: remember the account information as it is needed also during the installation in Raspberry Pi.

Once you have account and access to no-ip and have signed in, it is time to create host.

1. Select add a host

2. Givee hostname. Hostname is the name of your site, e.g. mylogger.ddns.net. After the setup, when you write this to your browser, it connects to temperaturelogger index.php page. Good part is that you don't need to know Raspberry Pi's IP address anymore.

3. When ready, save with "add host"

Now go back to you Raspberry Pi terminal and create folder for the noip by typing

mkdir /home/pi/noip

Go to that folder by typing

cd /home/pi/noip

Get the software package

wget http://www.no-ip.com/client/linux/noip-duc-linux....

You noticed that software is packed and need to be extract. For extracting, type:

tar vzxf noip-duc-linux.tar.gz

Now select the noip folder that was extracted. This folder changes along with version changes. Easiest way to select latest is to type

cd ./n and press tab and then enter to select

Now compile and install the noip software from the extracted source. Type

sudo make && sudo make install

During the install, you will be asked for the no-ip account information and after that everything is set.

Check that you can access the page with hostname you gave (e.g.. mylogger.ddns.net) by typing it to web browser.

You should again see the temperaturelogger temperature data. Notice that you can now check temperatures with any web enabled device by just setting that host name to your web page e.g. try it with your phone.

Now everything is set, but remember that if you restart your Raspberry Pi, no-ip need to be started manually by typing.

sudo /usr/local/bin/noip2

However this can be easily tweaked so that no-ip is automatically run on a startup. For doing that you can follow this tutorial: http://www.stuffaboutcode.com/2012/06/raspberry-p...

That's all for this instructable. Thank you for reading it all the way through and congratulations for finishing it. I hope you had as fun following it through as I had while putting it all together. In case you have some questions, please don't hesitate to leave question or contact me.

Thanks and best regards,

JJ

Comments

author
sevej made it! (author)2017-07-23

JJ -

Thank you very much for an excellent project!

I use your project to monitor the temperature of a water heater and the garage in which it's installed. I've taken the index.php file and converted it to generate a chart using Google charts. An attached image shows a typical chart with a week's worth of temperature and humidity data from both sensors. The php code is attached below.

Also attached is a picture of my installation (packaging not my strong suite). The water heater temperature sensor is mounted above the red box that houses the Raspberry Pi and is in contact with a metal plug on the side of the tank. The garage ambient temperature is measured by the sensor that hangs below the Pi.

Cheers!

sevej

<?php

// settings

// host, user and password settings

$host = "localhost";

$user = "logger";

$password = “<insert your password>“;

$database = "temperatures";

$sensor1 = "Water Heater";

$sensor2 = "Garage";

$type1 = "Temp";

$type2 = "Humidity";

//how many hours backwards do you want results to be shown in web page.

$hours = 168;

// make connection to database

$con = mysql_connect($host,$user,$password);

// select db

mysql_select_db($database,$con);

// sql command that selects all entires from current time and X hours backwards

//NOTE: If you want to show all entries stored in the database, comment out the line that starts with

// "AND t1.dateandtime..." by inserting a "#" at the beginning of that line

$sql="SELECT year(t1.dateandtime) AS year, month(t1.dateandtime) AS month, day(t1.dateandtime) AS day,

hour(t1.dateandtime) AS hour, minute(t1.dateandtime) AS minute,

t1.sensor AS sensor1, t1.temperature AS temp1, t1.humidity AS hum1,

t2.sensor AS sensor2, t2.temperature AS temp2, t2.humidity AS hum2

FROM temperaturedata AS t1

INNER join temperaturedata AS t2

ON t1.dateandtime = t2.dateandtime AND t2.sensor = '" . $sensor1 . "'

WHERE t1.sensor = '" . $sensor2 . "'

AND t1.dateandtime >= (NOW() - INTERVAL $hours HOUR)

ORDER BY t1.dateandtime";

// set query to variable

$data = mysql_query($sql);

// format current time for display

$today = date("D M j, Y G:i:s T");

// create content to web-page

?>

<html>

<head>

<!-- Comment out the following line to disable auto-refresh every 15 minutes -->

<meta http-equiv="refresh" content="900"> <!-- Refresh every 15 minutes -->

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript">

google.charts.load('current', {'packages':['corechart']});

google.charts.setOnLoadCallback(drawChart);

function drawChart() {

var data = new google.visualization.DataTable();

data.addColumn('datetime', 'Datetime');

data.addColumn('number', '<?php echo $sensor1 . " " . $type1 ?>');

data.addColumn('number', '<?php echo $sensor1 . " " . $type2 ?>');

data.addColumn('number', '<?php echo $sensor2 . " " . $type1 ?>');

data.addColumn('number', '<?php echo $sensor2 . " " . $type2 ?>');

data.addRows([

<?php

// loop all the results that were read from database and "draw" to web page

while ($row=mysql_fetch_assoc($data)) {

echo " [ ";

echo "new Date(".$row['year'].", ";

echo ($row['month']-1).", "; // adjust month from mysql to javascript format

echo $row['day'].", ";

echo $row['hour'].", ";

echo $row['minute']."), ";

echo $row['temp1'].", ";

echo $row['temp2'].", ";

echo $row['hum1'].", ";

echo $row['hum2']." ";

echo "],\n";

}

?>

]);

var options = {

title: 'Bakersfield Home - <?php echo $today ?>',

width: 1000,

height: 600,

curveType: 'function',

legend: { position: 'bottom' },

crosshair: { trigger: 'both' },

series: {

0: { targetAxisIndex: 0 },

1: { targetAxisIndex: 0 },

2: { targetAxisIndex: 1 },

3: { targetAxisIndex: 1 }

},

vAxes: {

0: {

title: '\u00B0Fahrenheit',

viewWindowMode: 'explicit',

viewWindow: {

max: 135,

min: 35

}

},

1: {

title: '%Humidity',

viewWindowMode: 'explicit',

viewWindow: {

max: 100,

min: 0

}

}

},

hAxis: { title: 'Time of Day' }

};

var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

chart.draw(data, options);

}

</script>

</head>

<body>

<div id="curve_chart" style="width: 1200px; height: 500px"></div>

</body>

</html>

Bakersfield Temperatures.png20170723_095249.jpg
author
KissK made it! (author)2017-03-26

Hi ! I got this error in step 10.

temperature.jpg
author
hernameismariana made it! (author)hernameismariana2017-07-13

Follow this tutorial

author
hernameismariana made it! (author)2017-07-12

Hey! I need your help pls! I have a problems with the step 10 :C

2017-07-13-005815_1366x768_scrot.png
author
hernameismariana made it! (author)hernameismariana2017-07-13

Debido a que nadie pudo contestarme, sigan este tutorial! PUDE RESOLVERLO!

https://www.youtube.com/watch?v=Bk2wHmkxx34

author
hernameismariana made it! (author)hernameismariana2017-07-13

Pls!somebody help me! :C @jjpfin

author
DavidC407 made it! (author)2016-01-13

Thank you! It works great, i'm going to expand apon this and make a full website that monitors all weather conditions. However, I've not very good with Python and i would like to convert the data being put into the database to be in Fahrenheit instead of Celsius. While i could have the PHP convert the data before it echo's it to the website, it would be better to have it in the correct format to start with so that i can use the data else where.

author
DavidC407 made it! (author)DavidC4072016-01-13

I think i got it... i changed:

sqlCommand = "INSERT INTO temperaturedata SET dateandtime='%s', sensor='%s', temperature='%s', humidity='%s'" % (currentTime,sensor2,sensor2temperature,sensor2humidity)

to

sqlCommand = "INSERT INTO temperaturedata SET dateandtime='%s', sensor='%s', temperature='%s', humidity='%s'" % (currentTime,sensor2,(sensor2temperature * (9.0 / 5.0) +32),sensor2humidity)

author
jjpfin made it! (author)jjpfin2016-01-31

Hi,

Sorry about the delayed answer...busy, busy, busy. :)

However, I'm glad that you found the solution for the question.

author
MichaelS1334 made it! (author)MichaelS13342017-07-10

How do I change the warning email to also display in fahrenheit?

author
MichaelS1334 made it! (author)MichaelS13342017-07-13

I solved this by editing the comment out in /root/Adafruit_Python_DHT/examplesAdafruitDHT.py to change from Celcius to Farenhieht ther intead on /root/DHT22-TemperatureLogger/DHT22loger.py.

author
MichaelS1334 made it! (author)MichaelS13342017-07-10

How do I change the warning email to also display in fahrenheit?

author
MichaelS1334 made it! (author)2017-07-10

I've worked out my GPIO issue and everything tests and works. I've tweaked it to auto refresh, assign and page title and heading to differentiate between multiple Pi and changed the comment in the DHT22logger.py to use fahrenheit instead of celsius, but the high limit emails stille send in Celcius.

Anyone know how to change the high and low limits and warning emails to fahrenheit?

Great write up by the way, thanks you very much for doing it, very helpful. My issue with the GPIO was I was using pin 7, but the physical pin 7 maps to pin 4... I didn't know that and used this guide I attached.

Pi_GPIO.PNG
author
MichaelS1334 made it! (author)2017-07-05

Is there a hard coded GPIO value somewhere? I'm using a 2302 and GPIO pin 7; I started with https://www.instructables.com/id/Raspberry-Pi-Temp... and I can successfully test my sensor, but when I do ./AdafruitDHT.py 2302 7 as root, I get "Failed to get reading. Try again!"

Do I have to use GPIO pins 22 or 23?

author
ajb04 made it! (author)2017-06-19

Good Project! I am having trouble with one thing though. I set everything up and had it running with no issues. Then at midnight it quit logging and now the page is blank and it wont log. Anybody else had this issue? Thanks

author
MichaelS1334 made it! (author)MichaelS13342017-06-26

Did you use Raspberry Pi 3 and Jessie, or an Pi 2 and Wheezy?

author
ajb04 made it! (author)ajb042017-06-27

I think I got it. I started running the temperature logger script without crontab and was getting multiple SMTP errors. I looked at my email setup and found I had to activate an option in gmail to get my email working. Once I got the email working it started logging. I then set crontab up again and now its working,

author
ajb04 made it! (author)ajb042017-06-27

Raspberry PI 3

author
AlG43 made it! (author)2017-06-04

Thanks for a great Instructable !

Just a note to say I used the DHT22 wired version (AM2302 from Adafruit). When my leads to the GPIO pins were short (<12 inches) I was fine with 3.3 V Power - however when I mounted the sensor in my coldframe I had about a 20 ft wire lead (I used 4 conductor telephone cable). When the longer lead was connected to 3.3 V Power I got low temperature reads (low by about 1/2) and very high humidity 3000+ percent - and about 95% failed to read errors. When I switched the long leads to 5 V power all returned "accurate readings" and there were only rare "failed to reads".

Thanks again for your wonderful "how to" !

alg

author
mjriguero made it! (author)2017-05-27

Hello

I am having trouble with Step 12. Getting an error message. Please help.

pi@raspberrypi:~ $ sudo apt-get install apache2 php5 libapache2-mod-php5 php5-mysql php-cli -y

Reading package lists... Done

Building dependency tree

Reading state information... Done

E: Unable to locate package php-cli

THANK YOU!!!!!

author
purplexed made it! (author)purplexed2017-06-01

Since you are using php5 you will want that to be php5-cli. Hope this helps!

author
tostati made it! (author)2017-05-17

HI! I made, on a Raspberry2... but the strange thing is that temperature is very very wrong, there is 6 celsius degrees error... it reads 13c but there are 19c....

sersor is ok, 'cause testing it on an arduino, it reads 19c...

i dont know why....

author
redofromstart made it! (author)2017-04-16

Great project! Testing both sensors to see if they give similar results as they are very close to each other. After this test I'll add a cable to one of them and put it outside.

2017-04-15 09.20.12.jpg
author
andrelumiene made it! (author)2017-02-08

Hello there.Nice tutorial. Working perfect with raspberry pi3. Can you please tell me if I can write the database to an external remote server instead of the raspberry pi3. I want the raspberry to read the data and to write them somewhere in a server like a cloud. Any help will be acceptable. Can I remotely write a database from raspberry?

author
VladB27 made it! (author)VladB272017-03-24

see my solution in the comments below ;)

author
jjpfin made it! (author)jjpfin2017-03-02

Hi, It should be doable. Config.json has mysql part (host,user,password etc.) change localhost to remote address of your database and check what happens.

author
SaimonA2 made it! (author)2016-12-08

Hi.Thanks for this great tutorial. I'm new to all of this and I'm stuck, so I really need your help. So my DHT22 comes with 3 pins instead of 4 as shown in the tutorial. It also comes with wires. So I made the connections as instucted, but on a breadboard. And I just cannot seem to get any reading. I tried Adafruits example code, I even tried writing some python code I found online, but to no avail. I have not connected any power source to the breadboard, because I figured that adding power source to the pi would be enough. I made connections in the following fashion:

-Sensor wire for each pin to Breadboard

-Jumper wires from same vertical row on breadboard straight to the pi pins

* And I did put a 10k ohm resistor between the 3.3v and data pin.

Any kind of help is welcome.

Thanks.

author
EdwardM35 made it! (author)EdwardM352017-03-13

Hi, I'm a newbie to all this hardware stuff, too, and I had a similar problem. Turned out I didn't quite understand how breadboards work. I thought the + and - horizontal rows spanned the entire length of the board, but turns out they are separated into blocks or sections (2 on my board). Make sure you have the 3.3V and the GND lines attached to the breadboard block that contains the sensor wiring.

P.S. A Raspberry Pi T-cobbler/breakout board makes life much easier for prototyping circuits with a breadboard.

author
jjpfin made it! (author)jjpfin2016-12-22

Hi, Based on this information, I cannot really help you out much. There is so much possibilities e.g. bad connections.

Do you happen to have multimeter available. With that you could check if PI is giving enough power to the power pins. And you could also check that you have the connection all the way from the PI to the sensors pins (e.g. with continuity test mode).

Otherwise, I think that image about the connections could be handy. Maybe it would show if there is something wrong.

author
JaroslavO made it! (author)2017-02-18

Hi! Great tutorial, I've made it with my Raspberry Pi 2 and I used 1k ohm resistor instead of 4,7k. It works good. Thank you for your time spent on this project! :)

1487415952865252006114.jpg
author
jjpfin made it! (author)jjpfin2017-03-02

Hi. Good job. :)

author
ShelbyGTH made it! (author)2017-02-05

Hi JJ,

Do you know the best way to save /home/pi/DHT22-TemperatureLogger/Backups every day to an flash drive?

Thx Jeroen

author
jjpfin made it! (author)jjpfin2017-03-02

Hi,

I would mount the drive directly to RPI and change the SQL backup path from the config.json to point into this drive. And check that backup dump is enabled in config.json.

author
Mdecrem made it! (author)2017-02-14

Hi JJ

I have a problem using mysql_connect in index.php as it is shown. I am using PHP 5.6 . I heard that this command was now obsolete. What do you recommend to solve this problem ?

author
jjpfin made it! (author)jjpfin2017-03-02

Hi, You are right. It seems to be deprecated. http://php.net/manual/en/function.mysql-connect.ph...

I think the answer is mysqli_connect()

http://php.net/manual/en/function.mysqli-connect.p...

author
SylvainH8 made it! (author)2016-12-07

Hello ! I've got one simple question : does this can work on a raspberry pi 3 ? I saw on the github that there is a file to make it work on a RPI2, but is someone actually tried id on a RPI3 ? Thanks !

author
VladB27 made it! (author)VladB272017-01-17

I have set it up without problems on raspberry pi 3 with last version of raspbian

author
ozmatox made it! (author)ozmatox2017-01-15

Yes its work on RPI3 i have OSMC and with thi os work perfect. Only have one problem ;) mysql write temp. to tabels but i cant get this on index.php

author
jjpfin made it! (author)jjpfin2016-12-22

I have not tested it with RPI3, or haven't heard about that if someone has tried. But I think however, that it should run just fine.

author
VladB27 made it! (author)2017-01-17

Super Tutorial! Thank you! I tweak it a bit as my Pi is now remote behind a 3G dongle and I cannot access it from the web. Using "requests" library I am posting the info from the Pi to a DB on the internet. I have altered the python script as follows:

at begining where all imports are following line is added:

import requests

at the end in the "# insert values to db" section following lines are added after databaseHelper(sqlCommand,"Insert"). For Sensor 1:

postParameters = {'dateandtime':currentTime, 'sensor':sensor1, 'temperature':sensor1temperature, 'humidity':sensor1humidity}
postResponse = requests.post(url='http://your.url/posttemp.php',data=postParameters)

For Sensor 2:

postParameters = {'dateandtime':currentTime, 'sensor':sensor2, 'temperature':sensor2temperature, 'humidity':sensor2humidity}
postResponse = requests.post(url='http://your.url/posttemp.php',data=postParameters)

posttemp.php file is as following:

<?php
$servername = "localhost";
$username = "remote_database_user";
$password = "remote_database_password";
$dbname = "remote_database";

$dateandtime=htmlspecialchars($_POST["dateandtime"]);
$sensor=htmlspecialchars($_POST["sensor"]);
$temperature=($_POST["temperature"]);
$humidity=htmlspecialchars($_POST["humidity"]);

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO temperaturedata (dateandtime, sensor, temperature, humidity) VALUES ('".$dateandtime."', '".$sensor."', ".$temperature.", ".$humidity.")";

if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

than you can use the same php file to display the info. Please note that remote database is not regularly emptied as the one from the script.

Some (other) improvements that I have made:

- graph for temperature and humidity using PHPlot

- display of min/max Temperature/Humidity for last week and for all time period

- display of highest variation in between readings

- (WIP) start of a electrical heating radiator: on when temperature reaches 7° and off when temperature reaches 11°. The on switch seems easy as this is my min warning for inside sensor, but I will have to study the off at 11° as my up warning mark is at 18°

author
DadhieMJ made it! (author)2017-01-16

Hi! I made it! :D but somehow, the crontab won't work for me perfectly even the original script the the author made. i just dont know why :( so the i tried an alternate (Jobber). Credits to the author! ;)

THMM.PNG
author
woodcmiami made it! (author)2016-12-20

HI, great tutorial.

I am having a problem in that when it takes a reading from the DHT22 it will write the data to the mysql db but at the same time it sends an email to me stating that it 'Failed to read <sensor name> sensor'

How can it read the sensor and write it to the table but then send a warning that it Failed to read the sensor?


Note that at 14:00:01 it posted a reading but at 2:00 PM I get an email:

'Failed to read LSW118 sensor'

DHT22_mysql.png
author
jjpfin made it! (author)jjpfin2016-12-22

At glance. It seems that you have defined to use 2 sensors, but are actually using only one. First one gets reading just fine, but when trying to read second. It fails as sensor doesn't exist?

author
woodcmiami made it! (author)woodcmiami2016-12-23

I did leave 2 sensors in config.json but put the sensor amount to be 1. Should I remove sensor2 in config.json?

author
DadhieMJ made it! (author)DadhieMJ2017-01-16

Yes you have. I, myself, tried to remove all the commands using the second sensor and this works fine.

author
JanD123 made it! (author)2017-01-10

Python script works very well. Saved me a lot of time in my own project. Instead of a LAMP server I'm trying to make a nodejs + express server (maybe switch to mongodb too, for learning purposes). I'll be adding some nice GUI touches like charts, semantic ui or material css etc :) and i'll be adding a pi camera for creating timelapses of my pepper growtent.

author
foxfaisal made it! (author)2016-12-17

Hello. I am a newbie and I have 1 question. I would like to install 8 x temperature sensors AND 8 x humidity sensors in a room. Instead of using 4 sets of Raspberry Pis (each Pi connected to 2 x DHT22), is it possible to connect 8 x DHT22 to only 1 Raspberry Pi? Otherwise I think I've to spend more money to buy extra Raspberry Pi for every pair of DHT22. Thank you.

author
jjpfin made it! (author)jjpfin2016-12-22

Hi, Well. Out of the box, this project doesn't support more than 2 sensors. It will only try and read 2 sensors. Code could be refactored a way that it reads more sensors. But unfortunately I don't have time or plans for that at the moment.

author
teng soona made it! (author)2016-10-25

Lovely!!!

Thank you so much!

I saved a thousand dollars!

We are using it to monitor our vaccines in the fridge, someone was offering me a commercial solution for $1800. And i wondered really, does it REALLY take so much $$$ to make something like this. And thanks to you i fixed it with < $100.

The other question would be how can i connect this to the AWS IoT service to enable SMS and calls?

I tried IFTTT but it doesnt seem to work very well, but anyway, email is good enough for now.

fr.jpg
author
jjpfin made it! (author)jjpfin2016-12-22

Hi, And sorry for the delayed response. Haven't got so much time for this project lately. However, I am very pleased to hear that this was such an useful for you.

And what comes to AWS IoT. I haven't really thought about if that could be done or what it would require. So I cannot give you any answers.

About This Instructable

134,320views

194favorites

License:

Bio: .NET developer working in healthcare business
More by jjpfin:Raspberry PI and DHT22 temperature and humidity logger with LAMP and Email warnings
Add instructable to: