-->
Page 1 of 1

ESP8266-01+Arduino MEGA

PostPosted: Sat Oct 24, 2015 3:17 am
by bitmanrc
Hello,
I have a sketch for Arduino with esp8266-01,
Use two ESP.
I would only use an ESP to make in order to receive and transmit.
who can help to reduce this sketch so that it can use only one ESP
As seen in the sketch, I use two on two ESP SERIAL1 and SERIAL2
Thank you

Code: Select all 
#define SSID "Vodafone-xxxxxxx"      //your wifi ssid here
#define PASS "xxxxxxxx"   //your wifi key here
#define PAGE "/ARDUINO.asp"
#define HOST "www.mysite.it"
#define PORT  "80"


#define ESP_RST 2
Stream *esp = &Serial1;
int ACCESO=1;
int SPENTO=0;
#define ROSSO 7
#define VERDE 6
#define BLU 5

#define REPLYBUFFSIZ 255
char replybuffer[REPLYBUFFSIZ];
uint8_t getReply(char *send, uint16_t timeout = 500, boolean echo = true);
uint8_t ESPleggiLINEA(uint16_t timeout = 500, boolean multiline = false);
boolean sendCheckReply(char *send, char *reply, uint16_t timeout = 500);
unsigned long int Starte = 0;
String Andrea;
String inputString;
 
enum {WIFI_ERROR_NONE=0, WIFI_ERROR_AT, WIFI_ERROR_RST, WIFI_ERROR_SSIDPWD, WIFI_ERROR_SERVER, WIFI_ERROR_UNKNOWN};

#define DEBUG true

void LampeggioLED(int LEDPin, int NumberOfBlinks, int OnDuration)
{
 for (int x=1; x <= NumberOfBlinks ; x ++){
 digitalWrite(LEDPin,HIGH);
 delay(OnDuration);
 digitalWrite(LEDPin,LOW);
 delay(OnDuration);
 }
}


void setup()
{

  Serial.begin(115200);
  Serial1.begin(115200);   
  Serial2.begin(115200);

pinMode(VERDE,OUTPUT); 
pinMode(ROSSO,OUTPUT); 
pinMode(BLU,OUTPUT); 
digitalWrite(VERDE,0); 
digitalWrite(ROSSO,0); 
digitalWrite(BLU,0); 

  Serial.println(F("Hard reset..."));
 // hard reset if you can
  pinMode(ESP_RST, INPUT);
  digitalWrite(ESP_RST, LOW);
  pinMode(ESP_RST, OUTPUT);
  delay(100);
  pinMode(ESP_RST, INPUT);
  delay(1000);
  ESPReset();
  //test if the module is ready
  if(! ESPReset()) {
    Serial.println("Module didn't respond :(");
    debugLoop();
  }

  Serial.println(F("ESP Module is ready! :)"));

  //connect to the wifi
  byte err = WifiInvio();
 
  if (err) {
    // error, print error code
    Serial.print("setup error:");  Serial.println((int)err);
    debugLoop();
  }
 
 
 
  sendCheckReply("AT+CIPSTO=0", "OK");
   
  //set the single connection mode

 
pinMode(A0, INPUT);
pinMode(A1, INPUT);
pinMode(A2, INPUT);
pinMode(A3, INPUT);
pinMode(A4, INPUT);
pinMode(A5, INPUT);
pinMode(A6, INPUT);
pinMode(A7, INPUT);
pinMode(A8, INPUT); 
pinMode(A9, INPUT);
pinMode(A10, INPUT);
pinMode(A11, INPUT);
pinMode(A12, INPUT);
pinMode(A13, INPUT);
pinMode(A14, INPUT);
pinMode(A15, INPUT);


analogWrite(A0,0);   
analogWrite(A1,0); 
analogWrite(A2,0);
analogWrite(A3,0);     
analogWrite(A4,0);
analogWrite(A5,0);
analogWrite(A6,0);   
analogWrite(A7,0);   
analogWrite(A8,0);   
analogWrite(A9,0);   
analogWrite(A10,0);   
analogWrite(A11,0);   
analogWrite(A12,0);   
analogWrite(A13,0);   
analogWrite(A14,0);
analogWrite(A15,0);

Serial.println(F("Porte Analogiche Configurate in INPUT status 0...\n"));
 for (int z=22; z<50; z=z+2){
//Serial.print("Digitale:"); Serial.print(z); Serial.print("\n"); 
pinMode(z+1, INPUT);
pinMode(z,OUTPUT);   
digitalWrite(z,SPENTO);
digitalWrite(z+1,SPENTO);
  Serial.print(("Porte Digitale:"));
  Serial.print(z);Serial.print((".OUTPUT=0........"));Serial.print(("Porte Digitale:"));
  Serial.print(z+1);Serial.print((".INPUT=0"));
  Serial.print(("\n"));
}
digitalWrite(VERDE, 1);
delay(2000);
digitalWrite(VERDE, 0);

  sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
  sendCommand("AT+CWMODE=1\r\n",1000,DEBUG); // configure as access point
  String connectStr = "AT+CWJAP=\"";
  connectStr += SSID;
  connectStr += "\",\"";
  connectStr += PASS;
  connectStr += "\"";
  sendCommand(connectStr,3000,DEBUG);
  delay(2000);
  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,80\r\n",1000,DEBUG); // turn on server on port 80
 
 
}

