Wemos webserver example

In this example we will create a basic webserver example using our Wemos, it will connect to your Wifi network and then you will navigate to a URL and a basic page will appear. This page will display 2 links , one will switch on an led connected to D5 and the other option will switch the led off.

Wemos D1 ESP8266 based board
Wemos D1 ESP8266 based board

Parts

1 x Wemos D1 or D2
1 x USB cable
1 x LED and resistor or use a module

Code

[codesyntax lang=”cpp”]

#include <ESP8266WiFi.h>
 
const char* ssid = "ssid name";
const char* password = "ssid password";
 
int ledPin = D5;
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 : ");
  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;
  }

   
 
  // 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("Click <a href=\"/LED=ON\">here</a> turn the LED on pin 5 ON<br>");
  client.println("Click <a href=\"/LED=OFF\">here</a> turn the LED on pin 5 OFF<br>");
  client.println("</html>");
 
  delay(1);
  Serial.println("Client disconnected");
  Serial.println("");
 
}

[/codesyntax]

Results

Open the serial monitor , all going well and you will see the IP address and messages like the following

wemos ip address
wemos ip address

Using your favourite web browser navigate to the IP above

wemos browser
wemos browser

 

 

Update

I tried this out and it uses a static IP address

[codesyntax lang=”cpp”]

//This example will set up a static IP - in this case 192.168.1.99

#include <ESP8266WiFi.h>
 
const char* ssid = "ssid name";
const char* password = "ssid password";
 
int ledPin = D5;
WiFiServer server(80);
IPAddress ip(192, 168, 1, 99); // where xx is the desired IP Address
IPAddress gateway(192, 168, 1, 1); // set gateway to match your network

void setup() {
  Serial.begin(115200);
  delay(10);
 
 
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);

  Serial.print(F("Setting static ip to : "));
  Serial.println(ip);
  
  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  IPAddress subnet(255, 255, 255, 0); // set subnet mask to match your network
  WiFi.config(ip, gateway, subnet); 
  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 : ");
  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;
  }

   
 
  // 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("Click <a href=\"/LED=ON\">here</a> turn the LED on pin 5 ON<br>");
  client.println("Click <a href=\"/LED=OFF\">here</a> turn the LED on pin 5 OFF<br>");
  client.println("</html>");
 
  delay(1);
  Serial.println("Client disconnected");
  Serial.println("");
 
}

[/codesyntax]

 

