Esp8266 Server Creation

After hours of troubleshooting I finally got my esp8266 to connect to my WIFI. Now I just need to get it to control something.

I’m trying to just turn a diode on and off via a web browser. I know there’s lots of YouTube videos and articles about this and I’ve tried to go through them all, as well as all the examples on the ide. I cant figure out how servers work and what each piece of code does. Can anyone tell me what’s wrong with my code and how i can accomplish what I’m trying to do?

#include <ESP8266WiFi.h>
//wifi connection info
const char* ssid = "SIKE";
const char* password = "YOU THOUGHT";

//set variables
byte userinput = 0;

//set pins
int connectionpin = 16;
int controlpin = 5;

//create server
const int port = 3005;
WiFiServer myserver(port);

//setup runs once
void setup() {

  //set pinmodes
  pinMode(connectionpin, OUTPUT);
  pinMode(controlpin, OUTPUT);

  //begin serial connection
  Serial.begin(9600);

  //beginning print
  Serial.println();
  Serial.print("Wifi connecting to ");
  Serial.println( ssid );

  //start connection
  WiFi.begin(ssid, password);
  Serial.println();
  Serial.print("Connecting");

  //waiting to connect
  while ( WiFi.status() != WL_CONNECTED )
  {
    delay(500);
    Serial.print(".");
  }

  //connection success
  digitalWrite( connectionpin , HIGH);
  Serial.println();
  Serial.println("Wifi Connected Success!");
  Serial.print("NodeMCU IP Address : ");
  Serial.println(WiFi.localIP() );
  myserver.begin();
}

// put your main code here, to run repeatedly:
void loop()
{
  //check if anything is connected to server
  WiFiClient client = myserver.available();

  //while something is connected check for input
  while (client.connected()) {
    //if input is recieved complete the following actions
    if (client.available())
    {
      userinput = client.read();
      usercontrol();
      client.write("thank you");
      client.stop();
    }
  }
}

//command to control what happens for each input
void usercontrol()
{
  switch (userinput)
  {
    case 48:
      {
        digitalWrite(controlpin, LOW);
      }
    case 49:
      {
        digitalWrite(controlpin, HIGH);
      }
  }
}

In order for the Arduino to be controlled by a web browser it is normal for the Arduino to publish a web page on which there are controls. The web browser connects to the server, displays the page and the user interacts with the controls. The Arduino receives the user input and acts on it

Is that what you want to happen ?

If so then most of that is missing from your code

Hi,

I found the same problem myself, every example I looked at seemed very confusing and completely different to the last one I had looked at, I think the problem is that there are many different ways to do it.

To clear it in my own head and figure out what works best for me I created this sketch which may be of interest which is the easiest way I know of to serve some basic web pages with a few control buttons etc.

You want to have a basic understanding of HTML so if you are not familiar with it you may benefit from first having a look at: https://www.w3schools.com/

Basic esp web server sketch

Another example for you to try

//adapted from https://tttapa.github.io/ESP8266/Chap10%20-%20Simple%20Web%20Server.html

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);    // Create a webserver object that listens for HTTP request on port 80

boolean redOn = false;
boolean greenOn = false;
boolean blueOn = false;
char redText[] = {"OFF"};
char greenText[] = {"OFF"};
char blueText[] = {"OFF"};
byte redState;
byte greenState;
byte blueState;

const byte redOutPin = D1;  //change these pin numbers to suit the board
const byte greenOutPin = D2;
const byte blueOutPin = D3;

