Introduction: Control ANY Light or Electrical Appliance With You Tablet or Smartphone (wifi)

Control ANY light or electrical appliance with you tablet or smartphone (wifi) using arduino, blynk and a wemos / ESP8266 board

In this tutorial we will be making something I call a wifi controlled ac switch. (But it also works for DC applications that are powered by a wall outlet) Basically we will make a small box that can control any ac electric current in your home, based on commands from your tablet or smartphone. On top of that it can be programmed to react to input from any kind of sensor. Tailored to your needs and limited only by your imagination. The total cost of the project is between €5 and €25 depending on what you have lying around at home.

Check out the video real quick and you will get the idea. (I apologise for filming with a potato). This is what you will make in very little time if you follow this instructable.

Why make this?

I had a problem. I have had it for a while. My beautiful girlfriend and now soon to be wife always falls asleep with the nightlight on, often with her head on my shoulder (Pic from yesterday afternoon attached!). The nightlight is on her side, as she needs the nightstand for her jewellery, and whatever else women keep in there? This puts me in the painful dilemma of either lying awake or waking her. Her long curls make any ninja attempts impossible. So I came with this idea: “What if I could control the nightlight from my phone?” This instructable is the result of months of research towards exactly that end. I am going to show you the best and most cost efficient way to hack your hot girlfriend’s nightlight but also to control any other electrical appliance. You will make a remotely controllable relay, a simple but effective arduino home automation sketch and a blynk smartphone app that you can share with your hot girlfriend, any other mistresses you may have and whomever else. Important to this project is that no damage is done to the electrical appliances you wish to control and it continues to operate as before with manual control. Safety is also an important feature, and tips and pointers will be given. We don’t want to electrocute our future spouses when they touch their nightlights, now do we?

Why else would you want to make this?

- You think the Phillips hue and all other commercial alternatives are way overpriced and you want a solution you can actually tailor to your needs for a fraction of the price.

- You want to scare the **** out of someone by switching their lights ON/OFF when they are home alone, they wont be able to comprehend what’s happening

- You want to hack the lights at the office you work, so all the lights go on every time you and only you enter.

- You want to control your kettle in the morning or your toaster,

- You have an electric heater you want to program to switch ON/OFF or control with your phone,

- You want to make all the lights in your house smartphone controlled, but also want them to turn off during bright day time to be sure none stay on needlessly.

- You want to create a fireworks or rocket detonator (I have a better instructable for that, but same idea – NEVER use a mechanical relay for this though),

- You want to turn a fan ON/OFF according to temperature in the room, time of day or smartphone command.

- You are making a custom project that requires remote control of a relay and maybe also sensory input.

- You want to program the lights in your house to go switch while you are on holiday in different order, to really make it seem that you are home.

- You want to switch on your desktop computer remotely (see my next instructable)

- You want to put current on the front door handle and electrocute burglars or your drunk teenage children sneaking in through the front door passed midnight. (Maybe this is a bad example?)

- You want to make a programmable switch that reacts to temperature, heat, light, movement, sound, or any combination, but at the same time you want to be able to override it remotely through your phone or pc.

Step 1: Intro and Parts Required

The box you saw in the video is what we will be making. I call it the Mona AC wifi switch and I sell tailor made versions of it on my website www.monaselectronics.com. It plugs in like an extension cord to your electrical appliance and regulates the current that goes from the socket to the appliance through a relay that is powered by an esp8266 and programmed in arduino or lua. The unit is powered by a small internal power supply. No batteries or other funny booboos. Ready to get started, read on!

The first thing you will need to do to build your Mona AC wifi switch is recycling or shopping. Most parts you likely already have so this wont be expensive. If you have a hard time finding the parts, check out aliexpress.com. All my supplies come from there and it is dirt cheap with free postage. Avoid western sites like sparkfun and amazon if you are on a budget.

NOTE ON IOT Microcontrollers:


If you want to make an IOT or arduino project that is connected to the internet over wifi, you need a board that can connect to wifi. It's that simple. The arduino uno, nano, micro, mega... cannot connect to wifi without the addition of expensive and outdated shields. So save yourself a lot of time and money and don't do this unless you have a good reason to. I learned the hard way... ESP8266 boards are great but often do not support arduino out of the box. A lot of headache is often involved in getting these to work with arduino and their size makes them hard to work with.

Instead get a wemos D1 mini from www.wemos.cc. The wemos D1 mini is an ESP8266 on a breakoutboard, features full wifi capabilities out of the box and costs only $4,00. Thats right, four dollars for a microprocessor that connects to wifi! It features all the things you know and love about the arduiono uno like: digital pins, analog pins, vin, GND, 3,3 v output, power supply connector, 5V output and a fast and easy micro usb connector to upload your sketches. Do yourself a favor and go for a board like this if you want to start making IOT projects in small quantities.

Parts:

An esp8266, I strongly recommend the wemos d1 mini, or mc lua boards WITH micro usb port.

One 5v / 10a relay, I recommend the ones with screw terminals often labelled “arduino relay”.

One AC to 5V DC power converter (these are in any and all phone, tablet and usb chargers).

One electronics box or any other NON-CONDUCTIVE box or case you may have.
I like the black ones from aliexpress because they are cheap and a perfect fit.

One AC 250v, 1a power switch – any type will do. (Find these in pretty much any old radio or toy).

One DC 5v pushbutton - any type will do. (Find these in pretty much any old radio or toy or arduino starter kits)

One line of screw terminals (min 10 amps is recommended here)

One micro usb cable for destroying (It can be damaged on the usb side, and does not need to be a data cable – we only need the micro usb plug side)

One micro usb cable for programming

Some cable / wire that can withstand 10A – I recycled mine from an old pc power supply cable.

Optional:

LEDS (I added one led in series with the push button because it makes testing way easier, I also added a bright blue led that can be programmed and switched on separately to find the bathroom at night)

One circuit breaker or fuse ( I did not put one in this project) most likely though, your home has these already on the wall outlet)

Epoxy or hot glue for potting your electronics (recommended for durability)

