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

182,716

210

109

Published

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

About: .NET developer working in healthcare business

25.4.2018 UPDATE

DHT22-TemperatureLogger code used for collecting sensor data to database and for mail sending, has gone through some serious refactoring. This was done to add some features and to fix some minor bugs.

If you have finished this instructable prior this update, but want to update the code. Jump to page 10, download the DHT22Logger code again, setup revised config.json and you are good to go.

Few examples about what changed:

Logging added. Execution of the code now creates rotating log files to DHT22-TemperatureLogger/Debugger/Logs/. Handy in case that something goes wrong.

Added support for 1-n sensors. First version supported only 1-2 sensors, now there can be as many as Raspberry pi has gpios. Attach sensor to RPI and add sensor configuration to config.json and it is taken into account when executed.

Code refactored from first "quick and dirty" implementation to separate logical components. Hopefully easier to understand and to extend or refactor for your personal use

Configurations renamed and rearranged for easier understanding e.g. connection check is now weekly averages as it actually sends weekly average temperatures (intention for this that rpi is reporting weekly that it is still alive)

Added configurable timeoutfor mail sending so that user can decide how long Logger waits before sending warnings after previously sended mail. Previously hardcoded value was used and that found out to be little inconvenient

Sql backup dump is no longer daily, user sets day when dump is taken. 0 is daily, 1-7 is from Monday to Sunday.

Weekly average temperatures sending is now also configurable. Works with same pattern as sql dump above. 0 is daily, 1-7 is from Monday to Sunday. Note that it will always count 7 days backwards and send average from those.

Possibility to choose from Fahrenheits or Celsius

And some more minor tweaks and fixes.


------------------------------------------------------------------------------------------------------------------------------------------------------

This is an Raspberry Pi based temperature and humidity logger that uses 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

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/update in github that is wanted on your setup as well, you need to fetch the code again.

Folder can either be removed and cloned again or fetched and reseted with Git. Either way, first backup configurations json file, backup also SQL backups from DHT22-TemperatureLogger/Backups folder, then remove DHT-TemperatureLogger folder.

To remove and re-clone 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 in "Setting up". 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.

For Git fetch and reset

Go to DHT22-TemperatureLogger/ folder

type git remote -v and you should see something similar like this:

origin https://github.com/jjpFin/DHT22-TemperatureLogger... (fetch)
origin https://github.com/jjpFin/DHT22-TemperatureLogger....(push)

Fetch latest version with git fetch --all

and reset folder to match latest version with git reset --hard

If Git approach didn't work, you can always just delete and re-clone as mentioned above.


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: Create configurations for sensors attached to your RPI. Notable is that each sensor need to have own configuration line.

name: 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. Also add GPIO from where sensor is found. Other values are triggerlimits.

SensorType: Keep this as 22 with dht22 sensor, this is here in case that i will later add support for other sensors as well. (However I think that DHT11 should work, but haven't tested it. Try it out...)

Temperature low and high are limits for triggering email warnings. E.g. if sensor low liimit is 0 and temperature on that location drops below 0, you will receive warning to email address that you assign later. Same goes with high limit. If temperature gets higher than set limit. Warning is sent.

Humidity limits works exactly like temperature limits, but send warnings if humidity received from sensor doesn't fit between the limits

Threshold is used for measuring if temperature or humidity drops more than set limit between 2 measurements. As example, TemperatureThreshold is set to 5, last measurement was 10 and on next measurement you get 0. This means that 5 or 15 would be ok, but anything below or above that is more than threshold and email warning is triggered. Use case for this is to follow if temperature raises or drops too quickly in monitored location.

NOTE: There is two example rows here for two sensors. If you want to attach more, just copy and paste more lines and edit values.

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)

sqlBackupDump: Backup dumps are either once a week or daily now.

BackupDumpEnabled y/n indicates if backup dumps are wanted in first place.

backupDay is day of the week when dump is taken. 1-7 (Monday to Sunday) 0 daily.

