Official ThingSpeak Library for Arduino, Particle, and ESP8266

We are thrilled to announce the official ThingSpeak Communication Library for Arduino, Particle, and ESP8266 devices. This library enables an Arduino or other compatible hardware to write or read data to or from ThingSpeak, an open data platform for the Internet of Things with built-in MATLAB analytics and visualization apps. Visit the ThingSpeak blog to learn more.

Arduino IDE Installation

  • In the Arduino IDE, choose Sketch/Include Library/Manage Libraries.
  • Click the ThingSpeak Library from the list
  • Click the Install button.Compatible Hardware (as of version 1.1.0)
  • Arduino or compatible using an Ethernet or Wi-Fi shield (we have tested with Uno and Mega)
  • Arduino Yun running OpenWRT-Yun Release 1.5.3 (November 13th, 2014) or later.
  • ESP8266 (we have tested with SparkFun ESP8266 Thing - Dev Board and NodeMCU 1.0 module)
  • Particle Core, Photon, and Electron (Formally Spark)ThingSpeak Examples
    The library includes several examples to help you get started.
  • CheerLights: Reads the latest CheerLights color on ThingSpeak, and sets an RGB LED.
  • ReadLastTemperature: Reads the latest temperature from the public MathWorks weather station in Natick, MA on ThingSpeak.
  • ReadPrivateChannel: Reads the latest voltage value from a private channel on ThingSpeak.
  • ReadWeatherStation: Reads the latest weather data from the public MathWorks weather station in Natick, MA on ThingSpeak.
  • WriteMultipleVoltages: Reads analog voltages from pins 0-7 and writes them to the 8 fields of a channel on ThingSpeak.
  • WriteVoltage: Reads an analog voltage from pin 0, converts to a voltage, and writes it to a channel on ThingSpeak.Complete source code and examples for the ThingSpeak Library are available on GitHub.

moderator: removed the cross-post

Just an update here -- I found a bug in reading values from ThingSpeak, and have recently updated it to version 1.1.1.

-Rob

rPurser,

Hi there,
I wonder if you could shed any light on the error I get when I try to compile a fresh install of the cheerlights example.

[code]
/*
  CheerLights
  
  Reads the latest CheerLights color on ThingSpeak, and sets a common anode RGB LED on digital pins 5, 6, and 9.
  On Spark core, the built in RGB LED is used
  Visit http://www.cheerlights.com for more info.

  ThingSpeak ( https://www.thingspeak.com ) is a free IoT service for prototyping
  systems that collect, analyze, and react to their environments.
  
  Copyright 2015, The MathWorks, Inc.

  Documentation for the ThingSpeak Communication Library for Arduino is in the extras/documentation folder where the library was installed.
  See the accompaning licence file for licensing information.
*/

#ifdef SPARK
	#include "ThingSpeak/ThingSpeak.h"
#else
	#include "ThingSpeak.h"
#endif

// ***********************************************************************************************************
// This example selects the correct library to use based on the board selected under the Tools menu in the IDE.
// Yun, Wired Ethernet shield, wi-fi shield, esp8266, and Spark are all supported.
// With Uno and Mega, the default is that you're using a wired ethernet shield (http://www.arduino.cc/en/Main/ArduinoEthernetShield)
// If you're using a wi-fi shield (http://www.arduino.cc/en/Main/ArduinoWiFiShield), uncomment the line below
// ***********************************************************************************************************
//#define USE_WIFI_SHIELD

// Make sure that you put a 330 ohm resistor between the arduino
// pins and each of the color pins on the LED.
int pinRed = 9;
int pinGreen = 6;
int pinBlue = 5;

#ifdef ARDUINO_ARCH_AVR
  #ifdef ARDUINO_AVR_YUN
    #include "YunClient.h"
    YunClient client;
  #else

    #ifdef USE_WIFI_SHIELD
      #include <SPI.h>
      // ESP8266 USERS -- YOU MUST COMMENT OUT THE LINE BELOW.  There's a bug in the Arduino IDE that causes it to not respect #ifdef when it comes to #includes
      // If you get "multiple definition of `WiFi'" -- comment out the line below.
      #include <WiFi.h>
      char ssid[] = "<YOURNETWORK>";          //  your network SSID (name) 
      char pass[] = "<YOURPASSWORD>";   // your network password
      int status = WL_IDLE_STATUS;
      WiFiClient  client;
    #else
      // Use wired ethernet shield
      #include <SPI.h>
      #include <Ethernet.h>
      byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
      EthernetClient client;
    #endif
  #endif
#endif

#ifdef ARDUINO_ARCH_ESP8266
  #include <ESP8266WiFi.h>
  char ssid[] = "<YOURNETWORK>";          //  your network SSID (name) 
  char pass[] = "<YOURPASSWORD>";   // your network password
  int status = WL_IDLE_STATUS;
  WiFiClient  client;
#endif

#ifdef SPARK
  TCPClient client;
#endif


/*
  This is the ThingSpeak channel number for CheerLights
  https://thingspeak.com/channels/1417.  Field 1 contains a string with
  the latest CheerLights color.
*/
unsigned long cheerLightsChannelNumber = 1417;

void setup() {
  #if defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_ESP8266)
    #ifdef ARDUINO_AVR_YUN
      Bridge.begin();
    #else
      #if defined(USE_WIFI_SHIELD) || defined(ARDUINO_ARCH_ESP8266)
         WiFi.begin(ssid, pass);
      #else
        Ethernet.begin(mac);
      #endif
    #endif
  #endif
  
  ThingSpeak.begin(client);

  #if defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_ESP8266)
      pinMode(pinRed,OUTPUT);
      pinMode(pinGreen,OUTPUT);
      pinMode(pinBlue,OUTPUT);
  #endif
}

void loop() {
  // Read the latest value from field 1 of channel 1417
  String color = ThingSpeak.readStringField(cheerLightsChannelNumber, 1);
  setColor(color);

  // Check again in 5 seconds
  delay(5000);
}

// List of CheerLights color names
String colorName[] = {"none","red","pink","green","blue","cyan","white","warmwhite","oldlace","purple","magenta","yellow","orange"};

// Map of RGB values for each of the Cheerlight color names
int colorRGB[][3] = {     0,  0,  0,  // "none"
                        255,  0,  0,  // "red"
                        255,192,203,  // "pink"
                          0,255,  0,  // "green"
                          0,  0,255,  // "blue"
                          0,255,255,  // "cyan",
                        255,255,255,  // "white",
                        255,223,223,  // "warmwhite",
                        255,223,223,  // "oldlace",
                        128,  0,128,  // "purple",
                        255,  0,255,  // "magenta",
                        255,255,  0,  // "yellow",
                        255,165,  0}; // "orange"};

void setColor(String color)
{
  // Look through the list of colors to find the one that was requested
  for(int iColor = 0; iColor <= 12; iColor++)
  {
    if(color == colorName[iColor])
    {
      // When it matches, look up the RGB values for that color in the table,
      // and write the red, green, and blue values.
      #if defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_ESP8266)
        analogWrite(pinRed,colorRGB[iColor][0]);
        analogWrite(pinGreen,colorRGB[iColor][1]);
        analogWrite(pinBlue,colorRGB[iColor][2]);
      #endif
      #ifdef SPARK
        RGB.control(true);
        RGB.color(colorRGB[iColor][0], colorRGB[iColor][1], colorRGB[iColor][2]);
      #endif
      return;
    }
  }
}

[/code]

Verifying this or trying to compile gives me the error, "exit status 1
'setColor' was not declared in this scope" or

Arduino: 1.6.7 (Windows 10), Board: "Generic ESP8266 Module, Serial, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck"

C:\Users\rytcd\AppData\Local\Temp\arduino_388e843c96865491b8f91c281d37585a\CheerLights.ino: In function 'void loop()':

CheerLights:107: error: 'setColor' was not declared in this scope

   setColor(color);

                 ^

exit status 1
'setColor' was not declared in this scope

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

I really appreciate your efforts and any help you can offer in this matter. Thanks a lot!

What version of the IDE are you using? You may need to move the setColor function definition BELOW the loop()

I am running 1.6.7. I tried simply cut/pasting the line just under the end of the void loop, but that did not compile either. There may be something glaringly obvious to programmers, but I am not one.

Thanks for the help :slight_smile:

