Posted on

#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: www.itead.cc/sonoff-wifi-wireless-switch.html (basic version)

Sonoff TH: https://www.itead.cc/sonoff-th.html (Temperature / Humidity version)

Slampher: www.itead.cc/slampher-wifi-wireless-light-holder.html (lamp holder version)

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.

52 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. 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

Leave a Reply

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