There are plenty of examples out there of temperature logging systems but I wanted to create my own and keep it nice and simple. The other thing I wanted to try out was logging the data to the internet using a third party service. I’ve done it before using my own website based databases but that is a little bit more involved.
So here is my attempt at a basic temperature “Internet of Things” device that hopefully will help others get started or form the basis for a project.
Hardware
The device consists of :
- Raspberry Pi Model A+
- Basic case
- BMP180 sensor module
- LED with 330ohm resistor
- Small switch
- 4-way female-female jumper cable
- 2 2-way headers
Sensor
I chose the BMP180 sensor as I already had one available which I used for my BMP180 I2C Digital Barometric Pressure Sensor article. This sensor is small, cheap and handles temperature and pressure. It communicates with the Pi via an I2C interface so requires a minimum of wiring.
LED (Optional)
To give some visual feedback I added a single green LED. The anode (+ve) was connected to pin 11 (GPIO17) and the cathode (-ve) was connected to pin 9 via a 330ohm resistor. I chose those two pins as they are next to each other and allowed me to use a 2-pin header and plug the LED directly onto the Pi’s GPIO header.
WiFi Dongle
As I wanted to use a model A+ I needed a WiFi dongle to allow the Pi to communicate with the internet. I’ve got a few Edimax EW-7811UN USB dongles so I used one of those. You will need to setup the WiFi so it can successfully connect to your network. You can use my Setting Up WiFi On The Raspberry Pi guide. I also disabled the power saving modes using this guide.
Switch
The switch is there to tell the script to exit and/or shutdown the Pi. It was connected to pin 15 (GPIO22) and pin 17 (3V3) using another 2-pin header. By default the script enables an internal pull down resistor on pin 15 so that GPIO22 is LOW. When the switch is pressed it is connected to 3.3V and pulled HIGH. The script monitors the switch and exits if it is pressed. By setting the AUTO_SHUTDOWN flag to 1 the Pi can also shut itself down if required.
Component Setup
Here is how I connected the temperature sensor, LED and switch.
Here are the connection details :
Signal Name | Header Pin | |
---|---|---|
Switch | GPIO22 | 15 |
Switch | 3V3 | 17 |
LED (+) | GPIO17 | 11 |
LED (-) | Gnd | 9 |
BMP180 VCC | 3V3 | 1 |
BMP180 Gnd | Gnd | 6 |
BMP180 SDA | I2C SDA | 3 |
BMP180 SCL | I2C SCL | 5 |
Thingspeak and The Internet of Things
For the third party service I looked at a number of options. I ruled out a number of them because they :
- Failed to make it clear what the cost was (if any)
- Failed to define what the difference was between free trials and paid options
- Failed to explain exactly how you submitted data
- Only retained data for a few days on the free option
I settled on Thingspeak.com simply because within one click of their homepage I knew exactly what I had to do to submit data. Configuring the dashboard was easy and didn’t require reading any additional help.OK setting up the gauges needed a bit more reading but the graphs were fairly straightforward.
My first script was working within five minutes after a bit of cutting and pasting. There are loads of other services out there but for this project Thingspeak suited me perfectly. I’m not opposed to paying for a service but I wanted everyone to be able to do something easy without worrying about the cost or having to use a free, time limited trial. For more elaborate systems with more data then you may want to pay for a more feature rich service.
To use my example script you will need to setup a Thingspeak account, create a new channel and acquire the “Write API Key” from the API settings. See the official documentation for help.
Python Script
The main script reads temperature and pressure and sends it to Thingspeak using “Field 1” and “Field 2”. It relies on an additional file to make use of the BMP180 sensor. Both scripts are required and should be saved in the same place :
You can download these two files directly to an internet enabled Pi either right-clicking on the links above in a web browser or running these at a command prompt :
wget https://bitbucket.org/MattHawkinsUK/rpispy-misc/raw/master/python/bmp180.py wget https://bitbucket.org/MattHawkinsUK/rpispy-misc/raw/master/python/templogger.py
The script can then be executed on the command line using :
sudo python templogger.py
The script prints text updates to the screen. When launching via SSH over WiFi I wanted the script to continue running after I disconnected so I used this command instead :
sudo python templogger.py > /dev/null &
In this command the status outputs are directed to “null” (i.e. ignored) and the & insures the script runs in the background.
Automatically Run On Boot
In order to avoid having to start the script manually you can configure it to launch when the Pi boots up. You can do this by editing the rc.local file :
sudo nano /etc/init.d/rc.local
then adding the following line at the bottom of the file :
sudo python /home/pi/templogger.py > /home/pi/templogger.log 2>&1
You can save and exit the nano editor using [CTRL-X], [Y] then [ENTER].
On startup the line runs the Python script and directs text output to a log file. This is a useful file to read if you are fault finding. The values in the log are comma separated so it could be loaded into a spreadsheet application if you wanted to analyse the data.
Pressing the switch at anytime will result in the script stopping. If AUTO_SHUTDOWN is set to 1 then the Pi will shutdown. After 20 seconds the power can be disconnected.
Configuration
The script has some values which you will need to adjust. The most important one is the Thingspeak API Key. You need to enter your own key to update your channel. You can either edit the Python script directly using :
nano templogger.py
or by providing a set of new values in a configuration file on the boot partition. If a file called “/boot/templogger.cfg” exists and the first line is “Temp Logger” the values that follow are used instead. Here is an example configuration file :
Temp Logger 0x77 1 17 22 10 1 ABCDEFG123456789 https://api.thingspeak.com/update
You can create a configuration file by using :
sudo nano /boot/templogger.cfg
Then create the content as in the example above.
As the file exists in the /boot partition you can edit the configuration file on a PC before powering up the device. This is sometimes useful if you want to change the INTERVAL between readings.
The script doesn’t check for errors in your file. Make sure all the values are specified in the correct order. They are expected in the same order as they are listed in the original Python script.
Final Results
Once the device is up and running and you’ve configured your Thingspeak Channel you can produce outputs like this :
The graphs update these in realtime as new data arrives. The channel also allows you to download your data in CSV, XML and Json formats.
With an interval of 10 minutes that gives you 144 data points every 24 hours. You can set the graphs to display a set number of data points so you can adjust this to give you a suitable spread of data.
I only used two streams of data in my example (temperature and pressure) but Thingspeak will accept a total of eight.
Here is my public RPiSpy Temp Logger Channel.
47 Comments
What version of python are you using for temp logger.py
2.7
Thanks, not working on v 3.4 urllib2 not available
Ah ok. I can’t try it myself but this will make a copy and then convert to 3.4 :
cp templogger.py templogger3.py
2to3 -w templogger3.py
Thanks
Nice project, almost what i’m looking for!
I’d like to monitor the temperature in a freezer. I don’t think it’s a good idea to place a pi in the freezer….
Does anyone know a temperature sensor, that could sent the data to the pi, so the pi can sent in to thingspeak?
kind regards,
Christophe
It might be possible to use a temp sensor on a wire so the Pi can be outside. ie a DS18B20
Info on DS18B2o mentioned by Matt. It’s a available sealed metal cyclinder with 3 core cable attached
http://www.maximintegrated.com/en/products/analog/sensors-and-sensor-interface/DS18B20.html#popuppdf
I am getting the following error:
File “templogger.py”, line 127, in
main()
File “templogger.py”, line 101, in main
GPIO.setup(LEDGPIO , GPIO.OUT)
UnboundLocalError: local variable ‘LEDGPIO’ referenced before assignment
LEDGPIO is defined at the top of the script. If it is not assigned the assignment line must be missing. Did you download the script direct to your Pi or did you cut and paste it? If you cut and pasted it the script is probably not as it should be.
i get that same error and i can see LEDGPIO is set to 17 i downloaded script direct and checked it in nano
Download the script again. I’ve main some changes which should correct the error.
Delete your templogger.py file and download again using wget. Should be fixed now!
Great article, saved me a lot of time. Converted to work with a DHT11 temperature and humidity sensor. Didn’t know about Thingspeak so thanks again.
Great article! Is there a way to “adjust” the pressure value to be more acurate?
…and did you already checked the BMP280? How to upgrade your script to use this sensor?
I’ve got a BME280 and will be trying that as soon as I get a chance.
Got a chance to try BME280?
Great work Matt! Can´t wait to get it working. Did you had a chance to try the BMP280? I only have that one and that doesn´t seem to work. Data is not uploaded to the site.
And is there a way of logging, for troubleshooting?
Hi Matt
On a brand new A+ and very recently downloaded NOOBS, the program stalls at the first line, i.e. it doesn’t find the System Management Bus module. I downloaded the listing directly from you. I’ve been having some other issues with configuring the A+ but… I’ve tried changing the smbus to SMBus but no change!
It’s a great project idea as I spend the winter three months away from home and need a log of the temperatures to guess how much heat to give the home!!
Thanks for any suggestion.
Geoffrey
Sounds like you haven’t installed the python-smbus module. It is part of the i2c interface setup required for the BMP180 sensor. Take a look at the Enabling The I2C Interface On The Raspberry Pi page.
Thanks for that Matt.
I hadn’t realised I had to!!
I will get onto it.
Thanks for all of your excellent work.
Geoffrey
Latest Update:
The advice worked just fine and it’s posting temperatures and pressures on line just as required.
Geoffrey
Hi Matt,
The Logger is working fine – up to a point! See https://thingspeak.com/channels/62333
It keeps stopping without any pattern of numbers of samples or time running. Anything from 2 hours to 36 hours. You can see some of the gaps before I can restart it manually.
I thought of the Power Saving issue with regard to the dongle and so ran iwconfig:
pi@raspberrypi ~ $ iwconfig
wlan0 IEEE 802.11bgn ESSID:”BTHub4-CG6F”
Mode:Managed Frequency:2.412 GHz Access Point: 18:83:BF:45:46:99
Bit Rate=65 Mb/s Tx-Power=20 dBm
Retry short limit:7 RTS thr:off Fragment thr:off
Power Management:off
Link Quality=61/70 Signal level=-49 dBm
Rx invalid nwid:0 Rx invalid crypt:0 Rx invalid frag:0
Tx excessive retries:303 Invalid misc:660 Missed beacon:0
lo no wireless extensions.
…and so I guess Power Saving is not the issue.
Any other thoughts?
The A+ is running with a powered hub and in the same room as the router. (for the moment. Eventually I need it to run in the loft!). The dongle is an RT5370.
Eventually I’m hoping that the logger will provide me with temperatures in the loft so that when, during Jan. thro’ March, I’m away abroad, I can adjust the temperatures downstairs to cope with a rural winter. If I can’t get it to work consistently I will then be asking how can I re-boot it over the net from an Android device!!
Geoffrey
Hi Matt.
Great post. Thanks for making it all so accessible. Just wondering if you know how I could extract the data to tweet it please. I’ve trawled the internet and keep trying to hack code from anywhere and everywhere but I just can’t get the relevant string to update Twitter. I’m using Tweepy as it seems pretty straightforward.
Thanks for any pointers you (or anyone else) can offer.
Jonathan
This is the easiest thing I have found to accomplish this. Works great. Thanks for sharing your work.
Hi Matt,
We have noticed that this script stops if internet connection fails for a while. Is there a way to start script again without dealing direct with console or restarting pi? Simple startup autostart does not help in this, and seems that templogger.py code itself is not stopping execution, but maybe urllib or urllib2 libraries. This is a problem with mobile broadband connection, it would be helpful if there would be some delay for “lost connection” without loosing code execution. Thanks for great code anyway, greetings from Finland 🙂
Hello Matt.
At the beginning I want to congratulate a great project.
Im get started with Rasberry and I dont know much about it.
I have a question and requests.
Is there a possibility to add to this project two additional sensors DS18B20 and DHT11 and transmission measurements on ThinkSpeak like BMP180?
If so, could in some simple way to explain how to do it?
I do not know much about PY and Raspberry.
I would be very grateful for your help.
Sorry for my english, I hope that I wrote understandable.
Thank you again.
Regards Damian
Great article! Where can I find a 4-way connector like the one you’re using?
It is just a section pulled of a 40 way female-female jumper cable strip.
How i can add a DHT11 in this sript for humidity and a second temperature?
I can read the sensor with the Adafriut-DHT-library but my python is not good enough for sendData 🙁
Hi Matt
Nice post. Looking into IOT. Since IOT is here, i’d like to ask some questions.
What about power consumption? Since iot also means low power. How would you tackle this ‘problem’?
Best Regards,
Samuel
Ultimately if you are using a Pi you are stuck with the power consumption of the model you are using. If you really need to reduce it down to the bare minimum you would better off using another device. Power consumption is why I prefer the A+ to the B+/Pi 2 or Pi 3. For temperature logging you could use an Arduino based device and there are lots of examples out there where people have done just that.
Great article, thinking of trying it with a Pi zero. Anyone know if it will work with a zero?
It should work with the PiZero but you will need to get it connected to the internet. So it will need a WiFi dongle connected to the USB port.
Thank you *very much* for yor article. It works like a charm!
I just changed the way it automatically runs on boot using the following article:
https://www.raspberrypi-spy.co.uk/2015/10/how-to-autorun-a-python-script-on-boot-using-systemd/
Hi Matt,
I have BME280. Waiting for your article on BME280
I am so new to this and this article is so great! I am just too new to figure out how and where to change the temp from Celsius to Fahrenheit (and the mBar in whatever the US uses!). Anyone with the solution?
Thanks!!
I do the same, but only using ESP8266 and DS18B20 – everythink cost: 4$ 🙂 + power suply
How do i change the code so that when the button is pressed, it only exits the python while loop and does NOT shut down the raspberry pi?
Change “AUTOSHUTDOWN = 1” to “AUTOSHUTDOWN = 0”.
Thank you for the article. How can I handle an exception to sendData again when there is an error ‘failed to reach the server’. Or catch the error and continue to run until the next sleep time is reached.
You can wrap the sendData line in a try block :
This is a great article, but I know it’s quite an old so I am wondering if things have changed.
When I run …
sudo python templogger.py
I get the following error …
Traceback (most recent call last):
File “templogger.py”, line 26, in
import bmp180 # Sensor library
ImportError: No module named bmp180
Have I missed something?
Thanks
Have you downloaded the bmp180.py script?
Hi discovered I had 3 API codes the initial one I received when opening the account with the ThingSpeak caused the error because that was the one I used. found that the write API is the one to use. Have now got data on the online graphs.
But this is still using the python program templogger .py that I modified to make useable
Excellent tutorial! Thanks a lot.