Introduction: ESP8266 As a Microcontroller

Picture of ESP8266 As a Microcontroller

As it was already mentioned in the Getting Started with ESP8266 ESP-01 tutorial, the Wi-Fi module is fully programmable, allowing us to use it as a microcontroller and manipulate inputs and outputs.

In this tutorial we are going to show how to program the ESP module via Arduino UNO to blink an LED and control it from a wireless device.

Step 1: Arduino Setup

First we need to set up the Arduino environment to make it compatible with the ESP module. It is required to have Arduino version 1.6.4 or higher in order to be able to install the ESP’s platform packages.

Once we open Arduino IDE we go to preferences and in the “Additional Boards Manager URLs:” section we type the following line:

http://arduino.esp8266.com/package_esp8266com_inde...

After clicking on “OK,” we go to Tools -> Board -> Boards manager and install the ESP8266 platform.

The Arduino can now be used to program the ESP8266 Wi-Fi module.

Step 2: Setup to Blink the LED

Picture of Setup to Blink the LED

The ESP8266 ESP-01 has two GPIOs: GPIO0 and GPIO2.

Every time we want to program the ESP module, it is required to ground GPIO0 before downloading a code.

An easy way to show how this works is using the “Blink” example.

Open the example on Arduino IDE and choose “Generic ESP8266 Module” as the board.

Make sure you change pin 13 to pin 2 in the code.

Remember that we are using the ESP’s GPIOs, not the Arduino’s.

Connect the ESP as shown in the images above.

Step 3: Setup to Blink the LED - Continued

Picture of Setup to Blink the LED - Continued

Make sure GPIO0 is grounded and upload the code.

After a couple of seconds you will get a message similar to the one above.

Step 4: ESP8266 As Access Point

Now we are going to control the LED wirelessly using only the ESP module.

In the previous two tutorials, Getting Started with ESP8266 EP-01 and Using ESP-01 and Arduino UNO, we have used the ESP-01 module in STA mode.

For this tutorial, however, we are going to use it in AP mode to see how it differs.

Step 5: Code

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
 
const char* ssid = "ESP";
const char* password = "123456789";
 
String form = "<form action='led'><input type='radio' name='state' value='1' checked>On<input type='radio' name='state' value='0'>Off<input type='submit' value='Submit'></form>";
 
ESP8266WebServer server(80);
 
const int led = 2;
 
void handle_led() {
  // get the value of request argument "state" and convert it to an int
  int state = server.arg("state").toInt();
 
  digitalWrite(led, state);
  server.send(200, "text/plain", String("LED is now le ") + ((state)?"on":"off"));
}
 
void setup(void) {
  Serial.begin(115200);
  pinMode(led, OUTPUT);
  WiFi.softAP(ssid, password);
 
  server.on("/", [](){
   server.send(200, "text/html", form);
  });
 
   server.on("/led", handle_led);
 
  // Start the server
  server.begin();
}
 
void loop(void) {
  // check for incoming client connections frequently in the main loop:
  server.handleClient();
}

Step 6: Code Explanation

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
 
const char* ssid = "ESP";
const char* password = "123456789";
 
String form = "<form action='led'><input type='radio' name='state' value='1' checked>On<input type='radio' name='state' value='0'>Off<input type='submit' value='Submit'></form>";
 
ESP8266WebServer server(80);
 
const int led = 2;
 
void handle_led() {
  // get the value of request argument "state" and convert it to an int
  int state = server.arg("state").toInt();
 
  digitalWrite(led, state);
  server.send(200, "text/plain", String("LED is now  ") + ((state)?"on":"off"));
}

In this first part of the code, we include the libraries required to initialize the ESP module in AP mode and create a web server. Then we provide the name and password of our access point (ESP module). This is the name that will appear in the available wireless networks.

If you want, you can leave the “password” section in blank so that you don’t have to type a password when you connect to the module. Then we create a string that contains html text to generate a submit button and two radio buttons that will allow us to choose the state of the LED (on or off).

Next we make the server listen to port 80 and assign the name “led” to pin 2 of the ESP module.

Finally we create a function that does three things. First, it gets the value of the request argument “state” and converts it into an integer. Second, it assigns the value to the state of the LED to turn it on (1) or off (0). Lastly, it sends a message to the web browser’s window stating whether the LED is currently on or off.

Step 7: Code Explanation - Continued

void setup(void) {
Serial.begin(115200); pinMode(led, OUTPUT); WiFi.softAP(ssid, password); server.on("/", [](){ server.send(200, "text/html", form); }); server.on("/led", handle_led); // Start the server server.begin(); }

In the setup section of the code, we start serial communication and define the baud rate.

Then we make the LED an output, initialize the ESP-01 as an access point and send the html code from the server to the client to display the buttons in the web browser.

Finally we call the function “handle_led” to manage the LED’s state and then we start the server.

Step 8: Code Explanation - Continued

void loop(void) {
// check for incoming client connections frequently in the main loop: server.handleClient(); }

In the loop, we constantly check if a client initiates connection with our server.

Step 9: Results

Picture of Results

When we open the Wireless Network Connections from our computer, we get a list of all the available networks.

We can see how our ESP-01 module appears in the list with the name “ESP.”

Step 10: Results - Continued

Picture of Results - Continued

When we connect to ESP we get the following window as shown above.

Here we type the password of the network and click “OK.”

Step 11: Results - Continued

Picture of Results - Continued

Once we are connected to our ESP module we can open a web browser’s window and type the following IP address, as shown in the image above.

Notice how the IP Address is different than when the module was operating in STA mode.

Each mode of operation has a different IP Address.

When we hit enter, we get the three buttons that allow us to change the LED’s state.

Step 12: Results - Continued

Picture of Results - Continued

When we click on the submit button, we get the following response, shown in the first image above with the effect on the LED shown in the second image.

Step 13: Results - Continued

Picture of Results - Continued

Similarly, if we choose off we get the following response, as shown above in the images.

Step 14: Conclusion

In this tutorial, we use the Arduino board to supply the module with power and as an intermediary to download the code to the ESP-01. However, after uploading the code to the module, we can get rid of the Arduino board by disconnecting the Rx and Tx lines of communication and powering the module with an external power supply.

An alternate way of programming the ESP module is using an FTDI connector.

If you have any questions about this tutorial, do not hesitate to post a comment, shoot us an email, or post it in our forum.

Check out the Jaycon Systemswebsite to pick up the materials you need from our online store.

While you're there, read through the other great tutorials we have available.

If you haven't done so already, visit our Instructables profile for more step-by-step guides to creating interesting projects. Let us know when you create something from a tutorial we created; we love hearing your stories!

Thanks for reading!

Comments

quanticchaos (author)2017-11-06

Another great tutorial, thanks. I began to make some test and everything worked great until I tried to connect mi esp-01 as a serial module to arduino and now I'm not getting anything at the monitor. I can still upload sketches to the esp and I works but it seems it lost its serial capabilities. I already uploaded a blank sketch to the esp-01 and mi arduino board but nothing, no answer of any kind. Can you throw me a light? thanks!

ahmedthamir (author)2017-07-02

think you for explain

esp2866

operation now

BharathM16 (author)2017-05-21

Hai,

I want to know how do you know the ip address as 192.168.4.1.And why it is same in my esp8266 ?

jijoami (author)2017-05-04

Hai,

I have done everything as per the instructions. All done. Compiled and done uploading without any warnings or errors. But now the problem is, i cannot find the module wifi "ESP" in the my laptop. please help me with this.

martinhui (author)2016-03-20

Hi there, I cannot upload code to ESP no matter grounded GPIO0 or not, it respond warnings, are there something wrong?

warning: espcomm_sync failed

error: espcomm_open failed

error: espcomm_upload_mem failed

MathewG15 (author)martinhui2017-04-17

I've replied above and I'm sure it'll work. Follow the exact procedure :)

JayconSystems (author)martinhui2016-06-06

Try uploading a BareMinimum example to the Arduino UNO to make sure it is not running other code. Then ground GPIO0. Next use a wire to ground the RST pin for a short time (don't leave it connected to gnd. Just do a quick reset of the chip). Try to download the blinky example to the ESP module. Hope this helps

mubashir hanif (author)martinhui2016-05-27

If you have found any solution plz share. thanks

martinhui (author)mubashir hanif2016-06-01

I tried below workable

add a push button as reset between CHPD and GND

add an one post switch between GND and GPIO0

add a pull up resistor between VCC and CHPD

1. grounded GPIO0 by flipping on the switch

2. push reset button once

3. download file and release GPIO0 afterward

mubashir hanif (author)2016-05-27

warning: espcomm_sync failed

error: espcomm_open failed

error: espcomm_upload_mem failed

MathewG15 (author)mubashir hanif2017-04-17

Well I had the same error and after a lot of googling found this amazing video

https://www.youtube.com/watch?v=Ao5XcORsYxA You can see the circuit and everything and in the end he says some points. You might need to ground the GPIO0 to flash the program...Well I'll write the steps. 1.Plug in the arduino keeping the GPIO0 pin grounded. 2. Flash the code given in this instructable (Thanks for the code). Now you've flashed the code. 3. Unplug the arduino and remove the grounding cable from GPIO0 4.Connect the arduino again.. Thats it...To reflash some other code repeat the steps again :) Hope this helps (Well it has helped me.)

Vrettel (author)mubashir hanif2016-08-03

The method JayconSystems suggests, works fine. To upload to the board without these error messages do the following:

1) Upload an empty project(i.e. BareMinimum from the examples) to the arduino uno board (not the ESP).
2) Wire everything correct according to this instructable.

3) Ground the GPIO0 pin of the ESP.

