Giter VIP home page Giter VIP logo

thingspeak-arduino's Introduction

ThingSpeak Communication Library for Arduino, ESP8266 and ESP32

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 MATLAB analytics and visualization.

Hardware specific examples are found here. But to give you an idea of usage examples for writing and reading with an ESP8266 are shown below. Complete documentation in also shown below.

ThingSpeak offers free data storage and analysis of time-stamped numeric or alphanumeric data. Users can access ThingSpeak by visiting http://thingspeak.com and creating a ThingSpeak user account.

ThingSpeak stores data in channels. Channels support an unlimited number of timestamped observations (think of these as rows in a spreadsheet). Each channel has up to 8 fields (think of these as columns in a speadsheet). Check out this video for an overview.

Channels may be public, where anyone can see the data, or private, where only the owner and select users can read the data. Each channel has an associated Write API Key that is used to control who can write to a channel. In addition, private channels have one or more Read API Keys to control who can read from private channel. An API Key is not required to read from public channels. Each channel can have up to 8 fields. One field is created by default.

You can visualize and do online analytics of your data on ThingSpeak using the built in version of MATLAB, or use the desktop version of MATLAB to get deeper historical insight. Visit https://www.mathworks.com/hardware-support/thingspeak.html to learn more.

Libraries and examples for Particle devices can be found here: https://github.com/mathworks/thingspeak-particle

Installation

In the Arduino IDE, choose Sketch/Include Library/Manage Libraries. Click the ThingSpeak Library from the list, and click the Install button.

--- or ---

  1. Download the ZIP file (below) to your machine.
  2. In the Arduino IDE, choose Sketch/Include Library/Add Zip Library
  3. Navigate to the ZIP file, and click Open

Compatible Hardware:

  • Arduino/Genuino or compatible using a WiFi Shield
  • Arduino/Genuino or compatible using a WiFi Shield 101 (Use the WiFi101 library version 0.13.0 or older.)
  • Arduino/Genuino or compatible using an Ethernet Shield
  • Arduino/Genuino or compatible using a MKR ETH Shield
  • Arduino MKR1000
  • Arduino MKR1010
  • Arduino VIDOR 4000
  • Arduino GSM 14000
  • Arduino Uno WiFi Rev2
  • Arduino Yún (Rev1 and Rev2)
  • ESP8266 programming directly (tested with SparkFun ESP8266 Thing - Dev Board and NodeMCU 1.0 module)
  • ESP8266 via AT commands
  • ESP32 (tested with SparkFun ESP32 Thing)

Examples

The library includes several examples organized by board type to help you get started. These are accessible in Examples > ThingSpeak menu of the Arduino IDE.

  • ReadField: Reading from a public channel and a private channel on ThingSpeak.
  • WriteSingleField: Writing a value to a single field on ThingSpeak.
  • WriteMultipleFields: Writing values to multiple fields and status in one transaction with ThingSpeak.
  • ReadMultipleFields: Reading values from multiple fields, status, location, created-at timestamp from a public channel on ThingSpeak
  • SecureConnect: Using the above features and connecting securely to ThingSpeak.

In this case, write to a field with an ESP8266 with an incrementing number.

#include <ESP8266WiFi.h>
#include "secrets.h"
#include "ThingSpeak.h" // always include thingspeak header file after other header files and custom macros

char ssid[] = SECRET_SSID;   // your network SSID (name) 
char pass[] = SECRET_PASS;   // your network password
int keyIndex = 0;            // your network key Index number (needed only for WEP)
WiFiClient  client;

unsigned long myChannelNumber = SECRET_CH_ID;
const char * myWriteAPIKey = SECRET_WRITE_APIKEY;

int number = 0;

void setup() {
  Serial.begin(115200);  // Initialize serial
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  
  WiFi.mode(WIFI_STA); 
  ThingSpeak.begin(client);  // Initialize ThingSpeak
}

void loop() {

  // Connect or reconnect to WiFi
  if(WiFi.status() != WL_CONNECTED){
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(SECRET_SSID);
    while(WiFi.status() != WL_CONNECTED){
      WiFi.begin(ssid, pass);  // Connect to WPA/WPA2 network. Change this line if using open or WEP network
      Serial.print(".");
      delay(5000);     
    } 
    Serial.println("\nConnected.");
  }
  
  // Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different
  // pieces of information in a channel.  Here, we write to field 1.
  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));
  }

  // change the value
  number++;
  if(number > 99){
    number = 0;
  }
  
  delay(20000); // Wait 20 seconds to update the channel again
}

In this case, read from a public channel and a private channel with an ESP8266. The public channel is the temperature(F) at MathWorks headquarters. The private channel is a counter that increments.

#include <ESP8266WiFi.h>
#include "secrets.h"
#include "ThingSpeak.h" // always include thingspeak header file after other header files and custom macros

char ssid[] = SECRET_SSID;   // your network SSID (name) 
char pass[] = SECRET_PASS;   // your network password
int keyIndex = 0;            // your network key Index number (needed only for WEP)
WiFiClient  client;

// Weather station channel details
unsigned long weatherStationChannelNumber = SECRET_CH_ID_WEATHER_STATION;
unsigned int temperatureFieldNumber = 4;

// Counting channel details
unsigned long counterChannelNumber = SECRET_CH_ID_COUNTER;
const char * myCounterReadAPIKey = SECRET_READ_APIKEY_COUNTER;
unsigned int counterFieldNumber = 1; 

void setup() {
 Serial.begin(115200);  // Initialize serial
 while (!Serial) {
   ; // wait for serial port to connect. Needed for native USB port only
 }
 
 WiFi.mode(WIFI_STA); 
 ThingSpeak.begin(client);  // Initialize ThingSpeak
}