backupHour is the hour of the day when dump is taken- 0-24

backupDumpPath is the path where dump is stored. By default it is in Backups folder.

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.

weeklyAverages: Used to define if weekly average temperatures are sent and on which day. This is done in order that you can be sure that logger is up and running even though warnings haven't been sent recently.

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

weekDayForSendingAverages: is day of the week when dump is taken. 1-7 (Monday to Sunday)

hourOfTheDayForSendingAverages: is the hour of the day when dump is taken 0-24.

useFahrenheits: y enabled, n disabled. Note that if you change to fahrenheits and back to celsius "on the fly", you might get some warning mails about exceeded threshold limits or broke limits.

mailSendingTimeoutInFullHours: 0-x

Used to reduce spam. If set to 0, logger will send mail from every warning. Bigger values allow it to send warnings only once per hour. Used so that mailbox doesn't get flooded in case that

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.

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

19 People Made This Project!

Recommendations

  • Make it Move Contest

    Make it Move Contest
  • Planter Challenge

    Planter Challenge
  • Oil Contest

    Oil Contest
user

We have a be nice policy.
Please be positive and constructive.

Tips

Hello jjpfin!

I have found the way to send more than one email receiver.

I edited config.json the receiveraddress to 2 row receiveraddress like this:

"receiveraddress1":"email1@gmail.com",

"receiveraddress2":"email2@yahoo.com",

Then i changed the Mailsender.py , insert more receiveraddress like this:

self.receiver = [configurations.get('mailConfig')[0]['receiveraddress1'],configurations.get('mailConfig')[0]['receiveraddress2']]

10 Questions

0

For some reason im stuck at the point where i run the python script after customizing it, i get an error that the sensors cant be read. i can run the sudo ./AdafruitDHT.py 22 22 & 23 commands and they give me a result. i do get an email saying there was a failure to get any readings.. what have i missed?

0

not sure why, but when i re-fetched and pushed the git clone for DHT22-TemperatureLogger it works now, posting just in case anyone else had this issue.

0

Hello jjpfin!

Your project tutorial is helpful for me...I follow your every instruction but mysql database can't read DHT22 sensor. I edit config.json file because I have one sensor. And also php file can't show any sensor value..Please help me..How can I solve this problem??

0

Hello jjpfin!

Your directions is incredible! Thank you very much for your instructions!

Could you please help me a favor, i want to send the email alert to more than 1 receiver, how about 2 to 4 receiver (send alert email to many person: person1@yahoo.com; person2@yahoo.com....)

Great guide, helped me out a lot with a project for school. Is there a way i can integrate this local database on the RPI into an already existing website?

0

Hello jjpfin!
Thank you for the very simple and clear guide you made for us!
Unfortunately i get an error at step 12 whilst trying to install apache.
Could you please look into this?
Thanks in advance!

apache2.PNGapache.PNG

If I try to run "DHT22logger.py" I get an authentication error. I am not sure what the Username in GMail is.

I also don't get anything in the temperatures database.

Thanks in advance

error2.PNGerror.PNG

0

Hi,

Have you checked the logs to see that inserting the measured values is working in first place?

You can either open latest debug.log from ~/DHT22-TemperatureLogger/Debugger/Logs/ or run the code from ~/DHT22-TemperatureLogger/ folder with "python DHT22logger.py" and see if exceptions are raised.

Can't recall where was that username set when creating the gmail account, but have you tried with first name you gave when creating the mail account? Or with first part of the gmail address. E.g.if your mail account would be myAddress@gmail.com -> try with myAddress as username.

-JJ

I have a problem with the index.php.
Syptome:
The content of the file is not displayed in the browser (white sheet)
If I add phpinfo() to the file, and comment out the part of the mysqldb, the phpinfo() is displayed normally


I am grateful for every hint.....

bob

p.s. sorry my english ist indeed terrible

