Facebook Twitter Instagram Pinterest YouTube
    Trending
    • Elecrow Meteor IPS Touchscreen with RGB LEDs
    • Pi Pico Pinout Display on the Command Line
    • How to Add a Raspberry Pi Pico Reset Button
    • Pi Pico Onboard LED
    • Pi Pico W Pinout and Power Pins
    • CrowPi L Raspberry Pi Laptop and Learning Platform
    • Pi Pico W Launched
    • Add Kodi to RetroPie Menu
    Facebook Twitter Instagram Pinterest YouTube RSS
    Raspberry Pi SpyRaspberry Pi Spy
    • Home
    • Categories
      • General
      • Hardware
      • Programming
      • Python
      • Software
      • Tutorials & Help
    • BerryClip
      • BerryClip Instructions
      • BerryClip Plus Instructions
      • Videos & Reviews
    • Buy
      • Buy Pi
      • Buy Pi Accessories
      • Buy Books
    • Tools
      • Ultimate Raspberry Pi Alexa Skill
      • Pi Power Estimator App
      • Pi-Lite 14×9 LED Matrix Sprite Editor
      • RPiREF Pin-out Reference App
      • Simple Ohm’s Law Calculator
      • Web Sites & Links
    • Tutorials & Help
        Featured
        November 9, 20200

        Raspberry Pi Temperature Monitoring

        Recent
        December 23, 2022

        How to Add a Raspberry Pi Pico Reset Button

        November 20, 2022

        Pi Pico Onboard LED

        May 6, 2022

        Add Kodi to RetroPie Menu

      1. Contact Us
      2. Site Map
      Raspberry Pi SpyRaspberry Pi Spy
      You are at:Home»Hardware»Interfaces»I2C»Basic Temperature Logging To The Internet With Raspberry Pi
      Basic Temperature Logger

      Basic Temperature Logging To The Internet With Raspberry Pi

      47
      By Matt on June 20, 2015 I2C, Sensors, Tutorials & Help

      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

      Basic Temperature LoggerThe 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

      BMP180 Pressure Temperature ModuleSensor

      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.

      Edimax 7811un WiFi Dongle

      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.

      Temperature Logger Hardware Circuit
      Here are the connection details :

      Signal NameHeader Pin
      SwitchGPIO2215
      Switch3V317
      LED (+)GPIO1711
      LED (-)Gnd9
      BMP180 VCC3V31
      BMP180 GndGnd6
      BMP180 SDAI2C SDA3
      BMP180 SCLI2C SCL5

       

      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.

      Basic Temperature LoggerMy 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 :

      • templogger.py
      • bmp180.py

      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 :

      Temperature and Pressure graphs

      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.

       

      Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
      Previous ArticleDigiMakers Bristol – 13th June 2015
      Next Article IMNEED 3200mAh Li-on Battery Power Bank Test

      Related Posts

      How to Add a Raspberry Pi Pico Reset Button

      Pi Pico Onboard LED

      Add Kodi to RetroPie Menu

      47 Comments

      1. Ray on June 27, 2015 11:37 pm

        What version of python are you using for temp logger.py

        Reply
        • Matt on June 28, 2015 1:37 am

          2.7

          Reply
          • Ray on June 28, 2015 9:04 am

            Thanks, not working on v 3.4 urllib2 not available

            Reply
            • Matt on June 28, 2015 1:45 pm

              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

              Reply
              • Ray on June 28, 2015 11:30 pm

                Thanks

      2. Christophe De Pauw on June 28, 2015 12:21 pm

        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

        Reply
        • Matt on June 28, 2015 1:46 pm

          It might be possible to use a temp sensor on a wire so the Pi can be outside. ie a DS18B20

          Reply
        • Ray on June 28, 2015 11:26 pm

          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

          Reply
      3. Peter on July 14, 2015 2:41 am

        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

        Reply
        • Matt on July 14, 2015 8:11 pm

          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.

          Reply
          • Dave on July 23, 2015 10:50 am

            i get that same error and i can see LEDGPIO is set to 17 i downloaded script direct and checked it in nano

            Reply
            • Matt on July 23, 2015 8:10 pm

              Download the script again. I’ve main some changes which should correct the error.

              Reply
        • Matt on July 23, 2015 8:10 pm

          Delete your templogger.py file and download again using wget. Should be fixed now!

          Reply
      4. Tim on September 10, 2015 9:42 am

        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.

        Reply
      5. Bernd on October 12, 2015 3:17 pm

        Great article! Is there a way to “adjust” the pressure value to be more acurate?

        Reply
        • Bernd on October 12, 2015 6:43 pm

          …and did you already checked the BMP280? How to upgrade your script to use this sensor?

          Reply
          • Matt on October 13, 2015 12:57 pm

            I’ve got a BME280 and will be trying that as soon as I get a chance.

            Reply
            • techsteer on May 29, 2016 11:59 pm

              Got a chance to try BME280?

              Reply
            • Ruben on July 8, 2016 10:10 pm

              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?

              Reply
      6. Geoffrey on October 26, 2015 10:35 pm

        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

        Reply
        • Matt on October 27, 2015 11:16 am

          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.

          Reply
          • Geoffrey on October 28, 2015 9:58 am

            Thanks for that Matt.

            I hadn’t realised I had to!!

            I will get onto it.

            Thanks for all of your excellent work.

            Geoffrey

            Reply
            • Geoffrey on October 28, 2015 2:39 pm

              Latest Update:

              The advice worked just fine and it’s posting temperatures and pressures on line just as required.

              Geoffrey

              Reply
      7. Geoffrey on November 5, 2015 10:27 am

        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

        Reply
      8. Jonathan on November 22, 2015 7:42 am

        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

        Reply
      9. Tom on December 17, 2015 7:56 am

        This is the easiest thing I have found to accomplish this. Works great. Thanks for sharing your work.

        Reply
      10. Pekkis on December 29, 2015 8:09 pm

        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 🙂

        Reply
      11. Damian on January 2, 2016 3:53 pm

        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

        Reply
      12. Rania on February 25, 2016 6:29 pm

        Great article! Where can I find a 4-way connector like the one you’re using?

        Reply
        • Matt on February 26, 2016 12:19 am

          It is just a section pulled of a 40 way female-female jumper cable strip.

          Reply
      13. Blui on March 4, 2016 11:23 pm

        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 🙁

        Reply
      14. Samuel on March 16, 2016 8:28 am

        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

        Reply
        • Matt on March 19, 2016 11:47 am

          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.

          Reply
      15. Tony on March 19, 2016 11:12 am

        Great article, thinking of trying it with a Pi zero. Anyone know if it will work with a zero?

        Reply
        • Matt on March 19, 2016 11:44 am

          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.

          Reply
      16. Alex Castella on April 11, 2016 4:49 pm

        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/

        Reply
      17. techsteer on May 29, 2016 11:57 pm

        Hi Matt,
        I have BME280. Waiting for your article on BME280

        Reply
      18. Daniel on June 26, 2016 4:12 pm

        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!!

        Reply
      19. JJ on July 22, 2016 5:33 pm

        I do the same, but only using ESP8266 and DS18B20 – everythink cost: 4$ 🙂 + power suply

        Reply
      20. Tyler on August 22, 2016 4:20 pm

        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?

        Reply
        • Matt on August 30, 2016 8:23 pm

          Change “AUTOSHUTDOWN = 1” to “AUTOSHUTDOWN = 0”.

          Reply
      21. Perry on September 17, 2016 4:50 am

        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.

        Reply
        • Matt on September 29, 2016 8:47 pm

          You can wrap the sendData line in a try block :

          try:
            sendData(THINGSPEAKURL,THINGSPEAKKEY,'field1','field2',temperature,pressure)
          except:
            time.sleep(0.1)
          Reply
      22. JD on September 10, 2017 3:20 pm

        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

        Reply
        • Matt on September 14, 2017 9:14 pm

          Have you downloaded the bmp180.py script?

          Reply
      23. John on February 5, 2018 5:44 am

        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

        Reply
      24. Bert Carremans on January 3, 2019 11:14 am

        Excellent tutorial! Thanks a lot.

        Reply

      Leave A Reply Cancel Reply

      This site uses Akismet to reduce spam. Learn how your comment data is processed.

      Recent Posts
      March 13, 2023

      Elecrow Meteor IPS Touchscreen with RGB LEDs

      December 26, 2022

      Pi Pico Pinout Display on the Command Line

      December 23, 2022

      How to Add a Raspberry Pi Pico Reset Button

      November 20, 2022

      Pi Pico Onboard LED

      November 14, 2022

      Pi Pico W Pinout and Power Pins

      Categories
      • 1-wire
      • 3D Printing
      • Add-ons
      • BBC Micro:bit
      • BerryClip
      • Books
      • Camera Module
      • Cases
      • Events
      • General
      • Hardware
      • I2C
      • Infographics
      • Interfaces
      • Minecraft
      • Model A+
      • Model B+
      • News
      • Pi Models
      • Pi Pico
      • Pi Zero
      • Power
      • Programming
      • Python
      • Raspberry Pi OS
      • Raspbian
      • RetroGaming
      • Robotics
      • Sensors
      • Software
      • SPI
      • Tutorials & Help
      Tags
      Arduino audio battery berryclip Birthday bluetooth cambridge camera CamJam DigiMakers display games GPIO I2C interface Kickstarter Kodi LCD LED Linux media Minecraft Model A motionEyeOS PCB photography photos Pi-Lite Pi Pico power python Raspberry Jam Raspberry Pi Bootcamp raspbian Retrogaming retroPie screen SD card security sensor SPI SSH temperature ultrasonic video
      Raspberry PI Related
      • Adafruit Blog
      • Average Maker
      • Official RaspBerry Pi Site
      • Raspberry Pi Pod
      • RasPi.tv
      • RaspTut
      • Stuff About Code
      Tech Resources
      • MattsBits – Pi Resources
      • Microbit Spy
      • Technology Spy
      Archives
      About

      Unofficial site devoted to the Raspberry Pi credit card sized computer offering tutorials, guides, resources,scripts and downloads. We hope to help everyone get the most out of their Pi by providing clear, simple articles on configuring, programming and operating it.

      Popular Posts
      September 19, 2014

      Top 5 Reasons The Raspberry Pi Sucks

      July 27, 2012

      16×2 LCD Module Control Using Python

      October 20, 2013

      Analogue Sensors On The Raspberry Pi Using An MCP3008

      Recent Posts
      March 13, 2023

      Elecrow Meteor IPS Touchscreen with RGB LEDs

      December 26, 2022

      Pi Pico Pinout Display on the Command Line

      December 23, 2022

      How to Add a Raspberry Pi Pico Reset Button

      Facebook Twitter Instagram Pinterest YouTube RSS

      Entries RSS | Comments RSS

      This site is not associated with the official Raspberrypi.org site or the Raspberry Pi Foundation. Raspberry Pi is a trademark of the Raspberry Pi Foundation.

      Copyright © 2022 - All Rights Reserved - Matt Hawkins

      mastodon.social@RPiSpy

      Type above and press Enter to search. Press Esc to cancel.