Stairs.  Entry group.  Materials.  Doors.  Locks.  Design

Stairs. Entry group. Materials. Doors. Locks. Design

» The device, principle of operation and connection of the Wi-Fi switch. Smart WiFi Light Switch PCB Making

The device, principle of operation and connection of the Wi-Fi switch. Smart WiFi Light Switch PCB Making

Hello, dear readers and guests of the Electrician's Notes website.

In my previous publications, I introduced you to touchscreens, controlled both manually and from the control panel.

But today I would like to draw your attention to the Sonoff relay (switch) of the Basic version with the ability to control directly from a mobile phone via a Wi-Fi network or the Internet.

The Sonoff Basic relay is a small device (88x38x23 mm), which can be easily placed behind the ceiling space, in a building niche, or in the bowl of a chandelier or lamp.

Its cost at the time of publication of the article is slightly less than 300 rubles. As you understand, this is quite reasonable money, and for such a modern device. I purchased it on the well-known AliExpress trading platform (the link will be at the end of the article).

The kit included two protective covers with mounting screws, but, unfortunately, there were no instructions.

The Sonoff relay has the following technical characteristics, some of which are displayed directly on its body:

  • maximum controlled load current 10 (A)
  • supply voltage from 90 (V) to 250 (V)
  • wireless standard 802.11 b/g/n
  • security protocol WPA-PSK/WPA2-PSK
  • operating temperature from 0°С to 40°С
  • weight about 50 g

Sonoff Basic relay capabilities:

  • load management via Wi-Fi
  • Internet load management
  • load control according to a given timer, both with direct and countdown
  • load management from multiple mobile phones

These are the capabilities of the Sonoff relay. It can be safely used in smart home systems and for other various needs and requirements.

First, I will tell you how to connect Sonoff, and then we will check all its declared control methods in practice.

So, let's go.

Installation and connection of Sonoff relay

For the Sonoff relay to operate, it needs a supply voltage of 220 (V), which means it can be installed without any problems in a place convenient for you, for example, in the bowl of a chandelier or directly under a suspended ceiling, as well as directly in the junction box if there is enough space there.

To attach the relay to the surface, it has two mounting holes.

The connection diagram for the Sonoff relay is very simple.

The phase and zero of the 220 (V) supply voltage are connected to the terminals (L) and (N) on the (Input) side, respectively. Naturally, when connecting, do not forget about .

Please note that the connected conductors must have a cross-section of no more than 1.5 sq. mm. But I still tried to connect wires with a cross-section of 2.5 sq. mm. As a result, a rigid (single-wire) wire can still be connected without problems, but a flexible (multi-wire) wire can be inserted into the terminal with great difficulty, so it even had to be slightly flattened and deformed.

For example, I used a power cable of the PVA brand, which just has a cross-section of 2.5 sq. mm. At the other end of the cable there is a plug, which I will later connect to any socket with a voltage of 220 (V).

The load phase and zero are connected to terminals (L) and (N) on the (Output) side, respectively.

To make it easier to connect the load, I connected a socket to the relay output.

By the way, terminal covers not only have a protective function, but also act as clamps for power wires or cables.

This is how everything turns out beautifully and neatly. Sonoff relay connected.

As a load, I connected an LED lamp, described in one of my articles.

Here is a simple example of a Sonoff relay wiring diagram for a group of lamps.

By the way, it is not necessary to use only a lamp or a group of lamps as a load. You can safely connect any other load to the output terminals, not exceeding the rated current of 10 (A). And if you still need to control a load with a current value above 10 (A), then you can connect it to a contactor, and use a relay to control the coil of this contactor.

In this regard, we can add that when using a contactor, you can control at least a single-phase load, at least three-phase, at least alternating current, even direct current.

It will look something like this.

Thus, the scope of application of Sonoff relays is very wide and varied. It can control at least one light bulb, a powerful single-phase electric heater, a three-phase electric motor, etc. It all depends on your needs and requirements.

Now let’s look at all the possibilities for controlling the Sonoff relay in more detail.

I will not open the relay and look at its structure; there is already plenty of information on this matter on the Internet - look at the relevant resources on electronics. And judging by the reviews, the performance of the relay is quite decent. By the way, for those interested in knowing, the relay is assembled on the basis of the famous Chinese microcontroller ESP8266.

Load management via phone via Wi-Fi network

Before I talk about controlling the relay via Wi-Fi, I will say that it can also be controlled manually. To do this, there is a small recessed black button on its body. So, when you press it briefly, the relay turns on, and when you press it again, it turns off. Moreover, for this it is not necessary that the relay be connected to a Wi-Fi network - control will also be carried out in Offline mode.

But besides this, the button also contains other functionality, which I will discuss below.

To implement the ability to manage load via Wi-Fi and the Internet, you need to install the eWeLink mobile application on your phone. This application can be found for both Android and iOS devices. To make it easier to find the application, you can use the necessary QR codes on the packaging.

For Android devices, the eWeLink application can be downloaded for free from Google Play and installed on your phone without any problems. The program interface supports Russian.

For iOS devices, this application is available in the App Store. I have not tried to download and install this application on an iPhone or iPad, so if you have tried this application on iOS devices, please post your results in the comments.

