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

Intro: 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

Sensors Contest 2016

Runner Up in the
Sensors Contest 2016

Share

    Recommendations

    • Fix It! Contest

      Fix It! Contest
    • Audio Contest 2018

      Audio Contest 2018
    • Furniture Contest 2018

      Furniture Contest 2018

    64 Discussions

    0
    None

    what if you plug in the wall socket in opposite direction than supposed? ("hot" goes in the place of neutral).

    Doesnt that mean that you don't have a ground going into mains device and there is a risk of electric shock?

    0
    None
    DanielH261

    1 year ago

    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

    0
    None
    rdgtech

    1 year ago

    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

    1 reply
    0
    None
    Resh87rdgtech

    Reply 1 year ago

    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!

    0
    None
    ChristianP117

    1 year ago

    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

    0
    None
    FreddieVong

    1 year ago

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

    0
    None
    yerdna

    2 years ago

    Hi Ruben,

    your eshop doesnt works now. Could you check it?

    1 reply
    0
    None
    Ruben Marc Speybrouckyerdna

    Reply 2 years ago

    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 :)

    0
    None
    jhunmar100

    2 years ago

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

    1 reply
    0
    None
    magicjimmy

    2 years ago

    finaly understand it,thanks.

    my gpio's from aliexpess are differend .

    Is this d1 r2 or retired?

    0
    None
    Khaled0kk

    2 years ago

    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
    2 replies

    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

    0
    None
    knightnet

    2 years ago

    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.

    1 reply
    0
    None

    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 ;)

    0
    None
    TorbjørnF1

    2 years ago

    This is awesome, thank you so much!

    0
    None
    AmazingEli

    2 years ago

    Jeez this is good! Love it

    0
    None
    IngridF8

    2 years ago

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

    1 reply
    0
    None

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