The use of the ESP8266 in the world of IoT

User avatar
By sheel1995
#64352 Hi Guys, So I am trying to get a simple json data from data.json file which is up on a hosting website alongwith other things. I am using esp8266 using AT commands via Arduino. The code is quite simple.
Code: Select all#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;
String ssid = "MY_SSID";
String password = "MY_PASS";
SoftwareSerial esp8266 (rxPin, txPin);
String path = "/data.json";
String server = "wsiproject995.000webhostapp.com";
String getRequest = "GET " + path + " HTTP/1.1\r\n" + "Host: " + server + "\r\n" + "Connection: keep-alive\r\n\r\n";
String getRequestLength = String(getRequest.length());
String response="";
void setup() {
  Serial.begin(9600);
  esp8266.begin(9600);
  delay(1000);
  reset();
  //setMode("1");
  connectWifi();
  }

void loop() {
  esp8266.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");
  if(esp8266.find("OK")) Serial.println("TCP Connection Ready");
  esp8266.println("AT+CIPSEND=" + getRequestLength);
  if(esp8266.find(">")) {
    Serial.println("Sending Request...");
    esp8266.print(getRequest);
    }
  if(esp8266.find("SEND OK")) Serial.println("Request Sent");
  while(!esp8266.available()) {};
  espRead();
  esp8266.println("AT+CIPCLOSE");
  if(esp8266.find("OK")) Serial.println("TCP Connection Closed");
  delay(5000);
  }

void espRead() {
  String c;
  while(esp8266.available()) {
    c = esp8266.readString();
    Serial.print(c);
    }
  }

void espClear() {
  while(esp8266.available()) {
    esp8266.read();
    }
  }

void reset() {
  Serial.println("Resetting WiFi");
  esp8266.println("AT+RST");
  delay(1000);
  if(esp8266.find("OK")) Serial.println("Reset!");
  }

void connectWifi() {
  espClear();
  Serial.println("Connecting...");
  String CMD = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";
  esp8266.println(CMD);
  while(!esp8266.available()) {};
  if(esp8266.find("OK")) Serial.println("Connected");
  else Serial.println("Couldn't connect to WiFi");
  }

void setMode(String mode) {
    Serial.println("Setting Mode = " + mode);
    esp8266.println("AT+CWMODE=" + mode);
    delay(1000);
    espRead();
    }


This gives me a response
Code: Select all+IPD,369:HTTP/1.1 200 OK
Date: Wed, 29 Mar 2017 01:59:13 GMT
Content-Type: application/json
Content-Length: 41
Connection: keep-alive
Last-Modified: Tue, 28 Mar 2017 14:32:57 GMT
Accept-Ranges: bytes
Server: awex
X-Xss-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Request-ID: b7864810f7110d2fd22278ddb9c8ebeb

{"relay":"OFF","current":10,"energy":200}
OK


The problem is that it prints a "OK" at the last line. From the examples I've looked this shouldn't happen.
What I want is to get the json string data out into a separate variable so I can parse it using some library.
I've tried using esp.8266.find("\r\n\r\n") or esp8266.readStringUntil("\r\n\r\n") and them do esp8266.readString() I get nothing.
Help.
Thanks.