I am using ESP-01 with 2 Channel 5V Relay. 12v solenoid lock is connected to relay & have built a Web server/microservice to control this lock. There is a random delay in HTTP response when I try to control lock. Here is my sketch.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
const char* ssid = “Redmi Note 10 Pro”;
const char* password = “Satyam10666”;
//Header security
const char* ESPUsername = “Admin”;
const char* ESPPassword = “Admin@123”;
const int led = 2;
const byte rel1ON[] = {0xA0, 0x01, 0x01, 0xA2}; //Hex command to send to serial for open relay
const byte rel1OFF[] = {0xA0, 0x01, 0x00, 0xA1}; //Hex command to send to serial for close relay
const byte rel2ON[] = {0xA0, 0x02, 0x01, 0xA3}; //Hex command to send to serial for open relay
const byte rel2OFF[] = {0xA0, 0x02, 0x00, 0xA2}; //Hex command to send to serial for close relay
ESP8266WebServer server(80);
void setup() {
pinMode(2, OUTPUT);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.begin(115200);
Serial.println(“”);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(“.”);
}
Serial.println(“”);
Serial.print(“Connected to “);
Serial.println(ssid);
Serial.print(“IP address: “);
Serial.println(WiFi.localIP());
server.on(“/openLock”, openLock);
const char * headerkeys[] = {“Username”,”Password”} ;
size_t headerkeyssize = sizeof(headerkeys) / sizeof(char*);
server.collectHeaders(headerkeys, headerkeyssize);
server.begin();
}
void loop() {
server.handleClient();
}
void openLock() {
int relay= 0;
if(server.hasArg(“relay”))
{
relay=server.arg(“relay”).toInt();
}
if(verifyheader() && relay>0)
{
if(relay==1)
{
Serial.write(rel1ON, sizeof(rel1ON));
delay(1000);
Serial.write(rel1OFF, sizeof(rel1OFF));
server.send(200, “text/plain”, “ON success”);
}
else if (relay==2)
{
Serial.write(rel2ON, sizeof(rel2ON));
delay(1000);
Serial.write(rel2OFF, sizeof(rel2OFF));
server.send(200, “text/plain”, “ON success”);
}
}
else
{
server.send(200, “text/plain”, “Invalid request”);
}
}
bool verifyheader()
{
if (server.hasHeader(“Username”) && server.hasHeader(“Password”)) {
String Username = server.header(“Username”);
String Password = server.header(“Password”);
Serial.println(Username);
Serial.println(Password);
if(Username == ESPUsername && Password == ESPPassword)
{
return true;
}
}
return false;
}