I have a problem at step9. When i quit and re-enter the mysql console by entering my password succesfully,i cant get into temperature database .It gives me an error:ERROR 1044 (42000): Access denied for user 'logger'@'localhost' to database 'temperature'

error.PNG

0

Is there a way to display the results ascending, that is to say so the most current result is the top most entry on the page?

I apologize for asking, I am not very good at coding.

I looked at the config.json and index.php and cant identify any existing method to perform this order.

Hi, in the index.php file (you can find it in the /var/www/html directory, see Step #12 for more details) change this line

// sql command that selects all entires from current time and X hours backwards
$sql="SELECT * FROM temperaturedata WHERE dateandtime >= (NOW() - INTERVAL $hours HOUR)";

to

// sql command that selects all entires from current time and X hours backwards
$sql="SELECT * FROM temperaturedata WHERE dateandtime >= (NOW() - INTERVAL $hours HOUR) ORDER BY dateandtime DESC";

This will display your entries from the latest one to the oldest one that have been recorded.

Hi there, I am currently making this project but I got stuck at step 9. You said they will ask for a ROOT password during the mysqldb download and set up installation. However it did not ask for one. The next step requires a password that I never set up. Please help.

109 Comments

hello guys i need a help

am working with DHT11 and when i type this command "python DHT22logger.py " i get this error :22-05-18 15:17:50 ERROR Sensors.SensorDataHandler Sensor reading raised exception

Traceback (most recent call last):

File "/home/pi/DHT22-TemperatureLogger/Sensors/SensorDataHandler.py", line 31, in readAndStoreSensorReadings

self.readingsFromSensors, self.failedSensors = self.sensorReader.getSensorReadings()

File "/home/pi/DHT22-TemperatureLogger/Sensors/SensorReader.py", line 41, in getSensorReadings

sensorName = sensor[0]['name']

KeyError: 0

22-05-18 15:17:50 ERROR root Sensor data handling failed:

Traceback (most recent call last):

File "DHT22logger.py", line 82, in main

SensorDataHandler(configurations,dbControl,mailSender).readAndStoreSensorReadings()

File "/home/pi/DHT22-TemperatureLogger/Sensors/SensorDataHandler.py", line 31, in readAndStoreSensorReadings

self.readingsFromSensors, self.failedSensors = self.sensorReader.getSensorReadings()

File "/home/pi/DHT22-TemperatureLogger/Sensors/SensorReader.py", line 41, in getSensorReadings

sensorName = sensor[0]['name']

KeyError: 0

PLEAAAASE COULD ANYONE HELP ME ..I WILL BE THANKFUL

1 reply

I'm sorry mimiya i'm a beginner in programming myself.
But i think ur dealing with the following problem:
The code is written for the DHT22 and not for the DHT11, if this is the case u could solve this by going into the python code and changing some 22's into 11's.
If you want to be a 100% sure u do not get this problem anymore i recommend you getting a DHT22 this will save you all the trouble since that works for me.

Hello all,
I'd like to introduce to you all the solution for monitoring temperature and humidity on cloud using raspberry pi 3 here https://smart-hub.cloud/docs

1 reply

Hi,

Please make the necessary adjustment on your site in the hardware requirement section, there's a lot of broken links (404 error).

Other than that, it's a very informative project. I've learn a lot for my own project like using relays to control fans/motors or other electric appliances.

i stumbled on your project looking for an less expensive solution to monitor the temp/humidity for my crypto miners. Thank you very much for this post! worked like a champ.

I did cheap out and get a DHT11 from the Frys in my area. It works, but I needed to tweak the config.json to change the sensortype. The sensor is the HUM1 from OSEPP

https://osepp.com/wp-content/uploads/2015/04/DHT11...

also, Adafruit does a breakdown on the two sensors here:

https://learn.adafruit.com/dht

For anyones reference:

sudo nano /home/pi/DHT22-Temperaturelogger/config.json

scroll to "sensortype";"22",

and change "22" to "11"

ctrl-x and y to save

This will tell the Adafruit script the correct config to load for the DHT11 sensor vs the DHT22.

Also, if anyone is wondering, you can successfully set this up with the PiTFT 2.8 screen for the record.

https://www.adafruit.com/product/1983

Notably I am running an old Rpi B+ that I had laying around, not an Rpi3 or anything.

Next I need to have it load the desktop and launch the browser so it boots right to the page. It is mounted on my network rack right by my KVM, so I can easily keep an eye on it when I am onsite.

again, thanks a lot. This helps me keep track of the environment in my shop to make sure my equipment doesnt boil.

Hi JJ, Can you please change your instruction as somethings has changed.

Installation of MYSQL is not asking for a root password.

To change password you need to add these steps
sudo mysql -u root


[mysql] use mysql;
[mysql] update user set plugin='' where User='root';
[mysql] flush privileges;
[mysql] \q

This needs to be followed by following command

# mysql_secure_installation


Installation of Apache and PHP has changed to PHP7

sudo apt-get install apache2 php7.0 php7.0-curl php7.0-gd php7.0-imap php7.0-json php7.0-mcrypt php7.0-mysql php7.0-opcache php7.0-xmlrpc libapache2-mod-php7.0

Grtz Jeroen

3 replies

Hi, could you maybe tell me how I could set a password for mysql, I did the installation command and followed your instructions, however I could still not set a password. Thanks.

I guess you missed the first command "sudo mysql -u root"

try the following:

sudo mysql -u root
use mysql;
update user set plugin='' where User='root';
flush privileges;
\q

mysql_secure_installation

Im no SQL Guru like Shelby, but it worked :-)

