本帖最后由 lz-esp-link 于 2019-6-20 11:55 编辑
1、概述
HTTP web server作为ESP8266的一个常用功能,在这里使用零知开源平台进行该示例的演示。2、软件和硬件
硬件使用零知-ESP8266;
软件使用零知开发工具,自带示例:
示例.jpg (133.74 KB, 下载次数: 8)
2019-6-20 11:48 上传3、方法步骤
(1)先在零知开发工具中打开AdvancedWebServer示例,或者复制下面的代码到零知开发工具中:
[mw_shl_code=arduino,true]/**********************************************************
* 文件: x.ino by 零知实验室(www.lingzhilab.com)
* -^^- 零知开源,让电子制作变得更简单! -^^-
* 时间: 2019/05/28 12:22
* 说明:
************************************************************/
#include
#include
#include
#include
#ifndef STASSID
#define STASSID "ssid"
#define STAPSK "passwd"
#endif
const char *ssid = STASSID;
const char *password = STAPSK;
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,
"\
\
ESP8266 Demo\body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }\
\
\
Hello from ESP8266!
\Uptime: %02d:%02d:%02d
\ \
\
",
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.mode(WIFI_STA);
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();
MDNS.update();
}
void drawGraph() {
String out = "";
char temp[100];
out += "\n";
out += "\n";
out += "\n";
int y = rand() % 130;
for (int x = 10; x < 390; x += 10) {
int y2 = rand() % 130;
sprintf(temp, "\n", x, 140 - y, x + 10, 140 - y2);
out += temp;
y = y2;
}
out += "\n\n";
server.send(200, "image/svg+xml", out);
}[/mw_shl_code]
(2)验证上述代码并上传到零知-ESP8266开发板;
(3)我们打开零知开发工具的串口调试窗口,可以看到如下信息:
调试窗口.jpg (38.38 KB, 下载次数: 4)
2019-6-20 11:49 上传
(4)现在我们用ping工具测试下网络,得到如下信息:
ping.jpg (63.15 KB, 下载次数: 5)
2019-6-20 11:49 上传
(5)上述步骤成功后,我们现在打开浏览器,打开网址:http://esp8266.local,可以看到如下信息:
结果.jpg (39.22 KB, 下载次数: 6)
2019-6-20 11:50 上传
更多详细资料可到零知实验室官网免费获取。