4) Prepare the sketch to be uploaded to the ESP.

5) Select the Generic ESP8266 Module from the board list

6) Press Upload and before the upload starts connect the RST pin of the ESP to Ground. Disconnect immediately and let the process continue. If the errors appear, try again with a better timing. Don't forget, during the upload only the GPIO0 pin must be connected. After the upload you can connect the other GPIO too.

Sorry for the spam, not sure if the timing i described is the only correct one.

Try uploading a BareMinimum example to the Arduino UNO to make sure it is not running other code. Then ground GPIO0. Next use a wire to ground the RST pin for a short time (don't leave it connected to gnd. Just do a quick reset of the chip). Try to download the blinky example to the ESP module. Hope this helps

antochildjesus (author)2016-10-20

can i use android app for this program... you have any app please send... my mail id antochildjesus@gmail.com. Thank you.

MathewG15 (author)antochildjesus2017-04-17

U can make an android app.. I'm a beginner and I could make one with a few lines of code. Just google "sending http request background". You'll find easy way to send http link requests from an app on button click or something :)

hernanbadilla (author)2017-03-04

My beginnig.

antochildjesus (author)2016-10-20

can i use android app..

ashwinigunjal (author)2016-10-17

Hello , I have following error please help me to solve this

"error: espcomm_open failed
error: espcomm_upload_mem failed

"

i try all solution given in comments still i didn't get solution.please help me.

TarekJamal (author)2016-09-07

Hello, first of all very nice instructable.

1- how can I make the form consists of 2 buttons without postback (like a mobile application)?

2- how can I increase the outputs for the esp8266?

Vrettel (author)2016-08-05

Hello, first of all very nice instructable. I followed it and it works perfect. There is only one problem. For some reason, when i restart the ESP8266, the sketch is being erased from ESP. I think that every time there is a power loss, on reconnection ESP8266 erases it's memory or flashes again the. The only way to keep the sketch in memory, is to disconnect the GPIO0 pin (which is grounded for the Upload process) and also disconnect the ledpin! Only by disconnecting both of the GPIO pins, the program can keep the sketch in memory. Thing is that i need the ledpin connected all the time to control my device. Have you found a solution on this problem?

Thanks in advance, George

LewisM24 (author)Vrettel2016-08-08

after uploading the sketching and verify it working then disconnect unused wires before powering down (tx/rx/rst/gpio0). Then power down and power back up and it should be working. i beleive you are reseting the unit but grounding gpio0 or rst.

Vrettel (author)LewisM242016-08-08

I found out that the board doesn't erases it's memory but just fails to load the sketch. I have all the pins you said disconnected before I power down. The only solution I found is to disconnect both I/O pins and restart the board. Only then I manage to get the sketch working. Tried it in 3 different esp8266 e01 boards and had exactly the same results.

Thanks for your answer !
George

