Begin typing your search above and press return to search. Press Esc to cancel.

Control an LED from Webserver using NodeMcu or Esp8266 programming with Arduino IDE.


In this blog, we will see How to "Turn On and Turn Off" an LED that has connected to the Esp8266, the esp8266 has programmed from Arduino IDE to control the LED.

We will connect the Esp8266 to the Wi-Fi router using SSID and password of our Home network Wifi , where the esp8266 connect to our wifi and create a webserver, which can be accessed by looking through the serial Monitor of the Arduino window or you can also log into your Wifi router and check for the list of clients connected to your Wi-Fi router.

Here's a window which explains the step by step procedure to connect the Esp8266 to the Wi-fi server and How to access the Webpage and control the LED connected to the Esp8266


For the above video I have used NodeMcu, you can use any type of Esp8266 to make this thing work in your web browser. 



look for the mapping of pins in with your Esp8266 vendor, if the program not working properly for you , the fault will be with the pin mapping functionalities, Here I used the D7 pin which mapped to 13th pin when program from the Arduino IDE.


Connect your Esp8266 to Arduino IDE and Select the correct COM Port and board type and 
upload the program. 

Note change the SSID to your WiFi Name and password to your Wifi password. if you forget to change it , esp8266 will not connect connect your wifi.

--------------------------------------------------------------------------------------------------------------------------


#include <ESP8266WiFi.h>
 
const char* ssid = "Magesh";
const char* password = "jayakumar";
 
int ledPin = 13; // GPIO13
WiFiServer server(80);
 
void setup() {
  Serial.begin(115200);
  delay(10);
 
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
 
  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
 
  // Start the server
  server.begin();
  Serial.println("Server started");
 
  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
 
}
 
void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
 
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
 
  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();
 
  // Match the request
 
  int value = LOW;
  if (request.indexOf("/LED=ON") != -1)  {
    digitalWrite(ledPin, HIGH);
    value = HIGH;
  }
  if (request.indexOf("/LED=OFF") != -1)  {
    digitalWrite(ledPin, LOW);
    value = LOW;
  }
 
// Set ledPin according to the request
//digitalWrite(ledPin, value);
 
  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");
 
  client.print("Led pin is now: ");
 
  if(value == HIGH) {
    client.print("On");
  } else {
    client.print("Off");
  }
  client.println("<br><br>");
  client.println("<a href=\"/LED=ON\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/LED=OFF\"\"><button>Turn Off </button></a><br />");  
  client.println("</html>");
 
  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");
 
}
 
-------------------------------------------------------------------------------------------









If everything completed you can turn to your serial monitor and check for the ip address that your devices has connected to . you will presented with an serial monitor that look exactly to the picture below.


if you like the above tutorial and if you want try out with cool projects you can also check this link here , that's the amazon book link where you can use that book to make IoT with Esp8266 or Nodemcu, that books gives you basic coverage on how to do simple things and get yourself started with arduino and goes on developing projects like sending data to webserver and creating a webserver, uploading and controlling data from a webpage, how to interface TFT LCD and I2C devices and many more things can find on the link.

