How to Send Data to ThingSpeak Cloud using Raspberry Pi

How to send data to ThingSpeak Cloud using Raspberry Pi

In previous tutorials we learned about installing operating system in Raspberry Pi, now lets move ahead to the first step in building any IoT project using Raspberry Pi, that is to upload the data to any cloud server using Raspberry Pi. In this simplest Raspberry Pi IOT project, we will use ThingSpeak as cloud server to store the data. Here Raspberry Pi will read its CPU temperature and send it to ThingSpeak, and it can be monitored from anywhere in the world using internet. This will be useful if you are running the Pi for long time for some application at some remote place and need monitor its CPU temperature.

ThingSpeak is an open IoT platform for monitoring your data online. In ThingSpeak channel you can set the data as private or public according to your choice. ThingSpeak takes minimum of 15 seconds to update your readings. Its a great and very easy to use platform for building IOT projects.

There are also some other platforms available for monitoring your data online which we will cover in later articles but there are some advantages of ThingSpeak over other platforms like it is very easy to set up and it also has many options to plot graph.

 

Components Required

  1. Raspberry Pi
  2. Power Cable
  3. WiFi or Internet

 

Steps for building Raspberry Pi Data Logger on Cloud

Step 1: Signup for ThingSpeak

For creating your channel on ThingSpeak you first need to sign up on ThingSpeak. In case if you already have account on ThingSpeak just sign in using your id and password.

For creating your account go to www.thinspeak.com

ThingSpeak

 

Click on signup if you don’t have account and if you already have account click on sign in.

After clicking on signup fill your details.

 Signup for ThingSpeak

 

After this verify your E-mail id and click on continue.

 

Step 2: Create a Channel for Your Data

Once you Sign in after your account verification, Create a new channel by clicking “New Channel” button

 Create Channel for Your Data on ThingSpeak

 

After clicking on “New Channel”, enter the Name and Description of the data you want to upload on this channel. For example I am sending my CPU data (temperature), so I named it as CPU data.

Now enter the name of your data (like Temperature or pressure) in Field1. If you want to use more than one Field you can check the box next to Field option and enter the name and description of your data.

After this click on save channel button to save your details.

 

Step 3: Getting API Key in ThingSpeak

To send data to ThingSpeak, we need an unique API key, which we will use later in our python code to upload our CPU data to ThingSpeak Website.

Click on “API Keys” button to get your unique API key for uploading your CPU data.

 Getting API Key in ThingSpeak

 

Now copy your “Write API Key”. We will use this API key in our code.

 

Step 4:  Python Code for Raspberry Pi

Complete code is given at the end of this tutorial, just make a file with any name and .py extension and copy-paste the code and save the file. Don’t forget to replace the API key with yours. You can run the python file any time using below command:

python /path/filename.py

 

Assuming you already installed python in Raspberry pi using this command

sudo apt-get install python

 

Case 1: If you are using monitor screen then just use the given code.

Now install all libraries:

sudo apt-get install httplib
sudo apt-get install urllib

 

After installing libraries run your python code (python /path/filename.py)

If the code runs properly you will see some CPU temperature values as shown in below image.

 Python Code for Raspberry Pi

 

If there are any errors uploading the data, you will receive “connection failed” message.

 

Case 2: If you are using “Putty” then you should follow these commands:

First update your pi using:

sudo apt-get update

 

After this make a file cpu.py using:

nano cpu.py

 

After creating this file copy your code to this file and save it using CTRL + X and then ‘y’ and Enter.

After this install all libraries using:

sudo apt-get install httplib
sudo apt-get install urllib

 

After installing libraries run your python code using:

python cpu.py

 

If the code runs properly you will see some CPU temperature values as shown in above image.

 

Step 6: Check ThingSpeak site for Data Logging

After completing these steps open your channel and you will see the CPU temperature data is updating into ThingSpeak website.

 Check ThingSpeak site for Data Logging

 

Like this you can send any sensor data connected with Raspberry pi to the ThingSpeak Cloud. In next article we will connect LM35 temperature sensor with Raspberry Pi and send the temperature data to ThingSpeak, which can be monitored from anywhere.

Complete Python code for this Raspberry Pi Cloud Server is given below. Code is easy and self-explanatory to understand.

Code