void loop() {

 int statusCode = 0;
 
 // Connect or reconnect to WiFi
 if(WiFi.status() != WL_CONNECTED){
   Serial.print("Attempting to connect to SSID: ");
   Serial.println(SECRET_SSID);
   while(WiFi.status() != WL_CONNECTED){
     WiFi.begin(ssid, pass); // Connect to WPA/WPA2 network. Change this line if using open or WEP network
     Serial.print(".");
     delay(5000);     
   } 
   Serial.println("\nConnected");
 }

 // Read in field 4 of the public channel recording the temperature
 float temperatureInF = ThingSpeak.readFloatField(weatherStationChannelNumber, temperatureFieldNumber);  

 // Check the status of the read operation to see if it was successful
 statusCode = ThingSpeak.getLastReadStatus();
 if(statusCode == 200){
   Serial.println("Temperature at MathWorks HQ: " + String(temperatureInF) + " deg F");
 }
 else{
   Serial.println("Problem reading channel. HTTP error code " + String(statusCode)); 
 }
 
 delay(15000); // No need to read the temperature too often.

 // Read in field 1 of the private channel which is a counter  
 long count = ThingSpeak.readLongField(counterChannelNumber, counterFieldNumber, myCounterReadAPIKey);  

  // Check the status of the read operation to see if it was successful
 statusCode = ThingSpeak.getLastReadStatus();
 if(statusCode == 200){
   Serial.println("Counter: " + String(count));
 }
 else{
   Serial.println("Problem reading channel. HTTP error code " + String(statusCode)); 
 }
 
 delay(15000); // No need to read the counter too often.
 
}

begin

Initializes the ThingSpeak library and network settings, whether performing a secure connection or a normal connection to ThingSpeak.

bool begin (client) // defaults to ThingSpeak.com
Parameter Type Description
client Client & TCPClient created earlier in the sketch

Returns

Always returns true. This does not validate the information passed in, or generate any calls to ThingSpeak.

Remarks

use #define TS_ENABLE_SSL before #include <thingspeak.h> so as to perform a secure connection by passing a client that is capable of doing SSL. See the note regarding secure connection below.

writeField

Write a value to a single field in a ThingSpeak channel.

int writeField(channelNumber, field, value, writeAPIKey)
Parameter Type Description
channelNumber unsigned long Channel number
field unsigned int Field number (1-8) within the channel to write to.
value int Integer value (from -32,768 to 32,767) to write.
long Long value (from -2,147,483,648 to 2,147,483,647) to write.
float Floating point value (from -999999000000 to 999999000000) to write.
String String to write (UTF8 string). ThingSpeak limits this field to 255 bytes.
const char * Character array (zero terminated) to write (UTF8). ThingSpeak limits this field to 255 bytes.
writeAPIKey const char * Write API key associated with the channel. If you share code with others, do not share this key

Returns

HTTP status code of 200 if successful. See Return Codes below for other possible return values.

Remarks

Special characters will be automatically encoded by this method. See the note regarding special characters below.

writeFields

Write a multi-field update. Call setField() for each of the fields you want to write first.

int writeFields (channelNumber, writeAPIKey)	
Parameter Type Description
channelNumber unsigned long Channel number
writeAPIKey const char * Write API key associated with the channel. If you share code with others, do not share this key

Returns

HTTP status code of 200 if successful. See Return Codes below for other possible return values.

Remarks

Special characters will be automatically encoded by this method. See the note regarding special characters below.

writeRaw

Write a raw POST to a ThingSpeak channel.

int writeRaw (channelNumber, postMessage, writeAPIKey)	
Parameter Type Description
channelNumber unsigned long Channel number
postMessage const char * Raw URL to write to ThingSpeak as a String. See the documentation at https://thingspeak.com/docs/channels#update_feed.
String Raw URL to write to ThingSpeak as a character array (zero terminated). See the documentation at https://thingspeak.com/docs/channels#update_feed.
writeAPIKey const char * Write API key associated with the channel. If you share code with others, do not share this key

Returns

HTTP status code of 200 if successful. See Return Codes below for other possible return values.

Remarks

This method will not encode special characters in the post message. Use '%XX' URL encoding to send special characters. See the note regarding special characters below.

setField

Set the value of a single field that will be part of a multi-field update.

int setField (field, value)
Parameter Type Description
field unsigned int Field number (1-8) within the channel to set
value int Integer value (from -32,768 to 32,767) to write.
long Long value (from -2,147,483,648 to 2,147,483,647) to write.
float Floating point value (from -999999000000 to 999999000000) to write.
String String to write (UTF8 string). ThingSpeak limits this field to 255 bytes.
const char * Character array (zero terminated) to write (UTF8). ThingSpeak limits this field to 255 bytes.

Returns

HTTP status code of 200 if successful. See Return Codes below for other possible return values.

setStatus

Set the status of a multi-field update. Use status to provide additonal details when writing a channel update. Additionally, status can be used by the ThingTweet App to send a message to Twitter.

int setStatus (status)	
Parameter Type Description
status const char * String to write (UTF8). ThingSpeak limits this to 255 bytes.
String const character array (zero terminated). ThingSpeak limits this to 255 bytes.

Returns

HTTP status code of 200 if successful. See Return Codes below for other possible return values.

setLatitude

Set the latitude of a multi-field update.

int setLatitude	(latitude)	
Parameter Type Description
latitude float Latitude of the measurement (degrees N, use negative values for degrees S)