53 comments:

  1. http://www.amazon.in/ESP8266-Serial-Wireless-Transceiver-Module/dp/B00O34AGSU/ref=sr_1_1?ie=UTF8&qid=1452944269&sr=8-1&keywords=esp+8266

    Can I control the LED using my module - A blog would be appreciated.

    ReplyDelete
  2. Hi,
    thank you for this tutorial. I bought your kindle book and did the 'blink; example.
    Then I tried 'Control an LED from Webserver using NodeMcu' but after loading the the code and opening the serial monitor it only writes points (....................................) not the URL number. Can you help me?

    ReplyDelete
    Replies
    1. Hi have you configured your SSID and password for your browser correctly? if you get only (.........) as your output it means that your ESP8266 is not connected to your browser. mail me at jayakumarmagesh@gmail.com

      Delete
    2. Good day my friend,

      my name is Carlos Zapien, I was looking your totorial of Control an LED from Webserver using NodeMcu or Esp8266 programming with Arduino IDE, everything is ok but, i have problems with the conections and a can't conect the arduino uno and the ESP8266 to turn it on the led, can you help me please?, it just the conection between both devices, your code is running now, thank you so much my friend!!!



      Saludos!!!

      Delete
  3. This works great! Thanks for taking the time to write this tutorial.

    ReplyDelete
  4. Hello,
    Thanks for this tutorial.
    I am new to NodeMCU ESP8266 12E.
    I have done a few blinking and accesspoint examples and all works fine with Arduino IDE 1.6.7 and my Win 7 PC.

    I tried your tutorial code and on my Arduino IDE serial port, I am getting an 'Exception (3)' error:
    Connecting to Magesh
    Exception (3):
    epc1=0x401003e9 epc2=0x00000000 epc3=0x00000000 excvaddr=0x4002a839 depc=0x00000000
    ctx: cont
    sp: 3ffef8b0 end: 3ffefc90 offset: 01a0
    >>>stack>>>
    3ffefa50

    When I modified, changed the ssid and password, I am getting the same error that 'Nadav Ziv' was getting;
    always telling me 'connecting to ' and never stops!

    Your help is much appreciated...

    ReplyDelete
  5. You should never use an LED without resistor or you will destroy it.

    ReplyDelete
  6. Thanks for sharing the code and great work.

    Can you please help combine this with the ESP8266WebServer.h - HttpBasicAuth in the example? I really like to add a login at the beginning of accessing server.

    ReplyDelete
  7. Very nice article!
    got successfully control my led.

    ReplyDelete
  8. Thanks dude doing a great job...thanks a lot

    ReplyDelete
  9. Thanks dude doing a great job...thanks a lot

    ReplyDelete
  10. can u send book name please i am not able to see the book in amezon .. plz mail me the name of book on amazon rangrezumarfarukh@gmail.com

    ReplyDelete
  11. my is showing --Error compiling board node MCU 0.9(ESP-12 Mode)

    Board nodemcu(platform esp 8266,package esp 8266) is unknown
    error compiling for board nodeMCU 0.9(ESP-12 Module).

    plies help me

    ReplyDelete
    Replies
    1. I have the same problema.
      What can I do?
      Thank you

      Delete
    2. The same problema with V0.9 and V1.0

      Delete
  12. #include

    const char* ssid = "Kontrol_Bol";
    const char* password = "11qq22ww";

    ReplyDelete
  13. ok works. :) how can i add more 3 leds.
    and on smartphone is menu buttons too small whic line can i menu larger.

    ReplyDelete
  14. otima espricacao.

    esta dando erro neste serto oque pode ser pque estou aprendendo ainda
    obrigado
    / Inicie o servidor
    servidor. Começar ();

    ReplyDelete
  15. Thanks a lot for this tutorial :D

    ReplyDelete
  16. Hey first thanks for the great tutorial works great and its still simple!!!!
    But I have this problem that the server is only accesible in the first 20-40 minutes after that i have to reset the esp/wemos because the server is down!

    Can please anyone tell me how to fix this?

    Thanks

    ReplyDelete
  17. Worked on the way,........Thank you for all code....I have modified it as per my requirements

    ReplyDelete
  18. The LEDs can be controlled from anywhere with the help of the given URL or it has to be connected to the same wifi on which the esp is connected?I mean if we have the URL then can I control the led anywhere around the globe?

    ReplyDelete
    Replies
    1. no it(device) had to be connected with the same connection(wifi) as the the ESP's.

      Delete
  19. Brilliant thank you just what I have been looking for.
    Could you tell me how to monitor a switch connected to the ESP8266 from a webpage?

    ReplyDelete
  20. I have tried to copy and paste the code from the webpage , when I put it into an Arduino sketch I get an error

    ReplyDelete
    Replies
    1. I copied it from the box and it works ok

      Delete
  21. Wow gracias amigo me ayudaste un monton recien empece con el esp

    ReplyDelete
  22. hi nice project...thanks for sharing.
    how to control more than 1 gpio.
    and is there any direct link to turn leds off and on?
    :)

    ReplyDelete
  23. i want to connect given ip address by wifi.localip() to another webpage which is not connected to nodemcu wifi network



    9

    ReplyDelete
  24. Good day my friend,

    my name is Carlos Zapien, I was looking your totorial of Control an LED from Webserver using NodeMcu or Esp8266 programming with Arduino IDE, everything is ok but, i have problems with the conections and a can't conect the arduino uno and the ESP8266 to turn it on the led, can you help me please?, it just the conection between both devices, your code is running now, thank you so much my friend!!!

    Regards!!!

    ReplyDelete
    Replies
    1. Hi Carlos,

      There is no Arduino Uno involved. It all runs on the NodeMCU itself, including connecting the LED.

      Delete
  25. why it stops responding after sometime???

    ReplyDelete
    Replies
    1. You have to replace:
      while(!client.available()){
      delay(1);
      }
      with:
      int t = millis();
      while(!client.available()){
      delay(1);
      if (millis()-t>130) return;
      }
      because sometime the module locked into the while loop so we have to return if it locked for more than 130 milliseconds! I read it from: https://openhomeautomation.net/control-a-lamp-remotely-using-the-esp8266-wifi-chip/

      Delete
  26. This is super and worked first time for me, it worked even when I entered the IP address on my iPhone! Now... next step... if I wanted to use (style) and a .class to change the appearance of the button, is there any way to do that?

    ReplyDelete
  27. after copying the url onto a browser it is showing this site can not be reached please help what is the problem

    ReplyDelete
    Replies
    1. Maggie, try the SSID#, example 192.168.1.1 (I think the default the AP mode uses, is 192.168.4.1).. But, since this is using the local router, it will be a different number.

      Delete
    2. I stand corrected, the IP#, not the SSID.. (forgive me, Networking newbie)

      Delete
  28. The Article give Where Everyone And Everything Will Be Monitored On The Internet is awesome.It Give brief information about How the Internet of Things Gone work.Thanks for Sharing the information about it.

    seo expert in nepal

    ReplyDelete
  29. hi.
    always still waiting ...........
    and it never give me any adresse to open it :(
    can anyone help me please ?

    ReplyDelete
  30. Welcome Post very usefull informatation.and iam expecting more posts like this please keep updating us........

    ReplyDelete
  31. same project, you can see another instruction here
    http://engineer2you.blogspot.com/2017/06/esp8266-esp12e-web-server-with-arduino.html

    ReplyDelete
  32. Can any one please give me code fo multiple channel output @shubhamrajput00722@gmail.com

    ReplyDelete
  33. Very simple but useful project. I test it in my NodeMCU 1.0 (ESP-12E) module and worked perfectly . Programmed using Arduino IDE 1.8.3.

    ReplyDelete
  34. Thanks for a great starter project. It worked first time... until I scanned my home network with the "Fing" app on my phone. It locked up.

    You need to add
    count = 0;
    while(!client.available()){
    delay(1);
    count++;
    if ( count > 1000 )
    {
    Serial.println("Abandoned Client");
    return;
    }
    }
    to stop network scans from locking it up.

    ReplyDelete
  35. It's so cool. I tried and liked the implementation.

    ReplyDelete
  36. Is it possible to connect to multiple client and control the LED?

    ReplyDelete
  37. does it works on ny other wifi mobile network if they turn on the led????

    ReplyDelete
  38. Help! I get this error:
    aggregate 'ip_addr_t addr' has incomplete type and cannot be defined

    ip_addr_t addr;
    I do not know what the problem is please help!

    ReplyDelete
  39. Hi, I uploaded your code on my NodeMCU V2 Amica.
    I don´t get an error message, but the serial Monitor prints out only questionmarks.
    I only changed the ledPin to LED_BUILTIN because I don´t have a LED right now.
    I also noticed, that I don´t have the "Upload using Serial" button at my tools menue.
    Please help.

    ReplyDelete
    Replies
    1. ok, I changed the Baud adjustment. Now it is all dots. I know it means it can´t connect to the router. But I´m sure I used the right name and Passwort.

      Delete