Whatever sensors you wish to add (I did not add any for this project but I did add an additional pushbutton that can be programmed to do anything (send email, switch power ON for just a short time, crash the device, flash all Lights and leds in SOS pattern, etc.)

Male and female wall plug (like you would find on the two ends of an extension cord)

Disclaimer:
I am not associated with any of the products or services mentioned in this instructable. AC current is dangerous (Like seriously, DO NOT underestimate it). This guide prides itself on being noob friendly and will allow anyone to make an ac wifi switch and enter inexpensive home automation. It is for you to decide if you should. That being said, if you are confident that you can handle this project and you know that touching both ends of a powered line is gonna be aauwieeee, keep reading!

Step 2: Assembly

The first thing you want to do is make sure everything fits in your box / case you choose to use and the lid still closes. Sounds obvious, but I have often overlooked this step. Next, you want to drill holes in your box were the screw terminals of both the relay and normal screw terminals will come. On one side you will have two screw terminals for your hot and neutral wire coming from the wall. On the other side you will have your relay with the hot wire and one extra terminal for the neutral wire. (see pictures and fancy hand drawn schematics - attached is a PDF of the schematics with much higher resolution)

You also want to drill holes for the switch, leds, pushbuttons and any sensors you may have planned to use at this point. Do not wait with drilling. Drilling afterwards risks you drilling into your electronics or breaking your case when everything is already glued and mounted (again, I learned this from experience).

Now you want tostrip your first micro usb cable. This will provide you with enough colour coded wire for all the 3,3V and 5v parts of the circuit. Additionally you need the plug (male side) to power the wemos d1 mini board through its usb port. Do not cut the usb and mini usb connectors off to short; you need a bit of wire later to work with. The usb side you don’t need any more for this project but save it because you could use it as:

1) An fdi for programming small microcontrollers without usb ports

2) A power supply for usb powered projects, like an LED reading light for your laptop.

3) A data connector for your next project.

A note on relays: I strongly recommend going for a normal relay, not for an SSR. The reason being that mechanical relays are much safer. I have heard that solid state relays tend to bleed a bit of current on the outside. Additionally most arduino labelled SSR’s don’t support over 2 amps. A classic living room standing lamp will easily drain more than this. Mechanicals relays are safer and will last plenty long under normal use. Another plus is that they make a distinct “click sound” when activated. Most people find this sound very satisfying to hear, as it really makes you feel that the circuit is safely interrupted, even if you were not looking. I personally love it.

A second note on relays: Relays usually feature two configuration options. Choose “normally closed” for this project. This is important because it allows the nightlight to operate as before when your wifi is down or when you switch your mona ac wifi switch off. Normally open (contrary to what you might think) means that the circuit is interrupted by default, meaning that if your mona switch box is switched off, offline or malfunctioning, your light will NOT go on. The location varies from relay to relay so check the markings on yours.

Now it is time toglue the terminalsand the relay into place. Make sure the wire (10 amp) from the neutral terminal IN to the neutral terminal OUT is already in place before glueing. The same goes for the hot wire that goes from the terminal IN to the relay. (look at the pics if this makes little sense to you now) Also run two small 5v wires from the two IN terminals in parallel with the 10 amp ones, these will power the power converter for the wemos (or the microcontroller you choose to use).Your hot IN terminal should go to the normally closed gate of your relay. See Relay picture above

Once the terminals are in place, you need tosolder the two 5v wires from previous steps to your ac to 5v dc converter on the side clearly marked “IN”. Optimally you should also solder a switch in between one of the wires and the converter. This will allow you to switch of the power supply and thus the microprocessor. Solder the red and black cables from the male usb plug to the converter on the side marked “OUT”. (make sure to connect the red cable to + and the black to -). The green and white wires are not needed here. I also used some heat shrink wire and hot glue to strengthen and insulate. Highly recommended for safety and durability. I use a normal lighter to shrink my heat shrink (see pic).

NOTE: it is good practice to also allow a terminal from ground (the 3rd pin in your wall outlet) to go to ground. I did not do this. Additionally, a fuse or circuit breaker on one of your hot wires can really improve fire safety. I do incorporate these in the products I sell, but the first versions were kept as simple as possible and worked just fine. Most homes have a capable circuit breaker built into the wall outlet.

Now that this is done, solder 3 wires from your wemos d1 mini or other esp8622 board to your relay. The first should be from gnd to gnd, 5v to 5v and lastly D8 (Any gpio will work but this is what i used in the code) to input of your relay. This is also the time to solder any optionals to your microcontroller, I added two LED’s and two pushbuttons. I highly recommend that youat least add one push button, as this will allow you to use your Mona ac wifi switch without wifi too. You can program that button to override commands from the internet when needed or just to compliment your online commands. You can also program it to do completely different things like send an email or ring your door bell.

See schematics on how to connects LEDS and pushbuttons. In the code D5 (GPIO14) is used for the pushbutton that manually switches on the lights. D4 (GPIO2) is used for the LED That indicates actions.


You couldadd any sensor at this point too. A temperature sensor for example, could allow your switch to email you when it gets to hot in your bedroom and prompt you if you want to switch on your electric fan or not. A light sensor, that switches your lights on automatically when it gets dark. The possibilities are limitless. When you have made up your mind on sensors and optionals, glue everything in place. The hard part is now already is over!

A note on soldering: Solder both sides of your boards. Adding hot glue to strengthen the bond is always a good idea. An iron with moderate heat and a thin pencil sized tip is best for soldering on boards like the wemos. Be quick and accurate, but don't stress it. I redid severall connections and the boards did not get damaged from the heat. Just you know, dont poke the chips n stuff with your iron.

Step 3: Blynk Smartphone and Tablet App (IOS, Android)

To make our app we will be using blynk. Blynk is a simple tool that allows you to create apps on your phone and share those apps with other people.www.blynk.cc. It is a drag and drop system so no programming language is required and it takes direct control of your arduino's pins. It started as a kickstarter in 2015 but quickly grew to be a professional and highly useful tool. the best part: your app will be created in just one minute and will be fully customisable! Join the blynk forums if you need help or want to contribute.

Go to the apple store or play store on your phone or tablet and download blynk.
Make an account in the blynk app
Click the plus icon on top of the app to make a new project
Email the authorisation token (see pic 2) of the new project to yourself, you will need this in the arduino coding part of this instructable so keep that email open for the next step.
Under hardware model, select ESP8266 if you used a wemos or other esp based board.
Add two buttons to your project. PUSHBUTTONS (not switch) for GPIO0 (D3 in code) and one optionally for the second LED you may have added. (Remember I attached a bright led as a nighttime find bahtroom light)

