硬件购买
在网上购买了一个5V电压驱动继电器,因为是PNP驱动的,低电压闭合,如果要使用ESP32来控制,需要将驱动电压降为3.3v,达到PNP关断必要的压降
接入点灯科技的远程管理
目前遇到的问题
1. 电灯科技的设备限制,只能接入一个
2. 远程管理的延迟大,免费的服务不稳定
接入代码
目前没有远程控制的需求,在局域网控制即可, 所以在ESP32里面加入了Http接口,通过网页控制,使用Ngrok DDNS未来也能远程控制,在下面的代码修改加入 WIFI的SSID 密码,点灯科技申请的ID
#define BLINKER_WIFI
#define BLINKER_WITHOUT_SSL
#include <Blinker.h>
#include <WiFi.h>
#include <WebServer.h>
// 继电器开关
#define SWITCH_PIN 14
bool switch_state = false;
WebServer server(80);
void switch_callback(const String & state)
{
BLINKER_LOG("get switch state: ", state);
if (state == BLINKER_CMD_ON) {
switch_state = true;
digitalWrite(LED_BUILTIN, HIGH);
digitalWrite(SWITCH_PIN, HIGH);
BUILTIN_SWITCH.print("on");
}
else if (state == BLINKER_CMD_OFF) {
switch_state = false;
digitalWrite(LED_BUILTIN, LOW);
digitalWrite(SWITCH_PIN, LOW);
BUILTIN_SWITCH.print("off");
}
}
void heartbeat(){
if (switch_state) BUILTIN_SWITCH.print("on");
else BUILTIN_SWITCH.print("off");
}
String summary(){
String data = "online, switch: " + STRING_format(switch_state ? "on" : "off");
return data;
}
void dataRead(const String & data){
BLINKER_LOG("Blinker readString: ", data);
Blinker.vibrate();
uint32_t BlinkerTime = millis();
Blinker.print("millis", BlinkerTime);
}
void handle_root() {
String s = server.arg("s");
if (s == "off") {
switch_callback("off");
} else {
switch_callback("on");
}
server.sendHeader("Location", "/", true);
server.send(302, "text/plain", "");
}
void handle_index() {
String s = "<!DOCTYPE html>";
s += "<head></head>";
s += "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">";
s += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">";
s += "<style type=\"text/css\">";
s += "a{padding: 20px; margin: 20px;font-size: 36px; color: white;border-radius: 5px;display:inline-block}";
s += "h1, p {text-align: center;}b{font-weight: bold;color: green}";
s += ".On {background-color: green;}";
s += ".Off {background-color: red;}";
s += "</style>";
s += "<body>";
s += "<h1>电源开关<b>";
s += (switch_state? "ON" : "OFF");
s += "</b></h1>";
s += "<p>";
s += "<a href=\"/pw1?s=on\" class=\"On\">ON</a>";
s += "<a href=\"/pw1?s=off\" class=\"Off\">OFF</a>";
s += "</p>";
s += "</body>";
s += "</html>";
server.send(200, "text/html", s);
}
void setup() {
Serial.begin(115200);
BLINKER_DEBUG.stream(Serial);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
pinMode(SWITCH_PIN, OUTPUT);
digitalWrite(SWITCH_PIN, HIGH);
switch_state = true;
Blinker.begin("", "", "");
Blinker.attachData(dataRead);
Blinker.attachHeartbeat(heartbeat);
Blinker.attachSummary(summary);
BUILTIN_SWITCH.attach(switch_callback);
server.on("/pw1", handle_root);
server.on("/", handle_index);
server.begin();
WiFi.setSleep(false);
}
void loop() {
Blinker.run();
server.handleClient();
}
运行结果
成本
自制的成本基本会超过淘宝购买的第三方非品牌的远程开关,还不包括电量统计,塑料外壳
- ESP32开发板 15
- 继电器 2
- 插座 5-8
唯一方便的地方,就是自主性强,如果有阿里云的服务器则更好了,映射到远端就能远程控制
当然当继电器 X8 X16的时候,自制的会便宜很多
220V注意用电安全,检查好电路才通电