ITEADLIB_Arduino_WeeESP8266 android response

im planing to do a project that using Arduino+esp8266 with android device,

at first my code was something like this.

#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(9,10); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                         // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                         // and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different

  pinMode(11,OUTPUT);
  digitalWrite(11,LOW);

  pinMode(12,OUTPUT);
  digitalWrite(12,LOW);

  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);

  pinMode(10,OUTPUT);
  digitalWrite(10,LOW);

  sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
  sendCommand("AT+CWMODE=1\r\n",1000,DEBUG); // configure as access point
  sendCommand("AT+CWJAP=\"Arsalan Wifi\",\"arsalan123\"\r\n",3000,DEBUG);
  delay(10000);
  sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendCommand("AT+CIPSERVER=1,8080\r\n",1000,DEBUG); // turn on server on port 80

  Serial.println("Server Ready");
}

void loop()
{
  if(esp8266.available()) // check if the esp is sending a message
  {


    if(esp8266.find("+IPD,"))
    {
     delay(1000); // wait for the serial buffer to fill up (read all the serial data)
     // get the connection id so that we can then disconnect
     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                       // the ASCII decimal value and 0 (the first decimal number) starts at 48

     esp8266.find("pin="); // advance cursor to "pin="

     int pinNumber = (esp8266.read()-48); // get first number i.e. if the pin 13 then the 1st number is 1
     int secondNumber = (esp8266.read()-48);
     if(secondNumber>=0 && secondNumber<=9)
     {
      pinNumber*=10;
      pinNumber +=secondNumber; // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number
     }

     digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin   


     String content;
     content = "چراغ ";
     content += pinNumber;
     content += " is ";

     if(digitalRead(pinNumber))
     {
       content += "ON";
     }
     else
     {
       content += "OFF";
     }

     sendHTTPResponse(connectionId,content);

     // make close command
     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId; // append connection id
     closeCommand+="\r\n";

     sendCommand(closeCommand,1000,DEBUG); // close connection
     Serial.print(connectionID);
    }
  }
}

/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug)
{
    String response = "";

    int dataSize = command.length();
    char data[dataSize];
    command.toCharArray(data,dataSize);

    esp8266.write(data,dataSize); // send the read character to the esp8266
    if(debug)
    {
      Serial.println("\r\n====== HTTP Response From Arduino ======");
      Serial.write(data,dataSize);
      Serial.println("\r\n========================================");
    }

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      } 
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

/*
* Name: sendHTTPResponse
* Description: Function that sends HTTP 200, HTML UTF-8 response
*/
void sendHTTPResponse(int connectionId, String content)
{

     // build HTTP response
     String httpResponse;
     String httpHeader;
     // HTTP Header
     httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
     httpHeader += "Content-Length: ";
     httpHeader += content.length();
     httpHeader += "\r\n";
     httpHeader +="Connection: close\r\n\r\n";
     httpResponse = httpHeader + content + " "; // There is a bug in this code: the last character of "content" is not sent, I cheated by adding this extra space
     sendCIPData(connectionId,httpResponse);
}

/*
* Name: sendCIPDATA
* Description: sends a CIPSEND=<connectionId>,<data> command
*
*/
void sendCIPData(int connectionId, String data)
{
   String cipSend = "AT+CIPSEND=";
   cipSend += connectionId;
   cipSend += ",";
   cipSend +=data.length();
   cipSend +="\r\n";
   sendCommand(cipSend,1000,DEBUG);
   sendData(data,1000,DEBUG);
}