I have to follow error message when I python DHT22logger.py

Traceback (most recent call last):

File "DHT22logger.py", line 422, in <module>

main()

File "DHT22logger.py", line 345, in main

emailWarning("Failed to read {0} sensor".format(sensor1),msgType)

File "DHT22logger.py", line 104, in emailWarning

server.login(username,password)

File "/usr/lib/python2.7/smtplib.py", line 622, in login

raise SMTPAuthenticationError(code, resp)

smtplib.SMTPAuthenticationError: (534, '5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbuo\n5.7.14 pi5YXM9tMWJSh1P5xDGOCCxD2goqhdOIDnbs6eWapc4eI2B4GDHjR9dq_sPEANU7iA6FUT\n5.7.14 5WrrRLqi91i4QXn1LxM1n-OgN4ZFgG6oRl5tzii9oYF6fdOwtFwTGWZ-Wv0FGOacZi1xCh\n5.7.14 WfoHB1ZMakQBTp2jy8bMHHyHnQVOlXZZvWDLyG_EpsCd3iWLIAcS6QUls8fxoFn9wmODD_\n5.7.14 tBuI0txuYF0E7DKVEDgC1ifDzYQbY> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 y28sm4783138edi.95 - gsmtp')

Hi!
Great and simpe project!!!

Do you know if I can use long cables to the DHT22?

I mean... I've the Pi inside my house, so I want check that place temperature and I want to check the temperature outside too.

Thanks!

4 replies

Hi,

And thanks. :)

I don't know what would be the maximum length, but I have sensors connected with 1 meter cables and haven't got any problems with those.

I can test with longer cables as well once I got some spare time.

I have setup two sensors at reasonable distance ( around 15m ) to the outside sensor. they should be on the 5V supply, (pins 2 or 4) and i added a pullup resistor at the raspberry connection as It would not read with the pullup only at the sensor. I left the pullup resistor at the sensor as i had heat shrunk the connections already. I am getting a couple of false reads a day, ie 3308% humidity but on the whole it works nicely. i used rather cheap 4core security cable. A shielded cable properly tapped to earth at one end would probably help too.

I have the same problem. Tested it on the 3v and same thing

