IOT Project: Home Automation using NodeMcu
Required Equipment:
- NodeMCU
- Relay
- Jumper Wire
- Adapter
- USB Cable
- AC Wire
- Bulb Holder
- Screwp
- Bulb
- 2 Pin Plug
- NodeMCU
- Relay
- Jumper Wire
- Adapter
- USB Cable
- AC Wire
- Bulb Holder
- Screwp
- Bulb
- 2 Pin Plug
Circuit Diagram:
Software install process:
Now download and install a driver CP2102
Now Copy and Paste this CODE in your IDE and upload to NodeMCU:
*******Warning: Please remove all the relay's wire from NodeMCU when uploading code.*******
#include <ESP8266WiFi.h>
WiFiClient client;
WiFiServer server(80);
const char* ssid = "Tenda_4F18B0"; //your wifi name
const char* password = "12345678"; //wifi password
String command =""; // Command received from Android device
// Set Relay Pins
int relay1 = D0;
int relay2 = D1;
void setup()
{
Serial.begin(115200);
pinMode(relay1, OUTPUT);
pinMode(relay2, OUTPUT);
digitalWrite(relay1,LOW);
digitalWrite(relay2,LOW);
connectWiFi();
server.begin();
}
void loop()
{
client = server.available();
if (!client) return;
command = checkClient ();
if (command == "r1on" || command == "light on" || command == "*on")
{
digitalWrite(relay1,LOW);
digitalWrite(relay2,LOW);
Serial.println("Relay1 On");
}
else if (command == "r1off" || command == "light off" || command == "*light off" || command == "off")
{
digitalWrite(relay1,HIGH);
digitalWrite(relay2,HIGH);
Serial.println("Relay1 Off");
}
else
{
digitalWrite(relay1,LOW);
digitalWrite(relay2,LOW);
}
sendBackEcho(command); // send command echo back to android device
command = "";
}
/* connecting WiFi */
void connectWiFi()
{
Serial.println("Connecting to WIFI");
WiFi.begin(ssid, password);
while ((!(WiFi.status() == WL_CONNECTED)))
{
delay(300);
Serial.print("..");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("NodeMCU Local IP is : ");
Serial.print((WiFi.localIP()));
}
/* check command received from Android Device */
String checkClient (void)
{
while(!client.available()) delay(1);
String request = client.readStringUntil('\r');
request.remove(0, 5);
request.remove(request.length()-9,9);
return request;
}
/* send command echo back to android device */
void sendBackEcho(String echo)
{
client.println("HTTP/1.1 200 OK ");
client.println("Content-Type: text/html");
client.println("");
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println(echo);
client.println("</html>");
client.stop();
delay(1);
}
No comments