Control Home Light With Android and Web

Control Home Light With Android and Web

Here is how to control home bulb with your smartphone and web. This tutorial uses Nodemcu with Arduino IDE. Just simple steps. Then you have a smart home if you are more smart ūüėÄ .

Prerequisite
  • Arduino IDE (download)
  • Nodemcu module
  • Android phone
  • Android Studio (Optional)
  • Wifi router (Optional)
  • Some jumper cables
  • 5v opto included relay
  • 5v power supply (old phone charger)

Download links

Android app

1. Build the circuit

nodemcu pinout

First we need to know little of nodemcu. It’s very popular these days among IoT because of simple and cheap (around $5 in eBay) .There are 16 general purpose pin. They can either use as digital input or output. Nodemcu module is integrated with¬† ESP8266 wifi soc chip. It is the heart of nodemcu. Nodemcu just provide easy access through usb and provide programming interface for ESP8266 chip. Nodemcu is first build for programming with Lua, but later it could combined with arduino IDE through¬†Arduino core for nodemcu¬†and also with micropython. It’s open source and you can refer the link for how to get supported nodemcu with arduino IDE. Because most people familiar with arduino it helps easily get work with nodemcu.

However we need just simple workaround and no need much knowledge of  nodemcu background.

And we need a 5v opto-isolated relay. Opto-isolated provide good accuracy and protection to nodemcu with 3.3v signals because nodemcu is work with 3.3v(High output level is 3.3v in GPIO pin) and relay work with 5v signals. We can give 5v for relay and 3.3v supply for signal in opto-isolated relay. With opto-isolated relays voltages are never mixed, they isolated with a optocoupler. It also prevent leak back electromagnetic spike to electronic components. Usually almost every 5v relay module comes with opto-isolated jumper. You can buy 2-relay 5v module(usually it comes with 2 modules) with local shop or ebay with around $2.

See the jumper in green color. With default, jumper is plugged in and no opto-isolated mode. You have to remove the jumper to use those pins.

See the JD-VCC pin. With default it is connected to Vcc pin. You have to give 5v for this pin and supply 3.3v volt for one of other Vcc pin that can be supplied from nodemcu. It has 3x3v3 pins.

Nodemcu has Vin pin and it’s the supply voltage pin, you can supply 5v to 20v this pin. But if you have exactly 3.3v supply you can supply it into any of those 3v3 pin in nodemcu. However in our project we only use 5v supply and you can directly give to Vin pin and direct another 5v wire to relay’s JD-VCC pin. It’s enough power one GND pin in relay. you can also get GND from nodemcu. Remember to power GND in nodemcu with power supply’s negative wire.

Then connect D2 pin(GPIO 05) to IN1 in relay. You can use any other GPIO pin also. Here is the complete circuit diagram with bulb attached to relay.

Circuit
Circuit

In relay module connection between COM and NO1 is activated when IN1 is at Low digital state (0).

Let’s programme the chip.

1. Programme!

Open the arduino IDE and connect the nodemcu. Select the correct bord type in Tools menu(eg: NodeMCU 1.0 ESP-12E ). And you have to know internal flash memory size, usually it is 4MB. Choose the Correct flash size also in Tools menu. If module is connected properly you can chose the port in Tools menu in IDE (eg: COM1 or ttyUSB0). If you are familiar with arduino you can easily understand the code.

#include <ESP8266WiFi.h>

const char* ssid = "SSID";
const char* password = "Password";
 
int relayPin = 4; // GPIO4
WiFiServer server(80);
 
void setup() {
 Serial.begin(115200);
 delay(2000);
 pinMode(ledPin, OUTPUT);
 digitalWrite(relayPin, HIGH); //Turn off at start
 
 // Connect to WiFi network
 Serial.println();
 Serial.println();
 Serial.print("Connecting to ");
 Serial.println(ssid);
 
 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://");
 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
 int value = LOW;
 if (request.indexOf("/LED=ON") != -1) {
 digitalWrite(relayPin, LOW);
 value = LOW;
 }
 if (request.indexOf("/LED=OFF") != -1) {
 digitalWrite(relayPin, HIGH);
 value = HIGH;
 }
 
 // Return the response
 client.println("HTTP/1.1 200 OK");
 client.println("Content-Type: text/html");
 client.println(""); // do not forget this one
 client.println("<!DOCTYPE HTML>");
 client.println("<html>");
 
 client.print("Light is now: ");
 
 if(value == LOW) {
 client.print("On");
 } else {
 client.print("Off");
 }
 client.println("<br><br>");
 client.println("<a href=\"/LED=ON\"\"><button>Turn On </button></a>");
 client.println("<a href=\"/LED=OFF\"\"><button>Turn Off </button></a><br />"); 
 client.println("</html>");
 
 delay(1);
 Serial.println("Client disonnected");
 Serial.println("");
 
}

You have to edit SSID and Password fields according to your home router or your mobile hotspot. Then upload the code to nodemcu and see the serial monitor. Then you can see the ip address that module has been obtained. Then type it in your web browser (web browser should be connected to same wifi network).You will see a web page like below if everything is success.

However if you are interested in how to build a android app for above scenario you can follow below tutorial. Else you can simply download the app here. Source code is on my github repository.

Type the url and then press the button.

It uses the simple HTTP request as we pressing the button in the web page, then it sends to nodemcu. Let’s see it.

3. Build the android app

I assume you have little knowledge of android.

To send HTTP request I’m using very efficient and open source¬† android library called Volley. Refer the link to know more about the library. You have to add the following code in app’s build.gradle file.

dependencies {
    ...
    compile 'com.android.volley:volley:1.1.0'
}

Then you can import the library in source code.

Here is the MainActivity.java in the app. You can clone full source code from my github repository. Then you can customize it and run your own request to control the devices.

package com.lakinduakash.smarthome;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

public class MainActivity extends AppCompatActivity {


    Button mainSwitch;
    EditText urlEdit;
    TextView textView;

    String curState = "";
    static final String[] STATES = {"/LED=ON", "/LED=OFF"};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mainSwitch = findViewById(R.id.button);//Toggle button of the light
        urlEdit = findViewById(R.id.editText);//Url field
        textView = findViewById(R.id.textView);//Status area
        //set onClick listener to button with toggle the states of bulb
        mainSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggle();
            }
        });
    }


    public void toggle() {

        String url; //url

        //switch the bulb according to current state.
        if (curState.equals(STATES[0])) {
            url = urlEdit.getText().toString().trim() + STATES[1];
            curState = STATES[1];
        } else if (curState.equals(STATES[1])) {
            url = urlEdit.getText().toString().trim() + STATES[0];
            curState = STATES[0];
        } else {
            url = urlEdit.getText().toString().trim() + STATES[0];
            curState = STATES[0];
        }
        //Request a queue to send HTTP request
        RequestQueue queue = Volley.newRequestQueue(this);

        //Handle the request
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        textView.setText(curState+response);
                    }
                },new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                try {
                    textView.setText("Error: " + error.networkResponse.statusCode);
                }
                catch (Exception e)
                {
                    textView.setText("Check Address ");
                }

            }
        });

        //add the request to queue.
        queue.add(stringRequest);
    }


}

If you have any questions ask in comments. ūüôā

Good luck

 

2 thoughts on “Control Home Light With Android and Web

Leave a Reply

Your email address will not be published. Required fields are marked *