ROJ
ROJ

Reputation: 57

Sending data to Thingspeak using ESP8266

I am trying to send data to Thingspeak using ESP8266. I am using this code that I downloaded from internet, but I am still unable to connect to WiFi.

#include <SoftwareSerial.h>
#define RX 2
#define TX 3

String AP = "Gladiator";           // CHANGE ME
String PASS = "1212ftth";          // CHANGE ME
String API = "PDRVGWQZWF6J25LR";   // CHANGE ME
String HOST = "api.thingspeak.com";
String PORT = "80";
String field = "field1";
int countTrueCommand;
int countTimeCommand; 
boolean found = false; 
int valSensor = 1;
SoftwareSerial esp8266(RX,TX); 
  
void setup() {
  Serial.begin(9600);
  esp8266.begin(115200);
  sendCommand("AT",5,"OK");
  sendCommand("AT+CWMODE=1",5,"OK");
  sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK");
}

void loop() {
 valSensor = getSensorData();
 String getData = "GET /update?api_key=" + API + "&" + field + "=" + String(valSensor);
 sendCommand("AT+CIPMUX=1",5,"OK");
 sendCommand("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT,15,"OK");
 sendCommand("AT+CIPSEND=0," + String(getData.length()+4),4,">");
 esp8266.println(getData);
 delay(1500);
 countTrueCommand++;
 sendCommand("AT+CIPCLOSE=0",5,"OK");
}

int getSensorData(){
  return random(1000); // Replace with 
}

void sendCommand(String command, int maxTime, char readReplay[]) {
  Serial.print(countTrueCommand);
  Serial.print(". at command => ");
  Serial.print(command);
  Serial.print(" ");
  while (countTimeCommand < (maxTime*1)) {
    esp8266.println(command);//at+cipsend
    if (esp8266.find(readReplay)) {
      found = true;
      break;
    }
    countTimeCommand++;
  }

  if (found == true) {
    Serial.println("OYI");
    countTrueCommand++;
    countTimeCommand = 0;
  }
  
  if (found == false) {
    Serial.println("Fail");
    countTrueCommand = 0;
    countTimeCommand = 0;
  }
  found = false;
}

I checked my circuit several times and everything is in the right place. Can anybody tell me what is the problem or show me a better way to connect to Thingspeak?

Upvotes: 0

Views: 935

Answers (1)

Christopher Stapels
Christopher Stapels

Reputation: 1

You should use the ESP to connect directly to ThingSpeak. You shouldn't have to use AT commands.

Have a look at the examples in the ThingSpeak write data documentation. There is a section on ESP8266. If you must use the AT commands, I suggest looking at the examples in the ThingSpeak Library for Arduino. There are also examples for connecting directly without using the AT commands in the library.

Upvotes: 0

Related Questions