In this, I will explain how to control a relay using web server. Here, I have connected a LED to relay.
First we need to setup NodeMCU in Arduino IDEStep 1Open Arduino IDE.Then go to File => Preference:
In Additional Boards Manager, copy and paste the URL and click ok: http://arduino.esp8266.com/stable/package_esp8266com_index.json
Open Board Manager by going to Tools => Board => Boards Manger.
Open Boards Manager and search for nodemcu.
After that download ESP8266WiFi library .
Open library Manager: Sketch => Include library => Manage Libraries
Search for ESP8266WiFi library:
Select Board and Port.
Select Port in same menu (in my case its Port-3):
Relay is an electromagnetic device which is used to isolate two circuits electrically and connect them magnetically. They are very useful devices and allow one circuit to switch another one while they are completely separate. They are often used to interface an electronic circuit (working at a low voltage) to an electrical circuit which works at very high voltage. For example, a relay can make a 5V DC battery circuit to switch a 230V AC mains circuit.
How it works
A relay switch can be divided into two parts: input and output. The input section has a coil which generates magnetic field when a small voltage from an electronic circuit is applied to it. This voltage is called the operating voltage. Commonly used relays are available in different configuration of operating voltages like 6V, 9V, 12V, 24V etc. The output section consists of contactors which connect or disconnect mechanically. In a basic relay there are three contactors: normally open (NO), normally closed (NC) and common (COM). At no input state, the COM is connected to NC. When the operating voltage is applied the relay coil gets energized and the COM changes contact to NO. Different relay configurations are available like SPST, SPDT, DPDT etc, which have different number of changeover contacts. By using proper combination of contactors, the electrical circuit can be switched on and off. Get inner details about structure of a relay switch.
The COM terminal is the common terminal. If the COIL terminals are energized with the rated voltage, the COM and the NO terminals have continuity. If the COIL terminals are not energized, then the COM and the NO terminals have no continuity.
The NC terminal is the Normally Closed terminal. It is the terminal that can be powered on even if the relay doesn't receive any or sufficient voltage to operate.
The NO terminal is the Normally Open terminal. It is the terminal where you place the output that you want on when the relay receives its rated voltage. If there is no voltage to the COIL terminals or insufficient voltage, the output is open and receives no voltage. When the COIL terminals receive the rated voltage or a little under, the NO terminal receives sufficient voltage and can turn on the device on the output.
What is NodeMCUNodeMCUis an open source IoT platform.It includes firmware which runs on the ESP8266Wi-FiSoC from Espressif Systems and hardware which is based on the ESP-12 module .
NodeMCU pin description.
How to program NodeMCU with Arduino IDE
To connect NodeMCU to pc serially you have to install cp2102 driver.
Once you installed driver, connect NodeMCU with pc ,open Arduino IDE and select board NodeMCU 1.0 and select port. After that upload the code.
How to connect NodeMCU with relayHere, I only connected one connection. You can even connect voltage pin to Vin of NodeMCU instead of 3.3V.
#include <ESP8266WiFi.h>
// http://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/readme.html
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
// ESP8266WebServer is to set up a web server on ESP8266.
#include <ESP8266mDNS.h>
/*
mDNS uses domain names with the .local suffix, for example http://esp8266.local. If your computer needs to send a request to a domain name that ends in .local, it will send a multicast query to all other devices on the LAN that support mDNS, asking the device with that specific domain name to identify itself. The device with the right name will then respond with another multicast and send its IP address.
Now that your computer knows the IP address of the device, it can send normal requests.
*/
MDNSResponder mdns; //Create an instance
const char* ssid = "....."; //your connection name const char* password = "................"; // password
ESP8266WebServer server(80);
int gpio1_pin = 2; //D4 of nodemcu
int gpio2_pin = 13; //D7
int gpio3_pin =14; //D5
//Check if header is present and correct bool is_authentified(){
Serial.println("Enter is authentified"); if (server.hasHeader("Cookie")){
Serial.print("Found cookie: ");
String cookie = server.header("Cookie"); Serial.println(cookie);
if (cookie.indexOf("ESPSESSIONID=1") != -1) { Serial.println("Authentification Successful"); return true;
}
}
Serial.println("Authentification Failed");
return false;
}
//login page, also called for disconnect void handleLogin(){
String msg;
if (server.hasHeader("Cookie")){ Serial.print("Found cookie: ");
String cookie = server.header("Cookie"); Serial.println(cookie);
}
if (server.hasArg("DISCONNECT")){ Serial.println("Disconnection"); server.sendHeader("Location","/login"); server.sendHeader("Cache-Control","no-cache"); server.sendHeader("Set-Cookie","ESPSESSIONID=0"); server.send(301);
return;
}
if (server.hasArg("USERNAME") && server.hasArg("PASSWORD")){
if (server.arg("USERNAME") == "ruchir" && server.arg("PASSWORD") == "ruchir" ){
server.sendHeader("Location","/"); server.sendHeader("Cache-Control","no-cache"); server.sendHeader("Set-Cookie","ESPSESSIONID=1"); server.send(301);
Serial.println("Log in Successful"); return;
}
msg = "Wrong username/password! try again."; Serial.println("Log in Failed");
}
String content = "<html><body
style='background-color:MediumAquaMarine'><form action='/login' method='POST'><p align ='center' style='font-size:300%;'><u><b><i> Log In
</i></b></u></p><br>";
content += " <p align ='center' style='font-size:160%'><b> UserName:<input type='text' name='USERNAME' placeholder='user name' required></b></p><br>";
content += "<p align ='center' style='font-size:160%'><b>Password:<input type='password' name='PASSWORD' placeholder='password' required></b></p><br>";
content += "<p align ='center' style='font-size:160%'><input type='submit' name='SUBMIT' value='Submit'></form>" + msg + "</p><br> </body></html>";
server.send(200, "text/html", content);
}
//root page can be accessed only if authentification is ok void handleRoot(){
Serial.println("Enter handleRoot"); String header;
if (!is_authentified()){ server.sendHeader("Location","/login");
server.sendHeader("Cache-Control","no-cache"); server.send(301);
return;
}
String content = "<body style='background: #80c6f7'><h1 align
='center'><b><u><i><strong>HOME AUTOMATION</strong></i></u></b></h1><br><p align ='center'>Switch #1 <a href=\"switch1On\"><button>ON</button></a> <a href=\"switch1Off\"><button>OFF</button></a></p>";
content += "<br><p align ='center'>Switch #2 <a href=\"switch2On\"><button>ON</button></a> <a href=\"switch2Off\"><button>OFF</button></a></p>";
content += "<br><p align ='center'>Switch #3 <a href=\"switch3On\"><button>ON</button></a> <a href=\"switch3Off\"><button>OFF</button></a></p>";
content += "<br><p><marquee direction='right'>Developed by RUCHIR SHARMA </marquee></p>";
content += "<br><br><br><br> <footer><p>Posted by: Ruchir Sharma</p><p><a href=\"mailto:someone@example.com\">........@.....com</a>.</p></footer></body
>";
if (server.hasHeader("User-Agent")){
content += "the user agent used is : " + server.header("User-Agent") + "<br><br>";
}
content += "You can access this page until you <a href=\"/login?DISCONNECT=YES\">disconnect</a></body></html>";
server.send(200, "text/html", content);
}
//no need authentification
void handleNotFound(){
String message = "File Not Found\n\n"; message += "URI: ";
message += server.uri(); message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST"; message += "\nArguments: ";
message += server.args(); message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void setup(void){
// preparing GPIOs
pinMode(gpio1_pin, OUTPUT); //sets the digital pin as output digitalWrite(gpio1_pin, LOW); //sets the pin off
pinMode(gpio2_pin, OUTPUT); //sets the digital pin as output digitalWrite(gpio2_pin, LOW); //sets the pin off
pinMode(gpio3_pin, OUTPUT); //sets the digital pin as output digitalWrite(gpio3_pin, LOW); //sets the pin off
delay(1000);
Serial.begin(115200); // Start the Serial communication WiFi.begin(ssid, password);
Serial.println("");
Serial.begin(115200); WiFi.begin(ssid, password); 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());
if (mdns.begin("esp8266", WiFi.localIP())) { Serial.println("MDNS responder started");
}
server.on("/", handleRoot); server.on("/login", handleLogin); server.on("/inline", [](){
server.send(200, "text/plain", "this works without need of authentification");
});
server.onNotFound(handleNotFound);
//here the list of headers to be recorded
const char * headerkeys[] = {"User-Agent","Cookie"} ; size_t headerkeyssize = sizeof(headerkeys)/sizeof(char*);
//ask server to track these headers server.collectHeaders(headerkeys, headerkeyssize );
// tell the server what URIs it needs to respond to
server.on("/",[ ]( ){
});
server.on("/switch1On", [ ]( ){ digitalWrite(gpio1_pin, HIGH); delay(1000);
});
server.on("/switch1Off", [ ]( ){ digitalWrite(gpio1_pin, LOW);
delay(1000);
});
server.on("/switch2On", [ ]( ){ digitalWrite(gpio2_pin, HIGH);
delay(1000);
});
server.on("/switch2Off", [ ]( ){ digitalWrite(gpio2_pin, LOW); delay(1000);
});
server.on("/switch3On", [ ]( ){ digitalWrite(gpio3_pin, HIGH); delay(1000);
});
server.on("/switch3Off", [ ]( ){ digitalWrite(gpio3_pin, LOW); delay(1000);
});
server.begin( );
Serial.println("HTTP server started");
}
void loop(void){ server.handleClient( );
}
ResultAfter login:
Comments