💬 Relay

  • Contest Winner


    I only wanted to raise the fact void receive(const MyMessage &message) may lead to trouble as 'message' content may change during processing of that function.

    As I already explained... message cannot change during the function, because of constness.

    The message handler is being called again from within itself (i.e. from wait()). You would then processing any new messages on that call. It looks as if the function may not be designed to perform recursively as you are trying to do in your code, so that would explain your unexpected/undefined results.

    So yes, block during the relay's holding state or use another non-blocking method (i.e. flag or timer/callback) as you mentioned. Fully process each message before allowing the library to handle subsequent message calls.


  • I was looking for a solution for a low consumption relay and i was adviced in this thread to use a latching relay.
    However since i just need to switch on or off a 12V Vcc (from Li ion battery) to trigger a solenoid valve, i'm wondering whether i need a relay for that :
    looking at the schematic from post #2 in https://forum.arduino.cc/index.php?topic=436555.0 may be i coud just have my solenoid valve directly in place of the relay in the schematic. In other words , i just need a transistor and not a real relay ... just because my application is a low voltage (12V to apply directly to the Vcc in the schematic) rather than 230V one: can someone confirm ? There is a diode in the schematic : what is it needed for ?


  • Hardware Contributor


    Since an inductor (im many cases a relay coil) cannot change it's current instantly, the flyback diode provides a path for the current when the coil is switched off. Otherwise, a voltage spike will occur causing arcing on switch contacts or possibly destroying switching transistors.


  • treat yor solenoid as it was a relay, the difference is that relay switches flow of current, and solenoid valve switches flow of water. so You have to use the same schematic, but put your valve where the relay is. But if You want power it from a battery, choose a latching solenoid valve instead of regular solenoid valve - and that requeires different schematic.

  • @rozpruwacz
    thanks, but do you mean that the schematic simply would not work for the regular valve or that it would work but not be low power cinsumption design anymore ?
    I have a regular solenoid valve but in my application the valve is normally closed and it will be only exceptionnally opened and for a short time when the 12V is applied, so i guess that i can live with it ...
    As for the transistor in the schematic, except it seems to be a NPN , i don't know if i need a particular one for it . probably i can just buy a 2N3904 , or is there a better choice?

  • the schematic you posted is not using latching relay/valve. it doesn't matter if it is relay or valve. both works the same and consume power when in ON state. If you plan to use it in a way that the valve will be ON for very short periods than it is not important if it is latching or not.

    when choosing a transistor for such use, You have to look at its datasheet into "absolute maximum ratings" section and check if it will handle the voltages you will apply to it. 2N3904 looks like it will handle 12V without a problem.

  • @rozpruwacz
    thanks , i will use 2N2222 because the valve needs between 200 and 400 mA.
    I'v read the 2N3904 is OK for < 100 mA

  • It works very well with the transistor and schematic posted above. I think the valve is a latching valve because it only discharges the battery when there is a transition. The only remaining problem is that the 5V arduino alone is too much power consuming. So i'm wondering if the transistor could as well work with a 3.3V arduino, that is when the signal level on the transistor Base is 3.3V rather than 5 V ... then i also could remove the arduino led but i'll need to keep the arduino regulator because my 3.7V cell voltage is too much greater than 3.3V

  • @fhenryco Actually the internal resistor of the solenoid is 27 Ohm while the resistance between C and E of the transistor in the passing state is 35 Ohm ... so it remains less than Vcc/2 for my solenoid which needs 12V ... so i need to tune my boost module at the max ==> more than 30V ... that does not seem ideal, may be i shoud choose another transistor with less internal resistor, but i have little experience with transistors : studied them a long time ago , so if someone can suggest something smart, ready to buy it ...

  • Can I suggest a change to this page?

    As it stands the wiring diagram only applies to sketch 1 (without switch). It could get confusing as the 2 sketches use different pins for the relay and there is no need for this.

    I propose that the wiring diagram be changed for the relay to be attached to pin 4.
    The first sketch needs the relay pin to change from pin 3 to pin 4.

    That's it. Then the diagram and sketches will work whichever way the builder wants to do it.

  • Mod

    Good idea @skywatch
    When doing the update, we should also rename RELAY_1 to RELAY_PIN to be consistent with sketch 2.

  • Mod

  • Mod

    https://www.mysensors.org/build/relay has been updated with new wiring instructions (picture + table)

  • That looks good, only the sketchs to go....On that note I wonder if Relay_1 might not be better choice as it gives a clue to people that if they want to add a second relay then that would be Relay_2.... Just a thought and maybe not needed.... 😉

  • @mfalkvidd when updating the example sketch you could maybe consider my version of the relay sketch which offers some nice additions: https://forum.mysensors.org/topic/6638/multiple-relays-motion-sketch-fully-customizable-optional-timer-manual-override

  • Mod

    @HenryWhite my mind is divided when it comes to that type of sketch. Yes, it has a lot of functionality. Yes, it is probably what people need anyway. But the examples are meant to be used by someone who is just getting into diy home automation. Someone new should be able to understand as much of the sketch as possible. There should be as little as possible to trubleshoot. If the sketch is complex, most people's initial reaction will be that there is something wrong with the code, when in reality almost all newbie problems are power or wiring-related. Keeping the sketch simple helps, at lest a bit.

  • @mfalkvidd You are right but may be should there be for each sensor or actuator first the most basic sketch but also at the end of the page a complete version with all functionalities and granted to work by the mysensors team.

    Of course for the complicated sketch version a big warning in red letters that this is not recommended for newbies would help...

  • After testing some functionalities of nodemanager, i was wondering if already somebody was working on making a GUI for nodemanager which would allow to build one's sketch completely from a graphical interface (at least the most common and basic functionalities) : i thing the great work that resulted in Nodemanager has so well structured the various functions needed that it has already paved the way for creating such a graphical interface.

  • Mod

    There was a user some time ago that was trying to make a web GUI

  • I would agree that more advanced sketches 'should' be included on the same page. Keep all the info in one resource place. Provided it is clearly marked as an advanced project it might help people looking for similar functionality or just interested in learning more about programming....

  • Admin

  • wow! fantastic! ... the github link readme warns that it's not yet fully ready but the interface is already impressive!
    I still have the same question i had for nodemanager though : for measuring another battery than the one that feeds Vcc obviously another pin is needed, however why not propose as well the option of measuring such pin voltage but with Vcc as the reference rather than the internal 1.1V which most of the time makes necessary a voltage divider ? Actually i did the modification in nodemanager.cpp to use DEFAULT (~3.3V) rather than INTERNAL (1.1V) reference for a 3.3 pro mini and i can get the expected battery level without any voltage divider.

    Another unrelated question i have is : could there be any way to adapt the idea of the readVcc method (which is to measure the internal 1.1V against the Vcc reference to get Vcc) but using any voltage applied to a pin as the reference to again measure the internal 1.1 against it ? This would allow the masurement of any voltage greater than 1.1 without voltage divider while the usual method would be applied for measuring any voltage lower than 1.1 ... what did i miss that makes this impossible ?

  • Mod

    We need to use the internal reference since it is the only stable voltage source and you need the voltage divider to lower the measured voltage between 0 and 1.1v. There are not many options to choose from

  • i also just realized that there is a special AREF pin intended for what i was thinking about ... but it's not available on the mini pro.

    My measurements using Vcc as Ref have been indeed very fluctuating, however what i get was highly sufficient to monitor the battery feeding a 3.3v step up regulator to the arduino and help anticipate failure

  • I just noticed another thing that should be changed in the 'relay with button' sketch....

    S_LIGHT should be S_BINARY
    V_LIGHT shoud be V_STATUS

  • I would like to clarify operation of the sketch, where more than 1 sensors input are used along with more than 1 relay actuator. in one node

    1. Does node need unique child ID for each sensor input AND relay output?
    2. If that is the case how child ID is assigned to relay actuators in the above examples?

  • This is a nice sketch and it is very universal for relays. Now m looking for a similar sketch for digital inputs such as buttons i.e.. I would like to join both. The problem: I want to use a mega for reading status of a lot of digital outputs (min.20) of another ISP. It is only High or Low. Only when the level changes, I want the mega send a message to the gateway. I tried this "for" loop, but it didnt help. There are too many informations sent to the gateway. I imagine a solution, where only a change at the pin will create an information, that is sent to the gateway.
    Here my test, which didnt run:
    void loop()

    for (int sensor=16, pin=BIN_1; sensor<=NUMBER_OF_BIN; sensor++, pin++)
    int BUTT;
    int BUTTOLD;
    BUTT =digitalRead(pin);
    if (BUTT != BUTTOLD && BUTT !=0){
    MyMessage msg(sensor, V_TRIPPED);
    send(msg.set(BUTT ? "1" : "0"));
    wait (900);
    Has anybody an idea or a hint for me?

  • Mod

    I believe there is a logic error in the sketch as you would need to declare global variables BUTTOLD_XX unique for each button, otherwise how can you keep track of the variable between each loop and FOR iteraction?

  • Thank You for Your quick answer.
    Do I understand You correctly: I must index the BUTTOLD?
    As BUTTOLD[pin) for example or how? Where?

  • Mod

    You need to create the single variables one by one, unless somebody else has a better way to do it

  • why i can't compile for arduino pro mini on other boards i can upload

  • Mod

    @mitja-blazinsek the error messages are usually essential to figuring out. Did you get any?

  • Arduino: 1.8.1 (Windows 7), Board: "Arduino Pro or Pro Mini, ATmega168 (5V, 16 MHz)"

    In file included from c:\users\mitja\appdata\local\arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2\avr\include\avr\io.h:99:0,

                 from c:\users\mitja\appdata\local\arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2\avr\include\avr\pgmspace.h:90,
                 from C:\Users\mitja\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.20\cores\arduino/Arduino.h:28,
                 from sketch\button_relay.ino.cpp:1:

    C:\Users\mitja\Documents\Arduino\libraries\MySensors/hal/architecture/AVR/MyHwAVR.cpp: In function 'bool hwUniqueID(uint8_t (*)[16])':

    C:\Users\mitja\Documents\Arduino\libraries\MySensors/hal/architecture/AVR/MyHwAVR.cpp:246:26: error: 'SIGRD' was not declared in this scope

    ((uint8_t)uniqueID) = boot_signature_byte_get(0x00);


    C:\Users\mitja\Documents\Arduino\libraries\MySensors/hal/architecture/AVR/MyHwAVR.cpp:247:30: error: 'SIGRD' was not declared in this scope

    ((uint8_t)uniqueID + 1) = boot_signature_byte_get(0x02);


    C:\Users\mitja\Documents\Arduino\libraries\MySensors/hal/architecture/AVR/MyHwAVR.cpp:248:30: error: 'SIGRD' was not declared in this scope

    ((uint8_t)uniqueID + 2) = boot_signature_byte_get(0x04);


    C:\Users\mitja\Documents\Arduino\libraries\MySensors/hal/architecture/AVR/MyHwAVR.cpp:249:30: error: 'SIGRD' was not declared in this scope

    ((uint8_t)uniqueID + 3) = boot_signature_byte_get(0x01); //OSCCAL


    Multiple libraries were found for "Bounce2.h"
    Used: C:\Users\mitja\Documents\Arduino\libraries\Bounce2
    Not used: C:\Users\mitja\Documents\Arduino\libraries\Bounce2-master
    exit status 1
    Error compiling for board Arduino Pro or Pro Mini.

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

  • OK it's probaly because ia have mini with 168 chip i have to buys 328 😞 again wait 1month to arive from china

  • hello.
    I am building a node with several kind of sensors and two relays.
    My sensors use CHILD ID from 0 to 3. I would like to start child ID of relay from 4.
    How I can't do that with this sketch?
    I guess I have to change this part of sketch :
    "for (int sensor=1, pin=RELAY_PIN; sensor<=NUMBER_OF_RELAYS; sensor++, pin++) {
    // Register all sensors to gw (they will be created as child devices)
    present(sensor, S_BINARY);"



  • @lekeb
    You may do something like this:
    In Header:

    uint8_t DS_First_Child_ID = 7; //First Child-ID to be used by Dallas Bus

    an then in presentation():

    for (int i = 0; i < numSensors && i < MAX_ATTACHED_DS18B20; i++) {
        present(i + DS_First_Child_ID, S_TEMP);

    But afaik, it's not recommended to shift the ChildID's for relays but always start with 1. Imo it's better to change the ChildID's of the other attached sensors. You may also take care (in case of shifting ID's) about a consistent mapping from ID to the PINs where the relays are attached.

  • Mod

    Agreed, set you sensors to higher ID numbers like 20 or 30 and you are good to go .

  • ok thanks a lot I will try this night

  • perfect it works great. I started my temperature sensor at CHILD ID 4 and let relays from 1 to 2. I had to add also "DS_First_Child_ID" in the sent message to gateway.

  • Hi
    Please put to this topic code your sketch....

  • Sur,

    my node controls two relays, one water pressure sensor and three DS18b20

     code pour controle cave a vin, temp et pression
    // Enable debug prints to serial monitor
    //#define MY_DEBUG
    // Enable and select radio type attached
    #define MY_RADIO_NRF24
    // Enable repeater functionality for this node
    #define MY_NODE_ID 15
    #include <SPI.h>
    #include <MySensors.h>
    #include <DallasTemperature.h>
    #include <OneWire.h>
    #define BARO_CHILD 0 //Child ID for pressure sensor
    #define BAR_SENSOR_ANALOG_PIN 0 // pin for pressure sensor
    #define COMPARE_TEMP 1 // Send temperature only if changed? 1 = Yes 0 = No
    #define ONE_WIRE_BUS 5 // Pin where dallase sensor is connected 
    #define MAX_ATTACHED_DS18B20 16
    #define RELAY_PIN 3 //pin for first relay
    #define NUMBER_OF_RELAYS 2
    #define RELAY_ON 1  // GPIO value to write to turn on attached relay
    #define RELAY_OFF 0 // GPIO value to write to turn off attached relay
    OneWire oneWire(ONE_WIRE_BUS); // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
    DallasTemperature sensors(&oneWire); // Pass the oneWire reference to Dallas Temperature. 
    float lastTemperature[MAX_ATTACHED_DS18B20];
    int numSensors=0;
    bool receivedConfig = false;
    bool metric = true;
    float lastpression;
    uint8_t DS_First_Child_ID = 4; //First Child-ID to be used by Dallas Bus
    MyMessage pressureMsg(BARO_CHILD, V_PRESSURE);
    MyMessage msg(0,V_TEMP);
    void before()
        for (int sensor=1, pin=RELAY_PIN; sensor<=NUMBER_OF_RELAYS; sensor++, pin++) {
            // Then set relay pins in output mode
            pinMode(pin, OUTPUT);
            // Set relay to last known state (using eeprom storage)
            digitalWrite(pin, loadState(sensor)?RELAY_ON:RELAY_OFF);
        // Startup up the OneWire library
    void setup()
    // requestTemperatures() will not block current thread
    void presentation()
        // Send the sketch version information to the gateway and Controller
        sendSketchInfo("Buanderie node", "1.0");
        //present pressure sensor
        present(BARO_CHILD, S_BARO);
        for (int sensor=1, pin=RELAY_PIN; sensor<=NUMBER_OF_RELAYS; sensor++, pin++) {
            // Register all sensors to gw (they will be created as child devices)
            present(sensor, S_BINARY);
    // Fetch the number of attached temperature sensors  
      numSensors = sensors.getDeviceCount();
      // Present all sensors to controller
      for (int i=0; i<numSensors && i<MAX_ATTACHED_DS18B20; i++) {   
         present(i + DS_First_Child_ID, S_TEMP);
    void loop()
      //read water pressure
    int lecture_adc = analogRead(BAR_SENSOR_ANALOG_PIN);
      float pression = ((lecture_adc*5/1024.0)-0.50)/1.7;
      if(pression != lastpression) { 
          send(pressureMsg.set(pression, 2));
      lastpression = pression;
      // Fetch temperatures from Dallas sensors
      // query conversion time and sleep until conversion completed
      int16_t conversionTime = sensors.millisToWaitForConversion(sensors.getResolution());
      // sleep() call can be replaced by wait() call if node need to process incoming messages (or if node is repeater)
      // Read temperatures and send them to controller 
      for (int i=0; i<numSensors && i<MAX_ATTACHED_DS18B20; i++) {
        // Fetch and round temperature to one decimal
        float temperature = static_cast<float>(static_cast<int>((getControllerConfig().isMetric?sensors.getTempCByIndex(i):sensors.getTempFByIndex(i)) * 10.)) / 10.;
        // Only send data if temperature has changed and no error
        #if COMPARE_TEMP == 1
        if (lastTemperature[i] != temperature && temperature != -127.00 && temperature != 85.00) {
        if (temperature != -127.00 && temperature != 85.00) {
          // Send in the new temperature
          send(msg.setSensor(i + DS_First_Child_ID).set(temperature,1));
          // Save new temperatures for next compare
    void receive(const MyMessage &message)
        // We only expect one type of message from controller. But we better check anyway.
        if (message.type==V_STATUS) {
            // Change relay state
            digitalWrite(message.sensor-1+RELAY_PIN, message.getBool()?RELAY_ON:RELAY_OFF);
            // Store state in eeprom
            saveState(message.sensor, message.getBool());
            // Write some debug info
            Serial.print("Incoming change for sensor:");
            Serial.print(", New status: ");

  • Mod

    @lekeb said in 💬 Relay:

    MyMessage pressureMsg(BARO_CHILD, V_PRESSURE);
    MyMessage msg(0,V_TEMP);

    Why are you using the same child ID (since you set #define BARO_CHILD 0)?

  • @gohan Effectively, he will never report any temp reading under ChildID 0. Within presentation() and the send() commands, the "0" is replaced by "i + DS_First_Child_ID".
    But you are partly right, to avoid any misunderstandings wrt. that the statement could also be written as follows:

    MyMessage msg(DS_First_Child_ID,V_TEMP);

  • correct, it makes sense. I will correct this error.
    However Domoticz reads correctly the temperature and links correctly the CHILD ID's, so...

  • Hello everybody !

    I would like to creat a sensor with two relays and two buttons to command this relay direct from the sensor (with actualisation of their stat in domoticz)
    Someone know the code to do this ? I'm a complete newbie on mysensor !

    Thank's a lot !

  • @jonathan-pucel Have a look at the code in this post.

  • Excellent ! It's perfect, thank's a lot rejoe2 !

  • This post is deleted!

  • Hi
    Using Home assistant, and Optimistic set to false in the mysensors config, the switch in homeassistant would turn the relay on, but in the view in homeassistant the flip switch jumped off straight after switching on. It was solved by adding the following line to the sketch, ensuring that hassio knows that the actuator actually have received the command. Not sure if this is a good way of doing it, but it seems to work for me.
    send(msg.set(state)); // Send new state and request ack back
    void receive(const MyMessage &message) {
    // We only expect one type of message from controller. But we better check anyway.
    if (message.isAck()) {
    Serial.println("This is an ack from gateway");

    if (message.type == V_LIGHT) {
    // Change relay state
    state = message.getBool();
    digitalWrite(RELAY_PIN, state?RELAY_ON:RELAY_OFF);
    // Store state in eeprom
    saveState(CHILD_ID, state);

     // Write some debug info
     Serial.print("Incoming change for sensor:");
     Serial.print(", New status: ");
     send(msg.set(state)); // Send new state and request ack back



  • Hi!

    I would like to control some 230VAC equipment (for now roller shutters), based on inputs from my mysensors sensors (temperature and light). For controller I use domoticz.

    I would like a safe, robust and preferably authorized/lawful solution (I'm in EU/Denmark).

    I came across the following solutions:


    I think the first one and maybe the second one will be authorized/lawful...? However, I have experience only with mysensors and neither z wave nor sonoff...

    Anyone has some experience/thoughts/suggestions to share?


  • Mod

    There are also roller shutters nodes running via zwave if you are looking at a retail solution

  • Thank you @gohan! Retail solution is not the keyword here. What I am searching for is an authorized/lawful (safe) solution.

    I decided to do my own node (mysensors) with a cheap relay module for the arduino. Once I achieve the desired functionality I will change to some more robust hardware. Following your suggestion this could be a z wave roller shutter (e.g. fibaro or qubino).

  • @arrawx said in 💬 Relay:

    Retail solution is not the keyword here. What I am searching for is an authorized/lawful (safe) solution.

    Sorry to comment negative, but your wording doesn't make sense. either you will go for a DIY solution, cheap and illegal (but not necessary a bad solution), or you will purchase a retail solution.
    Retail solution must have the required certificates to allow you to sell. Those are not cheap to get, which also provide the reason for a retail solution to
    be usually fairly expensive

    And also you need Notified Body

    And I know that Cetekom can create certificate for Country Approvals

  • There is a problem with the example code for RelayActuator.ino It is not checking for ACK messages. See the other example called SecureActuator.ino that does this. Without checking for ACK messages my relay gets an ON signal and turns on then immediately thereafter gets an ACK signal for V_STATUS command which is assumed in this example to be a control and the value is "0" so it turns off the relay.

  • Mod

    @slt1 I'm not sure I'm following. RelayActuator.ino does not send any messages, so it should never receive any ack messages. Compare with RelayWithButtonActuator.ino which does send messages, and therefore also checks for ack.

    Could you elaborate on the problem?

  • @mfalkvidd

    For some reason I am now unable to reproduce the issue on the standard RelayActuator.ino example. It was definitely sending ACK requests when I was testing a few days ago. I have subsequently updated MySensors library and also MyController to their latest Snapshot - so perhaps the issue comes up under one of those scenarios.

    The issue around this though is that the example does not report the current status of the relay in the loop. My own sketch was doing so. I guess many people take an example and modify it like I do. Therefore copying the example and adding in the code to send the current relay status periodically means the receive function will not work properly due to the Ack messages received,

    I would then suggest adding a note to the receive function of the relay example sketch to say that "if your node sends messages then you need to check for Ack and discard those messages" - or something along those lines. This will help !

  • Mod

    @slt1 thanks for explaining.

    I'll think about it for a bit but I hope to submit a pull request soon. I'll post here when it is ready.

  • Mod

    @slt1 sending current status won't generate an ack/echo message. So there should not be a need to handle the ack/echo flag. Hardware acks (which are enabled by default) do not trigger the receive function.

    The only case when an ack/echo message will be sent is if the sketch developer explicitly requests an ack/echo by setting the ack parameter in send() to true. If the sketch developer does that, they need to handle the ack/echo message inside the receive function, according to however they plan to handle the ack/echo message.

    My guess is that people set the ack flag to true without understanding what they are doing. I hope to make the documentation slightly less confusing by doing https://github.com/mysensors/MySensors/issues/1103

  • @mfalkvidd Thanks - and yes - I did make the assumption that send with ack = true means do a hardware ack. I was unaware that a "software ack" also exists. I read your comment here : https://forum.mysensors.org/topic/3346/discussion-reliable-delivery/17 and what you mention there needs to be made loud and clear in the docs - perhaps some mention in both the message send function and message receive function,

  • Mod

    @slt1 I agree. Made the same mistake and it took me 40 hours of reading documentation and troubleshooting before I realized there was a difference between the two acks.

  • The script for 'Example with button' works perfectly! Thanks for that.
    Has someone a script for multiple Relays with buttons ready to use for me?
    I want to use it in my garden to switch the lights with physical buttons and also control them with Domoticz.

  • This post is deleted!

  • I am having this particular switch to be recognized in "Mozilla WEBTHINGS".

    IS there some issue with having a repeater node and sensors/switches etc attaches to it? .. it sends in the data as it should when I check with MYSController and I can switch it from there with sending "V_STATUS" messages. but no luck so far of getting the sensors appear in WEBTHINGS , every other sensor works fine.

  • // Enable debug prints to serial monitor
    #define MY_DEBUG

    // Enables and select radio type (if attached)
    #define MY_RADIO_RF24
    //#define MY_RADIO_RFM69
    //#define MY_RADIO_RFM95

    #define MY_GATEWAY_ESP8266

    #define MY_WIFI_SSID "SSID"
    #define MY_WIFI_PASSWORD "PSW"

    // Enable UDP communication
    //#define MY_USE_UDP // If using UDP you need to set MY_CONTROLLER_IP_ADDRESS or MY_CONTROLLER_URL_ADDRESS below

    // Set the hostname for the WiFi Client. This is the hostname
    // it will pass to the DHCP server if not static.
    #define MY_HOSTNAME "ESP8266_GW"

    // Enable MY_IP_ADDRESS here if you want a static ip address (no DHCP)
    //#define MY_IP_ADDRESS 192,168,0,0

    // If using static ip you can define Gateway and Subnet address as well
    //#define MY_IP_GATEWAY_ADDRESS 192,168,178,1
    //#define MY_IP_SUBNET_ADDRESS 255,255,255,0

    // The port to keep open on node server mode
    #define MY_PORT 5003

    // How many clients should be able to connect to this gateway (default 1)

    // Controller ip address. Enables client mode (default is "server" mode).
    // Also enable this if MY_USE_UDP is used and you want sensor data sent somewhere.
    //#define MY_CONTROLLER_IP_ADDRESS 192, 168, 178, 68
    //#define MY_CONTROLLER_URL_ADDRESS "my.controller.org"

    // Enable inclusion mode

    // Enable Inclusion mode button on gateway
    // Set inclusion mode duration (in seconds)
    // Digital pin used for inclusion mode button

    // Set blinking period

    // Flash leds on rx/tx/err
    // Led pins used if blinking feature is enabled above
    //#define MY_DEFAULT_ERR_LED_PIN 16 // Error led pin
    //#define MY_DEFAULT_RX_LED_PIN 16 // Receive led pin
    //#define MY_DEFAULT_TX_LED_PIN 16 // the PCB, on board LED
    #define LWIP_OPEN_SRC whatever
    #define TCP_MSS whatever
    #define LWIP_IPV6 whatever
    #define LWIP_FEATURES whatever

    #include <MySensors.h>
    #include <SPI.h>
    //DHT with autodetection

    #include <dhtnew.h>

    DHTNEW mySensor(5); // ESP 16 UNO 6

    uint32_t count = 0;
    uint32_t start, stop;

    uint32_t errors[10] = { 0,0, 0,0, 0,0, 0,0, 0,0 };

    #define CHILD_ID_HUM 2
    #define CHILD_ID_TEMP 3
    MyMessage msgHum(CHILD_ID_HUM, V_HUM);
    MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);

    void presentation()
    // Send the sketch version information to the gateway
    sendSketchInfo("TemperatureAndHumidity", "1.1");

    // Register all sensors to gw (they will be created as child devices)
    present(CHILD_ID_HUM, S_HUM);
    present(CHILD_ID_TEMP, S_TEMP);


    void setup()
    Serial.print("LIBRARY VERSION: ");

    void loop()
    // show counters for OK and errors.
    if (count % 50 == 0)
    Serial.println("OK \tCRC \tTOA \tTOB \tTOC \tTOD \tSNR \tBS \tUNK");
    for (uint8_t i = 0; i < 9; i++)

    if (count % 10 == 0)

    start = micros();
    int chk = mySensor.read();
    stop = micros();

    switch (chk)
    case DHTLIB_OK:
    #ifdef MY_DEBUG
    Serial.print(mySensor.getHumidity(), 1);
    Serial.print(mySensor.getTemperature(), 1);
    Serial.print(stop - start);

    //send to gateway
    float humidity = mySensor.getHumidity();
    send(msgHum.set(humidity, 1));
    float temperature = mySensor.getTemperature();
    send(msgTemp.set(temperature, 1));


    // -- END OF FILE --

  • I was so happy to have finaly a fonctionnal sketch for my esp8266 gateway whith the DHT22 that i post directly my code.
    I hope that it will help some people.
    based on: https://github.com/RobTillaart/DHTNew/blob/master/examples/dhtnew_endless/dhtnew_endless.ino

  • Hi,
    Trying to go deep on the API and come this this doubt: The second example (with button) the child seems to be declared as "S_LIGHT" and the receiving messages are "V_LIGHT", while the first example seems better suitable for a relay (child as "S_BINNARY" and requests as "V_STATUS").
    I haven't found any "S_LIGHT" or "V_LIGHT" in the API, only "S_LIGHT_LEVEL" and "V_LIGHT_LEVEL". What is the most suitable type for a relay node with a local button?

  • @joaoabs A realy usually has only 2 states, on and off. So I would use S-BINARY and V_STATUS every time.

    A changeover realy also has 2 states so again I would go for binary and status.

    Light_Level is more suited to getting light levels from a sensor or sending a light level to a dimmable light.

  • Contest Winner

    Not sure if it ever has mentioned before, but the first example contains

    // Enable and select radio type attached
    #define MY_RADIO_RF24

    Which results in a compile error

    MySensors.h:287:4: error: #error No forward link or gateway feature activated. This means nowhere to send messages! Pretty pointless.
       #error No forward link or gateway feature activated. This means nowhere to send messages! Pretty pointless.

    It should be:

    // Enable and select radio type attached
    #define MY_RADIO_NRF24

    And then it compiles and works 🙂

  • Mod

  • Contest Winner

    @mfalkvidd I'm in an older version I discovered. Ran across more small differences.

  • @TheoL Sound like a good time to update to the latest version. it is the best yet and very stable.

Log in to reply

Suggested Topics

  • 3
  • 347
  • 109
  • 2
  • 109
  • 164