基于WeMos D1 Mini的外挂式门锁

learningman 12月 19, 2019

用WeMos D1 Mini做了个锁,芯片是ESP8266
先贴代码,回头写过程

static const char mainPage[] PROGMEM = u8R"(
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>门</title></head>
    <style>.main {
        width: 500px;
        height: 500px;
        position:absolute;
        left:0;
        top: 0;
        bottom: 0;
        right: 0;
        margin: auto;}</style>
<body>
<div class="main">
<h2 align="center">门</h2>
<h3 align="center">%s</h3>
<form method="post" action="setDoor">
    <table align="center"><tr><td>开门:</td><td>
        <button name="power" type="submit" value="1">点我开门</button>
    </td></tr><tr><td>关门:</td><td>
        <button name="power" type="submit" value="0">点我关门</button>
    </td></tr>
    </table>
</form>
<h3 align="center">Copyright by Zxilly</h3>
</div>
</body>
</html>
)";
//开门发送1,关门发送0

static const char errorPage[] PROGMEM = u8R"(
<!DOCTYPE html>
<html>
404 NOT FOUND
</html>
)";
#define WEBPAGE_IN_PROGMEM

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <Servo.h> 

#define server _esp8266WebServer
Servo myservo; 

int doorstatus=0; //1为开的状态,0为关的状态,初始化为关
int pos=0;

ESP8266WebServer server(80);

void goHome() {
  server.sendHeader("Location","/");
  server.send(303);
}

void errorcommand() {
  server.send(400, "text/plain", "400: Invalid Request"); 
}

void openDoor() {
  if(doorstatus==1)
    errorcommand();
  else
  {
    myservo.write(90);
    doorstatus=1;
  }
  goHome();
}

void closeDoor()  {
  if(doorstatus==0)
    errorcommand();
  else
  {
    myservo.write(1);
    doorstatus=0;
  }
  goHome();
}

void handleRoot() {
  server.send_P(200, PSTR("text/html"), mainPage);
}

void handleNotFound() {
  server.send_P(404, PSTR("text/html"), errorPage);
}

void handleDoor() {
  if (server.arg("power")=="1") 
  {
    openDoor();
    Serial.println("Open the Door");
  }
  else 
  {
    closeDoor();
    Serial.println("Close the Door");
  }

}
void setup() {
  Serial.begin(9600);
  myservo.attach(4);
  myservo.write(1);
  WiFi.begin("***","***");//SSID与密码,已经隐藏
  server.on("/", handleRoot);
  server.on("/setDoor",handleDoor);
  server.onNotFound(handleNotFound);
  server.begin();
}

void loop() {
  server.handleClient();
}

本文采用 CC BY-NC-SA 4.0 协议进行许可,在您遵循此协议的情况下,可以自由共享与演绎本文章。
本文链接:https://learningman.top/archives/212

  1. z说道:

    回头写过程,这个头回的有点长啊...

    1. learningman说道:

      这个锁的机械部分遇到了一些小故障。。。在重新设计再3d打印

发表评论

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