Serial ESP8266 and Arduino

    This page is to Setup and Config Serial ESP8266 and Arduino
 

Hardware and Software

Hardware 
    Serial ESP8266 and Arduino

Software 
    Arduino IDE



Example :

Important Notes 

  • Case 1 : Control By Arduino (Programming only on Arduino) (Example 2)
    • Upload standard frimware to ESP-01 (ESP8266的固件将更改为V0.9.2.3版本)
      • [System Ready, Vendor:www.ai-thinker.com]
      • AT+GMR
      • 0018000902
    • Modify ESP-01 SoftAP (SSID and Password for Client connect) 

  • Case 2 : Send and Receive Data between Arduino and ESP-01
    • Upload Program to Arduino and ESP-01 (Example)

  • Case 3 : Only ESP-01 for Software Server 

Sanki Notes

  •  Arduino ESP-01 
     D2TX 
      D3 RX 
       
       

  • SoftwareSerial on Arduino

Example : Simple Serial Between ESP-01 and Arduino 

  • This example is very simple Serial Communication ESP8266 and Arduino
  • ESP8266 ESP-01 have to update frimware to AT Command Mode
            
  1.   #include <SoftwareSerial.h>
    SoftwareSerial ESPserial(2, 3); // RX | TX
     
    void setup() 
    {
        Serial.begin(9600);     // communication with the host computer
        //while (!Serial)   { ; }
     
        // Start the software serial for communication with the ESP8266
        ESPserial.begin(9600);  
     
        Serial.println("");
        Serial.println("Remember to to set Both NL & CR in the serial monitor.");
        Serial.println("Ready");
        Serial.println("");    
    }
     
    void loop() 
    {
        // listen for communication from the ESP8266 and then write it to the serial monitor
        if ( ESPserial.available() )   {  Serial.write( ESPserial.read() );  }
     
        // listen for user input and send it to the ESP8266
        if ( Serial.available() )       {  ESPserial.write( Serial.read() );  }
    }