Returns

HTTP status code of 200 if successful. See Return Codes below for other possible return values.

setLongitude

Set the longitude of a multi-field update.

int setLongitude (longitude)	
Parameter Type Description
longitude float Longitude of the measurement (degrees E, use negative values for degrees W)

Returns

HTTP status code of 200 if successful. See Return Codes below for other possible return values.

setElevation

Set the elevation of a multi-field update.

int setElevation (elevation)	
Parameter Type Description
elevation float Elevation of the measurement (meters above sea level)

Returns

HTTP status code of 200 if successful. See Return Codes below for other possible return values.

setCreatedAt

Set the created-at date of a multi-field update. The timestamp string must be in the ISO 8601 format. Example "2017-01-12 13:22:54"

int setCreatedAt (createdAt)
Parameter Type Description
createdAt String Desired timestamp to be included with the channel update as a String.
const char * Desired timestamp to be included with the channel update as a character array (zero terminated).

Returns

HTTP status code of 200 if successful. See Return Codes below for other possible return values.

Remarks

Timezones can be set using the timezone hour offset parameter. For example, a timestamp for Eastern Standard Time is: "2017-01-12 13:22:54-05". If no timezone hour offset parameter is used, UTC time is assumed.

setTwitterTweet

Set the Twitter account and message to use for an update to be tweeted.

int setTwitterTweet	(twitter, tweet)	
Parameter Type Description
twitter String Twitter account name as a String.
const char * Twitter account name as a character array (zero terminated).
tweet String Twitter message as a String (UTF-8) limited to 140 character.
const char * Twitter message as a character array (zero terminated) limited to 140 character.

Returns

HTTP status code of 200 if successful. See Return Codes below for other possible return values.

Remarks

Prior to using this feature, a twitter account must be linked to your ThingSpeak account. To link your twitter account. login to ThingSpeak and go to Apps -> ThingTweet and click Link Twitter Account.

readStringField

Read the latest string from a channel. Include the readAPIKey to read a private channel.

String readStringField (channelNumber, field, readAPIKey)	
String readStringField (channelNumber, field)	
Parameter Type Description
channelNumber unsigned long Channel number
field unsigned int Field number (1-8) within the channel to read from.
readAPIKey const char * Read API key associated with the channel. If you share code with others, do not share this key

Returns

Value read (UTF8 string), or empty string if there is an error.

readFloatField

Read the latest float from a channel. Include the readAPIKey to read a private channel.

float readFloatField (channelNumber, field, readAPIKey)	
float readFloatField (channelNumber, field)	
Parameter Type Description
channelNumber unsigned long Channel number
field unsigned int Field number (1-8) within the channel to read from.
readAPIKey const char * Read API key associated with the channel. If you share code with others, do not share this key

Returns

Value read, or 0 if the field is text or there is an error. Use getLastReadStatus() to get more specific information. Note that NAN, INFINITY, and -INFINITY are valid results.

readLongField

Read the latest long from a channel. Include the readAPIKey to read a private channel.

long readLongField (channelNumber, field, readAPIKey)	
long readLongField (channelNumber, field)	
Parameter Type Description
channelNumber unsigned long Channel number
field unsigned int Field number (1-8) within the channel to read from.
readAPIKey const char * Read API key associated with the channel. If you share code with others, do not share this key

Returns

Value read, or 0 if the field is text or there is an error. Use getLastReadStatus() to get more specific information.

readIntField

Read the latest int from a channel. Include the readAPIKey to read a private channel.

int readIntField (channelNumber, field, readAPIKey)		
int readIntField (channelNumber, field)		
Parameter Type Description
channelNumber unsigned long Channel number
field unsigned int Field number (1-8) within the channel to read from.
readAPIKey const char * Read API key associated with the channel. If you share code with others, do not share this key

Returns

Value read, or 0 if the field is text or there is an error. Use getLastReadStatus() to get more specific information. If the value returned is out of range for an int, the result is undefined.

readStatus

Read the latest status from a channel. Include the readAPIKey to read a private channel.

String readStatus (channelNumber, readAPIKey)	
String readStatus (channelNumber)
Parameter Type Description
channelNumber unsigned long Channel number
readAPIKey const char * Read API key associated with the channel. If you share code with others, do not share this key

Returns

Returns the status field as a String.

String readCreatedAt()

Read the created-at timestamp associated with the latest update to a channel. Include the readAPIKey to read a private channel.

String readCreatedAt (channelNumber, readAPIKey)
String readCreatedAt (channelNumber)	
Parameter Type Description
channelNumber unsigned long Channel number
readAPIKey const char * Read API key associated with the channel. If you share code with others, do not share this key

Returns

Returns the created-at timestamp as a String.

readRaw

Read a raw response from a channel. Include the readAPIKey to read a private channel.

String readRaw (channelNumber, URLSuffix, readAPIKey)	
String readRaw	(channelNumber, URLSuffix)
Parameter Type Description
channelNumber unsigned long Channel number
URLSuffix String Raw URL to write to ThingSpeak as a String. See the documentation at https://thingspeak.com/docs/channels#get_feed
readAPIKey const char * Read API key associated with the channel. If you share code with others, do not share this key.

Returns

Returns the raw response from a HTTP request as a String.

readMultipleFields

Read all the latest fields, status, location, and created-at timestamp; and store these values locally. Use getField functions mentioned below to fetch the stored values. Include the readAPIKey to read a private channel.

int readMultipleFields (channelNumber, readAPIKey)
int readMultipleFields (channelNumber)
Parameter Type Description
channelNumber unsigned long Channel number
readAPIKey const char * Read API key associated with the channel. If you share code with others, do not share this key