Alexan24 (author)2016-05-26

Can you put links for the libraries?? Thnak you!

JayconSystems (author)Alexan242016-06-06

The libraries are automatically installed when you install the ESP's platform packages as described at the beginning of this tutorial. Once you select your board as "Generic ESP8266 Module" in the Arduino IDE, go to Skecth > Include Library. There you will find all the ESP libraries that come with the platform package.

BunceyTheInbred (author)2016-05-24

warning: espcomm_sync failed

error: espcomm_open failed

error: espcomm_upload_mem failed

Try uploading a BareMinimum example to the Arduino UNO to make sure it is not running other code. Then ground GPIO0. Next use a wire to ground the RST pin for a short time (don't leave it connected to gnd. Just do a quick reset of the chip). Try to download the blinky example to the ESP module. Hope this helps

hello sir i've got the same error as yours. Have you find any solution to overcome this error? I am using esp-01 with arduino mega2560. i've also tried PL2303 but got the same error. Waiting for your reply. Thank you

I tried holding down restart while it's compiling then letting go when it uploads with no success. However online I did read that this method works well for a lot of people. Maybe you could try that?

The next easy way I'm going to try is just simply using a serial adapter. Pretty cheap as well!

http://www.ebay.co.uk/itm/171868983294?_trksid=p20...

Good luck! :)

ennalta (author)2016-03-07

I had no idea that you could do this. How cool! I can make a web server that I stick in my pocket or anywhere else really.

JayconSystems (author)ennalta2016-03-08

Glad you enjoyed our tutorial! Let us know what you end up making with the knowledge learned in these steps! Thanks for reading! :]

lozi_dani (author)JayconSystems2016-04-18

Following the steps of your tutorial I get the next error:

warning: espcomm_sync failed

error: espcomm_open failed

error: espcomm_upload_mem failed

Another guy got it few comments before and nobody answer him. Maybe you could help me to know why I get this?