Hmm,

I just upgraded to 1.6.7, installed the 1.1.1 version of the libraries, and built the cheerlights example for the Arduino UNO with no issues. So, seems like the fundamentals are working, but some configuration thing is not working for you. What board are you building for?

-Rob

Ahh, progress. Turns out it also works on my system for Arduino Uno, but I am trying to build for a esp8266.

still having the same problem. Anyone have an idea?

rytcd:
still having the same problem. Anyone have an idea?

There's a bug in 1.6.6 and 1.6.7 where automatic function prototype generation breaks for this sketch when compiled for esp8266. So you can either manually declare the function prototype by adding the line:

void setColor(String color);

to the top of the sketch or you can use the hourly build from www.arduino.cc/en/Main/Software#hourly which has the bug fixed.

rpurser:
Just an update here -- I found a bug in reading values from ThingSpeak, and have recently updated it to version 1.1.1.

-Rob

Even use version 1.1.1, I still cant read the value from THingspeak CHannel 30454, pls help me.

You'll need to tell me more about what you're doing, post some code, or ..... something

All the best,
-Rob

Below is the code that I use

/*
  ReadWeatherStation
  
  Reads the latest weather data every 60 seconds from the public MathWorks
  weather station in Natick, MA https://thingspeak.com/channels/12397 on ThingSpeak.
  
  ThingSpeak ( https://www.thingspeak.com ) is a free IoT service for prototyping
  systems that collect, analyze, and react to their environments.
  
  Copyright 2016, The MathWorks, Inc.
  
  Documentation for the ThingSpeak Communication Library for Arduino is in the extras/documentation folder where the library was installed.
  See the accompaning licence file for licensing information.
*/

#ifdef SPARK
	#include "ThingSpeak/ThingSpeak.h"
#else
	#include "ThingSpeak.h"
#endif

/// ***********************************************************************************************************
// This example selects the correct library to use based on the board selected under the Tools menu in the IDE.
// Yun, Wired Ethernet shield, wi-fi shield, esp8266, and Spark are all supported.
// With Uno and Mega, the default is that you're using a wired ethernet shield (http://www.arduino.cc/en/Main/ArduinoEthernetShield)
// If you're using a wi-fi shield (http://www.arduino.cc/en/Main/ArduinoWiFiShield), uncomment the line below
// ***********************************************************************************************************
//#define USE_WIFI_SHIELD
#ifdef ARDUINO_ARCH_AVR

  #ifdef ARDUINO_AVR_YUN
    #include "YunClient.h"
    YunClient client;
  #else

    #ifdef USE_WIFI_SHIELD
      #include <SPI.h>
      // ESP8266 USERS -- YOU MUST COMMENT OUT THE LINE BELOW.  There's a bug in the Arduino IDE that causes it to not respect #ifdef when it comes to #includes
      // If you get "multiple definition of `WiFi'" -- comment out the line below.
      #include <WiFi.h>
      char ssid[] = "<YOURNETWORK>";          //  your network SSID (name) 
      char pass[] = "<YOURPASSWORD>";   // your network password
      int status = WL_IDLE_STATUS;
      WiFiClient  client;
    #else
      // Use wired ethernet shield
      #include <SPI.h>
      #include <Ethernet.h>
      byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x06};
      EthernetClient client;
    #endif
  #endif
#endif

#ifdef ARDUINO_ARCH_ESP8266
  #include <ESP8266WiFi.h>
  char ssid[] = "<YOURNETWORK>";          //  your network SSID (name) 
  char pass[] = "<YOURPASSWORD>";   // your network password
  int status = WL_IDLE_STATUS;
  WiFiClient  client;
#endif

// On Particle Core, Photon, and Electron the results are published to the Particle dashboard using events.
// Go to http://dashboard.particle.io, click on the logs tab, and you'll see the events coming in. 
#ifdef SPARK
  TCPClient client;
#endif

/*
  This is the ThingSpeak channel number for the MathwWorks weather station
  https://thingspeak.com/channels/12397.  It senses a number of things and puts them in the eight
  field of the channel:
  Field 1 - Wind Direction (degrees where 0 is North)
  Field 2 - Wind Speed (MPH)
  Field 3 - Humidity (%RH)
  Field 4 - Temperature (Degrees F)
  Field 5 - Rainfall (inches since last measurement)
  Field 6 - Atmospheric Pressure (inHg)
*/
unsigned long weatherStationChannelNumber = 30454;

