Esp8266 wifi webserver example.

I just executed the wifi webserer using the NodeMcu esp8266 12e v3. Works fine with the app I made.

But after every single command, the connection terminates. The client i.e my app gets disconnected. How do I prevent the webserver code from automatically disconnecting from the client?

Please post your code using code tags(</> button on the toolbar).

I got it done. I am assuming the line in the code

Serial.println("Client Disconnected;")

is responsible for disconnecting the client. But I am still confused as to HOW??? Serial.println is used to just print some data onto serial monitor

Shantanu24: I am assuming the line in the code

Serial.println("Client Disconnected;")

is responsible for disconnecting the client.

no

Shantanu24: Serial.println is used to just print some data onto serial monitor

yes

I'd like to help you but if you won't post the code there's nothing I can do, good luck figuring it out for yourself.

#include <ESP8266WiFi.h>

const char* ssid = "default";
const char* password = "dviewindia";

// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

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

  // D1
  pinMode(5, OUTPUT);
  //digitalWrite(5, 0);

   // D2
  pinMode(4, OUTPUT);
  //digitalWrite(4, 0);
  
  // 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.println(WiFi.localIP());
}

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 req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();

   // Match the request
  int valD1;
  if (req.indexOf("/?pin=OFF") != -1)
    valD1 = 0;
    //Serial.print(val);
  else if (req.indexOf("/?pin=ON") != -1)
    valD1 = 1;
    //Serial.println("value is");
    //Serial.print(val);
  //else
//    Serial.println("invalid request");
//    client.stop();
    //return;
  
  Serial.println("val of D1 is");
  Serial.print(valD1);

  // Set GPIO2 according to the request
  digitalWrite(5, valD1);
  Serial.println("D1 val is");
  Serial.print(valD1);
  
  client.flush();


   // Match the request
  int valD2;
  
  if (req.indexOf("/?pin=KZ") != -1)
    valD2 = 0;
    //Serial.print(val);
  else if (req.indexOf("/?pin=KV") != -1)
    valD2 = 1;
    //Serial.println("value is");
    //Serial.print(val);
  //else 
//    Serial.println("invalid request");
//    client.stop();
   // return;
  
  Serial.println("val of D2 is");
  Serial.print(valD2);

  // Set GPIO2 according to the request
  digitalWrite(4, valD2);
  Serial.println("D2 val is");
  Serial.print(valD2);
  
  client.flush();
  
  String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nLED is now ";
  s += (valD1)?"ON":"OFF";
  s += "</html>\n";

  
  client.print(s);
  delay(1);
  Serial.println("Client disonnected");

}

Here is the code. Now once i removed the last “Serial.println” command, the webserver did not disconnect.

Shantanu24:
once i removed the last “Serial.println” command, the webserver did not disconnect.

That’s strange. My understanding is that when you reach the end of the loop() function the client object goes out of scope and so is destroyed, therefore you don’t even need to call client.stop(). In fact if you look at File > Examples > ESP8266WiFi > WiFiWebServer it says in the comment:

// The client will actually be disconnected
// when the function returns and ‘client’ object is detroyed

Maybe without the Serial print it creates the new client object fast enough that it’s not disconnected?

What I did in one of my projects where I needed the wait for data from the client to not block the rest of loop() is to make the Client object global and then call client.stop() when I was ready to disconnect:

#include <ESP8266WiFi.h>

const char SSID[] = "myssid";
const char WiFiPassword[] = "mypassword";


const byte LEDpin = LED_BUILTIN;
int ledStatus = LOW;

WiFiServer server(80);
WiFiClient client;

void setup() {
  Serial.begin(115200);
  Serial.print(F("\n\n\n\n"));
  Serial.print(F("Web Server Test:"));

  pinMode(LEDpin, OUTPUT);
  digitalWrite(LEDpin, ledStatus);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print(F("Connecting to "));
  Serial.println(SSID);
  WiFi.begin(SSID, WiFiPassword);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.println(F("WiFi connected"));

  // Start the server
  server.begin();
  Serial.println(F("Server started"));

  // Print the IP address
  Serial.print(F("Web server IP address: "));
  Serial.println(WiFi.localIP());
}

