马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 划句顾 于 2021-9-4 09:54 编辑
data资源包:
data.zip
(1020 Bytes, 下载次数: 0)
代码如下:/***
*author:LaoGu
*time :2021/9/3
*purpose:利用网页控制ESP8266开发板的内置LED引脚
**/
#include<ESP8266WiFi.h>
#include<ESP8266WiFiMulti.h>
#include<ESP8266WebServer.h>
#include<FS.h>
ESP8266WiFiMulti wifiMulti;
ESP8266WebServer esp8266_server(80);
void setup() {
Serial.begin(9600);
Serial.println("");
pinMode(LED_BUILTIN,OUTPUT); //初始化NodeMCU控制板载LED引脚为OUTPUT
wifiMulti.addAP("小G的wife","g5201314");
wifiMulti.addAP("nanjishit","g5201314");
Serial.println("Connecting ...");
int i = 0 ;
while(wifiMulti.run()!=WL_CONNECTED){
delay(1000);
Serial.print(i++); Serial.print(" ");
}
Serial.println("/n");
Serial.print("Connected to ");
Serial.println(WiFi.SSID());
Serial.print("IP address:");
Serial.println(WiFi.localIP());
if(SPIFFS.begin()){
Serial.println("SPIFFS Started.");
}else {
Serial.println("SPIFFS Failed to start.");
}
esp8266_server.on("/LED-Control",handleLEDControl);
esp8266_server.onNotFound(handleUserRequest);
esp8266_server.begin(); //启动网站服务
Serial.println("HTTP server started");
}
void loop() {
esp8266_server.handleClient(); //处理用户请求
}
// 处理/LED-Control请求
void handleLEDControl(){
bool ledStatus = digitalRead(LED_BUILTIN); //此变量用于存放LED的状态
ledStatus == HIGH ? digitalWrite(LED_BUILTIN,LOW) : digitalWrite(LED_BUILTIN,HIGH); //点亮或熄灭LED
esp8266_server.sendHeader("location","/LED.html");
esp8266_server.send(303);
}
void handleUserRequest(){
//获取用户请求资源 uri():使用该函数可获取客户端发送的HTTP请求行中的请求资源路径信息。
String reqResource = esp8266_server.uri();
Serial.print("reqResource: ");
Serial.println(reqResource);
//通过handleFileRead函数处理用户请求资源
bool fileReadOK = handleFileRead(reqResource);
//如果在SPIFFS无法找到用户访问的资源,则回复404
if(!fileReadOK){
esp8266_server.send(404,"text/plain","404: Not Found");
}
}
//处理浏览器HTTP访问
bool handleFileRead(String resource){
if(resource.endsWith("/")){
resource = "/index.html";
}
String contentType = getContentType(resource); //获取文件类型
if(SPIFFS.exists(resource)){
File file = SPIFFS.open(resource,"r");
esp8266_server.streamFile(file,contentType);
file.close();
return true;
}
return false;
}
// 获取文件类型
String getContentType(String filename){
if(filename.endsWith(".htm")) return "text/html";
else if(filename.endsWith(".html")) return "text/html";
else if(filename.endsWith(".css")) return "text/css";
else if(filename.endsWith(".js")) return "application/javascript";
else if(filename.endsWith(".png")) return "image/png";
else if(filename.endsWith(".gif")) return "image/gif";
else if(filename.endsWith(".jpg")) return "image/jpeg";
else if(filename.endsWith(".ico")) return "image/x-icon";
else if(filename.endsWith(".xml")) return "text/xml";
else if(filename.endsWith(".pdf")) return "application/x-pdf";
else if(filename.endsWith(".zip")) return "application/x-zip";
else if(filename.endsWith(".gz")) return "application/x-gzip";
return "text/plain";
}
串口:
网页:
效果:
视频 |