void setup() {
  #if defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_ESP8266)
    Serial.begin(9600);
    #ifdef ARDUINO_AVR_YUN
      Bridge.begin();
    #else
      #if defined(USE_WIFI_SHIELD) || defined(ARDUINO_ARCH_ESP8266)
        WiFi.begin(ssid, pass);
      #else
        Ethernet.begin(mac);
      #endif
    #endif
  #endif
  
  ThingSpeak.begin(client);
}

void loop() {
  float windDirection = ThingSpeak.readFloatField(weatherStationChannelNumber,1);
  float windSpeed = ThingSpeak.readFloatField(weatherStationChannelNumber,2);
  float humidity = ThingSpeak.readFloatField(weatherStationChannelNumber,3);
  float temperature = ThingSpeak.readFloatField(weatherStationChannelNumber,4);
  float rainfall = ThingSpeak.readFloatField(weatherStationChannelNumber,5);
  float pressure = ThingSpeak.readFloatField(weatherStationChannelNumber,6);

  #if defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_ESP8266)
    Serial.println("======================================"); 
    Serial.println("Current weather conditions in Natick: "); 
    Serial.print(temperature);
    Serial.print(" degrees F, "); 
    Serial.print(humidity);
    Serial.println("% humidity"); 
    Serial.print("Wind at ");
    Serial.print(windSpeed);
    Serial.print(" MPH at "); 
    Serial.print(windDirection);
    Serial.println(" degrees"); 
    Serial.print("Pressure is ");
    Serial.print(pressure);
    Serial.print(" inHg");
    if(rainfall > 0)
    {
    	Serial.print(", and it's raining"); 
    }
    Serial.println(); 
  #endif
  #ifdef SPARK
    Particle.publish("thingspeak-weather", "Current weather conditions in Natick: ",60,PRIVATE);
    Particle.publish("thingspeak-weather", String(temperature) + " degrees F, " + String(humidity) + "% humidity",60,PRIVATE); 
    Particle.publish("thingspeak-weather", "Wind at " + String(windSpeed) + " MPH at " + String (windDirection) + " degrees",60,PRIVATE); 
    if(rainfall > 0)
    {
      Particle.publish("thingspeak-weather", "Pressure is " + String(pressure) + " inHg, and it's raining",60,PRIVATE);
    }
    else
    {
      Particle.publish("thingspeak-weather", "Pressure is " + String(pressure) + " inHg",60,PRIVATE);
    }
  #endif

  delay(60000); // Note that the weather station only updates once a minute

}

I only read the value 0, in the Serial Monitor. It mean that it cant read the last value was on the website. pls help me

Hi,

What device are you using? Are you sure the device is successfully connecting to the internet? What's the error code you're getting from getLastReadStatus?

https://htmlpreview.github.io/?https://raw.githubusercontent.com/mathworks/thingspeak-arduino/master/extras/documentation/class_thing_speak_class.html#a549941b4b0000a2ba89de94f038ed577

-Rob

I use Uno & Ethernet 5100, in the Serial Monitor, I get value ======================================
Current weather conditions in Natick:
0.00 degrees F, 0.00% humidity
Wind at 0.00 MPH at 0.00 degrees
Pressure is 0.00 inHg

I dont receive any error code when getting from getLastReadStatus. IT can connect ok,because I can use it to upload data to Channel,but when I use it to get data from Channel, it only 0 value

about 2 weeks ago, I can get correct data from Channel, but now, it only 0 value

Sounds like it's not connecting to the wi-fi and/or internet. For clarity, the demo does no error checking on the calls to configure and connect ethernet and internet. You should investigate & confirm that before going further.

-Rob

With the same hardware, when I upload Write Muitiple value to channel, it upload ok, but When, I run Read Last value, it only show value :0. I cant check whether or not It connect to the internet with the sample sketch from Thingspeak Library.

When I check the Mac address of hardware at Network Watcher, I can find the Mac address & IP address of hardware, so I think the hardware connect Ok to the internet