Toggling a Relais over WIFI with any Android phone

Posted on Posted in Arduino

 

Pretty much the same procedure as in the first tutorial. Toggling the output pin over a specific port with the esp8266 on a static ip adress. The Android phone simply opens the web page and the pin either toggles on or off. As the esp8266 just gives us a maximum as 3.3V on an output pin, we’re forced to add a transistor which is not a big deal though. In this example I used a simple lamp to be switched on/off, but you can replace it with anything with a maximum of 250Volts and 10A current (like a coffee machine/garage doors etc.)

 

Parts needed:

Wemos D1 Mini: www.ebay.de/WeMos-D1-mini  6€

Arduino Relais: www.ebay.de/Relais-Relay-Modul-Optocouple-5V 3€

Any Transistor like bc547 & two 220 ohm resistors ~1-2€

sum: 10€

 

 

Arduino source code:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>


// ******* NETWORK and HARDWARE settings, please change! *******
const char* ssid     = "*******************"; // SSID existing WIFI's
const char* password = "*****************"; // Password existing WIFI's
int outPinWeb = 12;    // the number of the output pin for WEB call
// ******* NETWORK and HARDWARE settings, please change! *******

IPAddress gateway(192, 168, 178, 1); // IP-Adress WIFI-Gateway
IPAddress subnet(255, 255, 255, 0); // Subnetmask
IPAddress ip(192, 168, 178, 45); // static ip adress for WEMOS

ESP8266WebServer server(80); // Webserver initalising on Port 80
float hBefore = 0.0;
float tBefore = 0.0;
int previous = LOW;
int previousWeb = LOW;
long times = 0;
long debounce = 200;

void setup() {
  
  pinMode(inPin, INPUT);
  pinMode(outPinLocal, OUTPUT);
  pinMode(outPinWeb, OUTPUT);

  // Open serial monitor
  Serial.begin(115200);

  // Establish WIFI-Connection
  WiFi.config(ip, gateway, subnet);
  WiFi.begin(ssid, password);
  Serial.print("Establishing connection");
  // Wait for connection..
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" successfull!");
  Serial.println("");
  Serial.print("Connected with: ");
  Serial.println(ssid);
  Serial.print("Signal strength: ");
  int rssi = WiFi.RSSI();
  Serial.print(rssi);
  Serial.println(" dBm");
  Serial.print("IP-Adress: ");
  Serial.println(WiFi.localIP());
  Serial.println("");
  server.send(300, "text/plain", "Connection established");

  // Handle http requests
  server.on("/relais_on", relais_on);
  server.on("/relais_off", relais_off);

  // HTTP-Server start
  server.begin();
}
void loop() {
  server.handleClient(); // wait for http requests
}
void relais_on() {
  if (previousWeb == LOW)
  {
    String temp = timestamp();
    digitalWrite(outPinWeb, HIGH);
    digitalWrite(outPinLocal, HIGH);
    Serial.println("Relais turned on over WEB at: " + temp + " (HH:MIN:SEC)"); 
    server.send(300, "text/plain", "Relais turned on");
    lcd.clear();
    lcd.print("Relais");lcd.setCursor(0,1);lcd.print("turned on!");
    previousWeb = HIGH;
    delay(3000);
    hBefore = 0.0; tBefore = 0.0;
  }
}

void relais_off() {
  if (previousWeb == HIGH)
  {
    String temp = timestamp();
    digitalWrite(outPinWeb, LOW);
    digitalWrite(outPinLocal, LOW);
    previousWeb = LOW;
    Serial.println("Relais turned off over WEB at: " + temp + " (HH:MIN:SEC)");
    server.send(300, "text / plain", "Relais turned off");
    delay(3000);
    hBefore = 0.0; tBefore = 0.0;
   }
}

String timestamp() 
{ // Uptime as Hours:Minutes:Seconds
   char stamp[10];
   int lfdHours = millis()/3600000;
   int lfdMinutes = millis()/60000-lfdHours*60;
   int lfdSeconds = millis()/1000-lfdHours*3600-lfdMinutes*60;
   sprintf (stamp,"% 03d: % 02d: % 02d", lfdHours, lfdMinutes, lfdSeconds);
  return stamp;
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.jonas.light_toggle">
    <!-- GCM connects to Internet Services. -->
    <uses-permission android:name="android.permission.INTERNET" />

    <!-- Network State Permissions -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:label="Coffee remote"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity.java

package com.example.jonas.light_toggle;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private WebView webView;
    private Button button1;
    private Button button2;

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

        webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        WebSettings webSettings = webView.getSettings();
        webSettings.setTextSize(WebSettings.TextSize.LARGEST);

        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button2.setEnabled(false);

        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                webView.loadUrl("http://192.168.178.45/relais_on");
                reloadWebUrl("http://192.168.178.45/relais_on");
                reloadWebUrl("http://192.168.178.45/relais_on");
                reloadWebUrl("http://192.168.178.45/relais_on");
                button2.setEnabled(true);
                button1.setEnabled(false);
                if (isOnline() == true)
                    webView.setVisibility(View.VISIBLE);
                else
                    Toast.makeText(getApplicationContext(), "Connection error)", Toast.LENGTH_LONG).show();
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                webView.loadUrl("http://192.168.178.45/relais_off");
                reloadWebUrl("http://192.168.178.45/relais_off");
                reloadWebUrl("http://192.168.178.45/relais_off");
                reloadWebUrl("http://192.168.178.45/relais_off");
                button1.setEnabled(true);
                button2.setEnabled(false);
                if (isOnline() == true)
                    ;
                else
                Toast.makeText(getApplicationContext(), "Connection error)", Toast.LENGTH_LONG).show();
            }
        });

    }

    public boolean isOnline() {
        ConnectivityManager cm =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnectedOrConnecting();
    }

    public void reloadWebUrl(String URL){
        final String url=URL;
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl(url);
            }
        }, 500);
    }
}

2 thoughts on “Toggling a Relais over WIFI with any Android phone

Leave a Reply

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