DIY Smart Home

DIY Smart Home Sensors with Arduino, MySensors and OpenHAB

James Bruce 16-12-2015

Smart home sensors cost a ridiculous amount of money. At $60-$100 just for a motion detector or humidity sensor, wiring a whole house becomes the domain of those with silly amounts of disposable income. Let’s build our own.


Luckily, the hard work has already been done by the fine folks behind Today I’ll be showing you how to use the MySensors framework to create a cheap array of smart home sensors that can feed into an OpenHAB install (see our guide to Getting Started with OpenHAB on Raspberry Pi) Getting Started with OpenHAB Home Automation on Raspberry Pi OpenHAB is a mature, open source home automation platform that runs on a variety of hardware and is protocol agnostic, meaning it can connect to nearly any home automation hardware on the market today. Read More . I’m assuming you have a working MQTT server already, and understand the basics of the MQTT messaging format; if not, be sure to read the follow up to the OpenHAB guide, which includes instructions for installing an MQTT server OpenHAB Beginner's Guide Part 2: ZWave, MQTT, Rules and Charting OpenHAB, the open source home automation software, far exceeds the capabilities of other home automation systems on the market – but it's not easy to get set up. In fact, it can be downright frustrating. Read More .

Although I’ll be dealing specifically with forwarding the MySensors data from a network of Arduinos, using MQTT, to an OpenHAB install, I should point out that the MySensors framework can feed into a number of different home automation controllers. I’ve presented this here as a complete solution that works for me, but please check out the MySensors site as you might find it also suits your similar purpose, but using slightly different hardware or a different messaging protocol. It’s incredibly versatile.

mysensors hardware -1

The hardware cost for my setup is less than $10 per node (a little more for the gateway), but additional sensors and actuators can be added for very little (the DHT11 humidity and temperature sensor for instance is about $1 each; a high voltage relay is around $3).

What We’re Making

The basic idea is that rather than adding onto our existing crowded local network using unreliable Wi-Fi or expensive Ethernet shields, we create an entirely separate mesh-capable network just for the Arduinos; then bridge that to the local network using a single gateway node, which has both an Ethernet connection and a radio connection to the other Arduinos. So we’re making a couple of sensor nodes, which gather data; and a gateway node, which relays that data onto the OpenHAB server.


Again, this is what works for me, because my Wi-Fi reception is so horrendous and I don’t want to clutter it with unnecessary data. If you’re happy with Wi-Fi, look at using the low cost ESP8266 Arduino-compatible Meet the Arduino Killer: ESP8266 What if I told you a there's an Arduino-compatible dev board with built-in Wi-Fi for less than $10? Well, there is. Read More with built-in Wi-Fi boards – MySensors supports those too.

Important Note for El Capitan Users and Arduino Clones: Apple managed to break the serial drivers used to communicate with a number of Arduino clone boards in the latest release of El Capitan thanks to new security measures. To see if you’re affected, look at your board and the chip closest the USB port. If it says CH340, you’re affected by this. Follow the instructions here to disable driver kext signing, install CH340 serial drivers again.

Components Needed

For the gateway, you’ll need:

  • Arduino Uno
  • Ethernet Shield (W5100 based)
  • NRF24L01 module – I’ve used the +PA+LNA versions throughout, which have an increased range of up to 1km. The wiring is the same whichever you choose.

For each sensor node:

  • Arduino Uno
  • NRF24L01 module
  • Sensors (to start with, I’d suggest a temperature and humidity DHT11 or DHT22 module)

Additional / Optional:

  • 10uF capacitors, one for each RF module you have (the link is for a pack of 50!)
  • Power Supply with 5v and 3.3v output (YwRobot MB102 works well and they’re $1 each) – required if using a clone Arduino. You’ll also need a 9-12v DC power supply for these.
  • Prototyping Shields, or short male-female jumper wires.

Working with NRF24L01 Modules

Let’s start with the NRF24L01 modules, as they’re most complex part of the project. I went for the more expensive, longer range version of these: technically known as NRF24L01+PA+LNA. They come with an on-board signal amplification circuit and antenna connection, though I suggest you try the cheaper non-antenna version of the modules first if you have a normal home with regular walls, not the meter-thick solid stone kind of wall that I do. The claimed range of these is about a kilometer, more than enough for me put into the garden shed.