void loop() {
  if (!client) {  //no client is currently connected
    client = server.available();  //check if there is a client available
  }
  if (client && client.available()) {  //there is a client connected and there is data available
    HTMLrequestHandler();
    sendHTMLresponse();
  }
}


void HTMLrequestHandler() {
  // Read the first line of the request
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();

  // Match the request
  if (req.indexOf("/off") != -1) {
    ledStatus = HIGH;
  }
  else if (req.indexOf("/on") != -1) {
    ledStatus = LOW;
  }
  digitalWrite(LEDpin, ledStatus);
  client.flush();
}


void sendHTMLresponse() {
  client.println("HTTP/1.1 200 OK");
  client.println("Content-type:text/html");
  client.println();
  client.print("The LED is ");
  if (ledStatus == HIGH) {
    client.print("off");
  }
  else {
    client.print("on");
  }
  client.println("
");
  client.println("
");
  client.println("Click <a href=\"/off\">here</a> turn the LED off
");
  client.println("Click <a href=\"/on\">here</a> turn the LED on
");
  client.println();
  client.stop();
}

Ok...great! I will try doing that also.

One more thing...the arduino reference is really unclear on client.flush(). Can you help me with the same?

Also, I am trying to function 2 LEDs using the webserver example now.

The problem is...when my 2nd led turns ON, the 1st one automatically turns OFF. and vice versa.

Shantanu24:
The problem is…when my 2nd led turns ON, the 1st one automatically turns OFF. and vice versa.

Just make valD1 and valD2 global, then they will remember the previous values:

#include <ESP8266WiFi.h>

const char* ssid = "default";
const char* password = "dviewindia";

// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

int valD1;
int valD2;

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

  // D1
  pinMode(5, OUTPUT);
  //digitalWrite(5, 0);

   // D2
  pinMode(4, OUTPUT);
  //digitalWrite(4, 0);
 
  // 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.println(WiFi.localIP());
}

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 req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();

   // Match the request
  if (req.indexOf("/?pin=OFF") != -1)
    valD1 = 0;
    //Serial.print(val);
  else if (req.indexOf("/?pin=ON") != -1)
    valD1 = 1;
    //Serial.println("value is");
    //Serial.print(val);
  //else
//    Serial.println("invalid request");
//    client.stop();
    //return;
 
  Serial.println("val of D1 is");
  Serial.print(valD1);

  // Set GPIO2 according to the request
  digitalWrite(5, valD1);
  Serial.println("D1 val is");
  Serial.print(valD1);
 
  client.flush();


   // Match the request
 
  if (req.indexOf("/?pin=KZ") != -1)
    valD2 = 0;
    //Serial.print(val);
  else if (req.indexOf("/?pin=KV") != -1)
    valD2 = 1;
    //Serial.println("value is");
    //Serial.print(val);
  //else
//    Serial.println("invalid request");
//    client.stop();
   // return;
 
  Serial.println("val of D2 is");
  Serial.print(valD2);

  // Set GPIO2 according to the request
  digitalWrite(4, valD2);
  Serial.println("D2 val is");
  Serial.print(valD2);
 
  client.flush();
 
  String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nLED is now ";
  s += (valD1)?"ON":"OFF";
  s += "</html>\n";

 
  client.print(s);
  delay(1);
  Serial.println("Client disonnected");

}

and.....you are right my friend!!!! It worked! thank you!

Shantanu24:
the arduino reference is really unclear on client.flush(). Can you help me with the same?

I think the way it works is in your sketch you have this:

String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();

client.readStringUntil(’\r’) reads the first line of the request(actually it stops before the last character “\n”). So there is actually more data available from the client that you don’t care about. client.flush() just dumps the rest of the request. In this case I don’t think it actually makes a difference.

You can see the effect by running this code:

#include <ESP8266WiFi.h>

const char* ssid = "default";
const char* password = "dviewindia";

// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);


  int valD1;
  
  int valD2;

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

  // D1
  pinMode(5, OUTPUT);
  //digitalWrite(5, 0);

   // D2
  pinMode(D4, OUTPUT);
  //digitalWrite(4, 0);
 
  // 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.println(WiFi.localIP());
}

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 req = client.readStringUntil('\r');
  Serial.println(req);
  Serial.print("pre-flush client.available()=");
  Serial.println(client.available());
  client.flush();
  Serial.print("post-flush client.available()=");
  Serial.println(client.available());

   // Match the request
  if (req.indexOf("/?pin=OFF") != -1)
    valD1 = 0;
    //Serial.print(val);
  else if (req.indexOf("/?pin=ON") != -1)
    valD1 = 1;
    //Serial.println("value is");
    //Serial.print(val);
  //else
//    Serial.println("invalid request");
//    client.stop();
    //return;
 
  Serial.println("val of D1 is");
  Serial.print(valD1);

  // Set GPIO2 according to the request
  digitalWrite(5, valD1);
  Serial.println("D1 val is");
  Serial.print(valD1);
 
  client.flush();


   // Match the request
 
  if (req.indexOf("/?pin=KZ") != -1)
    valD2 = 0;
    //Serial.print(val);
  else if (req.indexOf("/?pin=KV") != -1)
    valD2 = 1;
    //Serial.println("value is");
    //Serial.print(val);
  //else
//    Serial.println("invalid request");
//    client.stop();
   // return;
 
  Serial.println("val of D2 is");
  Serial.print(valD2);

  // Set GPIO2 according to the request
  digitalWrite(4, valD2);
  Serial.println("D2 val is");
  Serial.print(valD2);
 
  client.flush();
 
  String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nLED is now ";
  s += (valD1)?"ON":"OFF";
  s += "</html>\n";

 
  client.print(s);
  delay(1);
  Serial.println("Client disonnected");

}