Forgot to mention this is on a RPi model b+, just looked at another cron job logger which has run without any spurious readings for about 5 days on the same machine. might be the strange readings are due to other factors such as the other logger (which runs every minute) getting in first or too often..?

Awesome Project !

Got it all working thanks.

Did you ever made chart with that data ?
I am looking to cross chek temperature with indoor / outdoor.

Hi,

Hoping someone more knowledgeable can help.

I'm also getting the "This page isnt working - Localhost is currently unable to handle this request - HTTP ERROR 500".

Checking /var/log/apache2/error.log reveals this:

[Wed Nov 29 15:28:27.357047 2017] [:error] [pid 587] [client ::1:36414] PHP Fatal error: Uncaught Error: Call to u

ndefined function mysqli_connect() in /var/www/html/index.php:14\nStack trace:\n#0 {main}\n thrown in /var/www/htm

l/index.php on line 14

Line 14 in the index.php is: (counting 14 lines down the code, including blank lines)

$connectdb = mysqli_connect($host,$user,$password)

I'm using the code pasted in a reply earlier by Taekky and PHP 7 (v7.019).

Any help much appreciated. Everything else went fine!

Regards,

Mike

Thank you thank you! I finally got it working this morning!!

I had the same issues as others with updated packages. In particular, mysql didn't ask for a password when installed but apparently now looks for the password of the user it is run as (like root if you sudo). And for PHP7, as noted by others, the API has changed to mysqli* with changes in the params. As you pointed out, /var/log/apache2/error_log was pretty clear in what was broken in the php file.

Hello, I've updated "index.php" to work with PHP 7 (tested with v7.019).

[code]
<?php

// Settings
// host, user and password settings
$host = "localhost";
$user = "logger";
$password = "***********";
$database = "temperatures";

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

// make connection to database
$connectdb = mysqli_connect($host,$user,$password)
or die ("Can not reach database");

// select db
mysqli_select_db($connectdb,$database)
or die ("Can not select database");

// sql command that selects all entires from current time and X hours backwards
$sql="SELECT * FROM temperaturedata WHERE dateandtime >= (NOW() - INTERVAL $hours HOUR)";

//NOTE: If you want to show all entries from current date in web page uncomment line below by removing //
//$sql="select * from temperaturedata where date(dateandtime) = curdate();";

// set query to variable
$temperatures = mysqli_query($connectdb,$sql);

// create content to web page
?>
<html>
<head>
<title>Environment - 4thDnet</title>
</head>

<body>
</body>
<center>Temperatures</center>
<br><br>
<table width="800" border="1" cellpadding="1" cellspacing="1" align="center">
<tr>
<th>Date</th>
<th>Sensor</th>
<th>Temperature</th>
<th>Humidity</th>
<tr>
<?php
// loop all the results that were read from database and "draw" to web page
while($temperature=mysqli_fetch_assoc($temperatures)){
echo "<tr>";
echo "<td>".$temperature['dateandtime']."</td>";
echo "<td>".$temperature['sensor']."</td>";
echo "<td>".$temperature['temperature']."</td>";
echo "<td>".$temperature['humidity']."</td>";
echo "<tr>";
}
?>
</table>
</html>

[/code]

1 reply

Thank you for this - as I'm running PHP 7.0.19-1, I was hoping this would sort it for me! Unfortunately, I'm getting an HTTP ERROR 500. Rebooted the pi and still no luck.

Any ideas?

Thanks so much for this comprehensive &
step by step tutorial. I'm a beginner, and it has been a fun challenge
following it along.

I've got everything working, except index.php appears broken - when visited from a browser, it is spitting out code from the php file, and not drawing on data from the database. The database works perfectly, and produces expected results when "select * from temperaturedata;" is called.

Anyone
else have this issue? I'm using Raspian Stretch, not Wheezy, and I
assume there may be issues with php versions there, & that appears
to be where the code is breaking, but I don't really know.

Thanks, any help is appreciated.