Add the terminal widget. (Blynk has recently become a paying service for a certain amount of widgets, but you get plenty of free credit on sign up to make this app and it lasts forever). Choose v1 and set all options to "ON". (see pic 4)

Congratulations, you just made a smartphone app. You can share this app with whomever. There is plenty of other widgets to choose from that can incorporate and display sensory data from any sensors you may have added. You can also add a history graph (third pic middle block) to monitor your hot girlfriends long term nightligh activity, but in this instructable I choose to keep it simple. I do recommend adding the notification app, this one will automatically send you a notification if your device goes offline, great for testing but also many real world applications (Your girlfriend found out about your evil light controlling magic and unplugged it. NOOOOO!!!!). The email app seen in attached pic allows you to send emails to yourself and others when an event is triggered. Go to your blynk examples to see how it works and just copy paste it in the arduino sketch if you want to use it

NOTE: The pin layout of the wemos mini is different from the one on the standard ESP8266. Take this into account when working with wemos and blynk. See attached picture. Dark Green is the pin layout in Blynk, in arduino you just use the pin number marked on the board preceded by "D". Example: "digitalWrite(D1, LOW);"

Step 4: Code

Code:

Plug in the micro usb cable to your microprocessor and laptop (The cable you did not destroy -the male head you soldered serves for powering only). I programmed everything in arduino. Note that you can also program in lua and certain javascript alternatives. I personally like arduino best and find it to be easiest. Below and attached you will find the code I used with comments. If you have questions, please write them in the comments.

0) If you are new to arduino, do not be intimidated. Just download the latest version from arduino.cc and install. Then follow the steps below. You only need basic logic thinking to understand the code and no brain at all to upload my code.

I used two libraries:

1) Blynk library, find latest version on http://www.blynk.cc/getting-started/

2) elapsedMillis library, https://github.com/pfeerick/elapsedMillis

Also note that you need to install your board. If you used the wemos d1 mini like i did, navigate to http://www.wemos.cc/tutorial/get_started_in_arduino.html. select your version of the board and follow the installations steps. I recommend automatic installation through the arduino board manager (It is super fast and easy). Dont forget to select your board later on when uploading.

Without the latest version of the libraries and the correct board setting, your code will not work!

Important: the authorisation token in the code is the one you find in your phone or tablet in the blynk app and emailed to yourself in the previous step. This one is essential. Also do not forget to change the wifi password and ssid.


NOTE: The pin layout of the wemos mini is different from the one on the standard ESP8266. Take this into account when working with wemos and blynk. See attached picture. Dark Green is the pin layout in Blynk, in arduino you just use the pin number marked on the board preceded by "D". Example: "digitalWrite(D1, LOW);"


The code:

// written by Ruben Marc Speybrouck
// Check out my instructables for more great stuff: https://www.instructables.com/member/Ruben+Marc+Speybrouck/

#define BLYNK_PRINT Serial // Comment this out to disable prints and save space #include #include

WidgetTerminal terminal(V1);

// You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "60b462d1df8c465bb4d7c7f9a21856a0";//

int switchstate = 0; int switchstate2 = 0; int relaystate = 0;

//storing the variables that will read input.

#include elapsedMillis timeElapsed; unsigned int interval = 1000; // Wait one second (1000 microseconds ) between button presses to switch the light on or off again. This avoids glitches and improves stability. // after a lot of experimenting, I found one second to work best. DO NOT use delay for this as delay will also pause your wifi connection for one second, making it reset. // timeElapsed functions allow the void loop to keep running, contrary to the simple delay functioning and are therefore the only ones that should be used when working with network communications