boolean ESPinvioPaginaGET(char *host, uint16_t port) {
  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += host;
  cmd += "\",";
  cmd += port;
  cmd.toCharArray(replybuffer, REPLYBUFFSIZ);
delay(1500);
  getReply(replybuffer);

  if (strcmp(replybuffer, "OK") != 0) {
     if (strcmp(replybuffer, "Linked") != 0) {
       sendCheckReply("AT+CIPCLOSE", "OK");
       return false;
     }
  }
 
  String request = "GET ";
  request += PAGE;
  request += "?Azione=Tempo:.";
  request += int(Starte/1000); 
      String Ana = "";
      String Dig = "";
      for (int z=0; z<54; z++){Dig += digitalRead(z);Dig += ",";}
      for (int z=0; z<16; z++){Ana += analogRead(z);Ana += ",";}
      request += "&ComeAnalogico="; request += Ana;     
      request += "&ComeDigitale=";  request += Dig;
  request += "&Comando=CTRL&ArduinoIP=192,168,1,33";
  request += " HTTP/1.1\r\nHost: ";
  request += host;
  request += "\r\n\r\n";
 
  cmd = "AT+CIPSEND=";
  cmd += request.length();
  cmd.toCharArray(replybuffer, REPLYBUFFSIZ);
  sendCheckReply(replybuffer, ">");

LampeggioLED(BLU,5,25);

  Serial.print("Sending: "); Serial.println(request.length());
  Serial.println(F("*********SENDING*********"));
  Serial.print(request);
  Serial.println(F("*************************"));
 
  request.toCharArray(replybuffer, REPLYBUFFSIZ);

  esp->println(request);

  while (true) {
    ESPleggiLINEA(1500);  // this is the 'echo' from the data
    Serial.print(">"); Serial.println(replybuffer); // probably the 'busy s...'

    // LOOK AT ALL THESE POSSIBLE ARBITRARY RESPONSES!!!
    if (strstr(replybuffer, "wrong syntax"))
      continue;
    else if (strstr(replybuffer, "ERROR"))
      continue;
    else if (strstr(replybuffer, "busy s..."))
      continue;
    else if (strstr(replybuffer, "busy p..."))
      continue;
     
    else break;
  }
 
  if (! strstr(replybuffer, "SEND OK") ) return false;
 
  ESPleggiLINEA(1000);  Serial.print("3>"); Serial.println(replybuffer);
  char *s = strstr(replybuffer, "+IPD,");
  if (!s) return false;
  uint16_t len = atoi(s+5);
  //Serial.print(len); Serial.println(" bytes total");

  int16_t contentlen = 0;
  while (1) {
    ESPleggiLINEA(50);
    s = strstr(replybuffer, "Content-Length: ");
    if (s) {
      //Serial.println(replybuffer);
      contentlen = atoi(s+16);
      Serial.print(F("C-Len = ")); Serial.println(contentlen);
    }
    s = strstr(replybuffer, "Content-Type: ");
    if (s && contentlen) {
      int16_t i;
      char c;
     
      for (i=-2; i<contentlen; i++) {  // eat the first 2 chars (\n\r)
        while (!esp->available());
        c = esp->read(); //UDR0 = c;
        if (i >= 0) {
          replybuffer[i] = c;
        }
      }
      replybuffer[i] = 0;
      return true;
    }
  }
  //while (1) {
  //  if (esp.available()) UDR0 = esp.read();
  //}
}


