ESP8266控制开关

#include <ESP8266WiFi.h>        // 本程序使用 ESP8266WiFi库
#include <ESP8266WiFiMulti.h>   //  ESP8266WiFiMulti库
#include <ESP8266WebServer.h>   //  ESP8266WebServer库
#include <FS.h>                 //  闪存头文件
ESP8266WiFiMulti wifiMulti;     // 建立ESP8266WiFiMulti对象,对象名称是 'wifiMulti'
 
ESP8266WebServer esp8266_server(80);// 建立网络服务器对象,该对象用于响应HTTP请求。监听端口(80)

bool pinState;                      // 存储引脚状态用变量

void setup(void){
  Serial.begin(9600);   // 启动串口通讯
 
  pinMode(LED_BUILTIN, OUTPUT); //设置内置LED引脚为输出模式以便控制LED
  IPAddress local_IP(192, 168, 0, 166);    //设置esp8266 设别IP地址
  IPAddress gateway(192, 168, 0, 1);       //网关
  IPAddress subnet(255, 255, 255, 0);      //子网掩码
  WiFi.config(local_IP, gateway, subnet);  //设置静态IP
  WiFi.mode(WIFI_STA);                     //设置站点模式
  
  wifiMulti.addAP("B902", "meiyoumima123456"); // 将需要连接的一系列WiFi ID和密码输入这里
  wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2"); // ESP8266-NodeMCU再启动后会扫描当前网络
  wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3"); // 环境查找是否有这里列出的WiFi ID。如果有
  Serial.println("Connecting ...");                            // 则尝试使用此处存储的密码进行连接。
  
  int i = 0;                                 
  while (wifiMulti.run() != WL_CONNECTED) {  // 此处的wifiMulti.run()是重点。通过wifiMulti.run(),NodeMCU将会在当前
    delay(1000);                             // 环境中搜索addAP函数所存储的WiFi。如果搜到多个存储的WiFi那么NodeMCU
    Serial.print(i++); Serial.print(' ');    // 将会连接信号最强的那一个WiFi信号。
  }                                          // 一旦连接WiFI成功,wifiMulti.run()将会返回“WL_CONNECTED”。这也是
                                             // 此处while循环判断是否跳出循环的条件。
  
  // WiFi连接成功后将通过串口监视器输出连接成功信息 
  Serial.println('\n');
  Serial.print("Connected to ");
  Serial.println(WiFi.SSID());              // 通过串口监视器输出连接的WiFi名称
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());           // 通过串口监视器输出ESP8266-NodeMCU的IP

  if(SPIFFS.begin()){                       // 启动闪存文件系统
    Serial.println("SPIFFS Started.");
  } else {
    Serial.println("SPIFFS Failed to Start.");
  }

  esp8266_server.enableCORS(true);           //允许跨域
  esp8266_server.begin();                           // 启动网站服务
  esp8266_server.on("/setled", HTTP_GET, setHandleLED);   // 设置处理LED控制请求的函数'handleLED'
  esp8266_server.on("/getled", HTTP_GET, getHandleLED);   // 设置处理LED控制请求的函数'handleLED'
  esp8266_server.onNotFound(handleUserRequet);        // 设置处理404情况的函数'handleNotFound'
  Serial.println("HTTP esp8266_server started");//  告知用户ESP8266网络服务功能已经启动

}
 
void loop(void){
  esp8266_server.handleClient();                     // 检查http服务器访问
  pinState = digitalRead(LED_BUILTIN); // 获取引脚状态
}


 // 处理用户浏览器的HTTP访问
void handleUserRequet() {         
     
  // 获取用户请求网址信息
  String webAddress = esp8266_server.uri();
  
  // 通过handleFileRead函数处处理用户访问
  bool fileReadOK = handleFileRead(webAddress);

  // 如果在SPIFFS无法找到用户访问的资源,则回复404 (Not Found)
  if (!fileReadOK){                                                 
    esp8266_server.send(404, "text/plain", "404 Not Found"); 
  }
}

bool handleFileRead(String path) {            //处理浏览器HTTP访问

  if (path.endsWith("/")) {                   // 如果访问地址以"/"为结尾
    path = "/index.html";                     // 则将访问地址修改为/index.html便于SPIFFS访问
  } 
  
  String contentType = getContentType(path);  // 获取文件类型
  
  if (SPIFFS.exists(path)) {                     // 如果访问的文件可以在SPIFFS中找到
    File file = SPIFFS.open(path, "r");          // 则尝试打开该文件
    esp8266_server.streamFile(file, contentType);// 并且将该文件返回给浏览器
    file.close();                                // 并且关闭文件
    return true;                                 // 返回true
  }
  return false;                                  // 如果文件未找到,则返回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";
}

//处理LED控制请求的函数'handleLED'
void setHandleLED() {                          
    digitalWrite(LED_BUILTIN,!digitalRead(LED_BUILTIN));// 改变LED的点亮或者熄灭状态 
    pinState = digitalRead(LED_BUILTIN); //读引脚的状态

    if(pinState)
    {
        esp8266_server.send(200, "text/plain", "OFF"); 
    }else
    {
        esp8266_server.send(200, "text/plain", "OPEN");
    }
    
}

void getHandleLED() {                          
    
    pinState = digitalRead(LED_BUILTIN); //读引脚的状态

    if(pinState)
    {
        esp8266_server.send(200, "text/plain", "OFF"); 
    }else
    {
        esp8266_server.send(200, "text/plain", "OPEN");
    }
  
}
 
 
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
    </script>
    <style>
        .item_form {
            margin-top: 5%;
            margin-left: 45%;
            float: left;
        }
        .item_led {
            margin-top: 5%;
            margin-left: 20px;
            float: left;
            border-radius: 100%;
            width: 30px;
            height: 30px;
        }
    </style>

</head>

<body bgcolor="rgb(57,e6,de)">

    <button id="ledButton" class='item_form' style="float:left">开关按钮</button>
    <div id="led" class='item_led' style='background-color: #FF0000;'></div>


</body>

<script>
    setInterval(
        function name(params) {
            $.get("http://192.168.0.166:80/getled", function (data, status) {
            //console.log(data);
            if (data == "OFF") {
                document.getElementById('led').style = "background-color: #FF0000;"
                console.log(1);
            } else {
                document.getElementById('led').style = "background-color: #00FF00;"
                console.log(0);
            }
            });
        },3*1000);

    $("#ledButton").click(function () {
        $.get("http://192.168.0.166:80/setled", function (data, status) {
            if (data == "OFF") {
                document.getElementById('led').style = "background-color: #FF0000;"
                console.log(1);
            } else {
                document.getElementById('led').style = "background-color: #00FF00;"
                console.log(0);
            }
        });
    });

</script>

</html>
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值