Example 2 : Web Client ---> ESP-01 Server --> Arduino (By AT Command Call)

  •           Very Good for Web Client ---> ESP-01 Server --> Arduino (By AT Command Call)
  1.   /*
    Arduino Due - ESP 8266 WiFi Module

    Act as AP mode, CWMODE=2

    Serial (Tx/Rx) communicate to PC via USB
    Serial3 (Tx3/Rx3) connect to ESP8266
    Arduino Pin 2 --- Tx3 - ESP8266 Rx
    Arduino Pin 3 --- Rx3 - ESP8266 Tx
    ESP8266 CH_PD Connect to ESP8266 VCC

    #include <SoftwareSerial.h>
    SoftwareSerial ESP8266(2, 3); // RX | TX

    for firmware:
    "v0.9.5.2 AT Firmware"
    (http://goo.gl/oRdG3s)
    AT version:0.21.0.0
    SDK version:0.9.5

    How to Use 

    post : http://<Server>/len=0 or len=1

    Respore : message after post 
    Link

    +IPD,0,443:GET /len=1 HTTP/1.1
    Host: 192.168.4.1
    Conn


    */
    #include <SoftwareSerial.h>
    SoftwareSerial ESP8266(2, 3); // RX | TX
    //#define ESP8266 Serial3

    int LED = 13;

    boolean FAIL_8266 = false;

    #define BUFFER_SIZE 128
    char buffer[BUFFER_SIZE];

    void setup() {
      pinMode(LED, OUTPUT);
      
      digitalWrite(LED, LOW);
      delay(300);
      digitalWrite(LED, HIGH);
      delay(200);
      digitalWrite(LED, LOW);
      delay(300);
      digitalWrite(LED, HIGH);
      delay(200);
      digitalWrite(LED, LOW);
      delay(300);
      digitalWrite(LED, HIGH);
      delay(200);
      digitalWrite(LED, LOW);

      do{
        Serial.begin(9600);
        ESP8266.begin(9600);
      
        //Wait Serial Monitor to start
        while(!Serial);
        Serial.println("--- Start ---");

        ESP8266.println("AT+RST");
        delay(1000);
        if(ESP8266.find("OK"))
        {
          delay(5000);
          Serial.println("Module is ready");
          ESP8266.println("AT+CWMODE=2");
          delay(1000);
          clearESP8266SerialBuffer();

          //Get and display my IP
          sendESP8266Cmdln("AT+CIFSR", 1000);  
          
          //Get and display my IP
          //sendESP8266Cmdln("AT+CIPSTA=\"192.168.10.1\"", 1000);  
          //ESP8266.println("AT+RST");
          
          //Get and display my IP
          sendESP8266Cmdln("AT+CIFSR", 1000);  
          
          //Set multi connections
          sendESP8266Cmdln("AT+CIPMUX=1", 1000);
          //Setup web server on port 80
          sendESP8266Cmdln("AT+CIPSERVER=1,80",1000);
            
          Serial.println("Server setup finish");
            
          FAIL_8266 = false;
        }else{
          Serial.println("Module have no response.");
          delay(500);
          FAIL_8266 = true;
        }
      }while(FAIL_8266);
      
      digitalWrite(LED, HIGH);
      ESP8266.setTimeout(1000);
    }

    void loop(){

      if(ESP8266.available()) // check if the esp is sending a message 
      {
        Serial.println("Something received");
        delay(1000);

      //while (ESP8266.available())
      //  Serial.print(char(ESP8266.read()));
      //Serial.println("");

    /*
          Serial.println("--------------- DEBUG ----------------ORGINIAL");
          while (ESP8266.available())
            Serial.print(char(ESP8266.read()));
          Serial.println("\n--------------- END DEBUG ----------------"); 
    */
        
        if(ESP8266.find("+IPD,"))
        {
          String action;

          Serial.println("+IPD, found");
          int connectionId = ESP8266.read()-48;
          Serial.println("connectionId: " + String(connectionId));

          Serial.println("--------------- DEBUG ----------------A");
          char temp = char(ESP8266.read());
          while ((temp != '/') && (ESP8266.available())) {
            Serial.print(temp);
            temp = char(ESP8266.read());
          }
          Serial.println("\n--------------- END DEBUG ----------------"); 
        

          boolean isFound = ESP8266.find("len=");
          Serial.print("is Found : ");
          Serial.println(isFound);

            /*
          Serial.println("--------------- DEBUG ----------------B");
          while (ESP8266.available())
            Serial.print(char(ESP8266.read()));
          Serial.println("\n--------------- END DEBUG ----------------"); 
        */
           
          char s = ESP8266.read();
          
          if(s=='0'){
            action = "led=0";
            digitalWrite(LED, LOW);
          }else if(s=='1'){
            action = "led=1";
            digitalWrite(LED, HIGH);
          }else{
            action = "led=?";
          }
          
          Serial.println(action);
          sendHTTPResponse(connectionId, action);
          
          //Close TCP/UDP
          //String cmdCIPCLOSE = "AT+CIPCLOSE="; 
          //cmdCIPCLOSE += connectionId;
          //sendESP8266Cmdln(cmdCIPCLOSE, 1000);
        }
      }
      
    }

    void sendHTTPResponse(int id, String content)
    {
      String response;
      /*
      response = "HTTP/1.1 200 OK\r\n";
      response += "Content-Type: text/html; charset=UTF-8\r\n"; 
      response += "Content-Length: ";
      response += content.length();
      response += "\r\n";
      response +="Connection: close\r\n\r\n";
      */
      
      response = "\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\n";
      response += "<body align=center>";
      
      response += "<p>";
      response += "<a href=\"http://192.168.4.1/len=1\">ON</a><p>";
      response += "<a href=\"http://192.168.4.1/len=0\">OFF</a><p>";
                   
      response += content;

       response += "</body></html>\n";

      String cmd = "AT+CIPSEND=";
      cmd += id;
      cmd += ",";
      cmd += response.length();
      
      Serial.println("--- AT+CIPSEND ---");
      sendESP8266Cmdln(cmd, 1000);
      
      Serial.println("--- data ---");
      sendESP8266Data(response, 1000);
    }

    boolean waitOKfromESP8266(int timeout)
    {
      do{
        Serial.println("wait OK...");
        delay(1000);
        if(ESP8266.find("OK"))
        {
          return true;
        }

      }while((timeout--)>0);
      return false;
    }

    //Send command to ESP8266, assume OK, no error check
    //wait some time and display respond
    void sendESP8266Cmdln(String cmd, int waitTime)
    {
      ESP8266.println(cmd);
      delay(waitTime);
      clearESP8266SerialBuffer();
    }

    //Basically same as sendESP8266Cmdln()
    //But call ESP8266.print() instead of call ESP8266.println()
    void sendESP8266Data(String data, int waitTime)
    {
      ESP8266.print(data);
      delay(waitTime);
      clearESP8266SerialBuffer();
    }

    //Clear and display Serial Buffer for ESP8266
    void clearESP8266SerialBuffer()
    {
      Serial.println("= clearESP8266SerialBuffer() =");
      while (ESP8266.available() > 0) {
        char a = ESP8266.read();
        Serial.write(a);
      }
      Serial.println("==============================");
    }

Examples - Different SDK Version

  • Beware Different SDK Version ( This Example Version is : SDK 1.5.3 as at 2016) Check Here
  • This Sample Have Client and SoftAP but both IP can go into same Service by Arduino Programming

  • Preset on ESP-01
    • Client and SoftAP Mode : AT+CWMODE=3

    • SoftAP : AT+CWSAP="<SSID>","<Password>",11,3
      • (Two ESP-01 have two SSID)
    • SoftAP IP : AT+CIPAP="192.168.167.1"
    • Active DHCP : AT+CWDHCP=2,0
    • Set MultiConnect : AT+CIPMUX=1
    • Create Server Port : AT+CIPSERVER=1,80

    • Set Client :
    • AT+CWJAP="<SSID>","<Password>"
    • WIFI DISCONNECT
    • WIFI CONNECTED
    • WIFI GOT IP

    • Set Client IP : AT+CIPSTA="192.168.0.150"

  • CHECK 
    • Check SoftAP

    • AT+CIPAP="192.168.167.1"
    • OK

    • AT+CIPAP?

    • +CIPAP:ip:"192.168.167.1"
    • +CIPAP:gateway:"192.168.167.1"
    • +CIPAP:netmask:"255.255.255.0"
    • OK

    • AT+CWSAP?
    • +CWSAP:"<SSID>","<Password>",11,3,4,0
    • OK

    • Check Client
    • AT+CWJAP?

    • +CWJAP:"<SSID>","64:71:02:8e:be:42",9,-73

    • OK
    • AT+CIPSTA?

    • +CIPSTA:ip:"192.168.0.150"
    • +CIPSTA:gateway:"192.168.0.1"
    • +CIPSTA:netmask:"255.255.255.0"
            Last update : 20160505
  1. /* Arduino Due - ESP 8266 WiFi Module Act as AP mode, CWMODE=2 Serial (Tx/Rx) communicate to PC via USB Serial3 (Tx3/Rx3) connect to ESP8266 Arduino Pin 2 --- Tx3 - ESP8266 Rx Arduino Pin 3 --- Rx3 - ESP8266 Tx ESP8266 CH_PD Connect to ESP8266 VCC #include <SoftwareSerial.h> SoftwareSerial ESP8266(2, 3); // RX | TX for firmware: AT version:1.0.0.0 SDK version:1.5.2 How to Use post : http://<Server>/len=0 or len=1 Respore : message after post Link +IPD,0,443:GET /len=1 HTTP/1.1 Host: 192.168.4.1 Conn In This Programming ----- Receive Data from Serial ESP8266 to Arduino Find Postion : Serial.println("+IPD, found"); Read Next char : int connectionId = ESP8266.read()-48; ------------------------------------------------------- Default Setup on ESP8266 ESP-01 SSID : RemoteServer Password : <password> SoftAP IP : 192.168.167.1 SoftAP Gateway : "192.168.167.1" SoftAP netmask : 255.255.255.0 Setup ------ AT+CWSAP="RemoteServer","<password>",11,3 Testing --------- AT+CWSAP? +CWSAP:"RemoteServer","<password>",11,3,4,0 */ #include <SoftwareSerial.h> SoftwareSerial ESP8266(2, 3); // RX | TX //#define ESP8266 Serial3 int LED = 13; boolean FAIL_8266 = false; #define BUFFER_SIZE 128 char buffer[BUFFER_SIZE]; void setup() { pinMode(LED, OUTPUT); digitalWrite(LED, LOW); delay(300); digitalWrite(LED, HIGH); delay(200); digitalWrite(LED, LOW); delay(300); digitalWrite(LED, HIGH); delay(200); digitalWrite(LED, LOW); delay(300); digitalWrite(LED, HIGH); delay(200); digitalWrite(LED, LOW); do{ Serial.begin(115200); ESP8266.begin(115200); //Wait Serial Monitor to start while(!Serial); Serial.println("--- Start ---"); ESP8266.println("AT+RST"); delay(1000); /* Serial.println("--------------- DEBUG ----------------ORGINIAL"); while (ESP8266.available()) Serial.print(char(ESP8266.read())); Serial.println("\n--------------- END DEBUG ----------------"); */ if(ESP8266.find("OK")) { delay(5000); Serial.println("Module is ready"); /* ESP8266.println("AT+CWMODE=2"); delay(1000); clearESP8266SerialBuffer(); //Get and display my IP sendESP8266Cmdln("AT+CIFSR", 1000); //Get and display my IP //sendESP8266Cmdln("AT+CIPSTA=\"192.168.10.1\"", 1000); //ESP8266.println("AT+RST"); */ //Set multi connections sendESP8266Cmdln("AT+CIPMUX=1", 1000); //Setup web server on port 80 sendESP8266Cmdln("AT+CIPSERVER=1,80",1000); Serial.println("Server setup finish"); FAIL_8266 = false; }else{ Serial.println("Module have no response."); delay(500); FAIL_8266 = true; } }while(FAIL_8266); digitalWrite(LED, HIGH); ESP8266.setTimeout(1000); } void loop(){ if(ESP8266.available()) // check if the esp is sending a message { Serial.println("Something received"); delay(1000); //while (ESP8266.available()) // Serial.print(char(ESP8266.read())); //Serial.println(""); /* * --------------- DEBUG ----------------ORGINIAL 1,CLOSED 1,CONNECT +IPD,1,444:GET /len=1 HTTP/1.1 Host: 19 --------------- END DEBUG ---------------- */ /* ----------------------------------------------------------------------- String str = ""; Serial.println("--------------- DEBUG ----------------ORGINIAL"); // // String Control // while (ESP8266.available()) { str += char(ESP8266.read()); } Serial.println(str); // // Serial Control // //while (ESP8266.available()) { // Serial.print(char(ESP8266.read())); //} Serial.println("\n--------------- END DEBUG ----------------"); //------------------------------------------------------------------------------- */ if(ESP8266.find("+IPD,")) { String action; Serial.println("+IPD, found"); int connectionId = ESP8266.read()-48; Serial.println("connectionId: " + String(connectionId)); Serial.println("--------------- DEBUG ----------------A"); char temp = char(ESP8266.read()); while ((temp != '/') && (ESP8266.available())) { Serial.print(temp); temp = char(ESP8266.read()); } Serial.println("\n--------------- END DEBUG ----------------"); boolean isFound = ESP8266.find("len="); Serial.print("is Found : "); Serial.println(isFound); /* Serial.println("--------------- DEBUG ----------------B"); while (ESP8266.available()) Serial.print(char(ESP8266.read())); Serial.println("\n--------------- END DEBUG ----------------"); */ char s = ESP8266.read(); if(s=='0'){ action = "led=0"; digitalWrite(LED, LOW); }else if(s=='1'){ action = "led=1"; digitalWrite(LED, HIGH); }else{ action = "led=?"; } Serial.println(action); sendHTTPResponse(connectionId, action); //Close TCP/UDP //String cmdCIPCLOSE = "AT+CIPCLOSE="; //cmdCIPCLOSE += connectionId; //sendESP8266Cmdln(cmdCIPCLOSE, 1000); } } } void sendHTTPResponse(int id, String content) { String response; /* response = "HTTP/1.1 200 OK\r\n"; response += "Content-Type: text/html; charset=UTF-8\r\n"; response += "Content-Length: "; response += content.length(); response += "\r\n"; response +="Connection: close\r\n\r\n"; */ response = "\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\n"; response += "<body align=center>"; //response += "<img src=\"http://www.imediabank.com/_/rsrc/1462251563655/home/title.png\" />"; //response += "<img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAALVBMVEX///8EBwfBwsLw8PAzNjaCg4NTVVUjJiZDRUUUFxdiZGSho6OSk5Pg4eFydHTCjaf3AAAAZElEQVQ4je2NSw7AIAhEBamKn97/uMXEGBvozkWb9C2Zx4xzWykBhFAeYp9gkLyZE0zIMno9n4g19hmdY39scwqVkOXaxph0ZCXQcqxSpgQpONa59wkRDOL93eAXvimwlbPbwwVAegLS1HGfZAAAAABJRU5ErkJggg==\" />"; response += "<p></p>"; response += "<a href=\"\len=1\"><font size=\"6\">ON</font></a><p>"; response += "<a href=\"\len=0\"><font size=\"6\">OFF</font></a><p>"; response += "<font size=\"6\">"; response += content; response += "</font>"; response += "</body></html>\n"; String cmd = "AT+CIPSEND="; cmd += id; cmd += ","; cmd += response.length(); Serial.println("--- AT+CIPSEND ---"); sendESP8266Cmdln(cmd, 1000); Serial.println("--- data ---"); sendESP8266Data(response, 1000); } boolean waitOKfromESP8266(int timeout) { do{ Serial.println("wait OK..."); delay(1000); if(ESP8266.find("OK")) { return true; } }while((timeout--)>0); return false; } //Send command to ESP8266, assume OK, no error check //wait some time and display respond void sendESP8266Cmdln(String cmd, int waitTime) { ESP8266.println(cmd); delay(waitTime); clearESP8266SerialBuffer(); } //Basically same as sendESP8266Cmdln() //But call ESP8266.print() instead of call ESP8266.println() void sendESP8266Data(String data, int waitTime) { ESP8266.print(data); delay(waitTime); clearESP8266SerialBuffer(); } //Clear and display Serial Buffer for ESP8266 void clearESP8266SerialBuffer() { Serial.println("= clearESP8266SerialBuffer() ="); while (ESP8266.available() > 0) { char a = ESP8266.read(); Serial.write(a); //Serial.write(char(ESP8266.read())); } Serial.println(""); Serial.println("==============================\n"); }