pre-flush client.available()=272
post-flush client.available()=0

Just FYI I had originally left my ssid and password in the previous example so you'd need to change them back to your settings so the ESP8266 can connect to your router.

Got it! Will do! Thank You once again for all your help! I will try the new approach you advised!

i have the same problem but i use servo motor, can you help me
and this my code program, button on the web does not work on its servo motor :frowning:
#ifndef UNIT_TEST
#include <Arduino.h>
#endif
#include <ESP8266WiFi.h>
#include <Servo.h>

const char* ssid = “OPPO A57”;
const char* password = “febriani”;
WiFiServer server(80);//the port
Servo myservo; // create servo object to control a servo
IPAddress ip(192, 168, 43, 125);
IPAddress gateway(192, 168, 43, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress dns(192, 168, 43, 1);
void setup(void) {
Serial.begin(115200);
delay(10);
// attaches the servo on D2 or GPIO4 of the NodeMCU devkit v1.0
myservo.attach(D2);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print(“Connecting to “);
Serial.println(ssid);
//Static IP Setup Info Here…
WiFi.config(ip,dns,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 to connect: “);
Serial.print(“http://”);
Serial.print(WiFi.localIP());
Serial.println(”/”);
}
void loop()
{
int pos;
// 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);
client.setNoDelay(1);
}
// Read the first line of the request
String request = client.readStringUntil(’\r’);
Serial.println(request);
client.flush();
// Match the request for the angle movement of the servo motor
if (request.indexOf("/sweep left") != -1)
{
// goes from 0 degrees to 180 degrees
for(pos = 0; pos <= 180; pos += 1)
{ // in steps of 1 degree
// tell servo to go to position in variable ‘pos’
myservo.write(pos);
// waits 15ms for the servo to reach the position
delay(15);
}
}
if (request.indexOf("/sweep right") != -1)
{
// goes from 0 degrees to 180 degrees
for(pos = 0; pos <= 180; pos -= 1)
// in steps of 1 degree
{
// tell servo to go to position in variable ‘pos’
myservo.write(pos);
// waits 15ms for the servo to reach the position
delay(15);
}
}
// 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(“WEB CONTROLLED SERVO MOTOR”);
client.println(“

WEB CONTROLLED SERVO MOTOR”);
client.println(“

USING NODEMCU 1.0 BOARD”);
client.print("");
client.print("
“);
client.print(”
“);
client.println(”<a href="/sweep left"">

SWEEP LEFT

");
client.println("<a href="/sweep right"">

SWEEP RIGHT

"); client.println(""); client.println(""); delay(1); Serial.println("Client disconnected"); Serial.println(""); }