After installing the eWeLink application, you will need to immediately register by indicating your country and your email address. In this case, the phone must be connected to the Internet.

After this, a verification code will be sent to your email (valid for 30 minutes), which must be entered in the appropriate “Email code” line. On the same page you must enter a password to log into your future account (at least 8 characters).

By the way, letters reach the mail services Mail.ru and Mail.yandex.ru (Yandex mail) without problems. But as far as I know, letters with a verification code do not always reach the Gmail.ru mail service (Google Mail), so please take this into account.

Then you need to pair the relay and router by long-pressing (for 5 seconds) the same button on the switch body, after which the green LED on the relay will blink. Check the box for the first connection mode and click “Next”.

Now you need to select our Wi-Fi network from the list and enter its password. To avoid having to enter a password every time, you can check the “Remember password” checkbox. Click “Next”, after which the search for our device and its registration will begin (it took me no more than 2-3 minutes).

After successful pairing, the relay automatically transmits data to the Chinese cloud (Amazon AWS or Coolkit), which makes it possible to control it via the Internet. But I will return to this a little later.

As you can see, our relay is now displayed in the list of all devices (for now it is the only one in the list, but others will appear in the very near future).

When the relay is online, the green LED on its body is always lit. As soon as the LED starts blinking, it means the connection with the router or the Internet is lost. It is precisely by this indicator that it is convenient to determine whether the relay is online (Online) or not (Offline).

While I was testing this device, I did not notice any problems with network loss. The device is always online and responds stably to control commands.

Now you can try to turn on the relay via your phone. To do this, click on “Relay 1”. A red message immediately appeared indicating that it is necessary to update the eWeLink application, although the update is not displayed on Google Play.

We go to the device settings (three dots in the right corner) and see that the application has the current version 1.5.2, and a newer version 1.5.5 is available. Click on the “Download” icon and the application update begins. After the update, the red inscription disappears, and in the settings we can see the new current version 1.5.5.

Remember!!! The main condition for the relay to work is the availability of Internet access.

If Internet access suddenly disappears, the green LED on the relay body will start blinking, and the application will display Offline mode on its tab, i.e. not available for management.

So, to turn on our “Relay 1”, you need to enter it and click on the round virtual button in the center of the screen. Moreover, you can control the relay from the general list of all devices by clicking on the corresponding small button (on the left). In general, whatever you like.

When the relay is in the off position, the button is white with a gray background around it. When the relay is turned on, the button changes its color to green, and the background around it becomes blue.

In addition to the banal principles of control, you can set the time for turning the relay on or off using a timer by setting the appropriate date and time for its control.

What was surprising was that the relay operates according to a given timer even when it is offline, which means that all specified timer programs are stored directly in the relay’s memory.

Click on the “Add timer” button and go to the timers settings page. Each timer is configured to either turn the relay on or turn it off. There are two options for setting the timer:

  • one-time (one-time triggering on a given date and time)
  • repeated (periodic triggering on a given date and time, including indicating specific days of the week)

In addition to the countdown timer, there is a countdown timer. Very necessary functionality for certain purposes. It is configured similarly to a direct timer, only with the possibility of a single operation.

In addition to the forward and reverse timers, there is a cyclic timer in the “Settings” tab (three dots in the right corner).

In this tab you can configure various options for relay operation cycles. I won’t talk about this in detail, because... Everything here is simple and intuitive.

The total number of configured timers, including the cyclic timer, can be no more than 8. And be careful, because when different timers overlap each other, none of them may work!!!

Also in the settings you can specify in what position the relay will remain if the 220 (V) power supply is suddenly turned off. There are three options here. By checking the appropriate boxes, you can choose that when the 220 (V) power supply reappears, the relay can either turn on, turn off, or remain in its original state.

By the way, this is a very convenient feature. Just remember about the nuance that, when the 220 (V) power disappears and reappears, for some reason it always turns on, even when it is in the initial state off. Imagine that you are not at home, the voltage in the network “blinked” a little and the controller independently turned on the chandelier. Such an incident will not happen here, because... in this case, everything can be customized to suit your needs.

In addition to the above, all your connected devices in the eWeLink application can be grouped together and combined in various scenarios.

Is it possible to control the relay from several phones at once?

Can! Naturally, in this case, you need to install the eWeLink application on each phone.

There are two options here. The first option is to log into the eWeLink application with the same name and password from different phones and control the relay.

The truth is, if you log into the application on one phone, and then at the same time log into the application using the same username and password, but on another phone, then an error will occur on the first phone and the application will automatically exit. In this case, the second phone remains in the application and can be used to control devices.

At the same time, I would like to note that when controlling a relay from one phone, its status is displayed almost instantly on all phones that are connected to it.

Load management via the Internet

In addition to controlling the relay via your phone via a Wi-Fi network, it can also be controlled via the Internet from anywhere in your location, i.e. absolutely from anywhere in the world where there is Internet access.

So, to control the switch via the Internet, you need to log into the same eWeLink application using your name and password that you specified during registration. And then everything is by analogy. It’s the same application, the same settings, the same control buttons, etc., the only difference is that you are not at home within the coverage area of ​​your Wi-Fi network, but at a distance of hundreds and thousands of kilometers from home.