void setup(void)
{
  Serial.begin(115200);         // Start the Serial communication to send messages to the computer
  pinMode(redOutPin, OUTPUT);
  digitalWrite(redOutPin, LOW);
  pinMode(greenOutPin, OUTPUT);
  digitalWrite(greenOutPin, LOW);
  pinMode(blueOutPin, OUTPUT);
  digitalWrite(blueOutPin, LOW);
  delay(10);
  Serial.println('\n');
  WiFi.mode(WIFI_STA);
  WiFi.begin("XXXXXXXXXX", "XXXXXXXXX");
  Serial.println("Connecting ...");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println('\n');
  Serial.print("Connected to ");
  Serial.println(WiFi.SSID());              // Tell us what network we're connected to
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());           // Send the IP address of the ESP8266 to the computer
  server.on("/", HTTP_GET, handleRoot);     // Call the 'handleRoot' function when a client requests URI "/"
  server.on("/redLED", HTTP_POST, redLED);  // Call the 'redLED' function when a POST request is made to URI "/redLED"
  server.on("/greenLED", HTTP_POST, greenLED);  // Call the 'greenLED' function when a POST request is made to URI "/greenLED"
  server.on("/blueLED", HTTP_POST, blueLED);  // Call the 'blueLED' function when a POST request is made to URI "/blueLED"
  server.onNotFound(handleNotFound);        // When a client requests an unknown URI (i.e. something other than "/"), call function "handleNotFound"
  server.begin();                           // Actually start the server
  Serial.println("HTTP server started");
}

void loop(void)
{
  server.handleClient();                    // Listen for HTTP requests from clients
}

void handleRoot()                           // When URI / is requested, send a web page with a button to toggle the LED
{
  char buffer[600];
  sprintf(buffer, "<!DOCTYPE html>\
<html>\
<head>\
<style>\
.colourSquare {\
width: 200px;\
height: 200px;\
font-size: 80px;\
color: WHITE;\
font-weight:bold;\
display: inline-block;\
}\
</style>\
</head>\
  <form action=\"/redLED\" method=\"POST\"> <input type=\"submit\" class=\"colourSquare\" style=\"background-color:RED;\" value=\"%s\"> </form>\
  <form action=\"/greenLED\" method=\"POST\"> <input type=\"submit\" class=\"colourSquare\" style=\"background-color:GREEN;\" value=\"%s\"> </form>\
  <form action=\"/blueLED\" method=\"POST\"> <input type=\"submit\" class=\"colourSquare\" style=\"background-color:BLUE;\" value=\"%s\"> </form>\
  </html>", redText, greenText, blueText);
  server.send(200, "text/html", buffer );
}

void redLED()                            // If a POST request is made to URI /redLED
{
  redOn = !redOn;
  if (redOn)
  {
    strcpy(redText, "ON");
    redState = HIGH;
  }
  else
  {
    strcpy(redText, "OFF");
    redState = LOW;
  }
  Serial.print("The red LED is ");
  Serial.println(redText);
  server.sendHeader("Location", "/");       // Add a header to respond with a new location for the browser to go to the home page again
  server.send(303);                         // Send it back to the browser with an HTTP status 303 (See Other) to redirect
  digitalWrite(redOutPin, redState);
}

void greenLED()                            // If a POST request is made to URI /greenLED
{
  greenOn = !greenOn;
  if (greenOn)
  {
    strcpy(greenText, "ON");
    greenState = HIGH;
  }
  else
  {
    strcpy(greenText, "OFF");
    greenState = LOW;
  }
  Serial.print("The green LED is ");
  Serial.println(greenText);
  server.sendHeader("Location", "/");       // Add a header to respond with a new location for the browser to go to the home page again
  server.send(303);                         // Send it back to the browser with an HTTP status 303 (See Other) to redirect
  digitalWrite(greenOutPin, greenState);
}
void blueLED()                            // If a POST request is made to URI /blueLED
{
  blueOn = !blueOn;
  if (blueOn)
  {
    strcpy(blueText, "ON");
    blueState = HIGH;
  }
  else
  {
    strcpy(blueText, "OFF");
    blueState = LOW;
  }
  Serial.print("The blue LED is ");
  Serial.println(blueText);
  server.sendHeader("Location", "/");       // Add a header to respond with a new location for the browser to go to the home page again
  digitalWrite(blueOutPin, blueState);
  server.send(303);                         // Send it back to the browser with an HTTP status 303 (See Other) to redirect
}
void handleNotFound()
{
  server.send(404, "text/plain", "404: Not found"); // Send HTTP status 404 (Not Found) when there's no handler for the URI in the request
}

