Posted on 72 Comments

#17: Home automation control with Sonoff, Arduino, OpenHAB, and MQTT

The Sonoff from Itead Studio is a fantastic little mains-switching module with a built-in ESP8266 and WiFi. If you want an easy way to control mains devices such as lamps and fans, this could be it!

Sonoff modules are preloaded with firmware that allows them to be controlled by a phone app, so they’re very easy to get started. But that’s just the beginning: using a USB-serial converter and the Arduino IDE, you can load your own software on the Sonoff and make it do your bidding. I used the Arduino IDE to load a sketch with MQTT support and OTA (over the air) updates, allowing it to be controlled by OpenHAB.

Sonoff models mentioned in this video:

Start by adding ESP8266 support to the Arduino IDE by following the instructions at github.com/esp8266/Arduino. I used the simple “Boards Manager” method.

For OTA (over the air) update support you’ll also need to install Python 2.7.

You’ll also need a USB-serial converter with support for 3.3V I/O. I used the Freetronics USB-Serial Converter (of course!), which has a switch that lets you select 3.3V or 5V mode.

The “BasicOTABlink” example shown in the video can be found at github.com/superhouse/BasicOTABlink.

The “BasicOTARelay” example shown in the video can be found at github.com/superhouse/BasicOTARelay.

For more information, a fantastic resource is Pete Scargill’s blog post about Slampher and Sonoff.

If you want to upgrade the FLASH memory on your Sonoff, check out Pete Scargill’s blog post about upgrading ESP8266 memory.

Update 24 Sep 2016: fixed the example links.

72 thoughts on “#17: Home automation control with Sonoff, Arduino, OpenHAB, and MQTT

  1. Well now the problem is how to hook an human/physical switch for sending command to that sonoff or directly… more in/output available inside?

    I’ll definitively buy some but I’ll need a wall “esp” switch too!

    Tank you! This one help me ALOT in my reverse ingineering!
    Love your research.

    1. The mode button can also be used as an input, if you want to control it directly from the Sonoff. It’s connected to GPIO0, so if you hold it down during startup it goes into a mode waiting for a new program. But you can also check the button position in your sketch, and use it to toggle the output on or off each time it’s pressed.

      1. Received on basic sonoff and testing it with is own cloud eWeLink… really cool! But still want to control it with my openhab and MQTT Protocol (“homie” is a wonderfully well made arduino helper for that…).

        And now I think I’ll be the first to “wire” extend the mechanical button through an “surfacetouch” switch on the wall… I’ll need alot of a research…

        Of course I can just make my own esp8266 wall switch but It will depends on my wifi… again… but now I think of it… independent wifiWallSwitch will be awesome for modifyable Scene!

        Whoa whole lotta questions here!

    2. How would you convert a sonoff basic to a switch that would turn on for a second then auto turnoff

      1. It seems like I could do this by reflashing the firmware using a modified sketch of your BasicOTA Blink sketch but don’t have it loop. My application is to use the sonoff switch with a relay that would emulate pushing the manual button to open my garage door. The sketch you refer to in a lot of the projects looks more like a program to me, where can I learn more about this language, come from an old perl programming background swo this is all new to me but very interesting. Also I recently upgraded firmware of sonoff to verions 1.6.0 does this impact the ability to reflash this particular unit?

        1. I’m using the relatively new 1 channel Smart Switch (#IMI60426001) which includes the ability to switch between inching (momentary) and latched (on/off). It works great for the garage door, but it is a bare board at this time. It will handle up to 32 VDC/AC for control and has dry contacts for up to 250 volts. It will require (or not at 24V on both sides) an enclosure. It is less than $8 US. I hope this helps, albeit a little late.

      2. You can use the IFTTT function if you have android box to run the IFTTT app or you can use IFTTT integration in OpenHab.

    3. looks like the itead team solved the problem with the new launch of their product the sonoff mini check it out yourself
      https://www.itead.cc/smart-home/sonoff-mini.html

  2. Hi,

    The github links don’t seam to work, i found the correct ones seam to be :
    https://github.com/SuperHouse/BasicOTABlink
    and
    https://github.com/SuperHouse/BasicOTARelay

    (without tv in the end)

    1. Oops, sorry! You’re right. I’ll fix the links in the post now.

  3. Hi it would be beneficial to add a fuse somehow, It worries me shoving things in walls etc. you could use temp. sensor but no point knowing its overheating if your away on holidays.
    daniel

  4. Hi,

    What would be the best way to add a fuse, if the power supply overheats or faults for some reason having devices like this could be a fire disaster. you could monitor is temperature but if your away that’s not going to be much help.

    I think I sent this twice sorry.
    kind regards Daniel

    1. Yes, good point, safety is very important for any mains-voltage project. Here in Australia all power circuits are required to have a circuit breaker, which is pretty much a universal rule anywhere around the world. So there should already be some level of protection. You could also add a fuse in line with the Sonoff yourself if you wanted to, probably at a lower rating than the fuse on the whole circuit since the circuit provides power to many devices in your house. Please get advice from a local electrician first before you do anything like this, because regulations are different for each country and I want to make sure you do it safely!

  5. Brilliant project. You mentioned that the pairing button could be used as another input, to act like a manual on/off switch? I am a bit weak on the coding side so could suggest how I could update the project files to reflect this?
    And how you are planning to Pat the Dog’ with this one?

    Again awesome project….

    1. Thanks Wayne 🙂

      Yes, the pairing button could be used as a manual on/off switch by changing the code to detect when it’s pressed. I’m working on a follow-up video with more advanced Sonoff tricks, such as replacing the flash memory chip and using more advanced firmware. I’ll also cover how to use the built-in button, and how to connect an external button so you can control the Sonoff manually from a wall plate.

  6. Thanks for the information Jon, I’m a long time follower of all you projects 🙂

    I had just made an ESP based relay but wasn’t too keen on connecting it to the mains!

    This looks like the perfect piece of kit.

    Thanks once again and keep up the good work!

    Ed

  7. Thanks for all your work and willingness to share your experience with the community. I have 10 of these devices that I’m messing around with using arendst’s code. I am very interested in your last post regarding connecting an external switch. I’m also working on connecting a momentary switch with the led backlight to the board. I don’t think that it is the same one that you used for your light switches, but it is very similar.

    I look forward to your next video.

    James

  8. I’ve got problem with my sonoff. When i pair it with my phone, it says ” device belongs to other user”.
    Does anyone knows what’s the problem ?

  9. Nice tutorial, thanks for that!
    Did you make progress on connecting the external switch? I’m thinking about this as well.
    I’m mainly interested in if the low voltage from the Sonoff would be enough for the common wall switches (as they would normally not switch these low currents) and, off course, safety.

  10. You talked about modifying the code so that the button could be used as an on/off script.

    Were you still going to do this?

    1. I’m also waiting for this tutorial. I think its cool to have it as a working toggle switch.

    2. Yes, I have all the parts now to film another Sonoff episode talking about using external switches and other variations to the basic setup. I’m finishing an episode about electric window mechanisms right now, which is nearly done.

  11. That is great news. I was going to share how I got mine working with arendst’s sketch and an LED momentary switch, but it would be better illustrated in one of your videos.

    1. It’s always good to see how different people approach the same problem, so don’t be shy about sharing your project! I’d love to see it

      1. Here is the links for my project.
        Switch – https://www.amazon.com/gp/product/B01C7CQHLO/ref=oh_aui_detailpage_o03_s00?ie=UTF8&psc=1

        Arendst’s Code – https://github.com/arendst/Sonoff-MQTT-OTA-Arduino/wiki

        Drawing – https://mail.mcmurphys.net:8443/home/james@mcmurphys.net/Briefcase/external_switch.pdf

        I removed the LED on the sonoff and soldered the wires for the external LED to the board. I also cut the long post for the reset switch so that I could run the 4 conductor wire out of the sonoff housing using the hole where the post was accessed.

        Let me know if you have any issues accessing the drawing.

  12. Hi, what an awesome find! Thanks for sharing! Your videos have always inspired!

  13. Hi Jon,
    Great video.
    I’ve been playing about with the ESP-01 for some time now and have built my own version of what the Sonoff module does.
    The Sonoff beats mine hands-down as it’s much more compact and totally self-contained (and cheaper than the cost of all of my individual components). I’ve just taken delivery of 2 Sonoff units and have set to and installed the Arduino IDE version of the O/S.
    I just have one question regarding which pin of the Sonoff/ESP8266 controls the relay. On my ESP-01 I manipulate the GPIO2 to switch my relay on and off.
    I’ve had a look at your sketch ‘BasicOTARelay’ and it would appear to be Pin 12 that activates the relay on the Sonoff board. Is that correct?
    I loaded my own sketch onto the Sonoff and all looks good. I can talk to it via a web browser and the serial output reports correctly. I can’t test it fully until I apply mains voltage but just need to be sure about pin12 first.
    Thanks once again for such a great article.

  14. @Jon

    Have you tried this on the Sonoff Dual? It’s a little different on the inside. I’ve also seen some traffic that is saying that the Dual has two processors???

    1. I’ve just received a Dual so I’ll have a look inside. From what I’ve read, the Dual has a different pin connected to the button so you need to use a jumper wire across specific parts of the PCB to put it into bootloader mode. I haven’t tried that myself yet though.

  15. […] They come with their own software on them which is cloud based but you can upload Sketches via the Ardino software just like you would with an Arduino. So I have a sketch written by Jonathan Oxer who runs the Youtube Channel SuperHouse and also Director at Freetronics. http://www.superhouse.tv/17-home-automation-control-with-sonoff-arduino-openhab-and-mqtt/ […]

  16. @Jon

    So, the itead forum has had some discussion about the Dual… http://support.iteadstudio.com/support/discussions/topics/11000006870/page/1?url_locale=

    At this point the only thing that I have been able to do is upload to the device. Jumping Pin 15 to ground indeed puts the ESP into program mode.

    Where I am confused is how they are actually talking to the Silicon Labs F330. The relays appear to be controlled by this secondary MCU.

    Looking forward to hearing what you decide to do with this device.

    treborjm87

  17. I enjoyed your You Tube video on Sonoff switches. I too have been playing with this model and a new model issued by Sonoff that is packaged with a male plug on the back and female socket on the front. I have reprogrammed them with aRest ported to arduino by Marco Schwartz. They now host a web page on my home network and do not talk to any cloud servers.

  18. Great to find this project! I had been trying to build MQTT units for power switching out of ESP12s so having a cheap starting point that is CE certified was a great start.

    I’m trying to avoid bricking the Sonoff Dual that i’ve started with, and have got as far as setting up the Arduino IDE with ESP8266 libraries, but don’t seem to be able to find advised board choice/Arduino IDE settings for this.

    To complicate things I’m wanting to add OTA support. There’s some useful stuff in http://support.iteadstudio.com/support/discussions/topics/11000006870/page/1 where there’s an image of the point to attach the jumper that’s grounded to get the Dual into programming mode.

    So guess what I’m asking is, has anyone been reprogramming the Dual, and if so could they share their Arduino IDE board settings?

  19. You inspired me to buy a couple of these things. I took your sketch and added a couple features that I like. Hope others will too 😉

    https://github.com/PepijnVisser/Sonoff/blob/master/Sonoff_1_0_2.ino

  20. Have set this up and it is working really well.
    Where I am a little stuck in OTA updating from a different network segment. My WiFi and Wired networks run on different subnets, so in order to update I need to put my PC on the Wireless subnet for it to come up in the Network Ports list.

    Is there a way you are aware of I can scan the Wireless subnet from the Wired subnet?
    No amount of googling has pointed me anywhere near the right direction.

  21. The Duals has 12 jumper pins instead of 5. wich one do we need to upload the sketch?
    On the above forum there is a example with mqtt. its not directly talking to the gpio pins. but for me that is ok. I will use them as replacement for my KaKu switches.

    1. The single port is working fine. is there nobody using the dual ones?
      didn’t had much trouble finding the example code. but can’t upload it.

  22. Sorry if this is a stupid question but i’m really new to arduino. In regards to the relay code, both the payloads are 0. Should the first one be a 1?

  23. oh, should I change 49 to 1 and 48 to 0?

  24. of forget my last comments got it to work fine. that’s if my comments ever come out of moderation…….

  25. Just out of interest, do you have to define the clientid in the sketch? Can I remove this? If so what lines in total do I need to remove?

    1. Yes, the client needs to supply a client ID to the MQTT broker. That’s how the broker can tell different clients apart, and know which clients have received which messages. It probably depends on the broker, but I’ve found that with Mosquitto it doesn’t like having multiple clients with the same ID. It does wierd things like only send messages to one of the clients, and the other client never sees it. The good thing is that there’s nothing magic about the client ID: it can be anything, it just has to be unique. So you can use the end of the MAC address of the node to generate the client ID automatically, for example. That way your sketch can be the same in each node, and they all end up with unique IDs.

      1. Thanks for the reply Jon. I used your sketch to flash the sonoff then created a homekit accessory.js file to control it (via HAP-NodeJS on my pi3) but for the life of me couldn’t get it to work.

        I could control it via manual commands in mosquitto but the commands via the home app/siri wouldn’t turn it on. I then looked at the topic via mosquitto_sub -v -t ‘#’ and the “1” and “0” commands were both coming up when doing via home app and mosquitto but only mosquitto was actually turning it on. I was stumped.

        I initially thought the client id in the sketch needed to be the same as the client id in the accessory.js file. But decided to change it in the accessory.js to something different and hey presto, it worked!

  26. […] To learn about how to install new firmware, see SuperHouseTV Episode #17: Home automation control with Sonoff, Arduino, MQTT, and OpenHAB. […]

  27. Help needed:

    I’ve setup a homekit fan accessory using a raspberry pi, HAP-NodeJS, MQTT and a sonoff.

    It works fine but the one problem i’ve got with it is the status on the home app not showing correctly. When I turn the fan accessory ON the status in the home app my iOS device is correct and shows it’s ON.

    BUT if I leave it on for a while then go back into the home app is shows it’s OFF even though the accessory is still ON???

    I switch it ON then OFF again and it turns OFF.

    I used this code here for the .js file.

    https://github.com/jat80/ESP8266/blob/master/Home%20Automation/Part%208/relayLight_accessory.js

    But modified a few lines to make it look like a fan accessory.
    I don’t really have any experience with javascript (or coding in general for that matter) so don’t know if there is something else in the code that could be the problem with the status not showing correctly.

    Any help would be appreciated.

    Thanks!

    1. Sorry, I haven’t used Homekit so I don’t think I can help with that. Perhaps someone else has some insight?

      1. No problem. Thanks anyway.

        I’ve managed to fix the Slampher sonoff problem with the info on Peter Scargill’s website. Had to switch a zero ohm resistor over so you can put it into programming mode. After that I flashed it the same way as the sonoff.

  28. i’m trying to hack the Slampher sonoff. I’ve already done the regular sonoff, and tried the same method with the Slampher but getting these errors:

    Global variables use 33,408 bytes (40%) of dynamic memory, leaving 48,512 bytes for local variables. Maximum is 81,920 bytes.
    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed

    Any idea what is wrong?

    1. JT,

      Got the same error about espcomm
      This mean the device isn’t in programming mode.
      press and hold the button before connecting power. after this hold it for a few seconds. now try again.
      After this when using the serial monitor don’t forget to set it to 115200 baud

  29. also any help on my previous post would be awesome as well. Thanks.

  30. Is it possible to read state of switch?

  31. I have tried in multiple different ways but cannot get the OTARelay.ino file to compile. When trying it in Linux I get the following error.
    /home/charles/Downloads/BasicOTARelay-master/BasicOTARelay/BasicOTARelay.ino:14:26: fatal error: PubSubClient.h: No such file or directory
    #include
    ^
    compilation terminated.
    Using library ESP8266WiFi at version 1.0 in folder: /root/.arduino15/packages/esp8266/hardware/esp8266/2.3.0/libraries/ESP8266WiFi
    Using library ESP8266mDNS in folder: /root/.arduino15/packages/esp8266/hardware/esp8266/2.3.0/libraries/ESP8266mDNS (legacy)
    Using library ArduinoOTA at version 1.0 in folder: /root/.arduino15/packages/esp8266/hardware/esp8266/2.3.0/libraries/ArduinoOTA
    exit status 1
    Error compiling for board Generic ESP8266 Module.

    I also tried it in Windows but got similar errors complaining about missing directories or files. I was able to successfully upload the blink ino.

    Thanks

    1. You need to make sure you have installed the pubsubclient library in your applicable Arduino Library folder first. Download it from github.

      https://github.com/knolleary/pubsubclient

    2. In the Arduino IDE, go to:
      Sketch > Include Library > Manage Libraries
      in the “Filter your search” field, type ‘pub’.
      You will see the “PubSubClient” by Nick O’Leary. Simply highlight it and click install.

  32. Thanks for the great tutorial!
    I am just getting started in this and am a total beginner.
    Just installed MQTT and Openhab2 on a rapberry pi 3 and will flash my sonoff switches and try to connect them to openhab2.
    Are there any good step by step guides on how to link the sonoff to openhab and setup a UI in the phone?
    The learning curve on Openhab seems quite steep =/

  33. Hi I have refashed using BasicOTARelay from superhouse
    question is I need to reflash again how do you do that please

    nigel

    1. sorry i have sorted it my wiring was loose

  34. Jon, I’ve been playing with the OTA config but haven’t had much luck with uploading new sketches. Have you run into any scenarios where the IDE just returns a ‘no response’ message when trying to upload?
    I can see the devices on the network and in the IDE under the port selection menu.

  35. Loving the videos and explanations, was going to put together my own diy ESP8266 module until I saw these and definitely agree, for the money the Sonoff can’t be beat.

    I’ve got as far as uploading the simple blinking program, which works and have uploaded the BasicOTARelay – this is where I’m stumped and hoping you/someone could help.. the upload is 100% completed.. I’ve triple checked my wifi details.. assuming these are correct, i should see it connected with an IP address on my Router? (obviously I don’t – i was under the impression that if the upload was 100% then I’d covered all dependences, like PubSubClient.. even if I’ve got the mqtt side of things wrong.. I should still at least see the sonoff on my network with an ip add?)

    I know this sounds like a daft question 🙂

    Cheers

    Stan

  36. Great episode, thnx!

    I have a reasonable amount of experience with Arduino and ESP8266 so thought I’d have a go at the Sonoff hack. Everything worked as expected in your video, the sketch compilied, the Arduini IDE indicated a 100% upload, no errors, but after reset the LED did not blink.

    I tried the same Blink sketch on:
    * Another generic ESP8266 (flash with FTDI) – success
    * Arduino UNO and WEMOS D1 Mini – success
    * Three sperate Sonoff basic swicth units – fail – upload OK but no response from LED

    I also tried a number of different pins (inlcuding attaching external LED to GPIO14 + trying to swicth the relay on GPIO12) with no success.

    Have you come across this issue lately? From a brief internet search it seems to be an issue happening with recent Sonoff units (approx last six months?).

    Any advice much appreciated.

    thnx
    billd

    1. Hi Billd,

      I haven’t bought any new Sonoffs for quite a while, so I don’t have any with the current revision hardware / firmware. The update process seems to have changed with the v1.6 firmware. I ordered some new ones today so hopefully I’ll have them in a week or two, so I can try it for myself.

  37. Bill

    I just had the same problem and found he answer under the “Tools”setup.

    Set the “BuiltIn Led:” to 1

    This worked for me.

    Jonathan, great videos, really helping me get into this.

    Mark

  38. Hello Jonathan,

    Thank you for the useful information. Once you install the new software, would you still be able to control the device through Google Home? Sonoff devices are now advertised as Google Home comptible.

    Marco

  39. Hi I wondered if you could help.

    I was writing a program for the Sonoff basic that would allow me to send it commands using the UDP protocol. Using the serial monitor it said it was receiving the commands but the relay wasn’t firing. I also tried it with the LED instead of the relay and it still wouldn’t work. I also tried to add the relay to the OTABlink program provided and that two wasn’t working. I would really appreciate the help.

    Josh

  40. Thank your for the excellent vlog, I watched it a couple of months back and instantly order a sonoff as it appeared that it was the exact doo hickey I needed, also order an ESP8266 development board.

    Ultimately my desire is to use some device to monitor whether external security lights have been turned on.

    Well my sonoff came and after much fussing about I think I broke it, bugger, your directions at 25:17 indicated to use DIO for flashing the firmware. I eventually came across https://github.com/arendst/Sonoff-Tasmota/wiki/Theo's-Tasmota-Tips which indicates that some sonoffs are using a ESP8285 chip and you need to use DOUT and using DIO will brick the device. I don’t know whether that is the case with my sonoff as I cannot tell what chip I have, the teeny teeny writing on the chip is too teeny but that site says that DOUT will work with both the ESP2866 and the ESP8285.

    So whilst waiting for a new sonoff I played with my ESP8266 development board, your directions and descriptions for setting up the Arduino and loading fw allowed me to get OTARelay running on my development board and ultimately MQTT talking to it.

    Issues that I had and ultimately resolved or got around were:

    Bricked my first sonoff that may have been because of using DIO or may have been something else entirely, will see when my next sonoff turns up

    MQTT was a bit of an issue tried a package from http://mirror.lagoon.nc/pub/eclipse/mosquitto/binary/win64/ that didn’t work mosquitto didn’t seem to run, so found a package mosquitto-1.4.9-install-cygwin.exe and installed that it works until you reboot and then when you run mosquitto_pub.exe the pc tells you it can’t run, a reinstall fixes issue until the next reboot – still gotta fix that.

    Other stuff that came across that I thought useful:
    https://www.youtube.com/watch?v=eEWbmIY8EcY Using arduino as a serial convertor
    https://github.com/arendst/Sonoff-Tasmota/wiki/Theo's-Tasmota-Tips DOUT tip for ESP8285 chip
    https://arduino-esp8266.readthedocs.io/en/latest/faq/a01-espcomm_sync-failed.html about comms failures
    http://www.steves-internet-guide.com/install-mosquitto-broker/ directions for installing mosquitto

  41. Is it possible to connect a manual on/off switch to the Basic Sonoff keeping the original eWeLink software?

    1. Yes, but it will need to be a momentary switch that is only closed while you press it, not an alternate-action switch like a normal light switch. The factory firmware uses the built-in button to toggle the output, so if you wire an external momentary switch in parallel with the button it will also trigger an output change.

      1. Another question: instead of using an external momentary switch, maybe I could disrupt the source power? For example, I have a light outside my house, which has a regular switch by the front door. I would add a Sonoff device between the switch and the lamp (to get the regular funcionality of the Sonoff, using the phone app etc, as it is intended). Sure, the switch would have to be in the ON position so that current was supplied to the light (via the Sonoff). If I wanted to manually turn OFF the light (NOT using the phone app), I would manually turn off the regular switch (stopping the current to the Sonoff and the light). OK.
        But when I maually turn ON the regular switch, what would be the status of the Sonoff device?
        a) does it remember the last status (if the relay was ON of OFF)?
        b) is it always OFF (when power is first supplied)?
        c) does it always turn ON (when the power is supplied)?
        Thanks for any info you can give about this!

        1. Ihi Julia’s. I was thinking the same thing at one time.
          Requested tasmota feature to default to on when powered up so that light switch could operate the device.
          The feature was added and it works.
          I was thinking that openhab could be used to restore the previous state after a power failure.
          Tasmota is now quite configurable and can be set up to do any of the states you mentioned.
          Lack of Australian compliance is the concern with using Sonoff

  42. Hi Jonathan!
    I wanted to know if there’s any way to log the temperature and humidity data onto a google sheet or something. Will be really helpful. I would prefer using the original firmware, just wanted a way to get this logged. Thanks!

  43. the ITEAD team has come up with a solution for this. the sonoff mini it has a ports for the rocker switch also but right now they are selling only 1 gang model i will provide the link to the product below

    https://www.itead.cc/smart-home/sonoff-mini.html

    1. I’ve already recorded a video about this, it should be up soon but I’ve been wanting to finish part 2 of the WiFi video first. Otherwise they’ll be out of order!

Leave a Reply

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