import httplib
import urllib
import time
key = "ABCD"  # Put your API Key here
def thermometer():
    while True:
        #Calculate CPU temperature of Raspberry Pi in Degrees C
        temp = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1e3 # Get Raspberry Pi CPU temp
        params = urllib.urlencode({'field1': temp, 'key':key }) 
        headers = {"Content-typZZe": "application/x-www-form-urlencoded","Accept": "text/plain"}
        conn = httplib.HTTPConnection("api.thingspeak.com:80")
        try:
            conn.request("POST", "/update", params, headers)
            response = conn.getresponse()
            print temp
            print response.status, response.reason
            data = response.read()
            conn.close()
        except:
            print "connection failed"
        break
if __name__ == "__main__":
        while True:
                thermometer()
 

21 Comments

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package httplib

Please advice.

I together with my pals have been reading the excellent information on your website while at once developed an awful feeling I had not thanked you for those tips. All the people happened to be totally excited to see them and have simply been taking pleasure in those things. Many thanks for getting really considerate and for finding some high-quality subjects most people are really needing to learn about. My sincere apologies for not expressing gratitude to you sooner.

I simply wanted to develop a small note in order to say thanks to you for all of the stunning techniques you are giving out here. My time intensive internet research has now been recognized with useful strategies to exchange with my relatives. I 'd mention that many of us readers actually are very lucky to dwell in a decent place with so many lovely individuals with helpful techniques. I feel somewhat fortunate to have encountered your webpages and look forward to some more fun moments reading here. Thanks a lot again for all the details.

I enjoy you because of your entire effort on this website. Betty loves carrying out internet research and it's really easy to understand why. Most people notice all concerning the lively mode you provide powerful guidelines by means of your web blog and as well as attract contribution from website visitors on this issue plus my daughter is without question becoming educated a lot. Take advantage of the remaining portion of the year. You're the one performing a fantastic job.

I simply wanted to write down a remark to say thanks to you for all the nice instructions you are sharing here. My prolonged internet search has finally been honored with useful know-how to share with my partners. I 'd assert that most of us site visitors are undoubtedly blessed to dwell in a useful network with so many outstanding professionals with beneficial hints. I feel very much happy to have seen your weblog and look forward to plenty of more fabulous minutes reading here. Thanks a lot again for everything.

I'm writing to make you understand what a really good encounter my wife's princess went through checking the blog. She discovered such a lot of issues, with the inclusion of what it is like to possess an amazing teaching nature to let the others effortlessly completely grasp various impossible subject matter. You undoubtedly did more than my desires. I appreciate you for churning out the warm and friendly, dependable, revealing and also unique tips about this topic to Julie.

I am glad for commenting to make you understand what a really good experience my wife's princess developed checking your web site. She discovered several things, which include what it's like to have an ideal teaching nature to let many others just master various specialized subject areas. You truly did more than my expected results. I appreciate you for imparting these interesting, trusted, explanatory and easy thoughts on the topic to Lizeth.

My spouse and i were so ecstatic Albert managed to conclude his researching through your precious recommendations he got when using the site. It is now and again perplexing to simply possibly be giving out key points some other people could have been selling. And we all do know we now have the website owner to be grateful to for this. The main illustrations you have made, the simple blog navigation, the relationships you can give support to engender - it's got all excellent, and it's aiding our son and us reckon that this topic is fun, which is seriously pressing. Thanks for the whole thing!

I enjoy you because of all of the efforts on this blog. Debby takes pleasure in doing investigations and it is obvious why. My partner and i learn all of the powerful means you produce simple information via your website and even improve contribution from other ones on the idea plus our own child is truly understanding a lot of things. Have fun with the rest of the year. You're performing a pretty cool job.

I simply had to thank you so much yet again. I'm not certain what I would've done in the absence of the tricks shown by you relating to this subject. Certainly was a very traumatic concern in my position, however , encountering your specialized fashion you processed that made me to weep over happiness. I am just thankful for this information as well as pray you really know what a great job you happen to be undertaking teaching some other people thru a web site. I'm certain you haven't got to know all of us.

I enjoy you because of each of your work on this web site. My niece take interest in engaging in internet research and it's really easy to see why. We all know all regarding the compelling mode you render valuable tactics through this blog and even welcome response from some others on the content so our own princess is now starting to learn a whole lot. Take advantage of the rest of the new year. Your doing a really great job.