A little about the cloud.

But still, you will not be able to control the relay without the Internet, because... control occurs not through the local network, but through the Internet, i.e. the same Chinese cloud that I mentioned above. And it doesn’t matter whether control is via Wi-Fi or the Internet, control access is always via the cloud, and to access the cloud you need Internet access.

In this regard, various craftsmen have already figured out how to untie this device from the Chinese cloud or make control only through a local home network. For those interested, this information can be found on certain resources.

By the way, if you need a similar device, but with an additional radio control function from the remote control, then you can order a Sonoff relay of the RF version.

If you want to control the load where there is no Internet network at all, then you can use the Sonoff version G1 relay (GSM/GPRS with SIM card support). This manufacturer also has relays with temperature and humidity sensors Sonoff TN10/TN16 and two-channel (for controlling two independent loads) relays Sonoff Dual.

In general, the manufacturer Sonoff has many different devices, I will tell you about some of the most interesting and significant ones on the pages of my website, so subscribe to the newsletter so as not to miss interesting releases.

You can buy a Sonoff relay here:

  1. Sonoff Basic: https://goo.gl/jXyNm3
  2. Sonoff RF (with radio control): https://goo.gl/TRPqN6
  3. Sonoff G1(GSM/GPRS with SIM card support): https://goo.gl/EkpTdp
  4. Sonoff TN10/TN16 (temperature and humidity sensor): https://goo.gl/MWAL5p
  5. Sonoff Dual (two-channel): https://goo.gl/a7rV56

And by tradition, a video based on the article, where you can more clearly see the configuration and control of the Sonoff relay:

Good day, dear reader.

A little lyrics at the beginning. The idea of ​​a “smart” light switch is not new at all and, probably, this is the first thing that comes to mind for those who have begun to get acquainted with the Arduino platform and IoT elements. And I am no exception to this. Having experimented with circuit elements, motors and LEDs, I want to make something more practical, which is in demand in everyday life and, most importantly, will be convenient to use, and will not remain a victim of experimentation for the sake of comfort.

In this article I will tell you how I made a switch that will work like a regular switch (that is, one that is usually mounted on the wall) and at the same time allows you to control it via WiFi (or via the Internet, as is done in this case).

So, let's make a list of what you will need to implement your plan. I’ll say right away that I intended not to spend a lot on components and chose the components based on reviews on the forums and the price-to-quality ratio. Therefore, some components may seem inappropriate here for experienced electrical enthusiasts, but please do not judge too harshly, because I'm just a beginner in electromechanics and would really appreciate comments from more experienced people.

I also needed: a server with which the switch will be controlled via the Internet, an Arduino Uno with which I programmed the ESP, a router and consumables such as wires, terminals, etc., all this can vary depending on tastes and will not affect to the final result.

Prices are taken from Ebay, where I bought them.

And here is what the elements from the table look like:

Now you can create a connection diagram:

As you probably noticed, the scheme is very simple. Everything is assembled easily, quickly and without soldering. A kind of working prototype that you don’t need to tinker with for a long time. Everything is connected with wires and terminals. The only negative is that the relay did not fit into the switch socket. Yes, initially I planned to push it all into the wall behind the switch to make it look aesthetically pleasing. But to my regret, there was not enough space in the socket and the relay simply did not fit either lengthwise or across:

Therefore, I temporarily moved the relay behind the socket until I found a suitable switch box with an outlet to hide the iron inside. But there is nothing more permanent than temporary, isn’t it? So it all looks like this now:

Electrical tape will save you from electric shock... I hope.

Now let's talk about the software part.

And before we start analyzing the code and details, I will give a general scheme for implementing control of a light bulb.

I hope that someday I will rewrite everything and the connection will be based on a faster protocol than HTTP, but for a start it will do. Remotely, the light bulb changes its state in approximately 1-1.5 seconds, and from the switch instantly, as befits a decent switch.

Programming ESP8266-01

The easiest way to do this is with Arduino. You can download the necessary libraries for the Arduino IDE from GitHub. All instructions for installation and configuration are there.

Next we need to connect the ESP to the computer, for this you will need either a USB to Serial Adapter (such as FTDi , CH340 , FT232RL) or any Arduino platform (I had an Arduino Uno) with RX and TX outputs.

It's worth noting that the ESP8266-01 is powered by 3.3 Volts, which means you should never connect it to an Arduino, which is (often) powered by 5 Volts, otherwise it will burn to hell. You can use a voltage reducer, which is shown in the table above.

The connection diagram is simple: we connect TX, RX and GND of the ESP to RX, TX and GND of the adapter/Arduino, respectively. After this, the connection itself is ready for use. The microcontroller can be programmed using the Arduino IDE.

A couple of nuances when using Arduino Uno:

  • The Uno has a 3.3V output, but it wasn't enough. When you connect an ESP to it, everything seems to work, the indicators are on, but communication with the COM port is lost. So I used a different 3.3V power supply for the ESP.
  • In addition, UNO did not have any problems communicating with ESP, given that UNO was powered by 5V, and ESP by 3V.
After several experiments with the ESP8266-01, it turned out that the ESP is sensitive to the voltages connected to GPIO0 and GPIO2. At the moment of start, they should under no circumstances be grounded if you intend to start it in normal mode. More details about starting a microcontroller. I didn’t know this and I had to slightly change the scheme, because... in the ESP-01 version only these 2 pins are present and in my circuit both are used.

And here is the program for ESP itself:

Show code

#include #include #include #include #include extern "C" ( // this part is required to access the function initVariant #include "user_interface.h" ) const char* ssid = "WIFISSID"; // WiFi name const char* password = "***************"; // WiFi password const String self_token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // token for minimal communication security const String serv_token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // token for minimal communication security const String name = "IOT_lamp"; // switch name, read light bulbs const String serverIP = "192.168.1.111"; // internal IP WEB server bool lamp_on = false; bool can_toggle = false; int button_state; ESP8266WebServer server(80); // web server HTTPClient http; // web client const int lamp = 2; // Control the relay via GPIO2 const int button = 0; // "Catch" the switch via GPIO0 // function for ping the light bulb void handleRoot() ( server.send(200, "text/plain", "Hello! I am " + name); ) // function for invalid requests void handleNotFound ()( String message = "not found"; server.send(404, "text/plain", message); ) // Let there be light void turnOnLamp())( digitalWrite(lamp, LOW); lamp_on = true; ) / / Let there be darkness void turnOffLamp())( digitalWrite(lamp, HIGH); lamp_on = false; ) // Send manual on/off events to the server. void sendServer(bool state)( http.begin("http://"+serverIP+"/iapi/setstate"); String post = "token="+self_token+"&state="+(state?"on":"off "); // Using the token, the server will determine what kind of device it is http.addHeader("Content-Type", "application/x-www-form-urlencoded"); int httpCode = http.POST(post); http.end (); ) // Change the state of the lamp void toggleLamp())( if(lamp_on == true) ( ​​turnOffLamp(); sendServer(false); ) else ( turnOnLamp(); sendServer(true); ) ) // Receive from the server enable command void handleOn())( String token = server.arg("token"); if(serv_token != token) ( String message = "access denied"; server.send(401, "text/plain", message); return; ) turnOnLamp(); String message = "success"; server.send(200, "text/plain", message); ) // Receive a command from the server to turn off void handleOff())( String token = server.arg(" token"); if(serv_token != token) ( String message = "access denied"; server.send(401, "text/plain", message); return; ) turnOffLamp(); String message = "success"; server.send(200, "text/plain", message); ) // Set the MAC to give the same IP void initVariant() ( uint8_t mac = (0x00, 0xA3, 0xA0, 0x1C, 0x8C, 0x45); wifi_set_macaddr(STATION_IF, &mac); ) void setup(void)( pinMode(lamp, OUTPUT ); pinMode(button, INPUT_PULLUP); // It is important to do INPUT_PULLUP turnOffLamp(); WiFi.hostname(name); WiFi.begin(ssid, password); // Wait until we connect to WiFi while (WiFi.status() ! = WL_CONNECTED) ( delay(500); ) // Assign functions to requests server.on("/", handleRoot); server.on("/on", HTTP_POST, handleOn); server.on("/off", HTTP_POST, handleOff); server.onNotFound(handleNotFound); // Start the server server.begin(); ) void loop(void)( server.handleClient(); // Check whether the switch is pressed button_state = digitalRead(button); if (button_state == HIGH && can_toggle) ( toggleLamp(); can_toggle = false; delay(500); ) else if(button_state == LOW)( can_toggle = true; ) )


A couple of notes on the code:
  • It is very important to declare the GPIO0 pin as pinMode(button, INPUT_PULLUP), because In the circuit we do not use a resistor for this button. And ESP has its own “built-in” ones for these very purposes.
  • When catching the state of a button, it is advisable to set a delay when reading it to avoid false positives at the moment of pressing.

WEB server programming

Here you can give free rein to your imagination and use any available means to create a service that will process requests sent by the switch and send requests to turn it on/off.

I used for these purposes


This article will focus on ESP8266 Wi-Fi module, programming language LUA and firmware nodeMCU. SDK from the manufacturer will not be considered.

About three years ago I tried to implement a switch via a 1-wire bus. I really didn’t like how everything worked.

  • Single point of failure because all logic on the server;
  • Slow speed;
  • Each switch will have to be pulled from 2 wires (ideally a “twist”).

As a result, all this was successfully abandoned; other wireless solutions were considered, but were excluded due to high cost, insecure protocol and complexity of implementation. I wanted something simple with a minimum of components, with its own logic and cheap. I recently ordered 2 pieces esp8266 just for fun, without knowing what specific things can be done with them. After 2 evenings of dealing with the chip, I remembered the unfinished business with the button and decided to bring it to its logical conclusion.

There are already a number of firmwares for this module, and you can also write firmware for yourself using the SDK, but I did not delve into the details of writing, because After studying the nodeMCU API, I realized that I had enough of this functionality to spare and flashed both modules.

Iron

Cost is an important factor for a simple switch, so I tried to use as few parts as possible. I decided to make it from what I had at home, but I had to buy a solid-state relay. By the way, a “relay” costs more than a wifi module and can be replaced with an optocoupler, triac and harness; switching diagrams can be easily found on the Internet. There was a case when a bad contact in a light bulb socket knocked out a triac. Let's see how the optorelay performs, since I haven't worked with them before. It is worth considering that for heavy loads the installation of a radiator is mandatory.

Here I immediately encountered a problem: if on gpio it went to ground when turned on, the board went either to firmware mode or to an incomprehensible mode, because our button is normally open, there was nothing to alter with it and left it shorted to ground, and I set the opto-relay to positive through a resistor and turned it on with a feed of 0 and turned it off with a feed of 1, respectively. The result was the following diagram:


Attention, the scheme needs to be improved! The output to the relay should be supplied through a transistor, and the button should be pulled up through a resistor from the positive. The ingredients turned out like this:

  • switch;
  • spring (for converting a switch into a button);
  • esp8266 itself;
  • solid state relay used(S202T02);
  • scarf for design;
  • resistor 470 Ohm;
  • wires;
  • connectors to taste;
  • charging from phone 400mA 5v;
  • stabilizer 1117 3.3v;
  • a pair of capacitors.

Remaking the switch did not take much time; I threw out the standard LED. I ran the wires from the module in the center of the switch, placed the module itself outside under a plastic button, and the power part inside. Not many photos of the process (photo from phone):

nodeMCU

The firmware uses the Lua programming language, this language is somewhat similar to Javascript. The version is still somewhat damp, but the basic functionality is already quite well implemented. Immediately after loading, the module starts executing the script file init.lua, this file is not in the pure firmware, you have to create it manually. All operations can be carried out through the console connected to the “com” port; to simplify uploading files to the module, there is a luatool script. Filling works as follows and this code fully shows the process of writing to a file.

File.open("init.lua","w") file.writeline([]) file.writeline([[--comment]]) file.close()

Example of reading a configuration file. Doesn't look very good. Maybe there is another version of serialized data.

File.open("config") c_wifi_ssid = string.gsub(file.readline(), "n", "") c_wifi_key = file.readline() file.close()

An example loop using the API with a pause of 1000 milliseconds is shown below:

Tmr.alarm(1000, 1, function() if wifi.sta.getip()=="0.0.0.0" then --current ip print("connecting to AP..."..c_wifi_ssid.."/". .c_wifi_key) else print("ip: ",wifi.sta.getip()) tmr.stop() -- alarm stop end end)

Working with GPIOs

If your module model is ESP-01 new revision, then only 2 gpio are available to you without resorting to a dirty hack.


I decided to abandon this hack and use what I have.

One gpio button and a second output to a solid state relay. There is also Tx, but I couldn’t get it to work like gpio, and for indication I just send messages to the console print(). So far I’ve stuck it out that way. The longer the message, the longer and brighter the LED flashes. The owners of this modification are flying through the woods with such functions as (node.key, node.led), because... they can only use GPIO16, which is also not routed on the board.

All gpio can operate in several modes (OUTPUT, INPUT, INT), but the interesting thing is that the function gpio.read(), before counting, sends a low level, even if the mode is set to OUTPUT. That is, to get the current output state, this is not suitable. I had to use an external variable and write two functions for convenience, and then define the activity through the variable.

Function on() gpio.write(8,gpio.LOW) oo=1 end function off() gpio.write(8,gpio.HIGH) oo=0 end

You can use events as callback gpio.trig(pin, type, function(level)), the second parameter can take the following values: “up”, “down”, “both”, “low”, “high”. Everything seems to be clear here. If your output is in state 1 and we lower it to the ground, down is triggered, then when raised, up is triggered, but, to my regret, this did not happen, in the console I saw only down, depending on the speed of pressing the button, the event was triggered 1 or 2 times. I decided to put a cycle with a pause and a breakpoint of 1 on gpio.

For i=1,1000 do print(i) tmr.delay(10) tmr.wdclr() -- resets the counter and prevents auto reboot end

But the pause did not work, and without a pause the device went into reboot. But print(i) introduced a good delay. Made it through tmr.alarm, but at the moment there can only be one active cycle, which is not very suitable.

Function down() tmr.alarm(100, 1, function() timer = timer + 1 -- ok if gpio.read(9) == 1 then print(timer) tmr.stop() if timer< 20 then switch() else -- ... end timer = 0 end tmr.wdclr() end) end gpio.trig(9, "down", function (gp) if timer == 0 then timer = 1 down() end end)

HTTP server

The server starts like 2 fingers, but you won’t receive any array of request parameters. It is not yet clear what is the best way: either write your own bicycle, or find by substring. Agree, it looks terrible. In this example, 2 parameters are searched: key and mode=off,on,party. The last mode is a simple blinking of the light bulb every 200ms, you can set it faster, but I was afraid for the light bulb and rejected it.

Function HTTPd() print("start http serv") srv=net.createServer(net.TCP, 5) srv:listen(80,function(conn) conn:on("receive",function(conn,payload) print( payload) if string.find(payload, "key="..c_api_key) then msg = "key_ok" if string.find(payload,"mode=on") then on() else if string.find(payload,"mode =off") then tmr.stop() off() else if string.find(payload, "mode=party") then party(200) end end end else msg = "error_key" end conn:send("

mode= key="api_key"

") end) conn:on("sent",function(conn) conn:close() end) end) end

It’s not that difficult to write a simple web interface and place scripts and styles on external servers. Take only the index page from the module and communicate with it, for example, via json, this way there won’t be a big load and everything will fit into the file system, but we become dependent on the availability of the Internet.

I have long wanted to automate the process of drying the bathroom after bathing. I have had many reviews on the topic of humidity. By the way, in the winter we dry our clothes in the bathroom. But I haven’t decided yet what exactly to implement. I will describe another Chinese miracle to combat this evil.

In summer we dry clothes on the balcony, in winter - in the bathroom, just turn on the exhaust fan. But monitoring the fan is not always convenient. So I decided to install automation on this matter. The first implementation experience was unsuccessful. There was a review. But I didn’t give up... The second experience was more successful, I also did a review. But I didn’t manage to put it into practice. Frequent business trips take a lot of time.
But I did not expect such a gift at all. I saw a letter in a personal message with an offer to review a product by Itead Studio. It’s stupid to refuse a product for review if it’s interesting (let alone necessary) yourself. Immediately after, I looked through Muska. I found at least three reviews about Sonoff products. I’m not the first: (I can imagine how many votes there will be in the comments about the free cookie. But spitting in the back is the lot of the weak and losers. Therefore, this review is for those who consider themselves capable.
This is what the cart looks like with my selection:


But I made a small mistake, I didn’t pay attention to the text in the picture (on a red background). The switch came without a remote control: (This is an additional option, it must be purchased separately
The order came in a small box.


The TH16 module was without packaging.

The rest is in boxes. But there were no instructions. That's all I ordered.
I'm quite a lazy person. The only thing that can make me do something is an obligation to someone. They say that laziness is the engine of progress. My drive is a promise made to someone. Thus, I killed two birds with one stone: I wrote a review and figured out these magic switches/switches.
Let me remind you a little of my story.
When I moved into a new apartment, I almost immediately installed a fan with a check valve in the hood. A fan is necessary to dry the bathroom after bathing. A check valve is needed to prevent foreign odors from neighbors from entering the apartment (when the fan is silent). It happens. All the ventilation ducts are individual, but they apparently saved cement when laying them. The smell probably passes through the cracks.
I have different options for fans. There are simple ones, some with a timer (time interval adjustment), as in the photo.


This is exactly what I used to this day.
Since I live in an apartment “anthill”, the only place for drying clothes is the balcony. It may go dark in the bathroom. Drying requires either low humidity or air circulation. Fulfilling both conditions is the best option. A fan should have solved this problem. At first I did just that. The main thing is not to forget to turn it off. While the fan is operating, the window must be opened slightly. Don’t you need to remind me about the school problem with a swimming pool and two pipes? In order for the air to escape into the hood, it must enter the apartment from somewhere. Those who have wooden windows and not plastic will have no problems. Enough cracks. But with plastic ones, the apartment turns into a terrarium.
That’s when I started thinking about automating the process...
I have already shared my sad experience of implementing my idea. This is the module. It cannot work IN PRINCIPLE.


I also drew a diagram of the module.


The circuit is based on a comparator based on LM393. From the looks of it, everything should work. But there is one thing. The sensor is unusual. It changes its resistance with respect to frequency. To take readings, you need to apply a frequency to it (standard value 1 kHz). This is such sadness.
On one of the sites there were three comments from one user about this:

Strange, this is a standard sensor from Arduino peripherals - it should work.
There’s nothing to check yet - I’m not particularly interested in humidity, because I don’t have such a sensor yet. :)
I’ll order it when the opportunity arises and report back...
...I don’t have a single Arduino module that doesn’t work.
I’ll buy it for testing, maybe I’ll make a weather station for myself...
...do you think they would do this if they were not working?
A year has passed...
Apparently, I can’t wait.
I move on to the parcel.
The store page with the TH module looks like this:

On it you can select Sonoff TH modules depending on the relay current, as well as humidity and temperature modules. You can see exactly what I chose. I didn’t find the humidity module in a separate sale on the store page (maybe I didn’t look well). Therefore, when ordering, be careful...


There were no instructions either (already wrote).
The store has a help wiki page:

Everything is there, even the diagram:

Small in size.


Weighed, 79g.


I'm starting to analyze.
220V network wires are connected here.


The contactors are spring-loaded and very tight. But, for me, it’s more reliable with a screw.
The case is held on by latches.


Everything is in the mind. I have no comments.
Unscrewed 4 screws.


The Wi-Fi node is built on ESP8266 (who would doubt it). For aces there is a whole field for activity. The main thing is that the head works. The rest has already been done. There is no need to isolate a separate power supply for the module, and there is no need to look for a box either. Everything is assembled and working.




The board has been washed. There are no traces of flux. At the input there is a fuse and a 10D471K varistor against overvoltage (interpretation - diameter 10 mm, voltage 470 Volts).

I haven't seen this for a long time. I put everything back to its original state.
I turn to the humidity module. This one came in a box. You can read what is written on it (on the box). Photos allow you to do this.

The module is unusually large.

Connects via a connector similar to headphones.


It turns out this way.


Everything basic is written on the case.


The store has a wiki help page (already wrote):
- Temperature and humidity module
AM2301 Product Manual
There is also a manual for the temperature sensor:
- DS18B20 - Programmable Resolution 1-Wire® Digital Thermometer
I didn't order it. I'm not interested in him. Plus, AM2301 is more versatile. It has both a temperature sensor and a humidity sensor. Moreover, the TH10/16 housing has only one hole for the remote module.
I'm disassembling AM2301. Housing with four latches.


On one side of the module there is a temperature, humidity and quartz sensor.


The main diagram is on the reverse side.

I'm also building this module.
And finally, the Sonoff RF smart switch.



Also no instructions. Even smaller in size than Sonoff TH.


Weighed: 49g.



It's not of particular interest to me. But I'll show you what's inside.

The case is also latched. You can see the parsing sequence.
Screw contactors. For me, it's very convenient.


At the input there is a varistor 10D471K against overvoltage (interpretation - diameter 10 mm, voltage 470 Volts), as in the VT module.


Power supply unit with galvanic isolation from the network. They even made cuts in the board.
The board has been washed. There are no traces of flux.


Everything is in the mind. And I have no comments here.
And here the WiFi node is built on ESP8266.


Radio module in the form of a separate board.


I put everything back to its original state.
It's time to get down to business.
I'm putting together a training plan. I connect the Sonoff TH module to the network. The connection is not obvious to everyone. Therefore, look at the picture on the store page.

Few devices work in this way. Therefore, I put a red cross on the “extra” wires.
I hang a fan at the exit.
It's much easier with Sonoff RF. I connect an ordinary light bulb to the output for control.


All that remains is to connect the whole thing with the smartphone.
Smart switches support remote control via Wi-Fi, but only via the cloud :(
It's time to link them to the eWeLink control application. To do this, you must first download it :) Install, register...
The account has been created.
First I connect Sonoff TH. I launch the application and follow the instructions.
To add a device, click on the plus sign. Next, press the little white button and hold it for about 5 seconds. The blue LED should blink steadily. Exactly evenly! He may “go into a trance” :) and start giving strange signals. In this case, press and hold again.


The application asks you to enter your Wi-Fi password. Then it searches for devices.
You will need to enter a name for the new device.
See the photo for the sequence of pictures (from left to right, top to bottom).


The switch is “linked” to my account.
Same with Sonoff RF. After linking, the picture on the smartphone looks like this. You can turn the load on and off by pressing the buttons. Three pictures: off, on and not connected to 220V (offline)


In order to turn on the switch, you need to press a button on your virtual remote control from anywhere in the world where there is Internet and Wi-Fi.
When connected to a 220V network, the blue LED on the module lights up. When the load is turned on, the red LED additionally lights up.


But this is all manual mode. In order to enter automatic mode and get into setting the parameters for turning the switch on and off, you need to move the lever (Auto-Manual) to the auto position.


And in the settings I put what I need.
Let me explain the pictures. Now there is 55% humidity and the temperature is 18˚C (remote module on the windowsill). The switch is off. In this case, temperature and humidity are monitored online, regardless of what mode the switch is in (manual or auto).
Let me explain what I asked.
When the humidity reaches 65% the switch will turn on (fan). When the humidity reaches 60% it will turn off. You can do the opposite (for a humidifier).


This is for those who have very low humidity in winter.
When the humidity reaches 30%, the switch will turn on (humidifier mode). When the humidity reaches 40% it will turn off.
All settings are in accordance with GOST 30494-96 “Residential and public buildings”.


Pay attention to the optimal humidity in winter. This is not 60% as many people think! 60% is just acceptable, you can’t go higher, you have to fight. OPTIMUM 30-45%
You can control the switch using a timer. There are two options.


Temperature triggering can be configured. All settings are identical to the settings for humidity, only select the temperature.

A little about the Sonoff RF smart switch.
It differs from Sonoff TH in that it has a radio module (can be controlled using a remote control, which I don’t have). It also does not have the ability to work with a humidity and temperature sensor. The rest is the same: control via Wi-Fi with the ability to set a timer.
The virtual remote is a little different.


In automatic mode there are also two types of timers (like TN).


I repeat. It’s not of particular interest to me, but I’ll definitely find a use for it.
I will note the nuances of the operation of these switches. Without the Internet you will not get any control.
BUT there is one big plus. The automatic mode configured on the switches will continue to work regardless of the Internet!

When installing the application on several phones, you can control it from all of them, but only if you log in to eWeLink on each of them using the same username and password.
At the end I will summarize briefly.
Smart switches support remote control via Wi-Fi, but only via the cloud: (They need to be linked to the eWeLink control application. What if some good Uncle Liao wants to control your smart home? For those who don’t trust him, you’ll have to create your own MQTT server, and turn on/off the load according to your wishes and rules. For those who have programming skills, this is not difficult. For those who are calm about such a problem, just connect and use. For example, I don’t care when managing fan in the bathroom. But when the time comes to a full-fledged “Smart Home”, I will think about something.
That's all.
These modules are ideal for working with a fan, air conditioner, and humidifier. You can organize a smart watering system at your dacha. Even a gas boiler can be controlled by time and by a given room temperature.
Everyone decides for themselves how to properly use the information from my review. If something is unclear, ask questions. I hope it helped at least someone. Perhaps someone will want to help me. I'll be very grateful.

Good luck everyone!
Functional test and gutting:

The product was provided for writing a review by the store. The review was published in accordance with clause 18 of the Site Rules.

In the modern world, the “smart home” system is becoming widespread. With its help, you can remotely control many elements and devices of our home. You can also remotely control the lighting in the room. Such inventions contribute to the comfort of a given room, and are also used where elderly people and people with disabilities live. This article will discuss how it works and why a Wi-Fi light switch is needed, which is gaining increasing popularity among the population.

Strengths and weaknesses of the device

Wi-fi light switch has the following advantages:

  1. There is no need to lay additional cable.
  2. It is possible to centrally control lighting devices, that is, from one command point. In order to control the wireless light switch, you can use a smartphone, tablet, computer, or remote control. For tablets and other electronic devices, you must install the necessary software. It can be downloaded from the Internet or installed from disk.
  3. Large signal coverage area. Despite the walls, the digital radio signal penetrates into the desired room.
  4. This system is very secure. Even if the structure of the device is damaged, this does not threaten the resident with a strong electric shock, because the Wi-fi switch has a very low current strength.
  5. The device works normally with all types of light bulbs (LED, incandescent, energy-saving).
  6. You can set different combinations, as well as operating modes of lighting fixtures.

If we talk about the disadvantages of light switches, there are only a few. The main ones are that the price is much higher than conventional keyboard models and there is a certain risk of the batteries in the remote control being discharged or the Wi-Fi signal being poor.

Design features

The Wi-Fi switch kit includes a receiver and transmitter. The receiver is a control relay. You can control it via a smartphone with access to a Wi-Fi network, or using the remote control. When the relay receives a certain signal, it closes the electrical circuit. The relay is installed near or inside the lamp. This is possible due to the small dimensions of the device. The reason for installing the device near the lamp is so that it does not fall out of the radius in which the transmitter operates. If the room has spot lighting, the receiver can be placed in a distribution box or behind a suspended ceiling.

The switch or transmitter has a small power generator that is capable of generating electricity when you press a button on the remote control or send a specific command from a smartphone via a Wi-Fi connection. In turn, the pulse is processed into a radio signal, which enters the device. Such radio-controlled light switches are quite expensive, and their analogue is control from a remote control that contains batteries.

Types of switches and the best manufacturers

At this time, the range of Wi-fi light switches is not very large. However, products are classified according to several criteria:

  1. The device can be adjusted with electronic or mechanical keys. In the first case we are talking about the touch screen of the device. The keys are on the remote control (remote control).
  2. There are also light switches with both and regular keypads. Using the first devices, you can adjust the brightness of the lighting, thereby changing its intensity. To adjust the brightness, either hold or scroll the corresponding button.
  3. This switch can provide full control of not only one, but also two or three groups of lighting devices. However, the price for a wireless device that can control entire groups is quite high.

There are currently seven main manufacturers of wireless electrical accessories for lighting control:

  1. Legrand - country of origin: France. The company has a whole line of products called Celian.
  2. Vitrum is a country of origin: Italy. This company uses a technology called Z-Wave. It allows you to fully automate the control of lighting in the house.
  3. Delumo - products are manufactured by a Russian company, which in particular produces dimmers, switches and thermostats.
  4. Noolite – accessories are made by Belarusian manufacturers.
  5. Livolo is manufactured in China. This company produces specialized devices for automation. The product line also includes products for both single and double frames for switches.
  6. Broadlink (China). This manufacturer has a fairly large selection of products for lighting control.
  7. Kopou is the latest company that is also based in China. The manufacturer produces dimmers in the form of various key fobs.

The video below provides an overview of another interesting model of Wi-fi light switch:

Correct connection

In order to properly mount the switch, you need to know its operating principle, what the device consists of, and how to connect the Wi-fi switch. The connection diagram for this wireless device is very simple.

One of the advantages of a Wi-Fi light switch is its ease of use and connection. If you really want to, you can install the device yourself. It is important to strictly follow the instructions provided by the manufacturer. This installation takes only a few minutes.

The connection process consists of only two stages:

  1. Installing a radio receiver.
  2. Installation of a light switch (control button).

Basically, receivers have from two to four wires. They come out of the device body. To determine the input wire, you must read the instructions. The remaining wires will be output wires, for example, a double switch will have two outputs. To install the receiver, you must open the phase that supplies power to the lighting device and connect it to the circuit, while observing the sequence.

In the case where it is necessary to connect more than one lighting group, proceed as follows:

  • zero is supplied to all lighting fixtures;
  • the phase is branched in the Wi-fi switch;
  • the phase should be supplied separately to each group of lamps.

The control button is installed quite simply; first you need to make a hole in the wall using a hammer drill with a concrete cutter. A regular plastic socket box is inserted into the finished hole, and plaster can be used to secure it. The installation process is absolutely no different from the keyboard type. The only difference is that there is no need to lay wires, you just need to securely fasten the button in the socket.

Like( 0 ) I do not like( 0 )