However, these things are really difficult to work with; if you go ahead and plug everything in without reading these tips first, you will be disappointed.

  • The module needs 3.3v input power to the VCC pin – not 5v. If you put in 5v, you’ll fry it.
  • Solder a 10uF capacitor across the VCC/GND terminals. The solid grey line on the capacitor indicates the negative/GND side.
  • Use short, high quality jump cables; or better still, solder them directly to a prototyping shield to keep cable length to a minimum and solid connections.
  • If you’re using an Arduino clone, the voltage regulator doesn’t quite provide enough for them on 3.3v pin – you’ll need to use an external power supply board (linked above), available for about $1 each. These provide a stable 3.3v. If you’re using an original Arduino brand Uno, this doesn’t appear to be an issue.

I strongly suggest you do some basic tests first just to establish your radio is working. Wire two radios up as shown on the MySensors page. It doesn’t matter that their diagram show Arduino Micro boards – the same pin numbers are used. Note that the diagram shows the NRF24L01 from the top; you’ll actually be plugging things in from the underside. Mentally adjust accordingly. Ignore the gray IRQ pin, it’s not currently used. In summary:

  • VCC goes to 3.3v on your external power supply
  • GND goes to common ground rail
  • CE to pin 9
  • CSN/CS to pin 10
  • MOSI to pin 11
  • MISO to pin 12
  • SCK to pin 13

wiring from mysensors page

You’ll need two nodes fully wired to test with. Download the RF24 library and load the simplest Getting Started example. Power on both modules, but leave one connected over USB and open up the serial console. Type “T” and send, to switch it into transmit mode, at which point you should get debug messages saying it’s successfully pinging a message to the other node.

Building the MySensors MQTT Client Gateway

Ok, now that we know the RF24 radios are wired in and working correctly, go ahead and download the development branch of MySensors Arduino package. This tutorial was written using version 1.5, but should be ok with later versions too. We’re using the development branch because at the time of writing, the MQTT client gateway isn’t yet a part of the main package.

Although there is MQTTGateway available in the master branch, it acts as a server too, which we don’t want because we already have a stable MQTT server running on the Raspberry Pi. We just want to forward the MySensors data onto that. Again, if this isn’t what you want – if you’d rather not use MQTT at all – then look at EthernetGateway or SerialGateway, both of which are also compatible with OpenHAB.


It’s worth noting that the download package doesn’t just include essential MySensors files, it also includes compatible libraries needed for every possible sensor. To avoid conflicts, I’d suggest just backing up your entire current libraries folder and replacing it all with the ones in the download package.

Wiring for the gateway is a little different; once you have your Ethernet shield, use the following pins for the radio module:

  • CE to pin 5
  • CSN to pin 6
  • SCK to pin A0
  • MOSI to pin A1
  • MISO to pin A2

You also need to enable the #define SOFTSPI line in the libraries/mySensors/MyConfig.h file. Do this by removing the // to uncomment it, it’s around line 309 on mine.

We need to do this because both the radio module and network shield use SPI, and they’re incompatible; so we just shift the radio module SPI to some other pins and perform SPI communication in software instead (hence, soft SPI).

Load up the MySensors/GatewayW5100MQTTClient sketch. If you don’t see this under the MySensors menu, you don’t have the development branch installed. Use the link provided above to re-download the whole library.

mysensors gateway

You’ll need to define a static IP address for the controller, the IP of your network router and subnet, and the IP address of your existing MQTT server. Feel free to modify the topic prefixes too if you like. Upload, and plug that thing into the network. Briefly check the Serial console for any glaring errors like being unable to connect to your MQTT server, otherwise set it aside (but leave it on).

ip addresses to change

Building the Sensor Nodes

First, comment out that #define SOFTSPI line in the MyConfig.h file again by putting the // back at the start. It’s only needed for the gateway – we’re using the standard NRF24L01 wiring for the sensor nodes, which use hardware SPI. If you need reminding:

  • VCC goes to 3.3v on your external power supply (or on the Arduino itself if it’s an original and not a clone)
  • GND goes to common ground rail
  • CE to pin 9
  • CSN/CS to pin 10
  • MOSI to pin 11
  • MISO to pin 12
  • SCK to pin 13

Next, wire up your choice of sensor; I use DHT11 moisture and temperature sensor for testing, but if you scroll down to the sensors and actuators list on the sidebar of the MySensors page, you’ll find a huge selection of other options: doors, rain gauge, light, motion, even RFID – and loads more. You can see I also added a relay to the node pictured below, but more on that later.

mysensors hardware -2

Finally, load up the HumiditySensor example from the MySensors menu and add the following line immediately after the comments.

#define MY_NODE_ID 2

Since we’re using a special version of the controller which just forwards things onto our own MQTT server, it doesn’t have the standard controller feature that would automatically assign node IDs to each new node. Instead we’re just going to manually define it each time. Note down this number somewhere for your own records, and change it for each node.

Enable the debug output too:

#define MY_DEBUG

Finally, check the data pin of your DHT11 sensor is correct.


Then, upload!

It’s worth opening up the serial console to take a look. The crucial bit to look is st=, which is the status of the message. st=fail means the message wasn’t sent. It’s possible you haven’t defined a unique node ID, or that your gateway is offline. I faked these failures by simply unplugging the gateway:


If everything is working, you should start to see some data readings come into your MQTT server. Putting those into OpenHAB is outside the scope of this tutorial, but was covered in part 2 of the OpenHAB guide OpenHAB Beginner's Guide Part 2: ZWave, MQTT, Rules and Charting OpenHAB, the open source home automation software, far exceeds the capabilities of other home automation systems on the market – but it's not easy to get set up. In fact, it can be downright frustrating. Read More so you can refer back there.

Combining Sensor Code

Although getting a single sensor node up and running is relatively simple, it gets a little trickier when you want to add multiple sensors to each node. Essentially you’re going to blend together the code snippets from from two different examples. The easiest way to show you this is by example with a video! Here I’m combining our basic humidity sensor with a relay.

You can find the completed code for humidity sensor and relay here, which has already been modified with a non-blocking loop as I mentioned in the video. To learn more about the MQTT command structure needed to activate the relay, check the Serial API –but suffice to say the following channel controls the first relay in the code I’ve given (with a message body of 0 or 1):


Your only limitation now is the amount of memory on the Arduino, and I’ll say this – the most reliable sensors in my smart home are not the commercial Z-Wave modules that cost $80, but the MySensors custom ones.

I’ll end it there today, but if you have problems you can ask away in the comments or the very active user forums of MySensors. Will you be putting together your own cheap sensor nodes? How is your smart home coming?

Related topics: Arduino, Smart Sensor.

Affiliate Disclosure: By buying the products we recommend, you help keep the site alive. Read more.

Whatsapp Pinterest