Returns

HTTP status code of 200 if successful. See Return Codes below for other possible return values.

Remarks

This feature not available in Arduino Uno due to memory constraints.

getFieldAsString

Fetch the stored value from a field as String. Invoke this after invoking readMultipleFields.

String getFieldAsString (field)
Parameter Type Description
field unsigned int Field number (1-8) within the channel to read from.

Returns

Value read (UTF8 string), empty string if there is an error, or old value read (UTF8 string) if invoked before readMultipleFields(). Use getLastReadStatus() to get more specific information.

Remarks

This feature not available in Arduino Uno due to memory constraints.

getFieldAsFloat

Fetch the stored value from a field as Float. Invoke this after invoking readMultipleFields.

float getFieldAsFloat (field)
Parameter Type Description
field unsigned int Field number (1-8) within the channel to read from.

Returns

Value read, 0 if the field is text or there is an error, or old value read if invoked before readMultipleFields(). Use getLastReadStatus() to get more specific information. Note that NAN, INFINITY, and -INFINITY are valid results.

Remarks

This feature not available in Arduino Uno due to memory constraints.

getFieldAsLong

Fetch the stored value from a field as Long. Invoke this after invoking readMultipleFields.

long getFieldAsLong (field)
Parameter Type Description
field unsigned int Field number (1-8) within the channel to read from.

Returns

Value read, 0 if the field is text or there is an error, or old value read if invoked before readMultipleFields(). Use getLastReadStatus() to get more specific information.

Remarks

This feature not available in Arduino Uno due to memory constraints.

getFieldAsInt

Fetch the stored value from a field as Int. Invoke this after invoking readMultipleFields.

int getFieldAsInt (field)
Parameter Type Description
field unsigned int Field number (1-8) within the channel to read from.

Returns

Value read, 0 if the field is text or there is an error, or old value read if invoked before readMultipleFields(). Use getLastReadStatus() to get more specific information.

Remarks

This feature not available in Arduino Uno due to memory constraints.

getLastReadStatus

Get the status of the previous read.

int getLastReadStatus ()	

Returns

See Return Codes below for other possible return values.

Return Codes

Value Meaning
200 OK / Success
404 Incorrect API key (or invalid ThingSpeak server address)
-101 Value is out of range or string is too long (> 255 characters)
-201 Invalid field number specified
-210 setField() was not called before writeFields()
-301 Failed to connect to ThingSpeak
-302 Unexpected failure during write to ThingSpeak
-303 Unable to parse response
-304 Timeout waiting for server to respond
-401 Point was not inserted (most probable cause is the rate limit of once every 15 seconds)
0 Other error

Secure Connection

Securely connect to ThingSpeak API to use the above features and functionalities.

HTTPS

HTTPS ensures confidentiality as well as authenticity. Confidentiality: SSL Encryption using public-key cryptography. Authenticity: creates "trust", the device knows whether it's connected to the actual api.thingkspeak.com and not a spoof of it.

User Sketch Requirements

Always use #define TS_ENABLE_SSL before #include <thingspeak.h> so as to perform a secure connection. If not, then the default connection would be insecured HTTP.

Confidentiality without Authenticity

Case 1: TS_ENABLE_SSL macro defined + Client capable of doing SSL = Secure HTTPS Connection
Case 2: TS_ENABLE_SSL macro defined + Client not capable of SSL = Defualt HTTP connection with a warning message sent to the user
Case 3: TS_ENABLE_SSL macro undefined + Client capable of doing SSL = Error connecting to ThingSpeak status code returned to user
Case 4: TS_ENABLE_SSL macro undefined + Client not capable of SSL = HTTP connection

Confidentiality + Authenticity

Different client libraries have different methods of performing authenticity.
Some ways: Root Certificate Check, Certificate Fingerprint Check.
Perform the fingerprint and/or certificate check prior to invoking the begin() function.
The certificate has an expiration date associated with it, and hence it's the user's responsibility to fetch the updated certificate for the Confidentiality + Authenticity HTTPS connection to be established.
See the ReadMultipleFieldsSecure example on Fingerprint check HTTPS connection using ESP8266. See the ReadMultipleFieldsSecure example on Root Certificate check HTTPS connection using ESP32.

Special Characters

Some characters require '%XX' style URL encoding before sending to ThingSpeak. The writeField() and writeFields() methods will perform the encoding automatically. The writeRaw() method will not.

Character Encoding
" %22
% %25
& %26
+ %2B
; %3B

Control characters, ASCII values 0 though 31, are not accepted by ThingSpeak and will be ignored. Extended ASCII characters with values above 127 will also be ignored.

thingspeak-arduino's People

Contributors

afan31 avatar jasontwinters avatar jpkmw avatar rpurser47 avatar v-c avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

thingspeak-arduino's Issues

DFrobot Wifi Bee

Hi there, this ESP8266 module connects throught a shield on UNO using serrial 0 and 1 pins.
Thingspeak library does not work with this module... coudl you check and advice?
Thanks

WriteField and float

Hi,

I'am trying to send float value to ThingSpeak server. After reading the code, it seems that the float value is converted to char *.
However, it does not seems to be sent correctly to ThingSpeak server( '?' value is sent, which is not correct )

The issue is directly reproductible with your tests

ts::writeField (channelNumber: 31461 writeAPIKey: AFAKEAPIKEYFAKEX field: 1 value: 1.00000)
ts::writeField (channelNumber: 31461 writeAPIKey: AFAKEAPIKEYFAKEX field: 1 value: "?")
ts::writeRaw   (channelNumber: 31461 writeAPIKey: AFAKEAPIKEYFAKEX postMessage: "field1=?")
               Connect to default ThingSpeak URL...Success.
               POST "field1=?&headers=false

WriteMultipleVoltages example on Arduino

I am having trouble sending multiple values to thingspeak so I tried sample code but its not working either. I enabled PRINT_DEBUG_MESSAGES from ThingSpeak.h file then realized something weird.
If I send 4 field values it is ok but after 4 fields POST becomes empty:

ts::tsBegints::setServer (default)ts::setField (field: 1 value: "1.68622")
ts::setField (field: 2 value: "0.56696")
ts::setField (field: 3 value: "0.75269")
ts::setField (field: 4 value: "0.86510")
ts::writeRaw (channelNumber: 31461 writeAPIKey: LD79EOAAWRVYF04Y postMessage: "field1=1.68622&field2=0.56696&field3=0.75269&field4=0.86510")
Connect to default ThingSpeak URL...Success.
POST "field1=1.68622&field2=0.56696&field3=0.75269&field4=0.86510&headers=false"
Entry ID "8885" (8885)
disconnected.

ts::tsBegints::setServer (default)ts::setField (field: 1 value: "1.68622")
ts::setField (field: 2 value: "0.56696")
ts::setField (field: 3 value: "0.75758")
ts::setField (field: 4 value: "0.86510")
ts::setField (field: 5 value: "1.28543")
ts::writeRaw (channelNumber: 31461 writeAPIKey: LD79EOAAWRVYF04Y postMessage: "field1=1.68622&field2=0.56696&field3=0.75758&field4=0.86510&field5=1.28543")
Connect to default ThingSpeak URL...Success.
POST ""
Entry ID "8883" (8883)
disconnected.

"client" isn´t declared on the scope

I´m trying to use thingspeak with a NODEMCU from Lolin, and every time i try to compile the program i receive the error 'client' was not declared in this scope pointing to the ThingSpeak.begin(client); inside the setup() session.

ThingSpeak.h writeRaw() shows HTTP error code 302

I couldn't get the esp32's WriteMultipleFields example to work until I adjusted ThingSpeak.h. Until then it was giving:

Problem updating channel. HTTP error code 302

As a workaround, I added an additional line to my copy of ThingSpeak.h's writeRaw()

		// Post data to thingspeak
		if(!this->client->print("POST /update HTTP/1.1\r\n")) return abortWriteRaw();
		if(!writeHTTPHeader(writeAPIKey)) return abortWriteRaw();
		if(!this->client->print("Content-Type: application/x-www-form-urlencoded\r\n")) return abortWriteRaw();
		if(!this->client->print("Content-Length: ")) return abortWriteRaw();
		if(!this->client->print(postMessage.length())) return abortWriteRaw();
		if(!this->client->print("\r\n\r\n")) return abortWriteRaw();
		if(!this->client->print(postMessage)) return abortWriteRaw();
		if(!this->client->print("\r\n")) return abortWriteRaw();  //possible fix?

I'm too new at this to say whether it's a needed fix or if it's a usage error.

[solved] Reading float from ThingSpeak with ESP8266 takes long time

Hello,

i'm using your library with my DIY-Weatherstation.
The outside station sends every ten minutes temperature, humidity and pressure to ThingSpeak and after that it goes to deepsleep.
The inside station messures the inside temperature and the humidity and fetch the outside data from ThingSpeak to show it on an 2.4" TFT-screen. Both stations use a Wemos D1 Mini Pro (feat. ESP8266)

If i'm using the ThingSpeak library it takes about five seconds to get the temperature, humidity and pressure as float from TS. That's not good, because in this five seconds my display and the rest of the ESP8266 is doing nothing. I'm receiving the time from an NTP server and print it also on the display, and so the time stands still for five seconds and then proceed.

What i tested so far: I tried the example-sketch provided by the library and set the delay to one second (instead of 15 in the example). It took also about five seconds for the data to be shown on the serial monitor. So i think my code ist OK.

Is there a way to get the data faster?

My code of getting the data is:

float TS_Temp = ThingSpeak.readFloatField( ChannelID, 1, APIREADKEY);

I hope you can help me and now what i mean. Sorry for my bad English. I'm from Germany and my English is a little bit rusty.

Regards
Johnny

Set and sending fields doesn't work.

I'm trying to send multiple fields to my channel, but it is failing.
Using
ThingSpeak.setField(1,my1Value); ThingSpeak.setField(2,my2Value); ThingSpeak.writeFields(myChannel,myWriteAPI);
Could you review the code if it matches the latest API, please?

Does not work with WifiSSLClient

The library does not work with SSL connections.
I uploaded the certificate to the Wifi module but got error 301
In the end, I had to go into Thingspeak.h to change the port from 80 to 443
Would be good if there is a option to set the mode between HTTP and HTTPS

time-to-upload data too much

I've noticed ThingSpeak.writeField() function takes around 7-10 seconds for publishing data to channel, while if we use simple HTTPClient, it takes only 1-2 seconds on same network and same channel.

Confirm Upload example needed

Can someone please add upload confirmation to the writeFields() example? I have a counter that needs to clear when the upload is successful. Something like char error = ThingSpeak.writeFields() ); if (error = 200), count= 0; serial.print(error) Im not good at reading the .h files to understand what is returned.
Thanks for your help.

Getting response and entry key

Hi

I am working with your libraary and I am very happy. Good job.

sorry for raising this as an issue.

Maybe it is only for information.

DId not understand how to get the response and entry key after Thingspeak.writeFields.

Thanks for an example.

Cheers.

Method to clear a channel

For a project of mine I need to clear the data of a channel every time a sketch start. Can you implement a method in your library to achieve this results ?

Support for the new Arduino Uno Wifi board ?

Would it be possible for you to add support for the new Arduino Uno Wifi board? It supports writing to a ThingSpeak channel with the Ciao library, however, the Ciao library adds so much overhead that my sketch for a temp controller for a beer fermenter (details here) runs out of SRAM at run time.

I'm hoping that this would be a fairly easy addition to the library.

Thanks!
Michael

Continously connecting and disconnecting on router

Hi there,
using a ESP8266 NodeMCU to post humidity data to TS every 60s.
This works very well.

The only issue I have is that the wifi connection seems to get opened and closed instantly whenever a post to TS is done, so I get a new connection and instant disconnect on the router - which it does not really seem to like much.

This happens when I use the default "WriteMultipleFields.ino" example.

So is there a way to keep the wifi connection open between posts?
Best,

-T

Stack Smashing protect Failure!

Hello, I have the following issue, whenever I reach initialization of ThinkgSpeak ThingSpeak.begin(wifiObj); I get an error of "Stack Smashing protect Failure!".

Now, I know in which scenario this occurs, but I don't know what causes it and how to solve it.

Whenever I use ThingSpeak in a simple arduino sketch everything is fine, however, when I use xTaskCreatePinnedToCore for multitasking, I get the error. I guess that this has something to do with the stack size declared in the xTaskCreatePinnedToCore, but no matter how much memory I allocate I keep getting this error.

Please help!

location setting not working for update

Hi
I do setLatitude and setLongitude.
the initial setting worked
Option in Channel enabled : show location. Google maps with location was displayed.

now I wanted to change the location with new setLongitude, etc.
But nothing is updated.

What am I doing wrong?
Even in channel settings, location (longitude, latitude) are saying 0 but in Graph I do see the former location set on the map.

ThingSpeak.setLongitude(longitude);
ThingSpeak.setElevation(elevation);
ThingSpeak.setLatitude(latitude);

Thanks T

esp 8266

hii,
i am interfacing esp8266 01 with arduino-uno i don't understand that while thingspeak.write() is called then on what pin i m supposed to connect to TX and RX of the esp to the arduino
please help me .
asap....
send me mail
[email protected]

ThingSpeak.setCreatedAt seems to be not working

pinVoltage = 1.0;
ThingSpeak.setField(8,pinVoltage);
ThingSpeak.setCreatedAt("2017-03-17T20:59:59");
value = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
is not working - return code is 200 but no data point appears

The raw function works:
String postMessage = String("field1=20&field2=8&created_at=2017-03-17T20:59:59");
String value;
value = ThingSpeak.writeRaw(myChannelNumber, postMessage, myWriteAPIKey);

THINGSSPEAK CLOUD COMPUTING

please for any one with idea on how to upload sensor data to thingspeak cloud using arduino uno and gsm shield help me I'm a new in this field of cloud computing though i know to program with arduino

Readme needs updating

I know it's not a major thing, but there are a few mistakes in the read me file.
for example:

Complete documentation in aslo shown below.
should be
Complete documentation is also shown below.

bridge.io

Hi,

I noticed that you own bridge.io as a domain name although your domain name is thinkspeak.com. I'm interested in purchasing that domain name from you. Please feel free to contact me at [email protected].

Thanks,
Andrew

Thingspeak arduino library seem not to work with WiFi101OTA library

Hello,
From the example "WriteVoltage", if I add :

#include <WiFi101OTA.h>
….

void setup() {
…..
WiFiOTA.begin("Arduino", "password", InternalStorage);
}

void loop() {
WiFiOTA.poll();
…...
}

I have the error code -301 (Failed to connect to ThingSpeak)

Could you help me to use ThingSpeak with OTA functionality ?

Thing speak and Wemos D1 mini

I have not been able to get things peak commands to work with arduino ide and Wemos D1 mini. Anyone have a solution or change I need make?

For example, the readPrivateChannel example appears to run, but value returned is always 0.00 or null. I do not get any error messages.

ESP8266 / NodeMCU?

Hi!
I'm trying to get this to work with an ESP8266 (on an NodeMCU board).
To most sketches the ESP acts as a arduino with wifi board.
However, if I copy the WriteVoltage example, and force it (remove the other options) to a Wifi board, and include the esp8266 library, this library gives an error:

/Users/PanMan/Documents/Arduino/libraries/ThingSpeak/src/ThingSpeak.h:217:7: note:   no known conversion for argument 1 from 'WiFiClient' to 'int&'
no matching function for call to 'ThingSpeakClass::begin(WiFiClient&)'

WiFi.begin(ssid, pass); location in code

Hello, I'm having problems with wifi connection using your example code "WriteMultipleFields". Sometimes ESP module can't connect to wifi and just keep printing dots over serial line. I think the problem is with location of WiFi.begin. In your example code in located inside while loop, but in offical wifi example code it's located outside while loop. As soon as I move to outside of while loop, wifi is connecting correctly.

`
// Connect or reconnect to WiFi

WiFi.begin(ssid, pass); // Connect to WPA/WPA2 network. Change this line if using open or WEP network
if(WiFi.status() != WL_CONNECTED){
Serial.print("Attempting to connect to SSID: ");
Serial.println(SECRET_SSID);
while(WiFi.status() != WL_CONNECTED){
Serial.print(".");
delay(5000);
}
Serial.println("\nConnected.");
}
`

esp8266

it works on my adafruit esp8266.. thanks guys..

code:

/*
WriteVoltage

Reads an analog voltage from pin 0, and writes it to a channel on ThingSpeak every 20 seconds.

ThingSpeak ( https://www.thingspeak.com ) is an analytic IoT platform service that allows you to aggregate, visualize and
analyze live data streams in the cloud.

Copyright 2017, 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.
*/

#include "ThingSpeak.h"

// ***********************************************************************************************************
// This example selects the correct library to use based on the board selected under the Tools menu in the IDE.
// Yun, Ethernet shield, WiFi101 shield, esp8266 and MKR1000 are all supported.
// EPS32 is only partially compatible. ADC analogRead() for ESP32 has not yet been implemented in the SparkFun library. It will always return 0.
// With Yun, the default is that you're using the Ethernet connection.
// If you're using a wi-fi 101 or ethernet shield (http://www.arduino.cc/en/Main/ArduinoWiFiShield), uncomment the corresponding line below
// ***********************************************************************************************************

//#define USE_WIFI101_SHIELD
//#define USE_ETHERNET_SHIELD

// #define (ARDUINO_ARCH_ESP8266)
#include <ESP8266WiFi.h>

char ssid[] = "ssid";    //  your network SSID (name) --subject to change to your own network and password
char pass[] = "pwd";   // your network password
int status = WL_IDLE_STATUS;
WiFiClient  client;

// On ESP8266: 0 - 1023 maps to 0 - 1 volts
#define VOLTAGE_MAX 1.0
#define VOLTAGE_MAXCOUNTS 1023.0

/*


**** Visit https://www.thingspeak.com to sign up for a free account and create
**** a channel. The video tutorial http://community.thingspeak.com/tutorials/thingspeak-channels/
**** has more information. You need to change this to your channel, and your write API key
**** IF YOU SHARE YOUR CODE WITH OTHERS, MAKE SURE YOU REMOVE YOUR WRITE API KEY!!
*****************************************************************************************/
unsigned long myChannelNumber = 5752; // your thingspeak channel no.
const char * myWriteAPIKey = "AWJZGFEIB4DT1"; //your thingspeak writeapikey.

void setup() {
WiFi.begin(ssid, pass);

  ThingSpeak.begin(client);

}

void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading
// On Uno,Mega,YunArduino: 0 - 1023 maps to 0 - 5 volts
// On ESP8266: 0 - 1023 maps to 0 - 1 volts
// On ESP32: 0 - 4095 maps to 0 - 1 volts, but will always return 0 as analogRead() has not been implemented yet
// On MKR1000,Due: 0 - 4095 maps to 0 - 3.3 volts
float voltage = sensorValue * (VOLTAGE_MAX / VOLTAGE_MAXCOUNTS);

// Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different
// pieces of information in a channel. Here, we write to field 1.
ThingSpeak.writeField(myChannelNumber, 1, voltage, myWriteAPIKey);
delay(20000); // ThingSpeak will only accept updates every 15 seconds.
}

cant get channel settings using readRaw or any other means

i am trying to read the channel's latitude/longitude in arduino.
There is no method in the library to do so.
If i try to use readraw to do this
ThingSpeak.readRaw(myChannelNumber, ".json", myReadAPIKey);

the request fails with responsecode 400

Support for chunked transfer encoding

The ThingSpeak sever recently changed to use "chunked transfer encoding" for read requests.
So there is no Content-Length inside the htpp header, which is necessary for the current (V1.5.0) implementation of getHTTPResponse in case of be called by readRaw.
So currently the read functions do not work at least in my implementation.

I made a workaround for me, but this is not very nice.
https://community.thingspeak.com/forum/esp8266-wi-fi/suddenly-appearing-problems-reading-data-by-esp/

Is it possible to provide a library that supports the recognition of "chunked transfer encoding" use.
Many thanks for an answer.

Confirm upload of data

I'm using the ESP8266 and I've noticed that data uploads are missed if interrupts or timers(ticker) are used. Is there functionality that checks whether data is uploaded successfully?

Location update

Can the Arduino update the location parameters in my channel?

error duplicate define ERR_TIMEOUT when compile on esp board

error when compile on esp board.

in ThingSpeak.h
#define ERR_TIMEOUT -304 // Timeout waiting for server to respond

and in err.h (Arduino/hardware/espressif/esp32/tools/sdk/include/lwip/lwip)
#define ERR_TIMEOUT -3 /* Timeout. */

when change ERR_TIMEOUT in ThingSpeak.h to other (eg. ERR_TIMEOUT_1) can be compiled.

ESP8266

Hi,

I tried the read private channel example with my ardino uno and esp8266, but i had trouble with the WiFi.h library and the WiFIClient type. i don't realy know if i should include the library (if i won't include it' there is no such type wificluient, which is needed for the thingspeak functions...)

writeFields does not always succeed

Hello,
I have a simple example that just sets a variety of fields and then writes them in bulk. However, sometimes the writeFields call doesn't seem to complete.
Here is the log:

09:56:26.429 -> ts::setField (field: 2 value: "26.00000")
09:56:26.429 -> ts::setField (field: 3 value: "90.00000")
09:56:26.429 -> ts::setField (field: 4 value: "0.00000")
09:56:26.429 -> ts::setField (field: 5 value: "0.00000")
09:56:36.462 -> ts::setField (field: 6 value: "0.69811")
09:56:36.462 -> ts::setField (field: 7 value: "2.00000")
09:56:36.462 -> ts::setField (field: 8 value: "0.00000")
09:56:36.462 -> Connect to default ThingSpeak: api.thingspeak.com:80...[hostByName] request IP for: api.thingspeak.com
09:56:36.462 -> [hostByName] Host: api.thingspeak.com IP: 34.226.171.107
09:56:36.462 -> :ur 1
09:56:36.462 -> :del
09:56:36.462 -> :ref 1

