ESP8266 Arduino Code and Schematic to Send AT Commands and Print Output

by Miguel on December 27, 2014

in ESP8266

So you got the world wide famous ESP8266 wifi module to play around with it and your Arduino but don’t know where/how to get started? For starters, the ESP8266 requires a 3.3V input which we can get by connecting a 3.3V regulator to the Arduino’s Vin pin. The code is just as simple, a loop to receive and send commands, and another loop to print the response.

In this tutorial I will give you the code and circuit you need to get started. The code is below the video, and the schematic can be found in the video.

Video Tutorial:

Code For ESP8266 to Arduino Communication:

The goal of this code is simple: to receive AT commands from the Arduino’s serial window to send them to the ESP8266, and to print the ESP8266’s response to the command or to other actions (such as receiving an HTTP request).

#include <SoftwareSerial.h>

SoftwareSerial esp8266(2,3); // 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
}

void loop()
{
  if(esp8266.available()) // check if the esp is sending a message 
  {
    while(esp8266.available())
    {
      // The esp has data so display its output to the serial window 
      char c = esp8266.read(); // read the next character.
      Serial.write(c);
    }  
  }
  

  
  if(Serial.available())
  {
    // the following delay is required because otherwise the arduino will read the first letter of the command but not the rest
    // In other words without the delay if you use AT+RST, for example, the Arduino will read the letter A send it, then read the rest and send it
    // but we want to send everything at the same time.
    delay(1000); 
    
    String command="";
    
    while(Serial.available()) // read the command character by character
    {
        // read one character
      command+=(char)Serial.read();
    }
    esp8266.println(command); // send the read character to the esp8266
  }
}


Previous post:

Next post: