Example sketches for the new Arduino IDE for ESP8266

Moderator: igrr

User avatar
By perecastor
#39149 Hi everyone!

I create this topic because i'm in trouble....
It seems to be easy to have a simple webserver with just one bouton to swith a led on it working.
But i'm only able to run this sketch on my board (trully my fault and not the board) :

Code: Select all#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char *ssid = "Freebox-551B52";
const char *password = "**********";

ESP8266WebServer server ( 80 );

const int led = 2;

void handleRoot() {
   digitalWrite ( led, 1 );
   char temp[400];
   int sec = millis() / 1000;
   int min = sec / 60;
   int hr = min / 60;

   snprintf ( temp, 400,

"<html>\
  <head>\
    <meta http-equiv='refresh' content='5'/>\
    <title>ESP8266 Demo</title>\
    <style>\
      body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }\
    </style>\
  </head>\
  <body>\
    <h1>Hello from ESP8266!</h1>\
    <p>Uptime: %02d:%02d:%02d</p>\
    <img src=\"/test.svg\" />\
  </body>\
</html>",

      hr, min % 60, sec % 60
   );
   server.send ( 200, "text/html", temp );
   digitalWrite ( led, 0 );
}

void drawGraph() {
  String out = "";
  char temp[100];
  out += "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"400\" height=\"150\">\n";
  out += "<rect width=\"400\" height=\"150\" fill=\"rgb(250, 230, 210)\" stroke-width=\"1\" stroke=\"rgb(0, 0, 0)\" />\n";
  out += "<g stroke=\"black\">\n";
  int y = rand() % 130;
  for (int x = 10; x < 390; x+= 10) {
    int y2 = rand() % 130;
    sprintf(temp, "<line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" stroke-width=\"1\" />\n", x, 140 - y, x + 10, 140 - y2);
    out += temp;
    y = y2;
  }
  out += "</g>\n</svg>\n";

  server.send ( 200, "image/svg+xml", out);
}

void handleNotFound() {
   digitalWrite ( led, 1 );
   String message = "File Not Found\n\n";
   message += "URI: ";
   message += server.uri();
   message += "\nMethod: ";
   message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
   message += "\nArguments: ";
   message += server.args();
   message += "\n";

   for ( uint8_t i = 0; i < server.args(); i++ ) {
      message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
   }

   server.send ( 404, "text/plain", message );
   digitalWrite ( led, 0 );
}

void setup ( void ) {
   pinMode ( led, OUTPUT );
   digitalWrite ( led, 0 );
   Serial.begin ( 115200 );
   WiFi.begin ( ssid, password );
   Serial.println ( "" );

   // Wait for connection
   while ( WiFi.status() != WL_CONNECTED ) {
      delay ( 500 );
      Serial.print ( "." );
   }

   Serial.println ( "" );
   Serial.print ( "Connected to " );
   Serial.println ( ssid );
   Serial.print ( "IP address: " );
   Serial.println ( WiFi.localIP() );

   if ( MDNS.begin ( "esp8266" ) ) {
      Serial.println ( "MDNS responder started" );
   }

   server.on ( "/", handleRoot );
   server.on ( "/test.svg", drawGraph );
   server.on ( "/inline", []() {
      server.send ( 200, "text/plain", "this works as well" );
   } );
   server.onNotFound ( handleNotFound );
   server.begin();
   Serial.println ( "HTTP server started" );
}

void loop ( void ) {
   server.handleClient();
}



And now i would manage the led bouton but i don't know how......

So if somebody can help me for it, it would be awesome.
Thanks in advance and sorry for my bad english, i'm french :/
User avatar
By perecastor
#39208 Thx a lot for your reply ^^

I'm sad to say that the previous code wasn't the good one .....
it's also works on my board but i think it 's not the good way to turn on/off a led from a web page.

Here is a new one sketch.

Code: Select all/*
 *  This sketch demonstrates how to set up a simple HTTP-like server.
 *  The server will set a GPIO pin depending on the request
 *    http://server_ip/gpio/0 will set the GPIO2 low,
 *    http://server_ip/gpio/1 will set the GPIO2 high
 *  server_ip is the IP address of the ESP8266 module, will be
 *  printed to Serial when the module is connected.
 */

#include <ESP8266WiFi.h>

const char* ssid = "Freebox-551B52";
const char* password = "*****";

// 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);

  // prepare GPIO2
  pinMode(2, OUTPUT);
  digitalWrite(2, 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 val;
  if (req.indexOf("/gpio/0") != -1)
    val = 0;
  else if (req.indexOf("/gpio/1") != -1)
    val = 1;
  else {
    Serial.println("invalid request");
    client.stop();
    return;
  }

  // Set GPIO2 according to the request
  digitalWrite(2, val);
 
  client.flush();

  // Prepare the response
  String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
  s += (val)?"high":"low";
  s += "</html>\n";
 

  // Send the response to the client
  client.print(s);
  delay(1);
  Serial.println("Client disonnected");

  // The client will actually be disconnected
  // when the function returns and 'client' object is detroyed
}


I'm now able to turn on/off my led on gpio2 but i don't like to change the url to switch the led.
I tried to adapt your code on mine but it won't work. Because i can't use <ESP8266WiFi.h> and <ESP8266WebServer.h> on the same sketch (ardino ide stop the compilation ).
So do you konw another way to manage my switch bouton?
And again thanks a lot for helping me ;)
User avatar
By WereCatf
#39211
perecastor wrote:I tried to adapt your code on mine but it won't work. Because i can't use <ESP8266WiFi.h> and <ESP8266WebServer.h> on the same sketch (ardino ide stop the compilation ).


There's something wrong with your sketch or your Arduino-setup. You most definitely can (and should) use both of those include-files in the same sketch. Here is the Advancedwebserver-sketch adapted to use my example:
Code: Select all/*
 * Copyright (c) 2015, Majenko Technologies
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 * * Neither the name of Majenko Technologies nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

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

const char *ssid = "YourSSIDHere";
const char *password = "YourPSKHere";

ESP8266WebServer server ( 80 );

const int led = 13;

void TogglePin() {
  if (server.method() == HTTP_GET) {
    for ( uint8_t i = 0; i < server.args(); i++ ) {
      if (server.argName(i) == "gpio") {
        int pin = atoi(server.arg(i).c_str());
        pinMode ( pin, OUTPUT );
        digitalWrite(pin, !digitalRead(pin));
      }
    }
    server.send ( 200, "text/plain", "OK.");
  }
}

void handleRoot() {
   digitalWrite ( led, 1 );
   char temp[400];
   int sec = millis() / 1000;
   int min = sec / 60;
   int hr = min / 60;

   snprintf ( temp, 400,

"<html>\
  <head>\
    <meta http-equiv='refresh' content='5'/>\
    <title>ESP8266 Demo</title>\
    <style>\
      body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }\
    </style>\
  </head>\
  <body>\
    <h1>Hello from ESP8266!</h1>\
    <p>Uptime: %02d:%02d:%02d</p>\
    <img src=\"/test.svg\" />\
  </body>\
</html>",

      hr, min % 60, sec % 60
   );
   server.send ( 200, "text/html", temp );
   digitalWrite ( led, 0 );
}

void handleNotFound() {
   digitalWrite ( led, 1 );
   String message = "File Not Found\n\n";
   message += "URI: ";
   message += server.uri();
   message += "\nMethod: ";
   message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
   message += "\nArguments: ";
   message += server.args();
   message += "\n";

   for ( uint8_t i = 0; i < server.args(); i++ ) {
      message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
   }

   server.send ( 404, "text/plain", message );
   digitalWrite ( led, 0 );
}

void drawGraph() {
  String out = "";
  char temp[100];
  out += "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"400\" height=\"150\">\n";
  out += "<rect width=\"400\" height=\"150\" fill=\"rgb(250, 230, 210)\" stroke-width=\"1\" stroke=\"rgb(0, 0, 0)\" />\n";
  out += "<g stroke=\"black\">\n";
  int y = rand() % 130;
  for (int x = 10; x < 390; x+= 10) {
    int y2 = rand() % 130;
    sprintf(temp, "<line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" stroke-width=\"1\" />\n", x, 140 - y, x + 10, 140 - y2);
    out += temp;
    y = y2;
  }
  out += "</g>\n</svg>\n";

  server.send ( 200, "image/svg+xml", out);
}

void setup ( void ) {
   pinMode ( led, OUTPUT );
   digitalWrite ( led, 0 );
   Serial.begin ( 115200 );
   WiFi.begin ( ssid, password );
   Serial.println ( "" );

   // Wait for connection
   while ( WiFi.status() != WL_CONNECTED ) {
      delay ( 500 );
      Serial.print ( "." );
   }

   Serial.println ( "" );
   Serial.print ( "Connected to " );
   Serial.println ( ssid );
   Serial.print ( "IP address: " );
   Serial.println ( WiFi.localIP() );

   if ( MDNS.begin ( "esp8266" ) ) {
      Serial.println ( "MDNS responder started" );
   }

   server.on ( "/", handleRoot );
  server.on ( "/togglepin", TogglePin );
   server.on ( "/test.svg", drawGraph );
   server.on ( "/inline", []() {
      server.send ( 200, "text/plain", "this works as well" );
   } );
   server.onNotFound ( handleNotFound );
   server.begin();
   Serial.println ( "HTTP server started" );
}

void loop ( void ) {
   server.handleClient();
}