And that's it. Typically for a successfull call there is a response from writeFields like so:
09:45:44.505 -> Success.
09:45:44.505 -> ts::writeFields (channelNumber: 797035 writeAPIKey: XXXXXXXXXXX)

Any idea what could be happening?

Suggestion to include bulk update in library

This API is not included yet. It would be useful.

Matlab has posted code - but it is only for mkr1000 or esp - but not for ethernet shield:
You can use the bulk-update API in certain scenarios when you want to conserve your device power. When using the bulk-update API, you can collect data over a period of time and then upload the data to ThingSpeak™. Bulk-update API takes JSON encoded data and updates the channel.

https://de.mathworks.com/help/thingspeak/continuously-collect-data-and-bulk-update-a-thingspeak-channel-using-an-arduino-mkr1000-board-or-an-esp8266-board.html?searchHighlight=bulk&s_tid=doc_srchtitle

ESP8266 error for Arduino 101

Hello,

I am trying to compile the sketch on Arduino 101, but I get an error:
`Arduino: 1.6.10 (Mac OS X), Board: "Arduino/Genuino 101"

WARNING: library ThingSpeak claims to run on [avr architecture(s) and may be incompatible with your current board which runs on esp8266 architecture(s).
In file included from /Users/x/Documents/Arduino/Display_temp_LCD_RHT03_connectWiFi_uploadTS/Display_temp_LCD_RHT03_connectWiFi_uploadTS.ino:57:0:
/Users/x/Documents/Arduino/libraries/ThingSpeak/src/ThingSpeak.h:61:4: error: #error Only Arduino MKR1000, Yun, Uno/Mega/Due with either WiFi101 or Ethernet shield. ESP8266 also supported.
#error Only Arduino MKR1000, Yun, Uno/Mega/Due with either WiFi101 or Ethernet shield. ESP8266 also supported.
^
/Users/x/Documents/Arduino/libraries/ThingSpeak/src/ThingSpeak.h:84:3: error: #error "Platform not supported"
#error "Platform not supported"
^
exit status 1
Error compiling for board Arduino/Genuino 101.
`
I cannot understand why the board is listed as not esp8266 -> not compatible, while ESP8266 is afterwards declared as "also suported"

Ongoing issues passing floats in the setField command

I note that there appears to be many issues associated with sending floats as part of the sendmultiple fields workflow. I have experienced this myself recently working for the Arudino/ESP8266 example however attempting to setFields with float values.

A quick look at line 1647 of ThingSpeak.h suggests that there may be an error in function convertFloatToChar (can someone with better knowledge than I please check this?) as follows:

Line 1647 of ThingSpeak.h reads:
dtostrf(value,1,5,valueString);

however reference to https://www.microchip.com/webdoc/AVRLibcReferenceManual/group__avr__stdlib_1ga060c998e77fb5fc0d3168b3ce8771d42.html and others suggest that the 2nd parameter (currently coded as '1') should be the "minimum field width of the output string including possible negative signs and possible decimal point" with the third value '5' predetermining that the precision (i.e. number of digits after the decimal sign) will be 5. Given the test is for 19+1 (defined in line 350 of the same code) I would have thought the second field should also be 19 (instead of 1).

I'm hoping this gets a whole bunch of people out of trouble moving forward. Given the 'strange behaviour' and the number of reported issues around this, perhaps an example can be included in the documentation (or the existing example modified to show correct casting or alternate methods required).

Memory usage is excessive

Looking through the library, memory use seems excessive due to the use of static strings stored in SRAM as well as program memory, as well as class variables that are larger than required.

  • ALL the debug statement strings should be stored in program memory. Replacing Serial.print("foobar") with Serial.print(F("foobar")) will do this automatically in the Arduino environment, and save a significant hunk of memory when debugging behavior.
  • The client->print statements referencing static strings should be similarly altered. Client is based on Stream, based on Print, and the Print library has the appropriate wrappers for the __FlashStringHelper types. if(!this->client->print("GET ")) could easily be if(!this->client->print(F("GET "))) with no change in performance, though it would be more efficient to define some of these strings once in program memory and access them as needed, if they are used more than once.
  • Altering things such that the readRaw functions take flash memory strings would save another large chunk of memory. If the upstream function doesn't handle the FlashStringHelper properly, you can copy from flash into a stack char array before calling the raw function and only use memory during the actual function, not all the time.
  • Reconsider the use of the String library. It's convenient, but depending on how things are passed around, it can lead to significant heap fragmentation - which is a serious issue on the Arduino Uno, with 2048 bytes of RAM. It effectively creates a memory leak. In particular, functions that return a String type are hazardous, as this creates a copy that may then be used by the calling code after the allocations by the particular function have been freed. Instead of returning a string, require that the calling function provide a String type (pass it by reference), and this should help reduce the risk of heap fragmentation. Though, rewriting the code to simply never use dynamic allocation is far better.
  • String initializers are similarly in SRAM. If you can't move them to PROGMEM storage, this is a good reason to rewrite the code to not use Strings.

All of this, combined, should radically reduce the memory usage of this library. Remember, this is being used on embedded-scale devices, with very, very limited memory - and often people wish to use other libraries. This sort of wasteful memory use makes things harder for people, and prevents the use of as many libraries as the devices could otherwise support. It would be quite nice if you were to fix this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.