Leave a Reply

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

  1. Mic
    November 1, 2016 at 7:15 pm

    sorry, but i don't have HumiditySensor sketch in folder "MySensors-development".

  2. KFash
    October 11, 2016 at 9:08 pm

    This is very helpful. but what if i av an LED at those sensor nodes that i want to control? how do i go about it?

  3. Foad
    August 9, 2016 at 2:04 pm


    Can I program my sensors using MySensors Main Package and program my MQTT Client using Development branch?
    Are they compatible?

  4. Foad
    August 9, 2016 at 11:49 am

    Hi James,

    Thank you for your tutorial.

    My question is about MQTT protocol. Should all nodes in the network connected directly to the MQTT server? If some nodes are not directly in the range of MQTT server, how their messages carried to the server? Can other nodes be used as Repeater Nodes? How MQTT can handle long distances between sender and receiver nodes?

    • James Bruce
      August 9, 2016 at 11:55 am

      MQTT is only used after the messages reach the bridge, so the distance doesn't matter - the bridge is connected directly to the network.

      Most of your question then relates to the protocol used internally by MySensors, which I'm not an expert on, but yes, you can setup certain nodes to act as a repeater for other nodes. The network works itself out in a mesh to ensure deliverability.

      • Foad
        August 9, 2016 at 1:18 pm

        Thank you for your explanation, I got my answer.

  5. Loral
    July 1, 2016 at 7:33 pm


    Thanks again for another very helpful post. I just got done getting the stuff I needed together and getting my own setup up and going thanks to this article! I am really enjoying the combination of OpenHAB and MySensors.

    I have one question though. Do you know if the NRF24L01 and the +PA+LNA modules can be mixed and matched? Will the regular modules and the longer range versions talk to each other? I would like to use one of the long range modules on my gateway in the house and on some sensors around my yard that are a fair distance from my house. But then to save some money I was wondering if I could use the regular modules around the rest of my house. My concern is if I use regular modules on the sensors in my house if they will still be able to communicate with the longer range version module I have on my gateway?

    • James Bruce
      July 4, 2016 at 6:29 am

      I don't think they can be mixed, as the communication is a 2-way thing, but honestly I have no idea.

    • Alex
      July 5, 2016 at 6:47 pm

      I have the regular modules on all my sensors and the long range version on my gateway. I have only recorded sensor data though i.e. I have not tried sending commands to sensor nodes.

  6. Jack Cote
    May 4, 2016 at 12:18 am

    Hello James,
    Thanks so much for the super useful OpenHab tutorials. I can't wait to receive my components. I have a question regarding transmission security... If I wanted to control my garage door using a relay like you've set it up here,... shouldn't I be concerned with security? Am I wrong? Would you have recommendation(s) to secure those transmission commands?

    Again, many thanks

  7. Matt
    February 12, 2016 at 8:35 am

    Hi James,

    I've finally recieved my bits from China and started putting toegther my sensors, I've almost done it. I have a ethernet mqtt client up and running, I also have the temp sensor sending data to my mqtt broker running on the raspberry pi as described here. I am able to subscribe in MQTT fx and see the temp and humidity coming in, which is great. The only bit I'm now struggling with is getting that data into Openhab.

    I have added the following to my items file

    Number Bed_Temp "Bedroom Temperature [%.1f °C]" {mqtt="<[matt_broker:/mygateway1-out/2/1/1/0/0:state:default]"}

    Then this to my sitemap

    Text item=Bed_Temp

    I'm getting the following from the openhab logfile

    2016-02-12 08:26:09.142 [DEBUG] [b.mqtt.internal.MqttItemConfig] - Loaded MQTT config for item 'Bed_Temp' : 1 subscribers, 0 publishers
    2016-02-12 08:26:09.143 [DEBUG] [o.i.t.m.i.MqttBrokerConnection] - Starting message consumer for broker 'matt_broker' on topic '/mygateway1-out/2/1/1/0/0'

    I'm a bit stuck, it feels so close yet so far! Thanks for any help Matt

    • James
      February 12, 2016 at 9:08 am

      Hi Matt. I'm almost certain you shouldn't have that slash at the beginning of your channel name in the items file. /mygateway1 is actually adding a blank root level channel before mygateway1, compared to just mygateway1. Remove that and try again.

  8. mark
    February 4, 2016 at 3:13 am

    I tried distance example from Mysensors. Here is the output I get on node connected to distance sensor
    Ping: 176 cm
    req id
    send: 255-255-0-0 s=255,c=3,t=3,pt=0,l=0,sg=0,st=ok:

    the gateway also gets 255-255-0-0 s=255,c=3,t=3,pt=0,l=0,sg=0,st=ok:

    any idea why the payLoad pt=0 always ?

    I tried substituting constant value in statement


    as gw.send(msg.set(123));

    I still get pt=0

    Help is much appreciated.

    • James Bruce
      February 4, 2016 at 10:11 am

      Hi Mark, I think that message actually means it's "requesting an ID" from the gateway, and not getting one. The MQTT gateway doesn't act as a controller, which would give out IDs, so you need to manually specify the ID in your sensor sketch. Try adding the following line before the MySensors library is loaded:

      #define MY_NODE_ID 2

      (must be BEFORE the library gets pulled in)

  9. Raj
    January 29, 2016 at 3:31 am

    James ...I tried using the getting started program as suggested by you to check the communication using RF24 Library. But I get error as

    Now sending 5867...failed.

    Failed, response timed out.

    Now sending 7142...failed.

    Failed, response timed out.

    I then added capacitor of value 47microF ..but I still get the same error . any idea what I am doing wrong ?

    • James Bruce
      January 29, 2016 at 9:30 am

      Are you powering them with an external 3.3v power supply?

      • Raj
        January 29, 2016 at 9:22 pm

        I have UNO connected to laptop USB and acts as Transmitter and check the status on Serial I/O window ?.

        For receiver , I have Nano connected to iphone charger. The capacitor I am using is 47microFared NOT 4.7microFared. Does this make any difference ?

        • James Bruce
          January 30, 2016 at 9:36 am

          Is it an official Arduino Uno or a clone? Try a 10 uF if you don't have 4.7 - I haven't seen reference to 47 uF anywhere else, so I assume there's a reason for that.

        • Raj
          February 1, 2016 at 6:22 pm

          James ..Not sure clone or Official . Does this make a difference ?. I soldered the 4.7micro Fared capacitor b/w GND and VCC of mudule. Made sure to connect GND of capacitor to GND of Module. Still same message

          Now sending 5867…failed.

          Failed, response timed out.

          Now sending 7142…failed.

          Any idea what could be causing this ? Does using jumper cables make a difference. I am desperate to get this working as I need to get started on a project . Any help is greatly appreciated.

        • James Bruce
          February 1, 2016 at 7:54 pm

          You may need an external 3.3v supply then. I needed to use external supplies for non-original Arduino's, so it's likely that. Check the link above.

        • Raj
          February 3, 2016 at 4:20 am

          James...did not give up yet and got some working. But still an issues. One of the node (UNO + RF Module) can only transmit but cannot receive while other node (Nano + RF module ) can receive and transmit. I was able to confirm this by opening both COM port at the same time. Any idea how to resolve this issue ?.

  10. Astrofotograf
    January 27, 2016 at 1:56 pm

    Is there a reason why you use 10µF capacitors? The mysensors website suggests 4.7µF

    • James Bruce
      January 27, 2016 at 2:00 pm

      I couldn't find 4.7, somewhere else suggested 10 would be fine. I don't think it makes a difference, but I might be wrong.

      • Astrofotograf
        January 27, 2016 at 2:13 pm

        Ah okay, thanks

  11. Raj
    January 26, 2016 at 4:36 pm

    Great Tutorials James . Just few questions.

    1. How does the Node with Humidifier sensor know where to send the data ?. In the code for GatewayW5100MQTTClient , I don't see any code which is processing the data from sensor node ?.
    2. I have MQQT and Openhab running on Raspberry PI. How to make the sensor node send data to Raspberry PI ?.

    Again thanks for the great tutorials

    • James Bruce
      January 26, 2016 at 4:40 pm

      Hi Raj. The Gateway doesn't perform any processing - it just forwards packets from the MySensors network onto MQTT. It's just a dumb bridge.

      Check out part 2 of my OpenHAB guide to learn about how to connect MQTT to OpenHAB: //

      • Raj
        January 26, 2016 at 6:32 pm

        Thank James for the speedy response. Looks like I din't do a god job of explaining my requirements.

        In the gateway file we have the below code...

        // Set this nodes subscripe and publish topic prefix
        #define MY_MQTT_PUBLISH_TOPIC_PREFIX "mygateway1-out"
        #define MY_MQTT_SUBSCRIBE_TOPIC_PREFIX "mygateway1-in"

        // Set MQTT client id
        #define MY_MQTT_CLIENT_ID "mysensors-1"

        1. Assume I have 2 sensors , S1 and S2 and gateway G1. I want S1 to publish to topic home/s1 and S2 to publish message to topic home/s2. How to accomplish this ?

        2. When Gateway(G1) receives the message from controller(OpenHab)triggered
        by user for home/s1 , I want only sensor S1 to receive and trigger some action (like led ON). How to accomplish this ?

        3. When Gateway(G1) receives the message from controller(OpenHab)triggered
        by user for home/s2 , I want only sensor S2 to receive and trigger some action (like start Servo). How to accomplish this ?

        where to make code changes for this requirement ?.

        Thanks in advance for your help

        • James Bruce
          January 26, 2016 at 6:58 pm

          1. Change the topics prefixes to "home".
          2/3. Read the Serial.API documentation for further details on how to control a relay. You need to use the specified MySensors addresses, you cant just make those up.

  12. Matt
    January 17, 2016 at 11:03 am

    Hi James, Just comparing your build with mysenors, and wondering why you choose the uno over the nano board? My understanding is the nano doesn't need the extra power supply? You state in your instructions above that the uno board needs the power supply? I'm a little unclear why as I assumed it would take power directly from the usb connector on the board?

    But I'm sure you have sound reasons, but I'm just a little unclear about them, any advice would be much appreciated.

    • James Bruce
      January 17, 2016 at 3:06 pm

      No reason - I have a stash of Unos, no Nanos. However, that isn't the power issue. I think the added power is needed by the long range transmitters - if you use standard modules you probably wont have that problem on either board. Really, no difference in using Uno or Nano, but most people are more familiar with Unos.

  13. Matt
    January 14, 2016 at 10:59 pm

    Hi James,

    I'm going to follow your tutorial, but I'm looking for a good place in the UK to buy the components, but its a bit overwhelming, so any suggestions would be much appreciated.

    • James Bruce
      January 15, 2016 at 9:22 am

      Hi Matt, I'm in the UK too. I use almost exclusively for parts now. Many of the sellers will also list on eBay UK, but ultimately they still ship from China. Unless you need something desperately quickly, there isn't anywhere good located in the UK; you're just paying the middle man for their staff overheads, VAT and import charges.

      • Matt
        January 15, 2016 at 8:20 pm

        Thanks James, I guessed you must be in the UK, some great projects, I've been following your guide into setting up openHab :-) so thanks. I guessing it takes quite a while for delivery from AliExpress?

        • James Bruce
          January 18, 2016 at 10:14 am

          I'd say average is 2 weeks, but anywhere up to a month if you're really unlucky. Once after waiting 2 weeks, I traced the package to Heathrow, then when it didn't turn up after another 2 weeks, the seller sent out another package free of charge. Of course, the original one then turned up too ;)

  14. Fredrik
    January 10, 2016 at 2:52 pm

    First i want to begin with saying that II really love your tutorials, i have had loots of use for the OpenHAB ones.
    For the mysensors I have ordered some stuff from ebay to build some sensors but it takes some time for it to arrive but I am sure i will have some use of your tutorial i this cases also.

    A suggestion from my side is to create a tutorial where you use openhab with mysensors and combining this with a small simple display that you can have in your house to display data about for example temperature including max and min temp and maybe some more good things.
    The reason for this is to get some more knowledge about how to also send data all the way from openhab to a "mysensors display" since i think the integration between openhab and mysensors are a bit difficult.

    • James Bruce
      January 15, 2016 at 9:27 am

      Hi Fredrik, I think a display output is an excellent idea, I'll add it to my list of stuff to do. However, this would be more of an OpenHAB thing, since any dataset within OpenHAB will work. If you mean a bit of hardware on the MySensors side would be the display, I'd recommend against that. I dont think MySensors itself supports a display, though there are some great display/dashboards for OpenHAB. Once you have the MySensors data into OpenHAB you can display it anywhere, along with your other OpenHAB data.

  15. mike
    December 25, 2015 at 5:51 pm

    I've open an issue on github:

    do you have an idea please ?

    thanks in advance

    happy holidays

    • James Bruce
      January 15, 2016 at 9:24 am

      Sorry Mike, just seen this, though I don't have a clue what the problem might have been. I notice the issue is closed - did you find a solution?

  16. mike
    December 23, 2015 at 8:25 pm

    Thanks for your post !
    I'm starting work with mysensors and it's very powerfull.
    The mysensors's logic is hard to understand, but it's good for me now...