63 COMMENTS

  1. I used this code, but it is backwards for me. When it says OFF it is ON. ?? I am using the built in LED on D4.
    Thoughts?

  2. Thanks, I had wemose d1 and work very well,
    but local network how it work 3g,internet,eny where, and I need to control
    04 relay, pleas help me THanks,
    udith

  3. hi

    is there at way to make it with a static address like 192.168.0.205 ???

    i wish to make it run with a StepMotor and NeoPixels but i cant make it work…. only if i dont use the wifi, but i need the wifi.

    • I’ve added an example which seemed to work for me but basically you need to add the following

      // config static IP
      IPAddress ip(192, 168, 1, xx); // where xx is the desired IP Address
      IPAddress gateway(192, 168, 1, 1); // set gateway to match your network
      Serial.print(F(“Setting static ip to : “));
      Serial.println(ip);
      IPAddress subnet(255, 255, 255, 0); // set subnet mask to match your network
      WiFi.config(ip, gateway, subnet);

  4. What chip and what program are you using because the following line will not compile.
    Serial.print(F(“Setting static ip to : “));
    When I remark it out the compiler (Arduino with the basic 8266 chip) works.

  5. Hi, I don’t know why it will automatically disconnected when i trying to turn on/off the led.

    “connected to wifi
    ……………………
    WiFi connected
    Server started
    Use this URL : http://192.168.137.73/
    new client
    GET / HTTP/1.1
    Client disconnected

    new client
    GET /favicon.ico HTTP/1.1
    Client disconnected

  6. What security does this library understand? I can get this to connect to my iPhone’s hotspot, but not to my access point, It prints “Connecting to SSID” and dots forever. I have moved the Wemos within 10 feet of the AP. Any other reason besides security mismatch this would not work? Cisco 2600 series AP using only the 2.4GHz channels.

    Thanks, Jim

    • According to the library code in ESP8266WiFiScan.cpp

      case AUTH_OPEN:
      case AUTH_WPA_PSK:
      case AUTH_WPA2_PSK:
      case AUTH_WPA_WPA2_PSK:

      This has always worked out of the box for me, only thing I can suggest is to try some of the other examples that come if you setup support of the ESP8266 in the Arduino IDE. I have read about people having issues and having to disconnect before then trying to connect.

  7. HI, thanks for the code. I have an issue when I leave the board energized for a while (like 1 or 2 hours) without any connection. It simply stops to answer http requests in the IP address. I can ping the IP so it means it is there but the page never opens. Any idea on what could be happening?
    Thanks

    • I haven’t seen that I must admit – If it happened regularly I would add serial debug through the code and open the serial monitor and see if there was anything being outputted there as a start

      I did read – https://github.com/esp8266/Arduino/issues/1594 which had quite a few suggestions to what appears similar general issues, these range from hardware to software fixes

  8. Dear reader,

    My serial monitor prints in the first line:

    sd$ÜŸ|là<Œläc|�Ãä›r“#Œc„û ….. etc.

    What could be the problem?

    The code works fine otherwise.

      • Thanks for the quick response.

        But I think it’s not the problem.

        – void setup() {
        Serial.begin(115200);

        – Tools → Upload speed: 115200

        – Bottom right corner of the Serial Monitor Window: 115200

        Do you have another suggestion?

  9. Another question.

    What those this line do?

    – Serial.print(F(“Setting static ip to : “));

    On the site from Arduino they say:

    You can pass flash-memory based strings to Serial.print() by wrapping them with F(). For example :

    Serial.print(F(“Hello World”))

    To send a single byte, use Serial.write().

  10. Q: I get this, now what to do?

    Connecting to EHDT26

    Exception (2):
    epc1=0x3ffe8450 epc2=0x00000000 epc3=0x00000000 excvaddr=0x3ffe8450 depc=0x00000000

    ctx: cont
    sp: 3ffef820 end: 3ffefce0 offset: 01a0

    >>>stack>>>
    3ffef9c0: feefeffe feefeffe feefeffe feefeffe
    3ffef9d0: feefeffe feefeffe feefeffe feefeffe
    3ffef9e0: feefeffe feefeffe feefeffe feefeffe
    3ffef9f0: feefeffe feefeffe feefeffe feefeffe
    3ffefa00: feefeffe feefeffe feefeffe feefeffe
    3ffefa10: feefeffe 00000004 3ffefa70 3ffefa81
    3ffefa20: 40107020 00000000 3fff11e8 00000484
    3ffefa30: 3ffefc17 feefeffe 000000a5 feefeffe
    3ffefa40: feefeffe 00000000 00000000 3ffef9d0
    3ffefa50: feefeffe feefeffe feefeffe feefeffe
    3ffefa60: 3ffefa80 3ffefa70 00000004 feefeffe
    3ffefa70: feefeffe 3ffe8564 3fff11e8 00000068
    3ffefa80: 000000a5 3fff0d64 feefeffe feefeffe
    3ffefa90: feefeffe feefeffe feefeffe 4010031d
    3ffefaa0: feefeffe 00001028 3ffeec64 40100426
    3ffefab0: feefeffe feefeffe feefeffe 40100537
    3ffefac0: feefeffe 00001000 00000484 401006f5
    3ffefad0: 00000484 00001000 000003fd 4010724c
    3ffefae0: 40004b31 3ffefb10 0000001c 402244cd
    3ffefaf0: 40105ea2 402245b5 3fff0d64 000003ff
    3ffefb00: 000003fd 3ffefc17 3fff0d64 000003fd
    3ffefb10: ffffff00 55aa55aa 00000010 0000001c
    3ffefb20: 0000001c 00000013 00000013 000003ff
    3ffefb30: 402249a4 3fff0d64 3fff0d64 000000ff
    3ffefb40: 00000001 3ffefc37 40224aff 00000008
    3ffefb50: 3fff0d64 000000ff 3ffefc17 00000000
    3ffefb60: 3fff0e24 3ffefc78 00000001 40224b8c
    3ffefb70: 3ffefc17 3fff0d64 00000000 00000004
    3ffefb80: 3ffefc37 3fff709c 3fff0d64 00000000
    3ffefb90: 40224bc8 3ffe8414 3ffe8424 feefeffe
    3ffefba0: 402027ea 3ffe8424 3ffe8414 4020272a
    3ffefbb0: 00000000 feefeffe 00000000 4000050c
    3ffefbc0: 401041bc 00040000 00000000 00000000
    3ffefbd0: 00000000 00000000 0000001f 40105d55
    3ffefbe0: 4000050c 40103196 4010094e 00000030
    3ffefbf0: 40227116 3fff0571 3fff03cc 3fffdad0
    3ffefc00: 40227f3b 00000023 00000001 00000001
    3ffefc10: ffffff00 45ffffff 32544448 feef0036
    3ffefc20: 00000018 feefeffe feefeffe 0001c200
    3ffefc30: 0000001c 68000000 61737361 6965656e
    3ffefc40: 36323632 00000000 3ffe86e5 4020382c
    3ffefc50: 00000000 00000005 3ffe8429 3ffeecb0
    3ffefc60: 3ffe8370 00000006 3ffeec84 40202ed5
    3ffefc70: 3ffe86e4 00fe8368 3ffeec84 40202ed5
    3ffefc80: 3ffeeb40 00000000 00000001 40203904
    3ffefc90: 402010ae 0000000a 3ffeec84 3ffeecb0
    3ffefca0: 3ffe8370 3ffeeb40 3ffeec84 40202461
    3ffefcb0: feefeffe feefeffe feefeffe feefeffe
    3ffefcc0: 3fffdad0 00000000 3ffeeca9 40202fcc
    3ffefcd0: feefeffe feefeffe 3ffeecc0 40100958
    <<<stack<<<

    ets Jan 8 2013,rst cause:2, boot mode:(1,6)

    ets Jan 8 2013,rst cause:4, boot mode:(1,6)

    wdt reset

    • I’ve seen this researching the issue on the wemos forum

      As a solution I put:
      WiFi.persistent(false);
      in the beginning of setup() and lo-behold!! Crashes no more!

      Try that

  11. Thank you so much. My first wifi program!
    Do you know WHY I have to change the baud rate to 9600? Otherwise I get rubbish (B�L ��#�#��).
    I use Arduino IDE 1.8.0. The “Get board info” says BN: Unknown board, VID: 1A86, PID: 7523. How can I solve this?
    I miss a lot of information for the D1 I just bought in november (seems to be a R1). On http://www.wemos.cc there is almost no information. I tried to post a message to the forum on wemos.cc, but you have to wait 24 hours to post your first message. I think the wemos products won’t be a great success if they do it like that.. So thanks again for your great support.

  12. Hello.. I’ve just bought wemos d1 (unfortunatly not r2 but the retired version) and i m tring to run the example above. I first tried the first code and i didn’t managed to make it work. Then i tried the updated code and i managed to make my wemos connect to my wifi. That means that i have the expected message in serial monitor. The problem is that i cant connect from my chrome browser to the suggested url..
    Please help me…….

  13. Worked fine for me, with example. Then I wanted to change the SSID to another, but both phone and computer (used to connect to the wifi) only sees the OLD SSID, not the NEW one!? Is there a way to “flush” the clients that most likley “remembers” the old SSID?

  14. As I am testing , when you go the ip address of the web server it really does not read the real state of th relay …. it means that if i set it to ON and relogin again to the server it will show the state to OFF even though it is ON…
    What do i do wrong or it is something that is not solved in this sketch?

  15. thank you for your code, however i have a small issue , how can i use a name in browser insteated of using an ip address? for example if i want to be connected to wemos device , i go in browser i put like :Joseph

  16. It was very useful for me.
    Then I also used buttons to turn on/off the Led.

    I want to show in the client a value of a didital input.
    It works but it only refreshes the value when I turn on/off the LED.
    Do you know a way to update the value when it changes?

  17. I loaded this sketch in my Wemos D1 R2 ( it works in my Arduini Uno) but it does’nt works in D1 R2.
    Does anyone know why?
    /*
    Example Timer1 Interrupt
    Flash LED every second
    */

    #define ledPin 13
    int timer1_counter;
    void setup()
    {
    pinMode(ledPin, OUTPUT);

    // initialize timer1
    noInterrupts(); // disable all interrupts
    TCCR1A = 0;
    TCCR1B = 0;

    // Set timer1_counter to the correct value for our interrupt interval
    //timer1_counter = 64911; // preload timer 65536-16MHz/256/100Hz
    //timer1_counter = 64286; // preload timer 65536-16MHz/256/50Hz
    timer1_counter = 34286; // preload timer 65536-16MHz/256/2Hz

    TCNT1 = timer1_counter; // preload timer
    TCCR1B |= (1 << CS12); // 256 prescaler
    TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt
    interrupts(); // enable all interrupts
    }

    ISR(TIMER1_OVF_vect) // interrupt service routine
    {
    TCNT1 = timer1_counter; // preload timer
    digitalWrite(ledPin, digitalRead(ledPin) ^ 1);
    }

    void loop()
    {
    // your program here…
    }

    Thanks in advance!

  18. how to hold a value ? now if led 1 turns on and led 2 turns on the text shows its off but its not

    [code]
    //This example will set up a static IP – in this case 192.168.1.99

    #include

    const char* ssid = “Family_Zone”;
    const char* password = “xxxx”;

    int ledPin1 = D5;
    int ledPin2 = D6;
    int ledPin3 = D7;
    WiFiServer server(80);
    IPAddress ip(192, 168, 178, 200); // where xx is the desired IP Address
    IPAddress gateway(192, 168, 178, 1); // set gateway to match your network

    void setup() {
    Serial.begin(115200);
    delay(10);

    pinMode(ledPin1, OUTPUT);
    pinMode(ledPin2, OUTPUT);
    pinMode(ledPin3, OUTPUT);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, LOW);

    Serial.print(F(“Setting static ip to : “));
    Serial.println(ip);

    // Connect to WiFi network
    Serial.println();
    Serial.println();
    Serial.print(“Connecting to “);
    Serial.println(ssid);
    IPAddress subnet(255, 255, 255, 0); // set subnet mask to match your network
    WiFi.config(ip, gateway, subnet);
    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 : “);
    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 value1 = LOW;
    int value2 = LOW;
    int value3 = LOW;
    if (request.indexOf(“/LED1=ON”) != -1) {
    digitalWrite(ledPin1, HIGH);
    value1 = HIGH;
    }
    if (request.indexOf(“/LED1=OFF”) != -1){
    digitalWrite(ledPin1, LOW);
    value1 = LOW;
    }
    if (request.indexOf(“/LED2=ON”) != -1) {
    digitalWrite(ledPin2, HIGH);
    value2 = HIGH;
    }
    if (request.indexOf(“/LED2=OFF”) != -1){
    digitalWrite(ledPin2, LOW);
    value2 = LOW;
    }
    if (request.indexOf(“/LED3=ON”) != -1) {
    digitalWrite(ledPin3, HIGH);
    value3 = HIGH;
    }
    if (request.indexOf(“/LED3=OFF”) != -1){
    digitalWrite(ledPin3, LOW);
    value3 = LOW;
    }

    // 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(“”);
    client.println(“”);
    client.println(“”);
    client.println(” Led 1 =”);
    if(value1 == HIGH) {
    client.print(“On”);
    digitalWrite(ledPin1, HIGH);
    } else {
    client.print(“Off”);
    digitalWrite(ledPin1, LOW);
    }
    client.println(” Led 2 =”);
    if(value2 == HIGH) {
    client.print(“On”);
    digitalWrite(ledPin2, HIGH);
    } else {
    client.print(“Off”);
    digitalWrite(ledPin2, LOW);
    }
    client.println(” Led 3 =”);
    if(value3 == HIGH) {
    client.print(“On”);
    digitalWrite(ledPin3, HIGH);
    } else {
    client.print(“Off”);
    digitalWrite(ledPin3, LOW);
    }
    client.println(“ONONONOFFOFFOFF“);
    client.println(“”);

    delay(1);
    Serial.println(“Client disconnected”);
    Serial.println(“”);
    }
    [/code]

  19. Hey i cant get connect to wifi,i mean after connecting to … in serial monitor then it get dots forever,i have try connect to my android hotspot and my router,both are zonk. and i only change the name of ssid and password in the code,do i miss something?

  20. Hi, thanks for the tutorial. I tried it out and it all worked.

    However I do have one suggestion. I found that the client.print() and client.println() methods are slow to execute and calling them multiple times for a single page ends up taking about 3.8 seconds to completely upload the web page.

    However if you build the entire web page as a single String first then make a single call to client.print() you can reduce the page load time down to about 250ms.

    I’m using the WeMos D1R2.

  21. Found out that you must be on the same network as the WeMos.
    If you are trying to access your WeMos via the Internet
    It does not seem to work. However if your laptop is on the same
    network/router then it works just fine for me. It has a slight bug
    which was an easy fix, Operates fine just as it is.

  22. I’m trying it on a Wemos D1R1, with this code the serial monitor gets stuck in connecting, and with other code for analysing networks none are detected, tryed with router and hotspot and no answer. Do i have to have another consideration for this board? It’s just plugged via usb to the computer.

LEAVE A REPLY

Please enter your comment!
Please enter your name here