Downloading Data from Thingspeak

edited August 2017 in Share Your Work

This is a short example of how to download a block of data from a Thingspeak channel with Processing. Explanations are in the comments.

        //This sketch retrieves a large block of data from thingspeak. Here I use json as the format, though this can 
        //be done (with different parsing) with xml or csv files.
        // You can see the raw json file by pasting the following into the address bar of your browser:
        // http:// api.thingspeak.com/channels/11653/feed.json?key=E593NEBDKFBC84D6&start=2011-11-11%2010:10:10&end=2014-11-11%2011:11:11
        // Details on how to construct these urls can be found at Thingspeak Community: community.thingspeak.com/documentation/api/

        JSONObject json; // this is the full json object including the headers
        JSONArray totalData; // this is the array in the feeds part
        JSONObject record; // this is each one of the small json objects in the array
        int id; // this is just a counter provided by Thingspeak that increments with each new posted data point. It is an int
        String timeStamp; // this is the full time stamp provided by Thingspeak. It could be parsed to extract specific information for visualization
        int temp; // this is the data point that I uploaded from my arduino 
        // (a TMP36 analog temperature sensor --> Arduino Uno --> Ethernet Shield --> Thingspeak) using a standard arduino upload program

        void setup() {
          //below, you should use your own channel. If your channel is public, you don't need a key. If your channel is private, you need to generate a read key.
          json = loadJSONObject("http://"+"api.thingspeak.com/channels/11653/feed.json?key=E593NEBDKFBC84D6&start=2011-11-11%2010:10:10&end=2014-11-11%2011:11:11");
          totalData = json.getJSONArray("feeds"); // this moves just the records we care about into a special type of array called a JSONArray
          for (int i = 0; i < totalData.size(); i++) { // step through the array, one record at a time
            record = totalData.getJSONObject(i); // remember the items in the array are also JSON objects
            id = record.getInt("entry_id"); // the key "entry_id" is given by Thingspeak. This is essentially a counter
            timeStamp = record.getString("created_at"); // the key "created_at" is also given by Thingspeak. I will write a parser to unpack it into a Date class soon.
            temp = int(record.getString("field1")); // Thingspeak stored this as a string so I have to convert it to an int for visualisation
            println(id + ", " + timeStamp + ", " + temp); // Just checking that it is all there.
          }
        }
Tagged:

Comments

Sign In or Register to comment.