Ive used bits and pieces from both of the codes you guys provided and cant seem to get it to work. I got to the ip address thats provided and it just says it cant reach the page. Any ideas?

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
//wifi connection info
const char* ssid = "NOPE";
const char* password = "NOPE";

//set variables
byte controllight = 0;

//set pins
int connectionpin = 16;
int controlpin = 5;

//create server
ESP8266WebServer myserver(3005);

//setup runs once
void setup() {

  //set pinmodes
  pinMode(connectionpin, OUTPUT);
  digitalWrite(connectionpin, LOW);
  pinMode(controlpin, OUTPUT);
  digitalWrite(controlpin, LOW);

  //begin serial connection
  Serial.begin(115200);

  //beginning print
  Serial.println();
  Serial.print("Wifi connecting to ");
  Serial.println( ssid );

  //start connection
  WiFi.begin(ssid, password);
  Serial.println();
  Serial.print("Connecting");

  //waiting to connect
  while ( WiFi.status() != WL_CONNECTED )
  {
    delay(500);
    Serial.print(".");
  }

  //connection success
  digitalWrite( connectionpin , HIGH);
  Serial.println();
  Serial.println("Wifi Connected Success!");
  Serial.print("NodeMCU IP Address : ");
  Serial.println(WiFi.localIP() );
  myserver.on("/", HTTP_GET, funhomepage);
  myserver.on("/light", HTTP_POST, funlightswitch);
  myserver.onNotFound(funnotfound);
  myserver.begin();
  Serial.println("HTTP server started");
}

// put your main code here, to run repeatedly:
void loop()
{
  myserver.handleClient();
}

// When URI / is requested, send a web page with a button to toggle the LED
void funhomepage()
{
  char buffer[600];
  sprintf(buffer, "<!DOCTYPE html>\
<html>\
<head>\
<style>\
.colourSquare {\
width: 200px;\
height: 200px;\
font-size: 80px;\
color: WHITE;\
font-weight:bold;\
display: inline-block;\
}\
</style>\
</head>\
  <form action=\"/light\" method=\"POST\"> <input type=\"submit\" class=\"colourSquare\" style=\"background-color:RED;\" value=\"%s\"> </form>\
  <form action=\"/light\" method=\"POST\"> <input type=\"submit\" class=\"colourSquare\" style=\"background-color:GREEN;\" value=\"%s\"> </form>\
  <form action=\"/light\" method=\"POST\"> <input type=\"submit\" class=\"colourSquare\" style=\"background-color:BLUE;\" value=\"%s\"> </form>\
  </html>", "redText", "greenText", "blueText");
  myserver.send(200, "text/html", buffer );
}

// Send HTTP status 404 (Not Found) when there's no handler for the URI in the request
void funnotfound()
{
  myserver.send(404, "text/plain", "404: Not found");
}

//command to control light
void funlightswitch()
{
  switch (controllight)
  {
    case 0:
      {
        digitalWrite(controlpin, HIGH);
        controllight = 1;
      }
    case 1:
      {
        digitalWrite(controlpin, LOW);
        controllight = 0;
      }
  }
}

Are you are using the port number, ie 3005, when entering the IP address in the browser ?

how do i know what port number im using? I just type the ip address into the browser, nothing about the port.

One of the videos i watched said to just put whatever for the port in the code and it didnt matter.

So i changed the port to 80 and its working now. Where did that number come from? Why 80?

escapeartistaz:
Where did that number come from? Why 80?

80 is the default port for a browser client to connect to an http server.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.