I have followed all the steps, and everything seems to be ok until I upload the code. I have checked all the connections and everything is ok =(..Thanks for the help!

JayconSystems (author)lozi_dani2016-06-06

Try uploading a BareMinimum example to the Arduino UNO to make sure it is not running other code. Then ground GPIO0. Next use a wire to ground the RST pin for a short time (don't leave it connected to gnd. Just do a quick reset of the chip). Try to download the blinky example to the ESP module. Hope this helps

mubashir hanif (author)lozi_dani2016-05-27

hello sir i've got the same error as yours. Please help if you have find any solution. I am using esp-01 with arduino mega2560. i've also tried PL2303 but got the same error. Waiting for your reply. Thank you

ennalta (author)JayconSystems2016-05-27

I'm actually building an on/off remote circuit for lights using Amazon echo. unfortunately I can make everything work except for programming the actual esp8266. I can send AT commands to it but that's about it. I keep getting that same three line error that everyone else does.

JayconSystems (author)ennalta2016-06-06

Try uploading a BareMinimum example to the Arduino UNO to make sure it is not running other code. Then ground GPIO0. Next use a wire to ground the RST pin for a short time (don't leave it connected to gnd. Just do a quick reset of the chip). Try to download the blinky example to the ESP module. Hope this helps

Droxz made it! (author)2016-05-13

Thanks for your Intructable!
Used your code and it's working fine

I'm using the Adafruit Feather HUZZAH ESP8266, much easier to program.
It's more expensive but easier the start with :)

AlexM157 made it! (author)2016-05-09

thanks a lot ! it finally works , after 7 hours of trying :D

SwapnilS14 (author)2016-04-15

can we write code for many led like 4 or more. Please help me if you can Please give me thank

JayconSystems (author)SwapnilS142016-04-18

it could be possible, but it will need to be written into the code and each led will be named differently so that you can distinguish between them. read over step 6 again and also we have another tutorial that talks about getting started with the esp-01: http://www.jayconsystems.com/tutorials/esp01/
let me know if you have any problems

relieff (author)2016-04-08

is it possible to blink an existing LED on the arduino board?

JayconSystems (author)relieff2016-04-18

it should work. let us know if you run into a problem.

martinhui (author)2016-03-20

In your step 11, how you set the url to 192.168.4.1? I don't see in your code?

JayconSystems (author)martinhui2016-03-21

The 192.168.4.1 is the ip address. Please check out the first tutorial we had about the ESP - it has the setup for this tutorial as this tutorial takes the first tutorial a step further in the process. https://www.instructables.com/id/Getting-Started-With-the-ESP8266-ESP-01/ hopefully this will help you out. if not, then we will try and help with the problem you are having.

Best wishes, and thanks for reading!

martinhui (author)2016-03-20

The f/w version not changed

AT+GMR

AT version:0.40.0.0(Aug 8 2015 14:45:58)

SDK version:1.3.0

Ai-Thinker Technology Co.,Ltd.

Build:1.3.0.2 Sep 11 2015 11:48:04

MikeM144 (author)2016-03-10

I am quite new to microprocessors and am fighting an uphill learning curve to try and make an idea I have into reality

So my question would be this, if all I wanted to do was monitor one analogue value and then control an arduino compatible relay board with a digital output is the ESP enough of a functioning microcontroller do be able to do that without even needing an arduino?

Currently I was planning to use an arduino nano, a single relay board and then either a wifi board (the ESP) or the arduino compatible ethernet boards to give internet accessibility from a remote location

So could I do away with the arduino completely and only use the ESP or is it too limited to do that?

JayconSystems (author)MikeM1442016-03-10

Hello! Thanks for reading! In a previous tutorial, Getting Started with the ESP8266 ESP-01, Steps 18-20 describes how to use NodeMCU and we provide a link to download the firmware for NodeMCU, which is here https://github.com/nodemcu/nodemcu-firmware/releas...
Here is also the the link to our website version of the Getting Started tutorial: http://www.jayconsystems.com/tutorials/esp01/
If you explore our website, you'll also see our online store where you can explore the different components, including shields, that we carry.
Let us know if this helps.

MarcelS9 (author)JayconSystems2016-03-14

Do NOT use any of the pre-built binaries. They are hopelessly outdated and no longer maintained. It's fairly easy to build the firmware yourself: http://nodemcu.readthedocs.org/en/dev/en/build/

ambrose.clarke (author)MikeM1442016-03-10

Yes - except the ESP is 3.3v not 5v - so you would need to check the relay board you intend to use can operate at that low an input voltage. Maybe look at the solid state relays options.

I've just managed today to connect 3 items to a standalone ESP8266 - 3 commonly-used-with-Arduino temp sensors reporting to a server - these are extremely useful devices.

beavercddl (author)MikeM1442016-03-10

Potentially, yes. If you're going to do something like that, though, take a look at the NodeMCU (which is basically and ESP8266-12E with a USB front end and a bread-board friendlier form factor). You can program the NodeMCU directly in the Lua language or use the Arduino IDE as this Instructable does. There are also ESP8266-derived "shield" type boards for the NodeMCU; I buy most of that kind of stuff from banggood.com, since a lot of it hasn't been picked up by US vendors yet.

MikeM144 (author)beavercddl2016-03-10

That sounds awesome then, and would instantly remove me needing to not only learn to program two seperate boards, but also the need to learn how to get the two boards to talk to each other into the bargain which when starting from practically zero existing knowledge seems almost insurmountable at times

the ESP boards I bought to prototype are limited with I/O, but I will have a look around and see if theres one that can accomplish the task all by itself as its really just one analogue in, and at least 2 digital outputs. But obviously one having more might be worth a look

I was planning to avoid shields where possible though due to the cost if I got the project to a point where it was marketable. So the nano boards I bought were £2 including postage and the Wifi/ethernet boards are connected by wires rather than being stackable. Plus that approach reduced the size of the enclosure by quite a noticeable amount

Cheers for the reply, and I will give the other guide a read and if what I already have is useable for the instructions give it a go too

This site and the people who take the time to contribute to it never ceases to amaze me.

Thank you so much

Mike

About This Instructable

72,250views

712favorites

License:

Bio: We bring hardware products to life, specializing in engineering, prototyping, and mass manufacturing. We've worked with over 20 Kickstarter projects.
More by JayconSystems:How to Measure a Corner's Radius Using a 3D Printed ToolSending Commands Via the LCD BackpackProgramming a Single 7 Segment Display
Add instructable to: