Умное реле Sonoff Basic: руководство по использованию
Умное реле Sonoff Basic научит ваш телефон управлять бытовыми приборами на расстоянии, а также следить за текущим статусом работы. Больше не нужно вставать с постели, чтобы выключить свет или беспокоиться по дороге на работу о включённом утюге.
Модуль Sonoff Basic способен коммутировать нагрузку с напряжением 100–240 В и током до 10 А.
Видеообзор
Подключение и настройка
Подключение электроники
Для наглядности в качестве примера, соберём макет системы освещения.
Что понадобится
Инструкция по сборке
Программная настройка
Сопряжения с новыми устройствами
Умное реле Sonoff Basic поддерживает два режима сопряжения с новыми устройствами:
Режим быстрого сопряжения
Режим служит для быстрого сопряжения мобильного телефона с новыми устройствами Sonoff.
Режим совместимого соединения
Режим служит для сопряжения мобильного телефона с новыми устройствами Sonoff. В режиме совместимого соединения, модуль Sonoff сам создаёт Wi-Fi окружение, через которое проходит дальнейшая настройка
Примеры работы
Пришло время проверить умное реле Sonoff Basic в действии.
Физический переключатель
Изменяйте состояние устройства физическим нажатием на кнопку на модуле Sonoff Basic:
Беспроводной переключатель
Изменяйте состояние устройства нажатием на иконку кнопки в мобильном приложении:
Элементы платы
Приоткроем занавес и заглянем на внутренности модуля.
Чип ESP8266EX
За беспроводную технологию в Sonoff Basic Wi-Fi отвечает чип ESP8266. В основе кристалла входит процессор семейства Xtensa — 32-х битный Tensilica L106 с частой 80 МГц с ультранизким энергопотреблением, радиочастотный трансивер с физическим уровнем Wi-Fi IEEE 802.11 b/g/n и блоки памяти SRAM. Мощности процессорного ядра хватает для работы сложных пользовательских приложений и цифровой сигнальной обработки.
Электромеханическое реле
За коммутацию нагрузки отвечает электромеханическое реле. Подробнее про работу реле читайте в нашей документации.
Клеммник питания
Клеммник Input служит для подключения Sonoff Basic к источнику питания от бытовой сети 100–240 В.
Контакт
Функция
Подключение
L
Питание модуля / Фаза
Подключите к фазному проводу источника питания.
N
Питание модуля / Ноль
Подключите к нулевому проводу источника питания.
Если не знаете, где в вашей бытовой сети фаза L и ноль N , ничего страшного. Провода L и ноль N можно менять местами, если подключаемая нагрузка это предусматривает.
Клеммник нагрузки
Клеммник Output служит для подключения нагрузки к Sonoff Basic. Выходное значение коммутируемого напряжения равно входному напряжению на клеммнике питания.
Контакт
Функция
Подключение
L
Питание нагрузки
Подключите к фазному проводу нагрузки.
N
Питание нагрузки
Подключите к нулевому проводу нагрузки.
Светодиодная индикация
На модуле расположено два светодиода: индикатор нагрузки и индикатор сопряжения.
Индикатор нагрузки
Светодиодный красный индикатор нагрузки подскажет текущее состояния нагрузки.
Умное реле Sonoff BASICR2: руководство по использованию
Умное реле Sonoff BASICR2 научит ваш телефон управлять бытовыми приборами на расстоянии, а также следить за текущим статусом работы. Больше не нужно вставать с постели, чтобы выключить свет или беспокоиться по дороге на работу о включённом утюге.
Модуль Sonoff BASICR2 способен коммутировать нагрузку с напряжением 100–240 В и током до 16 А.
Подключение и настройка
Подключение электроники
Для наглядности в качестве примера, соберём макет системы освещения.
Что понадобится
Инструкция по сборке
Программная настройка
Сопряжения с новыми устройствами
Умное реле Sonoff BASICR2 поддерживает два режима сопряжения с новыми устройствами:
Режим быстрого сопряжения
Режим служит для быстрого сопряжения мобильного телефона с новыми устройствами Sonoff.
Режим совместимого соединения
Режим служит для сопряжения мобильного телефона с новыми устройствами Sonoff. В режиме совместимого соединения, модуль Sonoff сам создаёт Wi-Fi окружение, через которое проходит дальнейшая настройка
Примеры работы
Пришло время проверить умное реле Sonoff BASICR2 в действии.
Физический переключатель
Изменяйте состояние устройства физическим нажатием на кнопку на модуле Sonoff BASICR2:
Беспроводной переключатель
Изменяйте состояние устройства нажатием на иконку кнопки в мобильном приложении:
Элементы платы
Чип ESP8285
За беспроводную технологию в Sonoff BASICR2 отвечает чип ESP8285. В основе кристалла входит процессор семейства Xtensa — 32-х битный Tensilica L106 с частой 80 МГц с ультранизким энергопотреблением, радиочастотный трансивер с физическим уровнем Wi-Fi IEEE 802.11 b/g/n и блок Flash памяти на 1 МБ. Мощности процессорного ядра хватает для работы сложных пользовательских приложений и цифровой сигнальной обработки.
Чип ESP8285 расположен на плате управления внутри пластикового бокса.
Электромеханическое реле
За коммутацию нагрузки в Sonoff BASICR2 отвечает электромеханическое реле. Общий принцип работы реле читайте в нашей документации.
Электромеханическое реле расположено на плате управления внутри пластикового бокса.
Клеммник питания
Клеммник Input служит для подключения Sonoff Basic к источнику питания от бытовой сети 100–240 В.
Контакт
Функция
Подключение
L
Питание модуля / Фаза
Подключите к фазному проводу источника питания.
N
Питание модуля / Ноль
Подключите к нулевому проводу источника питания.
Если не знаете, где в вашей бытовой сети фаза L и ноль N , ничего страшного. Провода L и ноль N можно менять местами, если подключаемая нагрузка это предусматривает.
Клеммник нагрузки
Клеммник Output служит для подключения нагрузки к Sonoff Basic. Выходное значение коммутируемого напряжения равно входному напряжению на клеммнике питания.
Контакт
Функция
Подключение
L
Питание нагрузки / Фаза
Подключите к фазному проводу нагрузки.
N
Питание нагрузки / Ноль
Подключите к нулевому проводу нагрузки.
Светодиодная индикация
На модуле расположено два светодиода: индикатор нагрузки и индикатор сопряжения.
Индикатор нагрузки
Светодиодный красный индикатор нагрузки подскажет текущее состояния нагрузки.
Please see the Hardware Preparation page for general instructions.
You need to access the serial interface. The four serial pins (3V3, Rx, Tx, GND) are available in the middle of the PCB, right next to the on-board button. Newer versions of the Sonoff Basic device provide five pins below the button, ignore the pin furthest away from the Button (GPIO14 or I02) if available. The square pin right next to the button is the 3.3V line.
For flashing the Sonoff Basic, hold the button while connecting the 3.3V power. The LED remains off until the flashing process is done and the board is rebooted.
If your switch is powering up but is showing a solid-blink-reset pattern see this FAQ entry for advice.
GPIO00 — BUTTON
GPIO12 — RELAY
Sonoff Basic R3
This is the board layout for the third design iteration of the Sonoff Basic.
The Sonoff Basic R3 uses the ESP8285 chip. With this version, the mains power reverts to solder rails directly on the PCB. It also moves the Wi-Fi module to a separate PCB mounted on the main PCB. It makes access to the underside of the serial interface contacts quite difficult.
This version of the device supports the new Itead DIY architecture which allows OTA firmware upload. The device was reviewed by DigiblurDIY in this video.
The serial interface pins are broken out on the PCB making flashing using a serial adapter as well. Since the underside of the contacts is not easily reachable, use a solderless solution (i.e., friction) to maintain contact with the pins to flash the device.
Sonoff Basic R2
Around November 2018, Itead changed the layout of the Sonoff Basic (issue #4515). The new board is labeled as Sonoff RF R2 POWER V1.0. It is easily discerned from previous revisions since it uses wires instead of thick solder traces for mains power.
The new version of the Sonoff Basic smart switch uses an ESP8285 SoC with the 1MB flash integrated into the same SoC chip.
GPIO14 is no longer broken out to a contact on the PCB. Instead, GPIO02 (no pullup) is broken out. It is labeled as IO2 on the board. To use GPIO02, take care that it is not being pulled low when the device is booting. Otherwise, the device will not boot into its regular operational mode. Alternatively, you can use use GPIO03 (Rx) which does not have any boot function restrictions. However, both of these GPIO are pulled high momentarily after boot. This means that any connected device may «blink» when the Sonoff is powering up.
Unlike GPIO03, the GPIO02 PCB contact is not prepared for a pin. You will need to solder your cable directly on the board. Be careful. Too high a temperature or long heating can damage the contact and its connectivity. You should also make sure that there is no tension on the cable. Affix the cable with a cable tie and perhaps some hot glue.
GPIO02 as a user configurable input is implemented in the Sonoff Basic module (introduced in 6.3.0.15). If you use GPIO03, you must use a device template (rather than selecting the Sonoff Basic module), and also disable serial logging ( SerialLog 0 ).
You can remove the thick wires from the PCB to use the screw connection on the output side for low voltage. Then add a screw terminal next to the relay for the LINE OUT. This keeps all high voltage on one side of the board
Sonoff Basic R1
This is the board layout for the first board version of the Sonoff Basic.
(Image re-used from https://www.instructables.com/id/Use-Homie-Firmware-to-Drive-Sonoff-Switch-Module-E/ Thanks @amayii0)
Usable GPIO: — GPIO14 is broken out on the PCB adjacent to the GND pin. — GPIO13 — You must remove the bi-colour LED — GPIO04 — You must solder wire to pin on ESP chip
This is a walkthrough of flashing a Sonoff Basic R2 device with the Tasmota firmware so that it can connect to an MQTT broker.
I decided to write this because I wanted an easy way to automate my Christmas lights through Home Assistant. Doing this for the first time offered many different paths and the internet is full of a bunch of tutorials. Mainly I wanted to put together a clear end to end of everything needed and how to do it using macOS. All setup and screenshots will be done using macOS Catalina. The one assumption made is that you’ve already got an MQTT broker setup.
Hardware used:
Software used:
Start with the Software
Download Tasmota
You can download the latest version of Tasmota from the releases page on Github. The current version as of writing this is v7.1.2. Scroll down through the list and download the file named tasmota.bin towards the end of the list of files.
Note: There are others you can use most of which are in various different languages. An explanation of the different versions is on the release page if you are interested. Once downloaded set that to the side for now.
Let’s download and install PyFlasher.
Here you will find the releases page on Github. Go ahead and grab the latest release, which currently is V4.0.
Next download the driver for the USB Serial Adapter from FTDI.
Be sure to pick the right one for the operating system you are on. Installing this on macOS is fairly straight forward with one gotcha.
During the installation you are going to have to allow the install through Security & Privacy within System Preferences. Under the general tab there is a section labeled “Allow apps downloaded from.” Here you will see a button to click to allow the new driver install. Without doing this the USB Serial Adapter will never show up.
You should see a notification like this:
Moving on to prepping the Sonoff R2
Rip everything apart!
First step is to take the caps off the left and the right side of the R2. Then you are going to push the back plastic through the openings on the left and right to detach the top from the bottom.
Once thats all done you will just be needing the board and can set everything else off to the side.
Next let’s get the USB to serial adapter ready.
Make sure the little black jumper is connecting the 3v3 pin to the JP pin.
Go ahead and connect your four jumper wires to the remaining pins, which are RXD, TXD, GND, and VCC.
Note: If you don’t have jumper wires and want to use the cable that came with the serial adapter, you could alternatively insert some header pins into the female end of that cable and have the same setup as below.
Through the back of the board insert the jumper wire pins into the appropriate holes. They are as follows from the serial adapter to the R2 board.
If you have the serial adapter plugged in you should see the R2 start to light up and flash green. Now turn the board over and let it rest on the jumper wires.
Flashing time!
Get the R2 into programming mode.
Everything is now set to begin flashing the board.
Unplug the serial adapter.
Hold down the tall black button.
Plug in the serial adapter.
Release the button.
The ESP8266 chip on the R2 board will now be in programming mode.
Flashing Settings
Open up NodeMCU PyFlasher.
First click the select box for Serial port and look to see that your serial adapter shows up.
Note: If it doesn’t show up try pressing the refresh button to the right. If it still doesn’t show up, try restarting your computer to fix the issue.
Click the browse button and select the location where you downloaded tasmota.bin. Next select the following settings.
Baud rate: 115200
Flash mode: Dual Output
Erase flash: yes
After you have everything set, click the Flash NodeMCU button and wait until it tells you to restart the R2.
At this point unplug the serial adapter and plug it back in to get the R2 to reboot.
Time to Configure Tasmota
Setup Wifi
Open the wifi settings on your phone. Look for a network being broadcast thats named tasmota-xxxx where xxxx will be some numbers. Tap on that network and you should be prompted with a wifi configuration screen.
Next you can tap the Scan for wifi networks link and then select your network from the list that shows up or directly enter the ssid into the AP1 SSId field. Then enter your password in the AP1 Password field.
Once you have everything entered tap on the Save button and you will see a screen telling you the R2 is restarting and connecting to your network.
Get the IP Address
After the Sonoff R2 restarts and connects to your network you’ll need to get its ip address.
Note: This can be done through your router or an ip scanner application. It will show up with a hostname of tasmota-xxxx just as it did when we connected to it through wifi in the previous step.
The photo here is an example of what I saw when looking for the newly connected wifi device inside of my Eero App.
Open Tasmota
In your browser put in the ip address and you will see the main page for your R2.
Next click on Configuration and then Configure MQTT and you will see a screen like below.
Start by entering in the hostname or ip of your MQTT broker. Optionally a different port, username and password. The topic should be a unique identifier for your R2, so go ahead and change the default of Tasmota to whatever you’d like to name it.
At this point you could simply save and the Sonoff R2 would now be sending and receiving MQTT messages.
Note: I did make the conscious choice to configure my Tasmota flashed devices manually with Home Assistant and not use the auto discovery feature for no other reason that I wanted complete control and the auto discovery scares me. I also added Tasmota to the beginning of the full topic and all future devices I add will use Tasmota as the root of their topics as well.
What will the topics look like?
You’ve defined your unique %topic% and the %prefix% will be one of 3 things: cmd, stat, and tele. Cmd is for issuing commands or asking for status. Stat will report back status or configuration messages. Tele will report telemetry info.
In my case an example topic would be:
The payload might look like:
Note: I used MQTTBox to do my testing.
Optional Configuration
I also went into Configuration → Configure Other and changed the Friendly Name to be the same as the Topic name that I configured in MQTT.
The final thing I did was set the PowerRetain option in the console.
From the main menu click on Console. In the input type “PowerRetain ON” and press return. The state of the power messages will now be retained and anytime something such as Home Assistant connects to the broker they will know the last state of the device.
Putting it Back Together
So, I chose to add the R2 to an extension cord, but you could easily do the same thing to add it directly to the cord of anything you want to plug into an outlet. I used an extension cord since this is going to control my Christmas lights and I’d like to reuse it for other things once Christmas is over.
First go ahead and pop the R2 board back into the plastic enclosure. Set it in the base and snap the top on. The first time I did this I attached the cord before doing this and then realized I had to take the whole thing apart again.
Next let’s get the extension cord ready. You’ll need a wire stripper and a scissors or knife.
Start off by cutting the extension cord. I cut mine near the plug and gave it enough length that the R2 will rest on the ground. You can make the cord whatever length you’d like so if you want a 1 foot cord just cut off the excess.
Once you have it cut, take a scissors or knife and cut between the two wires about a half inch or so. Then take the wire stripper and strip about 1/4″ off. It really doesn’t need to be much.
Note: You might be wondering which wire goes in L (load) and which goes in N (neutral). If you look and feel the cord you’ll notice that one side is smooth and one is ribbed or not smooth. The not smooth one will be inserted into N.
Insert the male end or piece of the cord with the actual plug in the end of the R2 that says Input. Then tighten it down with a small flat head screwdriver.
Do the same with the other end of the extension cord on the Output side of the R2. Once both parts of the cord are secured put the caps on either side and tighten down the screws included in the box with a small phillips screwdriver.
Now go plug it in and you are set to go!
Wrapping Up
These are all the steps for setting up the Sonoff R2 using Tasmota and getting it talking with your MQTT broker. At this point you can integrate and control it however you would like either via its web interface or over MQTT. In another article I’ll show how to manually add these devices to Home Assistant, and setup some basic automations.