懒人是推动社会进步的第一动力!

不想下床关灯?居然还能这么做!

项目名称:物联网开关

所需材料:Node mcu模块,双路继电器,4p公对母杜邦线,

接线:看代码

编程软件:Arduino IDE (安装esp8266环境https://www.cnblogs.com/kekeoutlook/p/8216639.html)

代码:

/*
* 作者:趣讨教(qutaojiao.com)
* 时间:2017-12-20
* 描述:在局域网中通过web网页控制led
* 引脚连接:
* LED灯正极——D3
* LED灯负极——GND
*/

#include <ESP8266WiFi.h>

const char* ssid = “LEDE”; //要连接的wifi名称
const char* password = “982149172”; //WiFi密码

int ledPin = 0; // GPIO0—D3 of NodeMCU
WiFiServer server(80);

void setup() {
Serial.begin(115200);
delay(10);

pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);

// 连接到WiFi网络
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”);

// 启动服务器
server.begin();
Serial.println(“Server started”);

// 打印IP地址
Serial.print(“Use this URL to connect: “);
Serial.print(“http://”);
Serial.print(WiFi.localIP());
Serial.println(“/”);

}

void loop() {
// 检查客户端是否连接
WiFiClient client = server.available();
if (!client) {
return;
}

// 等到客户端发送玩一些数据
Serial.println(“new client”);
while(!client.available()){
delay(1);
}

// 读取请求的第一行
String request = client.readStringUntil(‘\r’);
Serial.println(request);
client.flush();

// 匹配请求

int value = LOW;
if (request.indexOf(“/LED=ON”) != -1) {
digitalWrite(ledPin, HIGH);
value = HIGH;
}
if (request.indexOf(“/LED=OFF”) != -1) {
digitalWrite(ledPin, LOW);
value = LOW;
}

// 根据请求设置ledPin
//digitalWrite(ledPin, value);

// 返回响应
client.println(“HTTP/1.1 200 OK”);
client.println(“Content-Type: text/html”);
client.println(“”); // do not forget this one
client.println(“<!DOCTYPE HTML>”);
client.println(“<html>”);

client.print(“Led is now: “);

if(value == HIGH) {
client.print(“On”);
} else {
client.print(“Off”);
}
client.println(“<br><br>”);
//html头部标题
// client.println(“<body background=‘https://wjsite.cn/wp-content/uploads/2018/12/header.jpg‘style=‘background-repeat:no-repeat ;background-size: cover;background-attachment: fixed;‘><h1 align=‘center‘> &#x6B22;&#x8FCE;&#x4F7F;&#x7528;&#x9648;&#x54E5;&#x7269;&#x8054;&#x7F51;&#x706F;</h1><a><center><button style=‘height:70px;width:100px;display:inline-block;‘>&#x5F00;</button> </center></a><p></p><a><center><button style=‘height:70px;width:100px;display:inline-block;‘>&#x5173;</button> </center></a></body>”);

client.println(“<a href=\”/LED=ON\”\”><center><button style=’height:70px;width:100px;display:inline-block;’>&#x5F00;</button></center></a>”);

client.println(“<p> </p>”);

client.println(“<a href=\”/LED=OFF\”\”><center><button style=’height:70px;width:100px;display:inline-block;’>&#x5173;</button></center></a>”);
client.println(“</html>”);

delay(1);
Serial.println(“Client disonnected”);
Serial.println(“”);

}

打赏

发表评论

电子邮件地址不会被公开。 必填项已用*标注