问题描述
继电器的状态仍然逃避我。任何帮助将不胜感激。我希望能够在浏览器中获得中继状态,但是不知道如何。例如:如果中继可以在网页上打印0或1,那将是一个很好的选择,然后我可以对homebridge进行编程以读取状态。使用下面的代码,我可以打开和关闭继电器,但是,如果我掉电,则重新启动后的状态通常是不正确的,因为没有设置继电器的真实状态。
#include <ESP8266WiFi.h>
const char* ssid = "abc"; // fill in here your router or wifi SSID
const char* password = "defgh"; // fill in here your router or wifi password
int value = LOW;
#define RELAY 0 // relay connected to GPIO0
WiFiServer server(80);
void setup()
{
Serial.begin(9600); // must be same baudrate with the Serial Monitor
pinMode(RELAY,OUTPUT);
digitalWrite(RELAY,LOW);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid,password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://192.168.0.222/");
Serial.print(WiFi.localIP());
Serial.println("/");
}
void loop()
{
// Check if a client has connected
WiFiClient client = server.available();
if (!client)
{
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available())
{
delay(1);
}
// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
// Match the request
if (request.indexOf("/RELAY=ON") != -1)
{
Serial.println("RELAY=ON");
digitalWrite(RELAY,LOW);
value = LOW;
}
if (request.indexOf("/RELAY=OFF") != -1)
{
Serial.println("RELAY=OFF");
digitalWrite(RELAY,HIGH);
value = HIGH;
}
// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // this is a must
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<head><title>ESP8266 RELAY Control</title></head>");
client.print("The relay is now: ");
if(value == HIGH)
{
client.print("OFF");
}
else
{
client.print("ON");
}
client.println("<br><br>");
client.println("Turn <a href=\"/RELAY=OFF\">OFF</a> RELAY<br>");
client.println("Turn <a href=\"/RELAY=ON\">ON</a> RELAY<br>");
client.println("</html>");
delay(1);
Serial.println("Client disonnected");
Serial.println("");
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)