void loop()
{
 //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
LampeggioLED(VERDE,2,30);
 
unsigned long int Ora = millis();

if ((Ora > Starte )  ){ 
  Starte = millis()+45000;
  ESPinvioPaginaGET(HOST, 80);
  Serial.println(F("\n**********REPLY***********\n"));
  Serial.print(replybuffer);
  Serial.println(F("\n**************************\n"));
  sendCheckReply("AT+CIPCLOSE", "OK");
 }

/*
  debugLoop();
  Andrea = replybuffer;
  Andrea.replace("busy s...","");
  Andrea.replace("busy p...","");
  Andrea.replace("ERROR",""); 
  Serial.print(Andrea);
    if (Andrea.substring(1, 2) == "#") {digitalWrite(ROSSO, 1);}
    if (Andrea.substring(0, 1) == "#") {digitalWrite(ROSSO, 0);}
  delay(1);
 */
 {
  if(Serial2.available()) // check if the esp is sending a message
  {
 
   
    if(Serial2.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 = Serial2.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48
         
     Serial2.find("pin="); // advance cursor to "pin="
         
     int pinNumber = (Serial2.read()-48); // get first number i.e. if the pin 13 then the 1st number is 1
     int secondNumber = (Serial2.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   
     
     // build string that is send back to device that is requesting pin toggle
     String content;
     content = "Pin ";
     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
    }
  }
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
}


//********************************************************************************************************************************************
boolean ESPReset() {
  getReply("AT+RST", 1000, true);
  if (! strstr(replybuffer, "OK")) return false;
   delay(2000);
  getReply("ATE0", 250, true);
  return true;
}
//********************************************************************************************************************************************
boolean ESPconnessioneAP(char *s, char *p) {
 
  getReply("AT+CWMODE=3", 1000, true);
  if (! (strstr(replybuffer, "OK") || strstr(replybuffer, "no change")) )
    return false;
  String connectStr = "AT+CWJAP=\"";
  connectStr += SSID;
  connectStr += "\",\"";
  connectStr += PASS;
  connectStr += "\"";
  connectStr.toCharArray(replybuffer, REPLYBUFFSIZ);
  getReply(replybuffer, 1000, true);
  ESPleggiLINEA(5000);
  Serial.print("<-- "); Serial.println(replybuffer); 

  return (strstr(replybuffer, "OK") != 0);
}
//********************************************************************************************************************************************
 


//********************************************************************************************************************************************
uint8_t ESPleggiLINEA(uint16_t timeout, boolean multiline) {
  uint16_t replyidx = 0;
 
  while (timeout--) {
    if (replyidx > REPLYBUFFSIZ-1) break;
   
    while(esp->available()) {
      char c =  esp->read();
      if (c == '\r') continue;
      if (c == 0xA) {
        if (replyidx == 0)   // the first 0x0A is ignored
          continue;
       
        if (!multiline) {
          timeout = 0;         // the second 0x0A is the end of the line
          break;
        }
      }
      replybuffer[replyidx] = c;
      // Serial.print(c, HEX); Serial.print("#"); Serial.println(c);
      replyidx++;
    }
   
    if (timeout == 0) break;
    delay(1);
  }
  replybuffer[replyidx] = 0;  // null term
  return replyidx;
}
//********************************************************************************************************************************************
uint8_t getReply(char *send, uint16_t timeout, boolean echo) {
  // flush input
  while(esp->available()) {
     esp->read();
  }
 
  if (echo) {
    Serial.print("---> "); Serial.println(send);
  }
  esp->println(send);
 
  // eat first reply sentence (echo)
  uint8_t readlen = ESPleggiLINEA(timeout); 
 
   //Serial.print("echo? "); Serial.print(readlen); Serial.print(" vs "); Serial.println(strlen(send));
 
  if (strncmp(send, replybuffer, readlen) == 0) {
    // its an echo, read another line!
    readlen = ESPleggiLINEA();
  }
 
  if (echo) {
    Serial.print ("<--- "); Serial.println(replybuffer);
  }
  return readlen;
}
//********************************************************************************************************************************************
boolean sendCheckReply(char *send, char *reply, uint16_t timeout) {
  getReply(send, timeout, true);

/*
  for (uint8_t i=0; i<strlen(replybuffer); i++) {
    Serial.print(replybuffer[i], HEX); Serial.print(" ");
  }
  Serial.println();
  for (uint8_t i=0; i<strlen(reply); i++) {
    Serial.print(reply[i], HEX); Serial.print(" ");
  }
  Serial.println();
*/
  return (strcmp(replybuffer, reply) == 0);
}
//********************************************************************************************************************************************
void debugLoop() {
    if (Serial.available()) {
      esp->write(Serial.read());
      delay(1);
    }
    if (esp->available()) {
      Serial.write(esp->read());
      delay(1);
    }
}


//********************************************************************************************************************************************
byte WifiInvio() {
  // reset WiFi module
/*
 Serial.println(F("Soft resetting..."));
  if (!ESPReset())
    return WIFI_ERROR_RST;

  delay(1000);
*/
  Serial.println(F("Checking for ESP AT response"));

  if (!sendCheckReply("AT", "OK"))
    return WIFI_ERROR_AT;
   
  Serial.print(F("Connecting to ")); Serial.println(SSID);
  if (!ESPconnessioneAP(SSID, PASS))
    return WIFI_ERROR_SSIDPWD;
 
  Serial.println(F("Multiple Client Mode"));
  if (!sendCheckReply("AT+CIPMUX=1", "OK"))
        return WIFI_ERROR_SERVER;
 
  return WIFI_ERROR_NONE;

//********************************************************************************************************************************************

//?????????????????????????????????????????????????????????????
/*
* Name: sendData
* Description: Function used to send data to Serial2.
* 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 Serial2 (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);
           
    Serial2.write(data,dataSize); // send the read character to the Serial2
    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(Serial2.available())
      {
       
        // The esp has data so display its output to the serial window
        char c = Serial2.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 Serial2.
* 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 Serial2 (if there is a reponse)
*/
String sendCommand(String command, const int timeout, boolean debug)
{
    String response = "";
           
    Serial2.print(command); // send the read character to the Serial2
   
    long int time = millis();
   
    while( (time+timeout) > millis())
    {
      while(Serial2.available())
      {
       
        // The esp has data so display its output to the serial window
        char c = Serial2.read(); // read the next character.
        response+=c;
      } 
    }
   
    if(debug)
    {
      Serial.print(response);
    }
   
    return response;
}