/*
* Name: sendCommand
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendCommand(String command, const int timeout, boolean debug)
{
    String response = "";

    esp8266.print(command); // send the read character to the esp8266

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      } 
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}


but then i chose to use library code for esp8266 and i use this link ITEADLIB_Arduino_WeeESP8266

now i have problem that i dont know how can i get a response message back to my android device,

also this is my code using library, (i know its really noobish code cuz im new but... it work atleast :D )


#include <doxygen.h>
#include "ESP8266.h"
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //moshakhas kardane pin haye LCD
SoftwareSerial mySerial(7, 8); // moshakhas kardane pin haye wifi
ESP8266 wifi(mySerial);
String msg;
#define SSID        "Arsalan Wifi"  //UserName wifi
#define PASSWORD    "arsalan123"  //Password wifi
String pinnum;
int count= 0;
void setup() {
  lcd.begin(20, 4);    
  Serial.begin(9600);
  pinMode(9,OUTPUT);
  digitalWrite(9,HIGH);
  String IP;
  Serial.print("setup begin\r\n");
  lcd.print("Connecting to Wifi");
  delay(3000);
  Serial.print("FW Version: ");
 
//  Serial.println(wifi.getVersion().c_str());
 
 

    if (wifi.setOprToStation()) {
        Serial.print("to station ok\r\n");

    } else {
        Serial.print("to station err\r\n");

    }

    if (wifi.joinAP(SSID, PASSWORD)) {
        Serial.print("Join AP success\r\n");
        Serial.print("IP: ");      
        Serial.println(wifi.getLocalIP().c_str());
        IP = wifi.getLocalIP().c_str();
        lcd.setCursor(0, 1);
        lcd.print("Join AP success");
        lcd.setCursor(0, 2);
        lcd.print("IP: "+IP);
    } else {
        Serial.print("Join AP failure\r\n");
        lcd.setCursor(0, 1);
        lcd.print("Join AP failure");
        lcd.setCursor(0, 2);
        lcd.print("Contact Administrator");
    }
     if (wifi.enableMUX()) {
        Serial.print("multiple ok\r\n");
    } else {
        Serial.print("multiple err\r\n");
    }
    if (wifi.startTCPServer(80)) {
        Serial.print("start tcp server ok\r\n");
        lcd.setCursor(0, 3);
        lcd.print("Server Ready");
    } else {
        Serial.print("start tcp server err\r\n");
        lcd.setCursor(0, 3);
        lcd.print("Server Setup Fail");
    }
    if (wifi.setTCPServerTimeout(10)) {
        Serial.print("set tcp server timout 10 seconds\r\n");
    } else {
        Serial.print("set tcp server timout err\r\n");
    }
 
   
    Serial.print("setup end\r\n");

}

void loop() {
   uint8_t buffer[128] = {0};
    uint8_t mux_id;
    uint32_t len = wifi.recv(&mux_id, buffer, sizeof(buffer), 100);
    if (len > 0) {
        Serial.print("Status:[");
        Serial.print(wifi.getIPStatus().c_str());
        Serial.println("]");
       
        Serial.print("Received from :");
        Serial.print(mux_id);
        Serial.print("[");
        for(uint32_t i = 0; i < len; i++) {
            Serial.print((char)buffer[i]);
            msg = "";
            msg += ((char)buffer[i]);
           
            if (msg == "p")
            {
              count=1;
             
             
            }
            
            if (msg != "p" & count ==1)
            {
              if(msg =="i")
              {
               
                count++;
              }
              else
              {
               
                count = 0;
              }
            }

            if (msg !="i" & count ==2)
            {
              if (msg =="n")
              {
                count++;
              }
              else
              {
                count = 0;
              }
            }
            if (msg !="n" & count ==3)
            {
              if(msg=="=")
              {
                count++;
               
              }
              else
              {
                count = 0;
              }
            }
            if (msg != "=" & count==4)
            {
              Serial.print(msg);
              pinnum =msg;
              count = 0;
            }
           
        }
        Serial.print(pinnum);
        Serial.print("]\r\n");
        int pin = pinnum.toInt();

        Serial.print(pin);
        digitalWrite(pin, !digitalRead(pin)); // toggle pin   
        String content;
     content = "چراغ ";
     content += pinnum;
     content += " is ";
    
     if(digitalRead(pin))
     {
       content += "ON";
     }
     else
     {
       content += "OFF";
     }


       
        if(wifi.send(mux_id, buffer, len)) {
            Serial.print("send back ok\r\n");
        } else {
            Serial.print("send back err\r\n");
        }
       
        if (wifi.releaseTCP(mux_id)) {
            Serial.print("release tcp ");
            Serial.print(mux_id);
            Serial.println(" ok");
        } else {
            Serial.print("release tcp");
            Serial.print(mux_id);
            Serial.println(" err");
        }
       
        Serial.print("Status:[");
        Serial.print(wifi.getIPStatus().c_str());
        Serial.println("]");
    }

 

}

iceng1 year ago

Do a flow chart of the code to understand whats actually going on then you will be able insert a message code where it does not interfere with operation.

I don't want to do it, because it is time consuming..

Arsalan Ahmadi (author)  iceng1 year ago

basicly it connect my esp8266 to my wifi modem, then i can connect with my android to it and send command to turn of led or turn it on.

the problem is for the response, i think this is the code :

* Name: sendHTTPResponse
* Description: Function that sends HTTP 200, HTML UTF-8 response
*/
void sendHTTPResponse(int connectionId, String content)
{

// build HTTP response
String httpResponse;
String httpHeader;
// HTTP Header
httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
httpHeader += "Content-Length: ";
httpHeader += content.length();
httpHeader += "\r\n";
httpHeader +="Connection: close\r\n\r\n";
httpResponse = httpHeader + content + " "; // There is a bug in this code: the last character of "content" is not sent, I cheated by adding this extra space
sendCIPData(connectionId,httpResponse);
}

but after i use library code it dont work.