loading

I wrote this instructable because Thingspeak -nevermind how easy to set up- has a few hurdles that I ran into and that, judging from reactions, other people are struggling with as well.

This instructable discusses the following:

  • How to set up Thingspeak
  • How to connect your Arduino with a W5100 Ethernetshield
  • How to connect your Arduino via an ESP8266-01
  • How to connect to Thingspeak with only an ESP8266-01

NOTE: Although this presented project does work well, I would probably never combine an Arduino with an ESP8266 again because it is overkill. The ESP8266 can do a lot of things the Arduino can do, especially if it is just collecting sensor data. Have look in the 'ESP8266 only' step of this instructable, or check my newer instructables such as the one here.

Things you need:
Arduino
WS5100 EthernetShield (if you have the old ENC28J60 ethercard, look here)
Thingspeak Account
Sensors (such as DHT11 and BMP180)
Internet connection
For the WiFi:
ESP8266-01 (or other ESP8266)

I wanted to collect some weather-data with my Arduino and have that available as nice graphs, on a webpage, so I could also monitor it from afar
I could ofcourse just use an Arduino as a webserver, but if you want to do anything more than send numbers to a webpage, The Arduino will soon run out of memory.
There are services that can digest and publish your data: Pachube, later called Xively is a known one but currently they have a waiting list for their free accounts. Truthfully, I have a Pachube account that became a Xively account, but just never got any results on it.

There're few alternatives for Xively:
http://2lemetry.com

http://exosite.com

https://www.carriots.com

https://www.grovestreams.com

https://thingspeak.com

http://openenergymonitor.org

I picked 'Thingspeak'
As the signup and creating a channel etcetera is quite easy and well explained I will not go into too much detail of that. Basically after you sign up you create a channel to which you add fields where later sensors will send their data.
Under the API tab you will find an API that you later should put in your program.

I describe a simpel connection with an ethernet cable and a connection via WiFi

Step 1: Hurdles and Solutions

Hurdle 1
Now where to find a program? a working example would be nice right? In the right top corner there is a button 'Support' that will go to 'Tutorials'.
Under 'Tutorials' you will find:

"Using an Arduino + Ethernet Shield to Update a ThingSpeak Channel"
Sounds great, so you download that program into your IDE, add the API -key and then compile it.
Darn.... it doesnt compile, you try to fix it (and that is certainly possible) until you come to a point you have no idea what is required.
Apparently the program still expects everybody to use the 022 or 023 IDE.
There is a link to a Github page but that will give u a program to tweet and that is not what you want, at least not for now.
Solution
You ill find a better program to start from right here:

https://github.com/iobridge/ThingSpeak-Arduino-Exa...

That program takes a reading from the A0 port and sends that to "Field1" in your datastream

Ok so you try that, you hang a variable resistor like an LDR or NTC on port A0, add your API in the program and run it.
That works fine, but I didnt only want to read a value from an Analog port, I had a DHT11 Moisture&Temperature sensor as well as a BMP180 Pressure & temperature sensor. I figured it shouldnt be too hard.

Hurdle 2
I added the necessary libraries to the Thingspeak, added the objects and read the sensors into a variable.
The sensors however have floats as outcome and Thingspeak wants you to send strings.
With most variables it is rather easy to turn them into a string with the simple 'string' function, but it isnt that easy for floats. With floats you have to use the "dtostrf" command (which I guess stands for 'double-to-string-function'

Trying to find info on that function on internet quickly led me to endless discussions on 'how stupid' it was and people asking questions were often told "why would you need that, Serial.print will do that for you" Yeah, true, but I don't want to print, I need it because Thingspeak wants it.

Solution
To use the dtostrf command you need to set up a buffer space where the string will be stored. It works like this:

char t_buffer[10];
t=(ReadSensor);
String temp=dtostrf(t,0,5,t_buffer);

That bufferspace is important. I had it working with '7' or even '5', but when I added a second sensor that needs this function, my datastream would crash and or I got the weirdest results. I also figured that I could use the same bufferspace alternating for each sensor, but that also didnt really work, so now i have a bufferspace for each sensor.
Now I am no crack in C, so maybe there is a better way to do this, if so i would love to hear it, but this worked for me.

Hurdle3
Once I had the string conversions, I could add the data to the datastream.
The Thingspeak example program shows that for one field only, but it becomes clear pretty fast that you have to add the strings and throw in the right amount of plussesand ampersands.

Solution
So for say 4 different fields it becomes like this:

updateThingSpeak("field1="+temp+"&field2="+humid+"&field3="+pres+"&field4="+temp2);

Step 2: Connecting With Ethernetshield

Below you will find the full code.
Just a few remarks:
The BMP180 is an updated version of the BMP085. The BMP085 libraries are compatible with the BMP180.
AdaFruit has 2 versions of the libray. I picked version 1 as i found it easier to work with. Version 2 also requires installation of the 'Sensor' library.
In the code I also present an extra float: 'm'. that gives the Pressure in "mmHg" as I havent used it for now there is no string conversion yet and it is not added to the datastream, but adding it should now be as simple as 1+1

/*
Arduino --> ThingSpeak Channel via Ethernet
The ThingSpeak Client sketch is designed for the Arduino and Ethernet.
This sketch updates a channel feed with an analog input reading via the
ThingSpeak API (http://community.thingspeak.com/documentation/)
using HTTP POST. The Arduino uses DHCP and DNS for a simpler network setup.
The sketch also includes a Watchdog / Reset function to make sure the
Arduino stays connected and/or regains connectivity after a network outage.
Use the Serial Monitor on the Arduino IDE to see verbose network feedback
and ThingSpeak connectivity status.
Getting Started with ThingSpeak:
* Sign Up for New User Account - <a href="https://www.thingspeak.com/users/new" rel="nofollow"> https://www.thingspeak.com/users/new
</a>
* Enter a MAC Address in this sketch under "Local Network Settings"
* Create a new Channel by selecting Channels and then Create New Channel
* Enter the Write API Key in this sketch under "ThingSpeak Settings"
Arduino Requirements:
* Arduino with Ethernet Shield or Arduino Ethernet
* Arduino 1.0 IDE
Network Requirements:
* Ethernet port on Router
* DHCP enabled on Router
* Unique MAC Address for Arduino
Created: October 17, 2011 by Hans Scharler (http://www.iamshadowlord.com)
Additional Credits:
Example sketches from Arduino team, Ethernet by Adrian McEwen
Added dht11/BMP180 showed dtostrf function by diy_bloke 22/11/2014
*/
#include <SPI.h>
#include <Ethernet.h>
#include <dht11.h>
#include <Wire.h>
#include <Adafruit_BMP085.h> // This is the version 1 library
#define DHT11PIN 4  // The Temperature/Humidity sensor
Adafruit_BMP085 bmp;
dht11 DHT11;

// Local Network Settings
byte mac[] = { 0xD4, 0x28, 0xB2, 0xFF, 0xA0, 0xA1 }; // Must be unique on local network
// ThingSpeak Settings
char thingSpeakAddress[] = "api.thingspeak.com";
String writeAPIKey = "REPLACE_THIS_BY_YOUR_API_BUT_KEEP_THE_QUOTES";
const int updateThingSpeakInterval = 16 * 1000; // Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval)
// Variable Setup
long lastConnectionTime = 0;
boolean lastConnected = false;
int failedCounter = 0;
// Initialize Arduino Ethernet Client
EthernetClient client;
void setup()
{
// Start Serial for debugging on the Serial Monitor
Serial.begin(9600);
// Start Ethernet on Arduino
startEthernet();
}
void loop()
{
// Read value from Analog Input Pin 0
String analogPin0 = String(analogRead(A0), DEC);
// Print Update Response to Serial Monitor
if (client.available())
{
char c = client.read();
Serial.print(c);
}
//------DHT11--------
int chk = DHT11.read(DHT11PIN);
char t_buffer[10];
char h_buffer[10];
float t=(DHT11.temperature);
String temp=dtostrf(t,0,5,t_buffer);
//Serial.print(temp);
//Serial.print(" ");
float h=(DHT11.humidity);
String humid=dtostrf(h,0,5,h_buffer);
//Serial.println(humid);

//-----BMP180-----------
bmp.begin();
            float p=(bmp.readPressure()/100.0);//this is for pressure in hectoPascal
            float m=(bmp.readPressure()/133.3);//  this is for pressure in mmHG
            float t2=(bmp.readTemperature());
            char p_buffer[15];
            char t2_buffer[10];
            String pres=dtostrf(p,0,5,p_buffer);
            String temp2=dtostrf(t2,0,5,t2_buffer);
            Serial.println(pres);
 //         }
//----------------

// Disconnect from ThingSpeak
if (!client.connected() && lastConnected)
{
Serial.println("...disconnected");
Serial.println();
client.stop();
}
// Update ThingSpeak
if(!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval))
{
updateThingSpeak("field1="+temp+"&field2="+humid+"&field3="+pres+"&field4="+temp2);
}
// Check if Arduino Ethernet needs to be restarted
if (failedCounter > 3 ) {startEthernet();}
lastConnected = client.connected();
}
void updateThingSpeak(String tsData)
{
if (client.connect(thingSpeakAddress, 80))
{
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+writeAPIKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(tsData.length());
client.print("\n\n");
client.print(tsData);
lastConnectionTime = millis();
if (client.connected())
{
Serial.println("Connecting to ThingSpeak...");
Serial.println();
failedCounter = 0;
}
else
{
failedCounter++;
Serial.println("Connection to ThingSpeak failed ("+String(failedCounter, DEC)+")");
Serial.println();
}
}
else
{
failedCounter++;
Serial.println("Connection to ThingSpeak Failed ("+String(failedCounter, DEC)+")");
Serial.println();
lastConnectionTime = millis();
}
}
void startEthernet()
{
client.stop();
Serial.println("Connecting Arduino to network...");
Serial.println();
delay(1000);
// Connect to network amd obtain an IP address using DHCP
if (Ethernet.begin(mac) == 0)
{
Serial.println("DHCP Failed, reset Arduino to try again");
Serial.println();
}
else
{
Serial.println("Arduino connected to network using DHCP");
Serial.println();
}
delay(1000);
}

Step 3: Connect to Thingspeak Using an ESP8266 WiFi Module

The previous presented internet connection was made via a cable. However, there is a cheap WiFi module that is available to attach to the Arduino: The ESP 8266.
The ESP8266 is a cheap WiFi module. Bear in mind that it needs 3.3 Volt. Some models however claim to be 5 Volt tolerant. I added 2 circuits that could be used as voltage converter.
The ESP8266 really needs its own 3.3 V source as the current coming from the Arduino just doesnt cut it.
There is plenty of information on how to connect the module, I want to focus on the software to make a Thingspeak connection
The SoftSerial library is added for debugging. it is not really necessary once the progrem is working. The same goes for all the print statements to the Software serial port
I use 3 analog values rather than an example with the BMP108 and DHT11 as that requires libraries, so the implementation of theESP8266 is easier to follow. Once you get that, it is easy to implement other sensors. Just make sure you turn all output into a string
Below a program to Connect 3 analog sensors to Thingspeak via an ESP8266 module:

// <a href="https://nurdspace.nl/ESP8266" rel="nofollow">  https://nurdspace.nl/ESP8266

</a>//https://www.instructables.com/id/Using-the-ESP8266-module/
//https://www.zybuluo.com/kfihihc/note/31135
//http://tminusarduino.blogspot.nl/2014/09/experimenting-with-esp8266-5-wifi-module.html
//http://www.cse.dmu.ac.uk/~sexton/ESP8266/
//https://github.com/aabella/ESP8266-Arduino-library/blob/master/ESP8266abella/ESP8266aabella.h
//http://contractorwolf.com/esp8266-wifi-arduino-micro/
//**********************************************************
#include <SoftwareSerial.h>
int sensor_temp = A0;
int value_temp;
int sensor_light = A1;
int value_light;
int sensor_humid = A2;
int value_humid;


#define DEBUG FALSE //comment out to remove debug msgs

//*-- Hardware Serial
#define _baudrate 9600

//*-- Software Serial
//
#define _rxpin      2
#define _txpin      3
SoftwareSerial debug( _rxpin, _txpin ); // RX, TX

//*-- IoT Information
#define SSID "[YOURSSID]"
#define PASS "[YOURPASSWORD]"
#define IP "184.106.153.149" // ThingSpeak IP Address: 184.106.153.149

// GET /update?key=[THINGSPEAK_KEY]&field1=[data 1]&field2=[data 2]...;
String GET = "GET /update?key=[ThingSpeak_(Write)API_KEY]";

void setup() {
   Serial.begin( _baudrate );
  debug.begin( _baudrate );

  sendDebug("AT");
  delay(5000);
  if(Serial.find("OK"))
  {
    debug.println("RECEIVED: OK\nData ready to sent!");
    connectWiFi();
  }

}

void loop() {
  value_temp = analogRead(sensor_temp);
  value_light = analogRead(sensor_light);
  value_humid = analogRead(sensor_humid);
  String temp =String(value_temp);// turn integer to string
  String light= String(value_light);// turn integer to string
  String humid=String(value_humid);// turn integer to string
  updateTS(temp,light, humid);
  delay(3000); //
}
//----- update the  Thingspeak string with 3 values
void updateTS( String T, String L , String H)
{
  // ESP8266 Client
  String cmd = "AT+CIPSTART=\"TCP\",\"";// Setup TCP connection
  cmd += IP;
  cmd += "\",80";
  sendDebug(cmd);
  delay(2000);
  if( Serial.find( "Error" ) )
  {
    debug.print( "RECEIVED: Error\nExit1" );
    return;
  }

  cmd = GET + "&field1=" + T +"&field2="+ L + "&field3=" + H +"\r\n";
  Serial.print( "AT+CIPSEND=" );
  Serial.println( cmd.length() );
  if(Serial.find( ">" ) )
  {
    debug.print(">");
    debug.print(cmd);
    Serial.print(cmd);
  }
  else
  {
    sendDebug( "AT+CIPCLOSE" );//close TCP connection
  }
  if( Serial.find("OK") )
  {
    debug.println( "RECEIVED: OK" );
  }
  else
  {
    debug.println( "RECEIVED: Error\nExit2" );
  }
}

void sendDebug(String cmd)
{
  debug.print("SEND: ");
  debug.println(cmd);
  Serial.println(cmd);
}

boolean connectWiFi()
{
  Serial.println("AT+CWMODE=1");//WiFi STA mode - if '3' it is both client and AP
  delay(2000);
  //Connect to Router with AT+CWJAP="SSID","Password";
  // Check if connected with AT+CWJAP?
  String cmd="AT+CWJAP=\""; // Join accespoint
  cmd+=SSID;
  cmd+="\",\"";
  cmd+=PASS;
  cmd+="\"";
  sendDebug(cmd);
  delay(5000);
  if(Serial.find("OK"))
  {
    debug.println("RECEIVED: OK");
    return true;
  }
  else
  {
    debug.println("RECEIVED: Error");
    return false;
  }

  cmd = "AT+CIPMUX=0";// Set Single connection
  sendDebug( cmd );
  if( Serial.find( "Error") )
  {
    debug.print( "RECEIVED: Error" );
    return false;
  }
}



NOTE

In the latest version of the ESP8266 firmware AT+CIOBAUD is no longer supported and returns ERROR.
The replacement command is AT+IPR. See here for further details :- www.esp8266.com/viewtopic.php?f=13&t=718

More note
Apparently lately there appear to be some people experiencing difficulties because they didnt connect the ESP8266 to the hardware serial but to the software serial.
This program expects an ESP connected to hardware serial

Step 4: Using Just the ESP8266

if you come upon this page and see gibberish... there was a full step here, but somehow Instructables decided it would be better to replace it with gibberish...after i already saved it. I will give it another go In the previous step I used an ESP8266 to send the sensorvalues that were read by an Arduino to Thingspeak. However, it is also possible to do it without an Arduino at all. I connected a DHT11 to pin 2 of my ESP8266-01 and used the following program. I can't take full credit for the program, I think the original is from Jeroen Beemster

#include <DHT.h> //  DHT.h library
#include <ESP8266WiFi.h> // ESP8266WiFi.h library

#define DHTPIN 2
#define DHTTYPE  DHT11

const char* ssid     = "YourNetworkSSID";
const char* password = "YourPassword";
const char* host = "api.thingspeak.com";
const char* writeAPIKey = "YourWriteAPI";

DHT dht(DHTPIN, DHTTYPE, 15);

void setup() {
  // Initialize sensor
 dht.begin();
  delay(1000);

//  Connect to WiFi network
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
}

void loop() {
 float humidity = dht.readHumidity();
 float temperature = dht.readTemperature();

  if (isnan(humidity) || isnan(temperature)) {
    return;
  }

// make TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    return;
  }

  String url = "/update?key=";
  url+=writeAPIKey;
  url+="&field1=";
  url+=String(temperature);
  url+="&field2=";
  url+=String(humidity);
  url+="\r\n";
  
  // Request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" + 
               "Connection: close\r\n\r\n");
    delay(1000);
}

It is not the goal of this instructable to explain how to program the ESP8266, there are plenty of sources for that. A good one is here. If you already have an USB-TTL module at 3.3 Volt, you dont need to worry about voltages. If you only have a 5Volt USB-TTL module you still can use it but have to use a voltage divider between the Tx of the module and the Rx of the ESP8266. Never ever put 5 volt on the ESP8266

Note: The DHT library from Adafruit contains an error that usually doesnt occur when using an Arduino, but can become apparent when using an ESP8266, especially if the program is a bit bigger. See the enclosed picture for changes you need to make in the cpp file. It basically is commenting out two lines

Step 5: A Bonus

In case you do not want to use Thingspeak but just want your own webserver: use this program:

/* 
 * DHT11 Sensor connected to Pin 2
 <a href="http://arduino-info.wikispaces.com/ethernet-temp-humidity" rel="nofollow">  http://arduino-info.wikispaces.com/ethernet-temp-...>
 Based on code by David A. Mellis & Tom Igoe
Adapted by diy_bloke
 * bmp180sensor on a4/a5

 */
/*-----( Import needed libraries )-----*/
#include <SPI.h>
#include <Ethernet.h>
#include <dht11.h>
#include <Wire.h>
//#include <Adafruit_Sensor.h>
//#include <Adafruit_BMP085_U.h>
#include <Adafruit_BMP085.h>
/*-----( Declare Constants and Pin Numbers )-----*/
#define DHT11PIN 2  // The Temperature/Humidity sensor

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

/*-----( Declare objects )-----*/
IPAddress ip(192,168,1, 177);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

//Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);
Adafruit_BMP085 bmp;
dht11 DHT11;  //The Sensor Object
/*-----( Declare Variables )-----*/

void setup()   /****** SETUP: RUNS ONCE ******/
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print(F("server is at "));
  Serial.println(Ethernet.localIP());
}//--(end setup )---

void loop()   /*----( LOOP: RUNS OVER AND OVER AGAIN )----*/
{
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println(F("new client"));
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connnection: close");
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          // add a meta refresh tag, so the browser pulls again every 5 seconds:
          client.println("<meta http-equiv=\"refresh\" content=\"5\">");
          client.println("<head>");
          client.println("<title>");
          client.println(F("My Home Environment"));
          client.println("</title>");
          client.println("</head>");
          client.println("<body>");
          client.print(F("<h3>My Home Environment</h3>"));
          //client.println("<br />");

          /*----(Get sensor reading, calculate and print results )-----------------*/

          int chk = DHT11.read(DHT11PIN);

          Serial.print(F("Read sensor: "));
          switch (chk)
          {
          case 0:
            Serial.println(F("OK"));
            break;
          case -1:
            Serial.println(F("Checksum error"));
            break;
          case -2:
            Serial.println(F("Time out error"));
            break;
          default:
            Serial.println(F("Unknown error"));
            break;
          }
          /* Get a new sensor (BMP085) event */
          // sensors_event_t event;
          // bmp.getEvent(&event);
          //--------------
          client.print(F("<table style='border:1px solid black; background-color: white;'>"));
          client.print(F("<tr><td>"));
          client.print("<font color='red'>Temperature</font> (°C): ");
          client.print(F("</td><td align='right'>"));
          client.println((float)DHT11.temperature, 1);
          client.println(F("<br />"));
          client.print(F("</td></tr>"));
          client.print(F("<tr><td>"));
          client.print("<b>Temperature</b> (°F): ");
          client.print(F("</td><td align='right'>"));
          client.println(Fahrenheit(DHT11.temperature), 1);
          client.println("<br />");
          client.print(F("</td></tr>"));
          client.print(F("<tr><td>"));
          client.print("<font color='blue'>Humidity</font> (%): ");
          client.print(F("</td><td align='right'>"));
          client.println((float)DHT11.humidity, 0);
          client.println("<br />");
          client.print(F("</td></tr>"));
          client.print(F("<tr><td>"));
          /*
          client.print("<b>Temperature</b> (°K): ");
           client.println(Kelvin(DHT11.temperature), 1);
           client.println("<br />");
           */
          client.print("<i>Dew Point</i> (°C): ");
          client.print(F("</td><td align='right'>"));
          client.println(dewPoint(DHT11.temperature, DHT11.humidity));
          client.println("<br />");
          client.print(F("</td></tr>"));
          client.print(F("<tr><td>"));
          client.print("<i>Dew PointFast</i> (°C): ");
          client.print(F("</td><td align='right'>"));
          client.println(dewPointFast(DHT11.temperature, DHT11.humidity));
          client.println("<br />");
          client.print(F("</td></tr>"));
          client.print(F("<tr><td>"));

          if (!bmp.begin()) {
            client.print("geen sensor");
          }
          else
          {
            client.print("Pressure (hPa): ");
            client.print(F("</td><td align='right'>"));
            client.println(bmp.readPressure()/100.0);
            client.print(F("</td></tr>"));
            client.print(F("<tr><td>"));
            client.print("Pressure (mmHg): ");
            client.print(F("</td><td align='right'>"));
            client.println(bmp.readPressure()/133.3);
            client.print(F("</td></tr>"));
            client.print(F("<tr><td>"));
            client.println("Temperature (°C): ");
            client.print(F("</td><td align='right'>"));
            client.print(bmp.readTemperature());
            client.println("<br />");
          }
          client.print(F("</td></tr>"));
          client.print(F("</table>"));
          /* Display the results (barometric pressure is measure in hPa) */

          /* Display atmospheric pressure in hPa */
          /*    client.print("Pressure: ");
           client.println(event.pressure);
           client.println(" hPa");
           client.println("<br />");
           */


          /*--------( End Sensor Read )--------------------------------*/
          client.println("</body>");
          client.println("</html>");
          break;
        }
        if (c== '\n'){
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println(F("client disonnected"));
  }
} // END Loop

/*-----( Declare User-written Functions )-----*/
//
//Celsius to Fahrenheit conversion
double Fahrenheit(double celsius)
{
  return 1.8 * celsius + 32;
}

//Celsius to Kelvin conversion
double Kelvin(double celsius)
{
  return celsius + 273.15;
}

// dewPoint function NOAA
// reference: <a href="http://wahiduddin.net/calc/density_algorithms.htm" rel="nofollow">  http://arduino-info.wikispaces.com/ethernet-temp-...>
double dewPoint(double celsius, double humidity)
{
  double A0= 373.15/(273.15 + celsius);
  double SUM = -7.90298 * (A0-1);
  SUM += 5.02808 * log10(A0);
  SUM += -1.3816e-7 * (pow(10, (11.344*(1-1/A0)))-1) ;
  SUM += 8.1328e-3 * (pow(10,(-3.49149*(A0-1)))-1) ;
  SUM += log10(1013.246);
  double VP = pow(10, SUM-3) * humidity;
  double T = log(VP/0.61078);   // temp var
  return (241.88 * T) / (17.558-T);
}

// delta max = 0.6544 wrt dewPoint()
// 5x faster than dewPoint()
// reference: <a href="http://en.wikipedia.org/wiki/Dew_point" rel="nofollow">  http://arduino-info.wikispaces.com/ethernet-temp-...>
double dewPointFast(double celsius, double humidity)
{
  double a = 17.271;
  double b = 237.7;
  double temp = (a * celsius) / (b + celsius) + log(humidity/100);
  double Td = (b * temp) / (a - temp);
  return Td;
}
/* ( THE END ) */



<p>Hi diy_bloke</p><p>I tried your code with the **exact specifications** as you gave, but it didn't seem to go well. I wired up my arduino to Esp and then i started getting this text all the time on the serial monitor. Can't figure out how to proceed further.... Your help would be really appreciated on this!</p><p>AT+CIPSTART=&quot;TCP&quot;,&quot;184.106.153.149&quot;,80</p><p>AT+CIPSEND=67</p><p>AT+CIPCLOSE</p><p>What could be the problem? I tried different power supplies, a solo power supply of 3v3 (actually it gave out 3.24) and then from the USB2Serial Converter (that was also a stable 3v3, i had tried it earlier on my esp and the IDE showed a successful flash).</p><p>P.S. Using arduino+esp is mandatory, else it is easy to do it with esp alone like you mentioned numerous times already in this instructable.</p><p>Thanks</p>
<p>Sorry to hear that. The 3.24 Volt should not be the problem.<br>Sadly though this project has been quite a while ago for me so I am a bit rusty on the AT commoands. I presume you are sure you connected the ESP to the right port and dont have Rx+Tx switched (I doubt you have but make sure).<br>Also you are using the right WiFi credentials?</p>
<p>is it possible for me to send text message to thingspeak web server? </p>
<p>what you send to theThingspeakserver is ascii text, but as far as I know it needs to be a cipher in ascii,as in the end it all goes in a graph presentation</p>
<p>1)Hi can u please give the connection diagram,using arduino uno esp8266 and 3 analog values?(so as to counter check whether my connection diagram is right?<br><br>2) Is this where i put my channel key?Have i put it correctly?<br><br>String GET = &quot;[ABBAVJ339FYK1ZZ]&quot;;</p>
<p>indeed that is where you put the api key.<br>Having said that, nowadays it is a bit of a waste to combine an ESP8266 with a Nano, as the ESP8266 can be used on its own</p>
<p>the connection between arduino and esp8266 is always TX-RX and RX-TX<br>the channel key should not have brackets around it.<br>In al honesty, it nowadays is a bit of a waste to use en Arduino in combo with an ESP8266 as the ESP8266 can do it alone and in fact it is easier to program as well. Now you may think ẅhat about analog values on the ESP8266? add a cheap ADC module (less than a dollar). Look<a href="https://arduinodiy.wordpress.com/2016/10/17/adding-a-pcf-8591-adcdac-to-esp8266-01/"> here a few lines of code and you are ready to go</a></p>
<p>Thankyou diy_bloke..</p><p>1)But my doubt is if I am using Hardware serial for esp8266, how does communication with serial monitor happen through pins 2 and 3?Because by default communication with serial monitor is with rx and tx pins right?</p><p>2) I have already used arduino uno in one of my projects,thats y I am hanging on to it.I can just addon esp code to it..</p><p>3)Also when I am separately checking with just serial monitor ,ESP module is sending and receiving ,but with this setup,module is not responding.What do u think could be the problem?</p><p>Thanking you,</p>
<p>where I say &quot;try this code&quot; the wrong link got inserted. Should be this one </p><p><a href="https://github.com/volca/cactus_micro_trial/blob/master/cactus_micro_trial.ino">https://github.com/volca/cactus_micro_trial/blob/m...</a><br>But again, I have some doubts on that code</p>
<p>Also will u plz tell how does the data flow happen with debug.print?</p>
<p>It has been a while, but as far as I recall I had the ESP on the hardware serial. The communication with the Serial monitor over pins 2 and 3 is through the softwareserial library.<br>Now if you look at the program you see that you can switch the debug (i.e. what is being sent to the Software Serial) on and off. That is so that when it is all werking, you do not need that part of the code anymore.</p><p>What you see in your 'Serial Monitor' depends on what port you choose. So suppose you would not connect the ESP8266 and connect an USB cable to the Arduino and subsequently look in your serial monitor, you would see what is being sent to the ESP8266, If you would connect your computer to the software serial port (e.g. with an FTDI) you would see what your arduino prints as debug messages (a long as your debug is true).<br>Also, you see the commandline </p><p>if(Serial.find( &quot;&gt;&quot; ) )</p><p>This also indicates that it is the regular serialport that the ESP8266 is connected to as you need to look for that return string in th ebuffer between the ESP8266 and the Arduino. It is the sign the ESP8266 comes back with a message, not the Arduino<br><br>As I found and find communication with the ESP8266 via AT commands rather cumbersome and as the ESP8266 is a microcontroller in itself, I have given up on combining it with an arduino but I understand your reason why.<br>Now one of the problems in having yr arduino comunicate with an ESP8266 is baudrate, in the early days supposedly there wereesp8266 modules that had different baudrates. Try change that.<br>Also, make sure not to feed the ESP8266 from yr arduino, it needs a decent psu preferably with somewhat of a buffer capacitor</p><p>If you do not have an ftdi handy, remove yr esp8266 and attach a usb cable to the standard serial port and see what commando's are being sent.<br><br>You said that if you &quot;normally check' the esp with yr serial monitor... can I presume that you then have it connected to an FTDI cable? What speed are you using?<br><br>Although it can happen that maybe Instructables corrupts the code, I copied it from instructables again and compiled and run it, that did fine (although I didnt have an esp connected to it). Nevertheless, it could be that somewhere a mistake slipt in so I'd say<a href="https://forum.arduino.cc/index.php?topic=409355.0"> try this code</a>. Mind you though that it is using different software serial pins. AND as far as I can see is using the software serial for ESP8266 comunication and I cannot garantee that code is actually working.<br><br>Also, you will find some problems<a href="https://forum.arduino.cc/index.php?topic=409355.0"> connecting to an ESP8266 discussed here</a>.<br><br><br></p>
<p>Thankyou diy_bloke..</p><p>1)I have powered esp8266 using lm317 and its getting 3.6V, not from arduino.But ground of arduino and esp is same.</p><p>2) Baud rate in serial monitor and program is 115200.</p><p>3)DEBUG is true as</p><p>#define DEBUG true </p><p>4) Your comment on different COM ports was really helpful. When </p><p>computer is connected to the software serial port (with an FTDI) ,serial monitor output is as in fig2.At times that Com port didnot get detected.When the ESP8266 is not connected and an USB cable to the Arduino was connected ,subsequent serial monitor output is fig 1.That is I find serial.print and sendDebug function is working but not debug.print.</p><p>can i see both com ports together?I guess not.</p><p>However i tried following connectoion</p><p>computer -ftdi cable( rx &gt;tx(software arduino ),tx&gt;rx(software arduino)) AND USB cable-arduino(hardware rx&gt;tx esp,harware tx&gt;rx esp)</p><p>5)Also found that Serial.find is not working.</p><p>6) When i said i normally checked esp with serial monitor,I did the the following.</p><p>a) Loaded bare minimum sketch in arduino.</p><p>b) connected tx&gt;tx and rx&gt;rx of arduino and esp.</p><p>c) sent at commands manually and it was receiving and sending fine at baud rate 115200.</p><p>Thanking you,</p>
<p>Hello,</p><p>Can you kindly confirm where to put the api key. This is how I tried to use it, but the data wasn't sent. To simplify things, I am not reading data from sensors. I just put some static values to see if they go through.</p><p>Using Arduino Nano and ESP8266-01</p><p>value_temp = 22; //analogRead(sensor_temp);<br> value_light = 0;//analogRead(sensor_light);<br> value_humid = 30;//analogRead(sensor_humid);</p><p>Please confirm the lines below. I didn't modify the commented line, but part of my key is in the second line.</p><p>// GET /update?key=[THINGSPEAK_KEY]&amp;field1=[data 1]&amp;field2=[data 2]...;</p><p>String GET = &quot;GET /update?key=9W8Z902N4YE&quot;;</p>
<p>Thanks for the tutorial, was very helpful. i spent lot of hours <br>trying to fix the DHT.cpp ERROR till i came accros this and it really <br>help. Thanks once again<br></p>
<p>Good. I hope it is of some comfort that I also lost hours on that error :-)</p><p>Be careful updating your libraries, I think the error is still present</p>
<p>Hey great tutorial thank you! I have difficulty sending the program from IDE to the arduino (i am using the arduino uno and a 8266 with two analog sensors). The program only uploads when I disconnect the Rx pin on the arduino (which is connected to the TX pin on the ESP). Without this connection, the program info isn't sent to things speak. Any suggestions? Also, will the program you posted connect to the ESP even after I have programmed the ESP to connect atuomatically to my phone's hotspot. </p>
<p>Pierce, let me start with yr last question. If you programmed any program in your esp, the AT instruction set is gone.</p><p>With regard to yr 1st question: indeed you cannot upload anything to your arduino if you have something else attached to the serialport. It is not the intention to keep uploading the program. You upload it once.to be able to connect the esp8266 and being able to debug the program defines a software serialport as well.</p><p>Having said this. Currently i would not attach an arduino to an esp8266 anymore as the esp can usually handle it alone</p>
<p>Hey man, nice tutorial, but it should be split into separate projects, because it's very long and complex and confusing.</p><p>Great work!</p>
<p>Tnx, maybe i could split it in different projects, but I thought make it a one stop place for Thingspeak. I will see if maybe I can clarify the different sections a bit more</p>
<p>hello can anyone help!!! , i want to upload water sensor data to thingspeak,I connected my ESP8266 with arduino uno, and took this code and made a little changes on it to serve my goal.</p><p>however no matter what i do the serial monitor gives these repeated lines:<br>AT+CIPSTART=&quot;TCP&quot;,&quot;184.106.153.149&quot;,80</p><p>AT+CIPSEND=52</p><p>AT+CIPCLOSE</p><p>I should mention that i didn't update the ESP8266 firmware, and its still with the same setting as i bought it, the power also is supplied from the arduino 3.3v pin, i know i should make a separate power supply, but i checked the voltage and it reads 3.3 at all pins. </p><p>this is my modified code:</p><p>#include &lt;SoftwareSerial.h&gt;</p><p>int sensor_water = A0;</p><p>int value_water;</p><p>#define DEBUG FALSE //comment out to remove debug msgs</p><p>//*-- Hardware Serial</p><p>#define _baudrate 9600</p><p>//*-- Software Serial</p><p>//</p><p>#define _rxpin 2</p><p>#define _txpin 3</p><p>SoftwareSerial debug( _rxpin, _txpin ); // RX, TX</p><p>//*-- IoT Information</p><p>#define SSID &quot;[waterfirst]&quot;</p><p>#define PASS &quot;[waterfirst]&quot;</p><p>#define IP &quot;184.106.153.149&quot; // ThingSpeak IP Address: 184.106.153.149</p><p>// GET /update?key=[THINGSPEAK_KEY]&amp;field1=[data 1]&amp;field2=[data 2]...;</p><p>String GET = &quot;GET /update?key=fghdhgdfhgdfahadh&amp;field1=0&quot;;</p><p>void setup() {</p><p>Serial.begin( _baudrate );</p><p>debug.begin( _baudrate );</p><p>sendDebug(&quot;AT&quot;);</p><p>delay(5000);</p><p>if(Serial.find(&quot;OK&quot;))</p><p>{</p><p>debug.println(&quot;RECEIVED: OK\nData ready to sent!&quot;);</p><p>connectWiFi();</p><p>}</p><p>}</p><p>void loop() {</p><p>value_water = analogRead(sensor_water);</p><p>String water =String(value_water);// turn integer to string</p><p>updateTS(water);</p><p>delay(3000); //</p><p>}</p><p>//----- update the Thingspeak string with 1 value</p><p>void updateTS( String W)</p><p>{</p><p>// ESP8266 Client</p><p>String cmd = &quot;AT+CIPSTART=\&quot;TCP\&quot;,\&quot;&quot;;// Setup TCP connection</p><p>cmd += IP;</p><p>cmd += &quot;\&quot;,80&quot;;</p><p>sendDebug(cmd);</p><p>delay(2000);</p><p>if( Serial.find( &quot;Error&quot; ) )</p><p>{</p><p>debug.print( &quot;RECEIVED: Error\nExit1&quot; );</p><p>return;</p><p>}</p><p>cmd = GET + &quot;&amp;field1=&quot; + W +&quot;\r\n&quot;;</p><p>Serial.print( &quot;AT+CIPSEND=&quot; );</p><p>Serial.println( cmd.length() );</p><p>if(Serial.find( &quot;&gt;&quot; ) )</p><p>{</p><p>debug.print(&quot;&gt;&quot;);</p><p>debug.print(cmd);</p><p>Serial.print(cmd);</p><p>}</p><p>else</p><p>{</p><p>sendDebug( &quot;AT+CIPCLOSE&quot; );//close TCP connection</p><p>}</p><p>if( Serial.find(&quot;OK&quot;) )</p><p>{</p><p>debug.println( &quot;RECEIVED: OK&quot; );</p><p>}</p><p>else</p><p>{</p><p>debug.println( &quot;RECEIVED: Error\nExit2&quot; );</p><p>}</p><p>}</p><p>void sendDebug(String cmd)</p><p>{</p><p>debug.print(&quot;SEND: &quot;);</p><p>debug.println(cmd);</p><p>Serial.println(cmd);</p><p>}</p><p>boolean connectWiFi()</p><p>{</p><p>Serial.println(&quot;AT+CWMODE=1&quot;);//WiFi STA mode - if '3' it is both client and AP</p><p>delay(2000);</p><p>//Connect to Router with AT+CWJAP=&quot;SSID&quot;,&quot;Password&quot;;</p><p>// Check if connected with AT+CWJAP?</p><p>String cmd=&quot;AT+CWJAP=\&quot;&quot;; // Join accespoint</p><p>cmd+=SSID;</p><p>cmd+=&quot;\&quot;,\&quot;&quot;;</p><p>cmd+=PASS;</p><p>cmd+=&quot;\&quot;&quot;;</p><p>sendDebug(cmd);</p><p>delay(5000);</p><p>if(Serial.find(&quot;OK&quot;))</p><p>{</p><p>debug.println(&quot;RECEIVED: OK&quot;);</p><p>return true;</p><p>}</p><p>else</p><p>{</p><p>debug.println(&quot;RECEIVED: Error&quot;);</p><p>return false;</p><p>}</p><p>cmd = &quot;AT+CIPMUX=0&quot;;// Set Single connection</p><p>sendDebug( cmd );</p><p>if( Serial.find( &quot;Error&quot;) )</p><p>{</p><p>debug.print( &quot;RECEIVED: Error&quot; );</p><p>return false;</p><p>}</p><p>}</p>
<p>which ESP8266 model?</p>
<p>ESP8266-01 black </p>
<p>before anything else, I strongly advise trying to feed it from a proper psu. Most of these problems are from an insufficient psu. that it still measures 3.3 does not mean that much, as the esp8266 may experience short drops as it starts sending... and then reset itself</p>
<p>I am really stuck with powering the ESP8266, till the point i think i burned the chip it self, is there any way to know if its still working or not.</p><p>I tried powering it from a regulator with a 3.3V and intensity up to 500mA, i tried voltage divider circuit and nothing, nothing is working. <br>the only thing i can do is send these commands <br>AT</p><p>AT+RST </p><p>AT+GMR </p><p>i think i managed to update its firmware as i get new version when i send this command AT+GMR, but rather than that nothing.</p><p>i see a lot of pages saying use (logic level shifter, use voltage regulator, use FTDI.... but i don't know i tried too many things and its not working).<br></p>
<p>well why not try the ESP826 with only one simple peripheral that doesnt <br>need any levelshifters like an LDR or a potentiometer, justto see if it <br>is working. Don't add an arduino but send it directly to Thingspeak, or <br>check it in your serial port. If an analog water sensor is all you need, an arduino is unnecessary<br>As long as it reacts to AT commands the chip is probably OK.<br><br>Use levelshifter... only necessary if you connect it to 5V hardware<br>Use voltage regulator.... yes in your psu<br>Use FTDI... indeed, to upload a program<br><br>Have<br> a look at my more recent ESP8266 instructables that use no <br>levelshifters, no arduino, just some simple peripheral hardware, and <br>connects to Thingspeak</p>
<p>hey guys..I am doing my final year project based on the cloud based Transformer monitoring system and I am using Think Speak to store my data and using Arduino Ethernet Shield along with the DHT 22 temperature sensor. i tried to use the above code provided but still not able to send the data to thinkspeak. In the serial monitor it say that &quot;Connecting Arduino with network&quot; and that all..can someone help me with the code..</p>
<p>if you used that code it should work, or at least the problem should not be in the code. Are you using the correct library?</p>
<p>the only thing i can see in the serial monitor saying that &quot;Connecting Arduino with network&quot; so that mean that there is something wrong in the loop that cause this problem..isnt it</p>
<p>well still could be other reasons why it is not connecting, but can you tell me are you using exactly the code I published here? Which library are you using and which version of the Ethernet shield?</p>
<p>I have interfaced Arduino Mega2560 with ESP8266-01,DHT11 temperature sensor and humidity sensor.</p><p>We have created Node.Js server in our office network for testing purpose. </p><p>Now i am able to send the data to Node.js server that is temperature and humidity values are getting updated to Node.js server.</p><p>Now i am stucked in receiving the data from Node.Js server(date and time from internet, also some parameters like a1,a2 etc for testing ) to ESp8266 and have to display on serial monitor of arduino,then TFT screen which is not happening .</p><p>Any Idea.</p>
<p>Keshavadk, sorry but I have no experience with Node.js server, so i have no idea what the problem could be. Maybe someone else knows</p>
<p>Hello!<br>I'm trying to modify the code in step 3 with 3 sensors but already in beginning I'm getting an error: 'debug' was not declared in this scope . I'm using arduino 1.6.9. and nodemcu 1.0 ESP-12E<br>thanks for help.</p>
<p>is that a fully unaltered code that gave you that error? did you perhaps not include the #define DEBUG ? or did you forget to include the software serial?</p>
<p>yes i just copy and past it in IDE without url's. now somehow it stops making me debug error but it making me error for 'A1' and 'A2' was not declared in this scope...A0 is somehow ok...</p>
<p>that is odd as A1 and A2 are just standard descriptions of the analog ports. May I first suggest you restart yr IDE and or computer</p>
<p>now is finally working and hope is gonna stay in that way<br>thanks</p>
<p>ok good to hear that. what did you do to make it work?</p>
<p>i change the code for dht22 and mg811 sensors :)<br>now I just need to figure out how to read this data on AP because I don't have wifi or internet in place where i'm using them.<br>` <br>#include &lt;DHT.h&gt;</p><p>#include &lt;SoftwareSerial.h&gt;</p><p>#define DHTPIN 0</p><p>#define DHTTYPE DHT22</p><p>DHT dht(DHTPIN, DHTTYPE);</p><p>int ppm;</p><p>#define MG_PIN (A0) //define which analog input channel you are going to use</p><p>#define BOOL_PIN (8)</p><p>#define DC_GAIN (11.5) //define the DC gain of amplifier</p><p>#define READ_SAMPLE_INTERVAL (200) //define how many samples you are going to take in normal operation</p><p>#define READ_SAMPLE_TIMES (5) //define the time interval(in milisecond) between each samples in </p><p> //normal operation</p><p>#define ZERO_POINT_VOLTAGE (0.240) //define the output of the sensor in volts when the concentration of CO2 is 400PPM</p><p>#define REACTION_VOLTGAE (0.050) //define the voltage drop of the sensor when move the sensor from air into 1000ppm CO2</p><p>float CO2Curve[3] = {2.602,ZERO_POINT_VOLTAGE,(REACTION_VOLTGAE/(2.602-3))}; </p><p>#define DEBUG FALSE //comment out to remove debug msgs</p><p>//*-- Hardware Serial</p><p>#define _baudrate 9600</p><p>//*-- Software Serial</p><p>//</p><p>#define _rxpin 2</p><p>#define _txpin 3</p><p>SoftwareSerial debug( _rxpin, _txpin ); // RX, TX</p><p>//*-- IoT Information</p><p>#define SSID &quot;ESP&quot;</p><p>#define PASS &quot;asdfgh&quot;</p><p>#define IP &quot;192.168.4.1&quot; </p><p>void setup() {</p><p> Serial.begin( _baudrate );</p><p> debug.begin( _baudrate );</p><p> dht.begin();</p><p> sendDebug(&quot;AT&quot;);</p><p> delay(5000);</p><p> if(Serial.find(&quot;OK&quot;))</p><p> {</p><p> debug.println(&quot;RECEIVED: OK\nData ready to sent!&quot;);</p><p> connectWiFi();</p><p> }</p><p> pinMode(BOOL_PIN, INPUT); //set pin to input</p><p> digitalWrite(BOOL_PIN, HIGH); </p><p>}</p><p>void loop() {</p><p> int percentage;</p><p> float volts;</p><p> volts = MGRead(MG_PIN);</p><p> percentage = MGGetPercentage(volts,CO2Curve);</p><p> float h = dht.readHumidity(); </p><p> float t = dht.readTemperature();</p><p> String temp =String(t);// turn integer to string </p><p> String humid=String(h);// turn integer to string</p><p> String ppm= String(percentage);// turn integer to string</p><p> updateTS(temp, humid, ppm);</p><p> delay(3000); //</p><p>}</p><p>//----- update the Thingspeak string with 3 values</p><p>void updateTS( String T, String P , String H)</p><p>{</p><p> // ESP8266 Client</p><p> String cmd = &quot;AT+CIPSTART=\&quot;TCP\&quot;,\&quot;&quot;;// Setup TCP connection</p><p> cmd += IP;</p><p> cmd += &quot;\&quot;,80&quot;;</p><p> sendDebug(cmd);</p><p> delay(2000);</p><p> if( Serial.find( &quot;Error&quot; ) )</p><p> {</p><p> debug.print( &quot;RECEIVED: Error\nExit1&quot; );</p><p> return;</p><p> }</p><p> cmd = &quot;&amp;field1=&quot; + T +&quot;&amp;field2=&quot;+ P + &quot;&amp;field3=&quot; + H +&quot;\r\n&quot;;</p><p> Serial.print( &quot;AT+CIPSEND=&quot; );</p><p> Serial.println( cmd.length() );</p><p> if(Serial.find( &quot;&gt;&quot; ) )</p><p> {</p><p> debug.print(&quot;&gt;&quot;);</p><p> debug.print(cmd);</p><p> Serial.print(cmd);</p><p> }</p><p> else</p><p> {</p><p> sendDebug( &quot;AT+CIPCLOSE&quot; );//close TCP connection</p><p> }</p><p> if( Serial.find(&quot;OK&quot;) )</p><p> {</p><p> debug.println( &quot;RECEIVED: OK&quot; );</p><p> }</p><p> else</p><p> {</p><p> debug.println( &quot;RECEIVED: Error\nExit2&quot; );</p><p> }</p><p>}</p><p>void sendDebug(String cmd)</p><p>{</p><p> debug.print(&quot;SEND: &quot;);</p><p> debug.println(cmd);</p><p> Serial.println(cmd);</p><p>}</p><p>boolean connectWiFi()</p><p>{</p><p> Serial.println(&quot;AT+CWMODE=1&quot;);//WiFi STA mode - if '3' it is both client and AP</p><p> delay(2000);</p><p> //Connect to Router with AT+CWJAP=&quot;SSID&quot;,&quot;Password&quot;;</p><p> // Check if connected with AT+CWJAP?</p><p> String cmd=&quot;AT+CWJAP=\&quot;&quot;; // Join accespoint</p><p> cmd+=SSID;</p><p> cmd+=&quot;\&quot;,\&quot;&quot;;</p><p> cmd+=PASS;</p><p> cmd+=&quot;\&quot;&quot;;</p><p> sendDebug(cmd);</p><p> delay(5000);</p><p> if(Serial.find(&quot;OK&quot;))</p><p> {</p><p> debug.println(&quot;RECEIVED: OK&quot;);</p><p> return true;</p><p> }</p><p> else</p><p> {</p><p> debug.println(&quot;RECEIVED: Error&quot;);</p><p> return false;</p><p> }</p><p> cmd = &quot;AT+CIPMUX=0&quot;;// Set Single connection</p><p> sendDebug( cmd );</p><p> if( Serial.find( &quot;Error&quot;) )</p><p> {</p><p> debug.print( &quot;RECEIVED: Error&quot; );</p><p> return false;</p><p> }</p><p>}</p><p>float MGRead(int mg_pin)</p><p>{</p><p> int i;</p><p> float v=0;</p><p> for (i=0;i&lt;READ_SAMPLE_TIMES;i++) {</p><p> v += analogRead(mg_pin);</p><p> delay(READ_SAMPLE_INTERVAL);</p><p> }</p><p> v = (v/READ_SAMPLE_TIMES) *5/1024 ;</p><p> return v; </p><p>}</p><p>int MGGetPercentage(float volts, float *pcurve)</p><p>{</p><p> if ((volts/DC_GAIN )&gt;=ZERO_POINT_VOLTAGE) {</p><p> return -1;</p><p> } else { </p><p> return pow(10, ((volts/DC_GAIN)-pcurve[1])/pcurve[2]+pcurve[0]);</p><p> }</p><p>}<br>`</p>
<p>ah ok thanks. So in th eend it turned out to be a sensor issue and not an ESP8266 issue. Not sure why you want to contact an AP if no internet</p>
<p>yes<br>because the AP is on another ESP8266 and it's connected to arduino to collect this sensors values.</p>
<p>Ah yes, clear.</p>
<p>How to modify this code to add thingspeak twitter app to get twitter alert if it reaches a certain temperature ,</p><p>#include&lt;stdlib.h&gt;<br>#include &quot;DHT.h&quot;<br><br>#define SSID &quot;AO5510&quot;//your network name<br>#define PASS &quot;&quot;//your network password<br>#define IP &quot;&quot; // thingspeak.com<br>#define DHTPIN 7 // what pin the DHT sensor is connected to<br>#define DHTTYPE DHT11 // Change to DHT22 if that's what you have<br>#define Baud_Rate 115200 //Another common value is 9600<br>#define GREEN_LED 3 //optional LED's for debugging<br>#define RED_LED 4 //optional LED's for debugging<br>#define DELAY_TIME 60000 //time in ms between posting data to ThingSpeak<br><br>//Can use a post also<br>String GET = &quot;GET /update?key=N7BMROH65LC8OBH8&amp;field1=&quot;;<br>String FIELD2 = &quot;&amp;field2=&quot;;<br><br>//if you want to add more fields this is how<br>//String FIELD3 = &quot;&amp;field3=&quot;;<br><br>bool updated;<br><br>DHT dht(DHTPIN, DHTTYPE);<br><br>//this runs once<br>void setup()<br>{<br> Serial.begin(Baud_Rate);<br> Serial.println(&quot;AT&quot;);<br> <br> delay(5000);<br> <br> if(Serial.find(&quot;OK&quot;)){<br> //connect to your wifi netowork<br> bool connected = connectWiFi();<br> if(!connected){<br> //failure, need to check your values and try again<br> Error();<br> }<br> }else{<br> Error();<br> }<br> <br> //initalize DHT sensor<br> dht.begin();<br>}<br><br>//this runs over and over<br>void loop(){<br> float h = dht.readHumidity();<br> // Read temperature as Fahrenheit (isFahrenheit = true)<br> float f = dht.readTemperature(true);<br><br> // Check if any reads failed and exit early (to try again).<br> if (isnan(h) || isnan(f)) {<br> LightRed();<br> return;<br> }<br> <br> //update ThingSpeak channel with new values<br> updated = updateTemp(String(f), String(h));<br> <br> //if update succeeded light up green LED, else light up red LED<br> if(updated){<br> LightGreen();<br> }else{<br> LightRed();<br> }<br> <br> //wait for delay time before attempting to post again<br> delay(DELAY_TIME);<br>}<br><br>bool updateTemp(String tenmpF, String humid){<br> //initialize your AT command string<br> String cmd = &quot;AT+CIPSTART=\&quot;TCP\&quot;,\&quot;&quot;;<br> <br> //add IP address and port<br> cmd += IP;<br> cmd += &quot;\&quot;,80&quot;;<br> <br> //connect<br> Serial.println(cmd);<br> delay(2000);<br> if(Serial.find(&quot;Error&quot;)){<br> return false;<br> }<br> <br> //build GET command, ThingSpeak takes Post or Get commands for updates, I use a Get<br> cmd = GET;<br> cmd += tenmpF;<br> cmd += FIELD2;<br> cmd += humid;<br> <br> //continue to add data here if you have more fields such as a light sensor<br> //cmd += FIELD3;<br> //cmd += &lt;field 3 value&gt;<br> <br> cmd += &quot;\r\n&quot;;<br> <br> //Use AT commands to send data<br> Serial.print(&quot;AT+CIPSEND=&quot;);<br> Serial.println(cmd.length());<br> if(Serial.find(&quot;&gt;&quot;)){<br> //send through command to update values<br> Serial.print(cmd);<br> }else{<br> Serial.println(&quot;AT+CIPCLOSE&quot;);<br> }<br> <br> if(Serial.find(&quot;OK&quot;)){<br> //success! Your most recent values should be online.<br> return true;<br> }else{<br> return false;<br> }<br>}<br> <br>boolean connectWiFi(){<br> //set ESP8266 mode with AT commands<br> Serial.println(&quot;AT+CWMODE=1&quot;);<br> delay(2000);<br><br> //build connection command<br> String cmd=&quot;AT+CWJAP=\&quot;&quot;;<br> cmd+=SSID;<br> cmd+=&quot;\&quot;,\&quot;&quot;;<br> cmd+=PASS;<br> cmd+=&quot;\&quot;&quot;;<br> <br> //connect to WiFi network and wait 5 seconds<br> Serial.println(cmd);<br> delay(5000);<br> <br> //if connected return true, else false<br> if(Serial.find(&quot;OK&quot;)){<br> return true;<br> }else{<br> return false;<br> }<br>}<br><br>void LightGreen(){<br> digitalWrite(RED_LED, LOW);<br> digitalWrite(GREEN_LED, HIGH); <br>}<br><br>void LightRed(){<br> digitalWrite(GREEN_LED, LOW);<br> digitalWrite(RED_LED, HIGH);<br>}<br><br>//if an error has occurred alternate green and red leds<br>void Error(){ <br> while(true){ <br> LightRed(); <br> delay(2000); <br> LightGreen();<br> delay(2000);<br> } }</p>
<p>you dont have to change your code for that. Thingspeak can do that for you </p><p><a href="https://nl.mathworks.com/help/thingspeak/act-on-your-data.html?searchHighlight=twitter">https://nl.mathworks.com/help/thingspeak/act-on-yo...</a></p>
<p>Check my project at </p><p>https://www.instructables.com/id/SMART-WEATHER-STATION/</p>
<p>well done</p>
<p>diy_bloke hello again :)</p><p>i am looking for the right sequence of posting to thingspeak , same project as above but using &quot;post&quot; methode rather then &quot;get&quot; method.</p><p>i am confused on the right sequence and syntax just after</p><p>openning the tcp ip and cipsend = length etc.</p><p>there is a chunk of http coding which comes line after the other with or without cr/lf's</p><p>like so which i copied from some other blog:- </p><p>--------------------------------------------</p><p>POST /update HTTP/1.1\n</p><p>Host: api.thingspeak.com\n</p><p>Connection: close\n</p><p>X-THINGSPEAKAPIKEY:[my api key here]\n</p><p>Content-Type: application/x-www-form-urlencoded\n</p><p>Content-Length: 32\n</p><p>field1=200&amp;field2=300&amp;field2=400\n</p><p>--------------------------------------------------------------------</p><p>closest i got was bad request from the ts server. while trying it on the SERIAL console.</p><p>do you have ready made working example for that ? ()</p><p>thanks</p><p>Oded.</p>
<p>if you ask me the sequence shld be as follows:</p><p>/*------------------------------------------------<br>Sends sensor data to Thingspeak<br>Inputs: String, data to be entered for each field<br>Returns: <br>------------------------------------------------*/<br>void ThingSpeakUpdate(String tsData)<br>{<br> Serial.println(&quot;Date string: &quot; + tsData);<br><br> Serial.println(&quot;...Connecting to Thingspeak&quot;);<br><br> // Connecting and sending data to Thingspeak<br> if(client.connect(&quot;api.thingspeak.com&quot;, 80))<br> {<br> Serial.println(&quot;...Connection succesful, updating datastreams&quot;);<br><br> client.print(&quot;POST /update HTTP/1.1\n&quot;);<br> client.print(&quot;Host: api.thingspeak.com\n&quot;);<br> client.print(&quot;Connection: close\n&quot;);<br> client.print(&quot;X-THINGSPEAKAPIKEY: &quot;+writeAPIKey+&quot;\n&quot;);<br> client.print(&quot;Content-Type: application/x-www-form-urlencoded\n&quot;);<br> client.print(&quot;Content-Length: &quot;);<br> client.print(tsData.length());<br> client.print(&quot;\n\n&quot;);<br><br> client.println(tsData); //the &quot;&quot;ln&quot; is important here.<br><br> // This delay is pivitol without it the TCP client will often close before the data is fully sent<br> delay(200);<br><br> Serial.println(&quot;Thingspeak update sent.&quot;);<br> }<br> else{<br> // Failed to connect to Thingspeak<br> Serial.println(&quot;Unable to connect to Thingspeak.&quot;);<br> }<br><br> if(!client.connected()){<br> client.stop();<br> }<br> client.flush();<br> client.stop();<br>}</p><p>now that is more or less like you have it, but you could try my routine</p>
Diy_bloke hi again and thanks for your fenomenal output!.<br><br>First the remarks regarding &quot; /n/r &quot; s is one thing <br>I needed.<br><br><br>Second<br><br>What is the client.print class you suggests and why cant i see <br>To which port in my arduino i am tx rx to<br><br>I assum the client object encapsulates whithin the wifi,and connection to server.(thingspeak)<br><br>This is confusing.<br><br><br>Thanks<br><br>Oded:)<br>
<p>sorry, the client.print class is from the Ethernet library, but as you are using ESP8266 I didnt think that was of relevance to you. only sent it to show the sequence</p>
<p>hi DIY_BLOKE</p><p>by now i am running the post sequence, with a sketch that i belive emulate</p><p>etehrnet library sketch </p><p>these are the fellows:- </p><p> &lt;WiFiEsp.h&gt;</p><p> &lt;WiFiEspClient.h&gt;</p><p> &lt;WiFiEspServer.h&gt;</p><p>it lets me define the serial1 as the hw serial for the esp8266 communication,(since other ethernet shields commnicate i believe over spi not like our esp8266-01)<br>and &quot;speak&quot; to the server in a client stuff vocabulary.</p><p>i found it extremely hard to figure out.</p><p>Actually here it is , stripped of all sensor data collection dht etc.</p><p>if it helps getting others to get themselves through POST or even GET using<br>ethernet shields vocabulary .</p><p>and maybe i contribute here something after all help i got from you.<br><br><br>CHEERS:)</p><p>---------------------just comm. without dht sensor library--------------------------------------------------------------------</p><p>#include &lt;WiFiEsp.h&gt;</p><p>#include &lt;WiFiEspClient.h&gt;</p><p>#include &lt;WiFiEspServer.h&gt;</p><p>#include &lt;WiFiEspUdp.h&gt;</p><p>String apiKey =&quot;QR74QZBRXADXPC3C&quot;; // api from ts</p><p>char MY_SSID[] = &quot;******************&quot;;</p><p>char MY_PWD[] = &quot;*******************&quot;;</p><p>#define WEBSITE &quot;api.thingspeak.com&quot;</p><p>//or const char* WEBSITE = &quot;api.thingspeak.com&quot;; if you prefer</p><p>void setup()</p><p>{</p><p> Serial.begin(9600);</p><p> Serial1.begin(115200);</p><p>WiFi.init(&amp;Serial1);//&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;</p><p>Serial.print(&quot;Connecting to &quot;);</p><p>Serial.println(MY_SSID);</p><p>WiFi.begin(MY_SSID, MY_PWD);</p><p> while (WiFi.status() != WL_CONNECTED) //not connected, ...waiting to connect</p><p> {</p><p> delay(1000);</p><p> Serial.print(&quot;.&quot;);</p><p> }</p><p> Serial.println(&quot;&quot;);</p><p> Serial.println(&quot;Credentials accepted! Connected to wifi\n &quot;);</p><p> Serial.println(&quot;&quot;);</p><p>}</p><p>void loop()</p><p>{</p><p> // HERE I ASSIGN SOME FAKE DATA TO 3 FIELDS </p><p> delay(2000);</p><p> // float h = dht.readHumidity();</p><p> float h =400;</p><p> // Read temperature as Celsius (the default)</p><p> //float t = dht.readTemperature();</p><p> float t = 400;</p><p> // Read temperature as Fahrenheit (isFahrenheit = true)</p><p> //float f = dht.readTemperature(true);</p><p> float f = 400;</p><p> // Check if any reads failed and exit early (to try again).</p><p> if (isnan(h) || isnan(t) || isnan(f))</p><p> {</p><p> Serial.println(&quot;Failed to read from DHT sensor!&quot;);</p><p> return;</p><p> }</p><p>//</p><p>// // Compute heat index in Fahrenheit (the default)</p><p>// float hif = dht.computeHeatIndex(f, h);</p><p>// // Compute heat index in Celsius (isFahreheit = false)</p><p>// float hic = dht.computeHeatIndex(t, h, false);</p><p> Serial.print(&quot;Humidity: &quot;);</p><p> Serial.print(h);</p><p> Serial.print(&quot; %\t&quot;);</p><p> Serial.print(&quot;Temperature: &quot;);</p><p> Serial.print(t);</p><p> Serial.print(&quot; *C &quot;);</p><p> Serial.print(f);</p><p> Serial.print(&quot; *F\t&quot;);</p><p>//WiFiClient client;</p><p>WiFiEspClient client;</p><p> if (client.connect(WEBSITE, 80))</p><p> { </p><p> Serial.println(&quot;WiFi Client connected &quot;);</p><p>//</p><p>// client.print(F(&quot;POST &quot;));</p><p>// client.print(&quot;/update?key=apiKey&amp;field1=&quot; </p><p>// + (String) h</p><p>// +&quot;&amp;field2=&quot; +(String) t</p><p>// +&quot;&amp;field3=&quot; +(String) f</p><p>// );</p><p> //need the length of our data string to give to ThingSpeak</p><p> String tsData = &quot;&amp;field1=&quot;+(String)h+&quot;&amp;field2=&quot; +(String)t+&quot;&amp;field3=&quot;+(String)f;</p><p> client.print(&quot;POST /update HTTP/1.1\n&quot;); //alternate sans 'update'client.print(F(&quot; HTTP/1.1\r\n&quot;));</p><p> client.print(&quot;Host: api.thingspeak.com\n&quot;);</p><p> client.print(&quot;Connection: close\n&quot;);</p><p> client.print(&quot;X-THINGSPEAKAPIKEY: &quot; + apiKey + &quot;\n&quot;);</p><p> client.print(&quot;Content-Type: application/x-www-form-urlencoded\n&quot;);</p><p> client.print(&quot;Content-Length: &quot;);</p><p> client.print(tsData.length()); //send out data string legth to ts</p><p> client.print(&quot;\n\n&quot;);</p><p> client.print(tsData);</p><p> delay(1000);</p><p> } //end client connect</p><p> else Serial.print(&quot;couldnt connect to ThingSpeak\n&quot;); //if client connect failed</p><p> client.stop();</p><p>}</p><p>-------------------------------------------------------------------------------------</p>

About This Instructable

174,731views

184favorites

License:

Bio: I am a physician by trade. After a career in the pharmeceutical world I decided to take it a bit slower and do things I ... More »
More by diy_bloke:Working With the Funduino W5100 Ethernet Module. Uploading Data to ThingSpeak With MQTT Adding an MCP23017 I/O Extender to Arduino or ESP8266 
Add instructable to: