参考资料:
从零开始的ESP8266探索(06)-使用Server功能搭建Web Server
https://blog.csdn.net/Naisu_kun/article/details/80398667
#include <ESP8266WiFi.h>
/*** 该工程可以在2.4.0版本esp8266库中运行,没在更高版本库中进行测试 ***/
const char *ssid = "HelloWifi";
const char *password = "123ab";
WiFiServer server(80);
String readString = ""; //建立一个字符串对象用来接收存放来自客户的数据
//响应头
String responseHeaders =
String("") +
"HTTP/1.1 200 OK\r\n" +
"Content-Type: text/html\r\n" +
"Connection: close\r\n" +
"\r\n";
//网页
String myhtmlPage =
String("") +
"<html>" +
"<head>" +
" <title>ESP8266 Web Server Test</title>" +
" <script defer=\"defer\">" +
" function ledSwitch() {" +
" var xmlhttp;" +
" if (window.XMLHttpRequest) {" +
" xmlhttp = new XMLHttpRequest();" +
" } else {" +
" xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");" +
" }" +
" xmlhttp.onreadystatechange = function () {" +
" if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {" +
" document.getElementById(\"txtState\").innerHTML = xmlhttp.responseText;" +
" }" +
" }," +
" xmlhttp.open(\"GET\", \"Switch\", true);" +
" xmlhttp.send(); " +
" }" +
" </script>" +
"</head>" +
"<body>" +
" <div id=\"txtState\">Unkwon</div>" +
" <input type=\"button\" value=\"Switch\" onclick=\"ledSwitch()\">" +
"</body>" +
"</html>";
bool isLedTurnOpen = false; // 记录LED状态
void setup()
{
pinMode(2, OUTPUT);
digitalWrite(2, HIGH); // 熄灭LED
Serial.begin(115200);
Serial.println();
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println(" connected");
server.begin();
Serial.printf("Web server started, open %s in a web browser\n", WiFi.localIP().toString().c_str());
}
void loop()
{
WiFiClient client = server.available(); //尝试建立客户对象
if (client) //如果当前有客户可用
{
boolean currentLineIsBlank = true;
Serial.println("[Client connected]");
while (client.connected()) //如果客户端建立连接
{
if (client.available()) //等待有可读数据
{
char c = client.read(); //读取一字节数据
readString += c; //拼接数据
/************************************************/
if (c == '\n' && currentLineIsBlank) //等待请求头接收完成(接收到空行)
{
//比较接收到的请求数据
if (readString.startsWith("GET / HTTP/1.1")) //如果是网页请求
{
client.print(responseHeaders); //向客户端输出网页响应
client.print(myhtmlPage); //向客户端输出网页内容
client.print("\r\n");
}
else if (readString.startsWith("GET /Switch")) //如果是改变LED状态请求
{
if (isLedTurnOpen == false)
{
digitalWrite(2, LOW); // 点亮LED
client.print("LED has been turn on");
isLedTurnOpen = true;
}
else
{
digitalWrite(2, HIGH); // 熄灭LED
client.print("LED has been turn off");
isLedTurnOpen = false;
}
}
else
{
client.print("\r\n");
}
break;
}
if (c == '\n')
{
currentLineIsBlank = true; //开始新行
}
else if (c != '\r')
{
currentLineIsBlank = false; //正在接收某行中
}
/************************************************/
}
}
delay(1); //等待客户完成接收
client.stop(); //结束当前连接:
Serial.println("[Client disconnected]");
Serial.println(readString); //打印输出来自客户的数据
readString = "";
}
}
参考2:
注意: wifiManager.resetSettings();
【LinkNode D1】ESP8266 连接到路由器上
http://jingyan.eeboard.com/article/75186
#include <WiFiManager.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiAP.h>
#include <ESP8266WiFiGeneric.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266WiFiScan.h>
#include <ESP8266WiFiSTA.h>
#include <ESP8266WiFiType.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <WiFiServer.h>
#include <WiFiUdp.h>
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
//reset saved settings
wifiManager.resetSettings();
//set custom ip for portal
wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
//fetches ssid and pass from eeprom and tries to connect
//if it does not connect it starts an access point with the specified name
//here "AutoConnectAP"
//and goes into a blocking loop awaiting configuration
wifiManager.autoConnect("LinkNodeAP");
//or use this for auto generated name ESP + ChipID
//wifiManager.autoConnect();
//if you get here you have connected to the WiFi
Serial.println("connected... :)");
pinMode(BUILTIN_LED, OUTPUT);
}
void loop() {
digitalWrite(BUILTIN_LED, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(BUILTIN_LED, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
需要安装:
参考3:
Arduino IDE for ESP8266 教程(一) 局域网 网页查看数据 不控制
https://www.cnblogs.com/kekeoutlook/p/8284213.html
/*
* 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 = "LRTech";
const char *password = "lanrui2017";
ESP8266WebServer server ( 80 );
const int led = 13;
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 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();
}
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);
}