void setup() { Serial.begin(9600); Blynk.begin(auth, "SSID", "Password"); // fill in your ssid (the name of your wifi network) and password here. Note that the quotation marks need to stay.

pinMode(D4, OUTPUT); pinMode(D2, OUTPUT); pinMode(D3, OUTPUT); pinMode(D5, OUTPUT); pinMode(D8, OUTPUT);

digitalWrite(D4, HIGH); digitalWrite(D2, HIGH); digitalWrite(D3, HIGH); digitalWrite(D5, HIGH); digitalWrite(D8, HIGH); delay(1000);

digitalWrite(D4, LOW); digitalWrite(D2, LOW); digitalWrite(D3, LOW); digitalWrite(D5, LOW); digitalWrite(D8, LOW);

//I found that switching everything on and off at boot gets rid of static electricity and other irregularities. //And added bonus of doing this is that the clicks from the relay let you know exactly when the device is connected to the internet and fully booted

delay(1000);

terminal.println(F("Blynk v" BLYNK_VERSION ": Device started")); terminal.flush(); //This will get the terminal widget of your blynk app started }

void loop() { Blynk.run();//initiate connection with the blynk server, for your phone app unsigned long currentMillis = millis();// start counting milliseconds for delays between button presses

switchstate = digitalRead(D3); switchstate2 = digitalRead(D5); //D3 is were your physical push button is, D5 is the button in my blynk app I choose.Note that gpios in the blynk app have different numbers. Serial.print(switchstate); Serial.print(" ------- "); Serial.print(switchstate2); Serial.print(" ------- "); Serial.print(" THE RELAY IS: "); Serial.println(relaystate);

// For troubleshooting I included serial print. This only works through usb from your microprocessor to your laptop with arduino's serial monitor open.

if (relaystate == LOW) { if (switchstate == HIGH || switchstate2 == HIGH) { //if the physical button or button in app is pressed if (timeElapsed > interval) // if more than one second has passed since the previous time a button was pressed, execute the code and change the relay state. { relaystate = HIGH; digitalWrite(D8, HIGH); digitalWrite(D4, HIGH); terminal.println("Bedroom light switched ON"); terminal.flush(); delay(5); timeElapsed = 0; // reset the counter to 0 so the counting starts over... } }

else { delay(5); // small delay to improve stability } }

// if the relay is on position off (low), switch it on if the blynk app button is pressed or the physical button is pressed. Change the state of the variable relaystate to on // Print to the blynk app terminal widget that the bedroom light is now on.

else if (relaystate == HIGH) { if (switchstate == HIGH || switchstate2 == HIGH) { if (timeElapsed > interval) // if more than one second has passed since the previous time a button was pressed, execute the code and change the relay state.

{

relaystate = LOW; terminal.println("Bedroom light switched OFF"); terminal.flush(); digitalWrite(D8, LOW); digitalWrite(D4, LOW); delay(5); timeElapsed = 0; } }

else { delay(5); } }

// if the relay is on position on, switch it off if the blynk app button is pressed or the physical button is pressed. Change the state of the variable relaystate to off // Print to the blynk app terminal widget that the bedroom light is now off.

}

The code is also attached in a seperate file, don't copy paste as it ruins the layout.

Step 5: Cables or Not?

To make this device non-intrusive ( I can’t damage my girlfriend’s nightlight if I wish to stay in her good graces) I also added the male and female plugs of an old extension cable to the ends of my screw terminals. This way you can control any ac or dc device in a non-intrusive way and easily change devices. If however you do not care about this, you could simply cut the cable the appliance you wish to control in half and connect the ends to your Mona AC wifi switch. The choice is yours. Note that you could also fit your Mona wifi ac switch in your wall underneath a switch plate if you choose a small enough box without cables.

Step 6: Testing

Now it is time to test your mona wifi switch. Unplug your micro usb cable and plug in the micro usb head that is connected to your 5v converter. Connect your mona ac wifi switch to your hot girlfriends nightlight on the relay side and to the wall outlet on the other side. WARNING: make sure that you only touch plastics and insulated materials in this step. Your box should be closed! If you did everything right, your sketch will boot, your wemos d1 mini will connect to your wifi, and you will hear your relay engage and see your leds flash. When you start your blynk app you should be able to switch the nightlight on and off by pressing the GPIO0 button you made. If something is off, you can still check all the connections at this point and troubleshoot. The most common reason for problems will be that the pins on your blynk app are different from the one in your sketch. Another likely problem is poor soldering or a typo in your wifi password, ssid or auth token. But most likely, all went well.

Congratulations! You big stud! You just made your own custom wifi switch and a custom app!

Step 7: Potting

A good practice when making electronics like this in a closed box is to “pot” them. Potting means submerging electronics in a fast hardening plastic or glue so that everything stays in place for decades to come. I choose to use transparent epoxy to do this. This works really well and makes your electronics waterproof and shockproof. I went for transparent epoxy because the end results can look really amazing, check out this other picture of an arduino nano alarm clock with buzzer and vibrator motor that I made and potted in an empty redbull can. It looks sick. I can however not recommend epoxy. It gave me a really sore throat and a headache even though I did everything outside, and it is really messy to work with. These days I tend to just fill my electronics boxes up with hot glue from a glue gun (I like coloured hot glue, just because it looks cooler and tidier). It is cheaper and can’t damage your health in unspeakable ways (I dare you epoxy fans to read the safety warnings that come with a bottle). After all we need to maintain a well functioning body if we are to score and hold on to our hot girlfiends! WARNING: when potting, do not submerge the usb connector, or you will not be able to reprogram in the future. (Unless you are ok with that, then glue that baby shut!). Also make sure your pushbutton and switch aren’t glued stuck.

Step 8: Adding the Sensors

It is a good idea to add at least one sensor to your mona switch. Therefore I will explain exactly how to add a photoresistor, a dht temperature and humidity sensor and a very accurate waterproof DS18b20 temperature sensor. It is very easy and inexpensive to implement these sensors. Some practical examples why this is a good idea:

1) You want the garden lights to turn of when the first sunlight hits your beautiful japanese zen garden
2) After you switched on your bathroom heater through your phone, you want it to automatically switch off once room temperature exceeds 30 degrees celcius.
3) When humidity exceeds 20 %, you want a fan to turn on.

Even if you do not plan on using a sensor now, it is still a good idea to include one because it is much harder to do so after you have glued and boxed everything.

Note About sensors:

Most sensors are available in two versions: just the sensor and a shield version that is breadboard friendly. If space or money matters, always go for the version without the shield. They are far cheaper and you can easily solder some connecting wires to the sensors contacts to make it breadboardfriendly and afterwards also make it easy to directly solder to your final product. Check out pic 5.

All the sensors I discuss operate both with 3,3V and 5V. In my experience the Wemos handles both voltages as input to its pins but it is best practice to use 3,3V and NOT 5v like I did in the schematics. This is especially true for the photoresistor.

Photoresistor:


A photoresistor will tell you how bright your environment is on a scale from 0 to 255. For most practical homeautomation applications, this is more than accurate enough. Buy your photoresistors here for about 3 cents a piece. Connect your photoresistor to 3,3v on one side and to A0 and gnd on the other with a 10 k resistor between the photoresistor and gnd. (See pic 1 and 2 - if you wanna make cool graphics like me, check out fritzing.com!) ) Notice the value of the resistor will change your readings. Without the resistor your readings will be gibrish, so dont be lazy! ;). Code wise it is as simple as doing an analog read of pin A0. Find the code below and attached.

The code:

// the setup routine runs once when you press reset:
void setup() { // initialize serial communication at 115200 bits per second:

Serial.begin(9600); }

// the loop routine runs over and over again forever:

void loop() {

// read the input on analog pin 0:

int sensorValue = analogRead(A0);

// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 3.2V):

float voltage = sensorValue * (3.2 / 1023.0);

// print out the value you read: Serial.println(voltage); }


DHT SENSOR

A DHT sensor gives you info on both humidity and temperature at the same time, while using only 1 pin. The DHT 11 (link to buy) is ok precise for only a little over a dollar. Use a DHT 22 if precision is very important (think breweries, greenhouses). Hooking it up is very easy. Connect pin 1 to 5v, pin 2 to any available digital pin and pin 4 to ground. But put a 4,7kresistor from the data line to 5v or it will not work - I had to find out the hard way.. (see pic 3 and 4). Below you will find the standard code to get both sensors running. Note that when working with network you must avoid all delays in your code. Also, in my experience the dht 11 can be unstable when reading individual temperature values. Therefore I implement code that takes the average of the last 10 readings. Here is how I do it:


temperatureDHT1 = dht.readTemperature();

temperature2 = (((temperatureDHT1 + temperatureDHT2 + temperatureDHT3 + temperatureDHT4 + temperatureDHT5 + temperatureDHT6 + temperatureDHT7 + temperatureDHT8 + temperatureDHT9 + temperatureDHT10) / 10) + temperatureDHTlast) / 2;

//take the average of the last ten temperature readings of the dht11, we do this to get a more consistent result. On average the dht is accurate but individual readings are aweful. Then calculate the average of the last 2 averages for a stable result.

temperatureDHTlast = temperature2;

Serial.println (temperature);

Serial.println(temperature2);

//MOVE ALL THE PREVIOUS TEMPERATUREREADINGS OF THE DHT11 ONE SPOT UP:

temperatureDHT10 = temperatureDHT9; temperatureDHT9 = temperatureDHT8; temperatureDHT8 = temperatureDHT7; temperatureDHT7 = temperatureDHT6; temperatureDHT6 = temperatureDHT5; temperatureDHT5 = temperatureDHT4; temperatureDHT4 = temperatureDHT3; temperatureDHT3 = temperatureDHT2; temperatureDHT2 = temperatureDHT1;

Note: Put your DHT sensor on the OUTSIDE of your project. Your electronics give of heat and will influence your results if the DHT is on the inside.

The stadnard DHT code:

Please notice that you need to download the DHT libary first. The code is also attached.


// Written by ladyada, public domain

#include "DHT.h"

#define DHTPIN D4 // what pin we're connected to

// Uncomment whatever type you're using!

#define DHTTYPE DHT11 // DHT 11

//#define DHTTYPE DHT22

// DHT 22 (AM2302)

//#define DHTTYPE DHT21 // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V

// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1

// to 3.3V instead of 5V! // Connect pin 2 of the sensor to whatever your DHTPIN is

// Connect pin 4 (on the right) of the sensor to GROUND // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor.

// Note that older versions of this library took an optional third parameter to

// tweak the timings for faster processors. This parameter is no longer needed

// as the current DHT reading algorithm adjusts itself to work on faster procs. DHT dht(DHTPIN, DHTTYPE);

void setup() { Serial.begin(9600);

Serial.println("DHTxx test!");

dht.begin();

}

void loop() {

// Wait a few seconds between measurements. delay(2000);

// Reading temperature or humidity takes about 250 milliseconds!

// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)

float h = dht.readHumidity();

// Read temperature as Celsius (the default)

float t = dht.readTemperature();

// Read temperature as Fahrenheit (isFahrenheit = true)

float f = dht.readTemperature(true);

// Check if any reads failed and exit early (to try again).


if (isnan(h) || isnan(t) || isnan(f)) {

Serial.println("Failed to read from DHT sensor!");

return;

}

// Compute heat index in Fahrenheit (the default)

float hif = dht.computeHeatIndex(f, h);

// Compute heat index in Celsius (isFahreheit = false)

float hic = dht.computeHeatIndex(t, h, false);

Serial.print("Humidity: ");

Serial.print(h);

Serial.print(" %\t");

Serial.print("Temperature: ");

Serial.print(t); Serial.print(" *C ");

Serial.print(f); Serial.print(" *F\t");

Serial.print("Heat index: ");

Serial.print(hic);

Serial.print(" *C ");

Serial.print(hif);

Serial.println(" *F");

}

DS18b20 waterproof temperature sensor


This is a very accurate sensor that you can use under water. Unlike the DHT it does not give info about humidity. It works really well both in open air and submerged.

Buy it here

In pic 7 you will find the schematic. Again, pay attention to the resistor or your sensor will not work!
You will need the dallas sensor library and the one wire library for this. The code to get this sensor to work is easily found in the dallas sensor examples "simple". See pic 8 for its location.

Step 9: Final Thoughts

If you did everything right, you now made a giant leap into IOT and open source home automation.Take a minute to comprehend how awesome that is. Never again will you be pinned down with the nightligh on. Let me be the first to congratulate you!

I hope you all enjoyed my tutorial. I plan to bring you more in the future. I read all your comments and I will answer your questions. Keep the community going!


For help on Blynk, check out their very active forum: http://community.blynk.cc/
For questions on Wemos: http://forum.wemos.cc/

This instructable entered a few competitions. Any votes, likes 'n shares are thus greatly appreciated ;)


Ruben

Comments

author
DanielH261 made it!(author)2017-07-17

Hey Ruben
Thank you for your instructions. What kind of ac-convertert (A?) are you using? I have a 1A-Converter, but think there is not enough power for the relay AND the controller. The Relay is a low-level-relay. Both LED (green&red) are on, but the pump on the relay is allways on, an if i push the button on app, nothing happens. Or could it be, there is a code-error due the cirrcumstanc its a low-level-relay?

Greets

Daniel

author
rdgtech made it!(author)2017-01-09

Hi Ruben, great project. It went together fairly easily mechanically using the hardware you suggested and the soldering was no problem. I am having a problem loading the program after it compiles. Any help would be appreciated, I have attached an image of the error codes.

esptool v0.4.9 - (c) 2014 Ch. Klippel
<ck@atelier-klippel.de>

setting
board to nodemcu

setting
baudrate from 115200 to 921600

setting
port from COM1 to COM7

setting
address from 0x00000000 to 0x00000000

espcomm_upload_file

espcomm_upload_mem

setting
serial port timeouts to 1000 ms

opening bootloader

resetting board

trying to connect

flush start

setting
serial port timeouts to 1 ms

setting
serial port timeouts to 1000 ms

flush
complete

espcomm_send_command:
sending command header

espcomm_send_command:
sending command payload

read 0,
requested 1

trying to connect

flush start

setting
serial port timeouts to 1 ms

setting
serial port timeouts to 1000 ms

flush
complete

espcomm_send_command:
sending command header

espcomm_send_command:
sending command payload

read 0,
requested 1

trying to connect

flush start

setting
serial port timeouts to 1 ms

setting
serial port timeouts to 1000 ms

flush
complete

espcomm_send_command:
sending command header

espcomm_send_command:
sending command payload

read 0,
requested 1

resetting board

trying to connect

flush start

setting
serial port timeouts to 1 ms

setting
serial port timeouts to 1000 ms

flush
complete

espcomm_send_command:
sending command header

espcomm_send_command:
sending command payload

read 0,
requested 1

trying to connect

flush start

setting
serial port timeouts to 1 ms

setting
serial port timeouts to 1000 ms

flush
complete

espcomm_send_command:
sending command header

espcomm_send_command:
sending command payload

read 0,
requested 1

trying to connect

flush start

setting
serial port timeouts to 1 ms

setting
serial port timeouts to 1000 ms

flush
complete

espcomm_send_command:
sending command header

espcomm_send_command:
sending command payload

read 0,
requested 1

resetting board

trying to connect

flush start

setting
serial port timeouts to 1 ms

setting
serial port timeouts to 1000 ms

flush
complete

espcomm_send_command:
sending command header

espcomm_send_command:
sending command payload

read 0,
requested 1

trying to connect

flush start

setting
serial port timeouts to 1 ms

setting
serial port timeouts to 1000 ms

flush
complete

espcomm_send_command:
sending command header

espcomm_send_command:
sending command payload

read 0,
requested 1

trying to connect

flush start

setting
serial port timeouts to 1 ms

setting
serial port timeouts to 1000 ms

flush
complete

espcomm_send_command:
sending command header

espcomm_send_command:
sending command payload

read 0,
requested 1

warning: espcomm_sync failed

error: espcomm_open failed

error: espcomm_upload_mem failed

error: espcomm_upload_mem failed

Thanks,

Richard

author
Resh87 made it!(author)2017-05-16

Hi, I had the same problem as you, the same error, and my fix was I connected d3 to ground, and didn't use d8, instead used d6 and everything worked!

author
ChristianP117 made it!(author)2016-12-12

Hi Ruben and first of all thanks for a great instructable!

I have a question tough, should it be possible to switch the relay using the 3.3v pins like D8 in your example? I cant get it to work with my Wemos D1 mini and the relay you linked to on Aliexpress?

Regards, Christian

author
FreddieVong made it!(author)2016-10-08

Ruben, do you know what the fastest way to call the ESP2688 module is?
TCP, UDP or using website POST/GET to transfer?

author
yerdna made it!(author)2016-08-03

Hi Ruben,

your eshop doesnt works now. Could you check it?

author
Ruben+Marc+Speybrouck made it!(author)2016-08-13

Hi Yerdna,

Due to getting a new job abroad, I had to abandon that project.

Thank you for noting that I still need to remove the link and thank you for reading my instructables :)

author
jhunmar100 made it!(author)2016-07-15

What software did you use to make an App? Can you share it to us please?

author
Ruben+Marc+Speybrouck made it!(author)2016-07-16

Blynk, it s described in detail in this instructble

author
magicjimmy made it!(author)2016-07-04

finaly understand it,thanks.

my gpio's from aliexpess are differend .

Is this d1 r2 or retired?

author
Khaled0kk+ made it!(author)2016-06-29

hi Ruben

I have a problem with the code when I do verify this message come to me

Arduino: 1.6.10 Hourly Build 2016/05/31 11:33 (Windows 10), Board: "WeMos D1 R2 & mini, 80 MHz, 921600, 4M (3M SPIFFS)"

C:\Users\Hp\Desktop\monawifiswitch\monawifiswitch.ino:6:32: fatal error: BlynkSimpleEsp8266.h: No such file or directory

#include <BlynkSimpleEsp8266.h>

^

compilation terminated.

exit status 1

Error compiling for board WeMos D1 R2 & mini.

This report would have more information with

"Show verbose output during compilation"

option enabled in File -> Preferences.

1.png
author
Ruben+Marc+Speybrouck made it!(author)2016-06-30

Hey there,

Did you install the librairies?
(Blynk and wemos)

Did you install the wemos board like it says on the site www.wemos.cc?

Also did you select the right board in your board settings?
There is two versions of the wemos d1 and mini, an old and new.

Please double check above and let me know if yo ustill have trouble

author
Khaled0kk+ made it!(author)2016-06-30

Thanks...I had a problem with the libraries

now is everything good the project is awesome

author
knightnet made it!(author)2016-05-31

Love this, well explained, you've got a vote from me!

Couple of things though. Firstly, I'd definitely put a mains fuse in that lot! If anything ever did go wrong with the wiring, you'd be looking at a nice electric fire next to the wall - Ouch!

Secondly, don't the electronics get a bit too hot if you enclose them all in in glue? I like the idea but I worry about them overheating.

Finally, I'd like to recommend looking at Node-Red as a home automation controller. You can run it off a Raspberry Pi and it is largely visual drag/drop "programming" so easy for beginners to get into. With it, you could not only build a web UI for the controls but also run lights or anything else on schedules. I've a mixture of commercial wireless remotes controlled this way and I can use both the commercial remote controls that come with the lights and my mobile or any other device that will display a web page to manually override the schedules.

Great stuff though, well done.

author
Ruben+Marc+Speybrouck made it!(author)2016-06-08

Hey knightnet,

Thank you for your feedback and vote!

Putting a fuse in is always a good idea. For lamps i dont feel it is that essential because your home s fuesbox would save the day if somethimg were to fail. High amp applications however, it really is a must and in my new projects i now use fuses or circuit breakers.

with epoxy the heat problem is relatively small i can say from personal experience. i worried too but found other people online that tested this thoroughly. with hot glue it helps to leave just the top of your parts unglued. That way everything is properly stuck and all connections r safe from vibration and wear.

raspberry pi is on my wishlist. thx for the tip ;)

author
Torbj%C3%B8rnF1 made it!(author)2016-06-06

This is awesome, thank you so much!

author
AmazingEli made it!(author)2016-06-06

Jeez this is good! Love it

author
IngridF8 made it!(author)2016-06-06

Well written and I hope you win, love <3 (the gf)

author
Ruben+Marc+Speybrouck made it!(author)2016-06-06

Thank you love!
I cant wait to see if I get any funzies to further terrorise you (and document it on instructables)

author
Aneriah made it!(author)2016-05-18

Hey man awesome idea. But how much does the project cost in total? Also I am an apple iphone user, will that be a problem?

author
Ruben+Marc+Speybrouck made it!(author)2016-05-18

Hey,

Thanks for the positive feedback!

The app is compatible with both apple and android products so no worries there.
What you will need for sure:

Wemos d1 mini 4 USD
Relay: 1 USD

Other things you can most likely recycle:

Case, anything non conductive will do
Power converter, commonly found in phone chargers
Power cords, an old extension cord is perfect

Cheap optional parts:

LEDS, buttons, USB port, sensors

So to answer your question, you should really be able to make this between 5 USD if you can recycle everything i mentioned and 20 USD if you use fancy new parts and slam in a sensor and some extra shiny buttons and LEDS.

Hope this answers your question, dont forget to vote if you havent allready ;)

author
NoseyNick made it!(author)2016-06-03

Hi Ruben, not sure if you can answer this yet or not - is this device also compatible with hot wives, or only hot girlfriends? ;-)

author
Ruben+Marc+Speybrouck made it!(author)2016-06-05

If hot wife compatability were to fail, try adding red wine and voting for this instructable ;)

author
Aneriah made it!(author)2016-05-18

What is the total cost? In US dollars?

author
Ruben+Marc+Speybrouck made it!(author)2016-05-18

As I tried to explain you above, it depends on what you add and need and allready have. How many you make and where you order also matters. So between 5 USD and 20 USD

author
Aneriah made it!(author)2016-05-18

Im sorry but I dont understand what 20 USD stands for? Thanks for your help.

author
Ruben+Marc+Speybrouck made it!(author)2016-05-18

20 united states dollars

author
rgratland made it!(author)2016-05-17

Ruben,

I saw your post on the light switch remote build on instructables. I'm a hobbiest woodworker and often need a similar idea with my power tools. The difference is I need a plug that will power my vacuum system when I start a power tool. An example is I need the vacuum system to turn on when the table saw starts. Even better for the high load for it to start a second or two after it starts and stops a second or two after I turn it off to clear all the sawdust. They sell commercial versions of this but they are very expensive. Do you see an option with your designs to achieve this? Keep in mind the actual plug/relay would need to carry 20+AMPS. Check out this link. http://www.woodcraft.com/Product/149950/iVac-Automated-Vacuum-Switch.aspx?gclid=CjwKEAjwguu5BRDq8uSKhaKIzDkSJACQ7WJlg86zM2U0HK5Jq9L4lz867Ht2tYHMbrWXHDDwhBh4PxoC_w7w_wcB

I have multiple vacuums for different tasks otherwise I could just connect multiple into this one unit. I'd love to know if you have a slick idea for this on the cheap! Thanks for the help and post! If I can DIY this successfully then I will definetly try it! Just need a little mentoring for such a device.

Get Outlook for iOS

author
Ruben+Marc+Speybrouck made it!(author)2016-05-18

Hey rgratland,

I can definitly imagine that my design would work for this application.

All it would take is some bigger relays, a bigger case and 20 to 30 amp rated wire and terminal connectors.

I have to warn you that 30 amp rated relays sell at about 4 - 5 dollars a piece whereas 10 amp relays sell for 90 cents.
30 amp circuit breakers and terminal screws are also significantly more expensive as is a larger more solid case. 30 amp power sockets also cost more.


You can beat the price of 41,00 dollars total cost. But frankly I would not recommend it if you want exactly the same product as you linked me.
The amount of money you will save wil be very small and it will take you a lot of time.

If you want a custom product however, higher amp rating, more plugs, other sensors or features etc. It is quickly worth doing it yourself.
I also make and sell custom version on my own site: www.monaselectronics.com, so I could help if you gave me more details so I could determine if I can actually save you money or not.

Hope this helps you make an educated decision ;)

author
ssj152 made it!(author)2016-05-17

Nice!

author
Ruben+Marc+Speybrouck made it!(author)2016-05-17

Thank you!

author
BillMil made it!(author)2016-05-17

John MacF posted about controlling a fan/light. Really like that idea because the fan is a "tense" spot in my marriage. She doesn't like the fan on and there are times when I need it on. The silly chain is too short and I have to use tongs to turn it off. Yes, I could get a longer chain but that's no fun. Controlling it from my phone would make me feel uber-geeky.

author
Ruben+Marc+Speybrouck made it!(author)2016-05-17

It is my nightlight problem in a different outfit, It is for people like you I wrote this tutorial. Making marriages better thorugh home automation! Make that fan smartphone controllable and never ever touch that silly chain again, send it back to the past were it belongs ;)

author
John+T+MacF+Mood made it!(author)2016-05-17

Very nicley done!

I'm interested in a SMALL receiver for my ceiling fan so I can turn off and on the light only, and wire into the light circuit only. Any ideas on sourses for the small ones. I don't want to ruin the look of the fan, but could put the reciever above the motor, but below the metal fixture that conceals the mount to the cieling. Putting it inside the mount fixture creates a Faraday cage, and that won't work. Perhaps a smallish wire antenna priotuding from the housing.... Any ideas?

author
Ruben+Marc+Speybrouck made it!(author)2016-05-17

Hey John,

Thank you for the positive feedback, it is much appreciated.
What I would do if I were you is make the box just the way I did it and mount it on the ceiling next to your fan. It s light so that should be easy enough.WIth a bit of patience you can probably make all the wires go tidely from your fan ceiling mount straight into the box.

A second and even better option would be to hack your wall switch. I assume you have a wall switch for your ceiling fan? It is very likely that if you screw the bracket of your wall switch that you have plenty of space there to hide all the components inside the wall or even the entire box (10x16 xm). (But switch of the main fuse while doing this)

Making it smaller is very hard, the power supply and relay can not be shrunken down a lot, even in mass produced products like phone chargers they are this size. The wemos d1 mini I used is currently also as small as it gets. Any tutorial I have seen so far telling that you can do AC IOT smaller than I did is unfortunately compromising something crucial like the power supply. Good luck, let me know if you have more questions, and please vote if you havent ;)

author
woorails made it!(author)2016-05-17

This is quite interesting. I definitely see a great idea for me as I want to be able to control the switch that controls my ponds pumps. The AC outlet controlled from anywhere would be a great advantage.

image.jpeg
author
Ruben+Marc+Speybrouck made it!(author)2016-05-17

You have a nice pond ;)
A mona box would do the trick. You could easily program it to be on at certain times and off at others. Maybe even depending on the weather/amount of sun light. Stay tuned for more, vote for me, and please share if you get that pump internet controlled, it would be cool to see ;)

author
Umbra55 made it!(author)2016-05-12

Great
instructable! I finally found what I was looking for: IOT for Dummies. (and I
loved the hand drawn schematics!)

I see that
the Wemos D1 mini has 8 digital outputs. Would it be possible to use a 6 or 8
way relay in order to switch on and off 6 or 8 series of lights individually (I’d
like to install several light circuits in my garden and control them
individually).

If yes, would
a standard 1A USB power supply still be sufficient?

To make it
even more complex, but truly amazing, I would like 1 of those circuits to switch
on when it gets dark and switch off at a user determined time (ideally potentially
different for each day of the week). Even better, I’d like a possibility to
switch on any of these circuits during 1 hour and then switch off without my
intervention.

Is all this
possible and would it require a major change in setup and code?

Thanks
again for the great instructable – I voted for you with both hands.

author
Ruben+Marc+Speybrouck made it!(author)2016-05-12

Hey Umbra55,

Thank you for your kind feedback and thank you for voting!
I want you to know I truely appreciate it.

Now to answer your questions as good as possible:

1) The wemos actually has 10 pins you could use if you count D0 and A1 too
2) Connecting severall relays to one wemos is totally possible. an 8 channel relay would work just fine and is much cheaper than making 8 Mona switch boxes,obviously.
3) An 8 channel relay drains up to 600 ma I believe, the wemos a bit over 200ma depending on use. So 1A should most likely be fine (best to test the drain of all your components first). But note that you def WONT get away with the cheaper 700 ma power supplies.
4) You would have to run two paralel circuit from the power supply to the relays and to the wemos seperately. DO NOT CONNECT the relays to the wemos 5v pin, the drain is to high for it to survive in the long run,
5) A photoresistor on A1 will allowe you to measure light and define what "dark" is in the code by doing a simple analog read.
6) To keep track of time, you need a Real Time Clock, The arduino/ESP8266 can not keep track of time accurately in the long run. You can use a physical chip one with a little battery or fetch info about time online.
7) The code you require to make all of this work is not per se a lot more complex, but will be a lot more elaborate then my example. You would make the same blynk app with 8 buttons like in the tutorial and you would include the same librairies. The basic idea stays the same but you would have to add code for 8 virtual blynk pins, the light sensor, time reading and setting, what has priority (smartphone app, light level or time)? etc,

Your project sounds really awesome and it is definitly doable with mostly the knowledge you acquired through my instructable, but some extra efforts will have to be made ;)

Luck would have it that a customer just ordered some light controlled wifi switches from my site www.monaselectronics.com so I will probably document the code and assembly of that project in a week or two. Stay tuned ;)

author
Ruben+Marc+Speybrouck made it!(author)2016-05-12

Also, you would want to include a proper fuse and prob a waterproof case for this kind of power, especially outside. Dont forget about safety ;)

author
Umbra55 made it!(author)2016-05-15

Thank you
for your clear and detailed answer. I’m glad you like my project. Don’t be
afraid to copy it :). Not only does this IOT solution provide
more possibilities, but it should actually be cheaper than a set of standard
light switches. I would even use less cabling (e.g. I want to be able to switch
on the lights in my garden shed and switch them off when back in the house or
the reverse). Using traditional switches, this would require 3 wires to the garden
shed, whereas with your solution, I only need 2 wires (provided that I have
Internet access in my garden, which is the case). I’m still scared about the
software though, especially the clock and light sensor. I think I’m going
to start the easy way. Basically your project but with a 6 or 8 way relay and
add more features gradually. Would your software work without any modification,
if the only thing I change is a 6-8 way relay instead of yours (and obviously put
the first light circuit on the relay connected to D8)?

author
Ruben+Marc+Speybrouck made it!(author)2016-05-17

Hey Umbra,

I sent you a pm, did you get it?


You are absolutely right about this being both cheaper and more efficient than standard switches.

Regarding software: the majority of my sketch is written to support a physical button as well as an app. If you are ok with only an app the sketch is really easy.

Just go to your arduino ide>file>examples>blynk and pick esp standalone (seee attached pic). Add your blynk token to this sketch, ssid and wifi pass and you are done ;)

Then just make a blynk app with 8 SWITCH buttons (not push) corresponding to the 8 pins you used. No further code required, the blynk library will handle everything for you. So just go for it ;)

I will post a tutorial on the light sensor by Thursday this week most likely

Naamloos.png
author
Orion96 made it!(author)2016-05-11

Great work, I've always loved the idea of a site like this one. It inspires others to build and/or get into such a creative hobby. Thanks for uploading and inspiring, I will definitely use this as a good guide.

Good luck with future Instructables

author
Ruben+Marc+Speybrouck made it!(author)2016-05-11

Hey Orion,

Thank you for your kind words. I am happy you found inspiration in my instructable the same I have found inspiration in many others! It motivates me to write more. Share your results and any questions you have during the building process, I d be happy to help.

I will def write more instructables :)

author
sikenotmine made it!(author)2016-05-11

Nice stuff! I have always been interested in home-automation, or IoT in general with JS (big follower of NodeBots also). This guide was perfect for me to get started, well written: humorous and informative to keep interest. Also, well written for people without technical background, I thought Arduino/Raspberry where the only things out there. I'm gattering/buying the pieces right now, wish me luck!

author
Ruben+Marc+Speybrouck made it!(author)2016-05-11

Best of luck buddy! Post the results? Dont forget to vote, it only takes two clicks ;)

author
WisterDeisgns made it!(author)2016-05-09

Your project doesn't look like in the picture lol. Do you know where can I get a red wire like this in Ali express?

author
Ruben+Marc+Speybrouck made it!(author)2016-05-09

My local electronics store caries these in black, they are really cheap and quite common: http://www.aliexpress.com/store/product/10pcs-10A-...

As you see in my pics I used the female one for my project. With these you can just buy or recycle any cable you want like i did. Hope this helps and thanks again for following ;)

author
WisterDeisgns made it!(author)2016-05-09

Huge thanks for double replay and support, It's gorgeous to see people like you that always try to support others. I see huge amount of potential in your projects and works. I'll try to find a red wire with this male and female connectors on Aliexpress and I hope that I'll make some pcs of this project. Respect you, Thanks for help <3

author
Ruben+Marc+Speybrouck made it!(author)2016-05-09

Thank you so much for your kind words, its people like you that make this hobby fun :)