ThingSpeak Communication Library for Arduino

repository·master·Indexed 19 days ago

https://github.com/mathworks/thingspeak-arduino

A library enabling Arduino, ESP8266, and ESP32 hardware to interact with the ThingSpeak IoT platform. It supports data logging via writeField() and writeFields(), data retrieval using read*Field methods, and raw POST/GET requests via writeRaw() and readRaw(). The library includes support for SSL secure connections through the TS_ENABLE_SSL macro and provides utilities for managing channel metadata such as status, location, and timestamps.

Tokens
4.2K
Snippets
16
Records
18
Agent score
17%

What's inside ThingSpeak Communication Library

  1. Enable HTTPS secure connections

    master

    To ensure confidentiality (SSL encryption) and authenticity (verifying the server), you must enable SSL.

    Requirement: You must define the TS_ENABLE_SSL macro before including the library header.

    If TS_ENABLE_SSL is defined but the client hardware cannot perform SSL, the library will fall back to a standard HTTP connection and issue a warning. If TS_ENABLE_SSL is undefined, the library will attempt an error connection if the client is SSL-capable, or a standard HTTP connection if it is not.

    #define TS_ENABLE_SSL
    #include <thingspeak.h>
  2. Install the ThingSpeak Library

    master

    You can install the ThingSpeak library in the Arduino IDE using two methods:

    Method 1: Library Manager (Recommended)

    1. Open the Arduino IDE.
    2. Navigate to Sketch > Include Library > Manage Libraries.
    3. Search for "ThingSpeak Library".
    4. Click Install.

    Method 2: Manual ZIP Installation

    1. Download the library ZIP file to your computer.
    2. In the Arduino IDE, navigate to Sketch > Include Library > Add .ZIP Library.
    3. Select the downloaded ZIP file and click Open.
  3. Typical Write Example (ESP8266)

    master

    This example demonstrates how to connect an ESP8266 to WiFi and write an incrementing integer to a specific field in a ThingSpeak channel every 20 seconds.

    #include <ESP8266WiFi.h>
    #include "secrets.h"
    #include "ThingSpeak.h"
    
    char ssid[] = SECRET_SSID;
    char pass[] = SECRET_PASS;
    WiFiClient  client;
    
    unsigned long myChannelNumber = SECRET_CH_ID;
    const char * myWriteAPIKey = SECRET_WRITE_APIKEY;
    
    int number = 0;
    
    void setup() {
      Serial.begin(115200);
      WiFi.mode(WIFI_STA); 
      ThingSpeak.begin(client);
    }
    
    void loop() {
      if(WiFi.status() != WL_CONNECTED){
        WiFi.begin(ssid, pass);
        while(WiFi.status() != WL_CONNECTED){
          delay(5000);
        }
      }
      
      int x = ThingSpeak.writeField(myChannelNumber, 1, number, myWriteAPIKey);
      if(x == 200){
        Serial.println("Channel update successful.");
      } else {
        Serial.println("Problem updating channel. HTTP error code " + String(x));
      }
    
      number++;
      if(number > 99) number = 0;
      delay(20000);
    }
  4. Typical Read Example (ESP8266)

    master

    This example demonstrates reading from both a public channel (using field number) and a private channel (requiring a Read API Key) using an ESP8266.

    #include <ESP8266WiFi.h>
    #include "secrets.h"
    #include "ThingSpeak.h"
    
    char ssid[] = SECRET_SSID;
    char pass[] = SECRET_PASS;
    WiFiClient  client;
    
    unsigned long weatherStationChannelNumber = SECRET_CH_ID_WEATHER_STATION;
    unsigned int temperatureFieldNumber = 4;
    
    unsigned long counterChannelNumber = SECRET_CH_ID_COUNTER;
    const char * myCounterReadAPIKey = SECRET_READ_APIKEY_COUNTER;
    unsigned int counterFieldNumber = 1; 
    
    void setup() {
      Serial.begin(115200);
      WiFi.mode(WIFI_STA); 
      ThingSpeak.begin(client);
    }
    
    void loop() {
      if(WiFi.status() != WL_CONNECTED){
        WiFi.begin(ssid, pass);
        while(WiFi.status() != WL_CONNECTED){
          delay(5000);
        }
      }
    
      // Read public channel
      float temperatureInF = ThingSpeak.readFloatField(weatherStationChannelNumber, temperatureFieldNumber);
      if(ThingSpeak.getLastReadStatus() == 200){
        Serial.println("Temperature: " + String(temperatureInF));
      }
      
      delay(15000);
    
      // Read private channel
      long count = ThingSpeak.readLongField(counterChannelNumber, counterFieldNumber, myCounterReadAPIKey);
      if(ThingSpeak.getLastReadStatus() == 200){
        Serial.println("Counter: " + String(count));
      }
      
      delay(15000);
    }
  5. Read data from a ThingSpeak channel

    master

    Use the read*Field methods to retrieve the latest data from a specific field in a channel. For private channels, you must provide the readAPIKey.

    Return Values & Behavior:

    • readStringField(): Returns the value as a String. Returns an empty string on error.
    • readFloatField(): Returns a float. Returns 0 if the field is text or an error occurs. Note that NAN, INFINITY, and -INFINITY are valid results. Use getLastReadStatus() for error details.
    • readLongField(): Returns a long. Returns 0 if the field is text or an error occurs.
    • readIntField(): Returns an int. Returns 0 if the field is text or an error occurs. If the value is out of range for an int, the result is undefined.
    • readStatus(): Returns the channel status as a String.
    • readCreatedAt(): Returns the latest update's timestamp as a String.
    String readStringField (channelNumber, field, readAPIKey)
    float readFloatField (channelNumber, field, readAPIKey)
    long readLongField (channelNumber, field, readAPIKey)
    int readIntField (channelNumber, field, readAPIKey)
    String readStatus (channelNumber, readAPIKey)
    String readCreatedAt (channelNumber, readAPIKey)
  6. Retrieve stored field values with getField*

    master

    After calling readMultipleFields(), use these functions to fetch the locally stored values for a specific field (1-8).

    Note: These functions are not available on Arduino Uno due to memory constraints.

    • getFieldAsString(field): Returns the value as a String. Returns an empty string on error.
    • getFieldAsFloat(field): Returns the value as a float. Returns 0 if the field is text or an error occurs. Note that NAN, INFINITY, and -INFINITY are valid results.
    • getFieldAsLong(field): Returns the value as a long. Returns 0 on error.
    • getFieldAsInt(field): Returns the value as an int. Returns 0 on error.

    If called before readMultipleFields(), these functions return the previously read (old) value.

    // Example workflow
    int status = readMultipleFields(myChannel, myKey);
    if (status == 200) {
        float val = getFieldAsFloat(1);
        int valInt = getFieldAsInt(2);
        String valStr = getFieldAsString(3);
    }
  7. Set field values for multi-field updates with setField()

    master

    The setField() method prepares a single field to be part of a multi-field update. You can call this multiple times with different field numbers to batch updates.

    Supported Types and Limits:

    • int: -32,768 to 32,767
    • long: -2,147,483,648 to 2,147,483,647
    • float: -999,999,000,000 to 999,999,000,000
    • String / const char *: UTF8 string, limited to 255 bytes.

    Returns HTTP status code 200 if successful.

    int setField (field, value)
  8. Read multiple fields using readMultipleFields()

    master

    The readMultipleFields() function fetches the latest fields, status, location, and created-at timestamp from a channel and stores them locally in the device memory. After calling this, you can use getField* functions to retrieve specific values.

    Note: This feature is not available on Arduino Uno due to memory constraints.

    // For public channels
    int status = readMultipleFields(channelNumber);
    
    // For private channels
    int status = readMultipleFields(channelNumber, readAPIKey);
  9. Write a single value to a field with writeField()

    master

    Use writeField() to send a single piece of data to a specific field in a ThingSpeak channel.

    Signature: int writeField(channelNumber, field, value, writeAPIKey)

    Parameters:

    • channelNumber (unsigned long): The ID of your ThingSpeak channel.
    • field (unsigned int): The field number (1-8) within the channel.
    • value: The data to write. Supported types:
      • int (-32,768 to 32,767)
      • long (-2,147,483,648 to 2,147,483,647)
      • float (-999,999,000,000 to 999,999,000,000)
      • String or const char * (UTF8 string, max 255 bytes)
    • writeAPIKey (const char *): The Write API Key for your channel.

    Returns:

    • Returns the HTTP status code. A value of 200 indicates success.
    // Example: Writing an integer to field 1
    int x = ThingSpeak.writeField(myChannelNumber, 1, number, myWriteAPIKey);
    if(x == 200) {
      Serial.println("Channel update successful.");
    }
  10. Check the status of the last read operation

    master

    Use getLastReadStatus() to retrieve the HTTP status code or error code from the most recent read attempt. This is useful for debugging failed requests or checking if a field was successfully updated.

    int status = getLastReadStatus();
  11. Write a raw POST to a ThingSpeak channel with writeRaw()

    master

    Use writeRaw() to send a raw POST request to ThingSpeak. This is useful for sending custom URL-encoded messages.

    Important: This method does not automatically encode special characters. You must manually use %XX URL encoding for any special characters in your postMessage.

    Returns HTTP status code 200 if successful.

    int writeRaw (channelNumber, postMessage, writeAPIKey)
  12. Read a raw response using readRaw()

    master

    Use readRaw() to fetch a raw response from a ThingSpeak channel as a String. This is useful for custom URL requests. If the channel is private, you must include the readAPIKey.

    // For public channels
    String response = readRaw(channelNumber, URLSuffix);
    
    // For private channels
    String response = readRaw(channelNumber, URLSuffix, readAPIKey);