My wife and i have been quite delighted when Edward could finish up his web research out of the ideas he received from your own site. It's not at all simplistic to simply possibly be making a gift of techniques which people could have been trying to sell. Therefore we figure out we have the writer to be grateful to for that. Most of the illustrations you have made, the straightforward blog navigation, the friendships you can help engender - it is everything awesome, and it's aiding our son in addition to the family recognize that this concept is awesome, and that is very pressing. Many thanks for the whole thing!

I and my pals have already been reading through the good guidelines located on the website and then all of the sudden I had a terrible feeling I had not thanked the blog owner for them. Most of the young men were passionate to learn all of them and already have sincerely been enjoying those things. I appreciate you for turning out to be indeed kind and for deciding upon such helpful issues most people are really needing to discover. My honest apologies for not saying thanks to you earlier.

I am glad for writing to make you know of the remarkable encounter my wife's child encountered studying your blog. She discovered a lot of pieces, which included what it's like to possess an ideal giving character to get the others with no trouble master certain problematic subject areas. You truly exceeded our desires. Many thanks for offering these productive, safe, educational and cool guidance on your topic to Emily.

I wish to express some thanks to this writer just for rescuing me from such a difficulty. Just after searching through the the net and seeing concepts which were not beneficial, I believed my entire life was gone. Being alive devoid of the answers to the problems you have fixed by way of the site is a serious case, as well as ones that might have in a negative way affected my career if I hadn't come across your web blog. That expertise and kindness in dealing with the whole lot was very helpful. I don't know what I would have done if I had not encountered such a stuff like this. I am able to at this moment look ahead to my future. Thank you so much for your high quality and effective guide. I will not hesitate to propose your web site to any person who should receive care on this issue.

Thank you for all your labor on this site. My mom loves conducting investigations and it's really obvious why. Many of us hear all regarding the powerful tactic you offer good tips and tricks via your blog and as well attract participation from others on the content plus our child is without a doubt becoming educated a lot of things. Have fun with the rest of the new year. Your doing a glorious job.

I want to show my appreciation to the writer just for rescuing me from this predicament. Because of researching through the world wide web and finding methods which were not helpful, I was thinking my life was gone. Existing devoid of the strategies to the problems you've fixed through your article content is a serious case, and those that might have in a negative way damaged my entire career if I had not come across your site. The competence and kindness in handling all areas was important. I don't know what I would've done if I hadn't discovered such a thing like this. I'm able to at this moment look ahead to my future. Thanks a lot so much for this reliable and results-oriented help. I won't think twice to endorse the sites to anyone who will need direction on this problem.

I would like to express thanks to you just for bailing me out of this circumstance. Right after looking out through the world wide web and obtaining notions which were not powerful, I believed my life was well over. Being alive without the solutions to the difficulties you've sorted out all through the report is a serious case, and the kind that might have in a negative way damaged my entire career if I hadn't discovered your web blog. Your own personal competence and kindness in maneuvering everything was very helpful. I am not sure what I would have done if I hadn't come across such a stuff like this. It's possible to at this moment look ahead to my future. Thanks so much for your specialized and amazing guide. I will not be reluctant to propose your web page to anybody who would like guidance on this situation.

I am commenting to make you understand what a excellent discovery my wife's child obtained reading your blog. She even learned such a lot of things, most notably what it's like to have an excellent teaching style to let others very easily have an understanding of specific impossible things. You undoubtedly exceeded my expectations. I appreciate you for producing these practical, healthy, educational not to mention easy guidance on the topic to Mary.

Hola. ¿Cómo estás? Soy Alberto del Departamento de Prensa. Muchas gracias por atenderme.

He pensado que podría interesarte cómo podemos hacer que tu empresa aparezca en más de 50 periódicos digitales como noticia (No será un anuncio) por una única cuota al mes sin permanencia. Las noticias no se borrarán

Periódicos de gran autoridad mencionarán la web de tu empresa para lograr una mejor reputación y posicionamiento web.

Este servicio incluye tanto la redacción de la noticia como el análisis de las palabras clave.

Si pudieras proporcionarme un teléfono, me encantaría programar una llamada para hablar contigo, resolver cualquier duda sin compromiso y explicar cómo puedes disfrutar del *mes gratuito* sin permanencia.

¡Muchas gracias!

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.