Skip to content
  • MySensors
  • OpenHardware.io
  • Categories
  • Recent
  • Tags
  • Popular
Skins
  • Light
  • Brite
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Brand Logo
  1. Home
  2. Development
  3. Invert the relay in the sketch

Invert the relay in the sketch

Scheduled Pinned Locked Moved Development
18 Posts 3 Posters 3.8k Views 2 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • derksuhD Offline
    derksuhD Offline
    derksuh
    wrote on last edited by
    #8

    @blacey

    The sketch works, but i still need the relay output inverted.
    Changing the values from relay_on and relay_off does not do the trick

    blaceyB 1 Reply Last reply
    0
    • derksuhD derksuh

      @blacey

      The sketch works, but i still need the relay output inverted.
      Changing the values from relay_on and relay_off does not do the trick

      blaceyB Offline
      blaceyB Offline
      blacey
      Admin
      wrote on last edited by
      #9

      @derksuh Is the relay working the way you want it to and you just want to invert the display in PiMatic? If so, you can do the following in the receive() method:

          send( msgRlay.set(state == 0 ? 1 : 0) );
      
      1 Reply Last reply
      0
      • derksuhD Offline
        derksuhD Offline
        derksuh
        wrote on last edited by
        #10

        @blacey

        The node is working. The problem
        Is that when it is connected to the gateway then the relay gets turned on but The status in pimatic does say it is turned off.

        1 Reply Last reply
        0
        • derksuhD Offline
          derksuhD Offline
          derksuh
          wrote on last edited by
          #11

          @blacey where should i put the code in your post?

          blaceyB 1 Reply Last reply
          0
          • derksuhD derksuh

            @blacey where should i put the code in your post?

            blaceyB Offline
            blaceyB Offline
            blacey
            Admin
            wrote on last edited by blacey
            #12

            As I said in my last post, you can put it in the receive() method of your node sketch. Basically, this will invert the relay state sent to PiMac only...

            void receive(const MyMessage &message) {
               Serial.println("Received message...");
             
               if (message.type == V_STATUS) {
                 // Change relay state
                 state = message.getByte();
                 digitalWrite(RELAY_PIN, state);
                 send( msgRlay.set(state == 0 ? 1 : 0) );
               }
            }
            
            1 Reply Last reply
            0
            • derksuhD Offline
              derksuhD Offline
              derksuh
              wrote on last edited by
              #13

              @blacey

              I did not get it working the way i would like. I now used a different sketch.
              here i had the same problem but i just set the relay_OFF from 0 to 1, and the Relay_ON from 1 to 0
              And with this sketch it worked fine.

              
              #define MY_NODE_ID 1
              // Enable debug prints
              #define MY_DEBUG
              
              // Enable and select radio type attached
              #define MY_RADIO_NRF24
              //#define MY_RADIO_RFM69
              
              #include <SPI.h>
              #include <MySensors.h>  
              #include <DHT.h>  
              
              #define CHILD_ID_HUM 1
              #define CHILD_ID_TEMP 2
              #define HUMIDITY_SENSOR_DIGITAL_PIN 6
              unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds)
              unsigned long lastRefreshTime = 0; // Use this to implement a non-blocking delay function
              
              #define RELAY_1  3  // Arduino Digital I/O pin number for first relay (second on pin+1 etc)
              #define NUMBER_OF_RELAYS 1 // Total number of attached relays
              #define RELAY_ON 0  // GPIO value to write to turn on attached relay
              #define RELAY_OFF 1 // GPIO value to write to turn off attached relay
              
              
              
              DHT dht;
              float lastTemp;
              float lastHum;
              boolean metric = true; 
              MyMessage msgHum(CHILD_ID_HUM, V_HUM);
              MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
              
              
              void setup()  
              { 
                dht.setup(HUMIDITY_SENSOR_DIGITAL_PIN); 
              
                metric = getConfig().isMetric;
              
                for (int sensor=1, pin=RELAY_1; 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);
                }
              }
              
              void presentation()  
              { 
                // Send the Sketch Version Information to the Gateway
                sendSketchInfo("Badkamer", "1.3");
              
                // Register all sensors to gw (they will be created as child devices)
                present(CHILD_ID_HUM, S_HUM);
                present(CHILD_ID_TEMP, S_TEMP);
              
                for (int sensor=1, pin=RELAY_1; sensor<=NUMBER_OF_RELAYS;sensor++, pin++) {
                  // Register all sensors to gw (they will be created as child devices)
                  present(sensor, S_LIGHT);
                }
              }
              
              
              void loop()      
              { 
                boolean needRefresh = (millis() - lastRefreshTime) > SLEEP_TIME;
                if (needRefresh)
                {
                    lastRefreshTime = millis();
                    
                    float temperature = dht.getTemperature();
                    if (isnan(temperature)) {
                        Serial.println("Failed reading temperature from DHT");
                    } else if (temperature != lastTemp) {
                      lastTemp = temperature;
                      if (!metric) {
                        temperature = dht.toFahrenheit(temperature);
                      }
                      send(msgTemp.set(temperature, 1));
                      Serial.print("T: ");
                      Serial.println(temperature);
                    }
                    
                    float humidity = dht.getHumidity();
                    if (isnan(humidity)) {
                        Serial.println("Failed reading humidity from DHT");
                    } else if (humidity != lastHum) {
                        lastHum = humidity;
                        send(msgHum.set(humidity, 1));
                        Serial.print("H: ");
                        Serial.println(humidity);
                    }
              
                }
                
              }
              
              void receive(const MyMessage &message) {
                // We only expect one type of message from controller. But we better check anyway.
                if (message.type==V_LIGHT) {
                   // Change relay state
                   digitalWrite(message.sensor-1+RELAY_1, 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(message.sensor);
                   Serial.print(", New status: ");
                   Serial.println(message.getBool());
                 } 
              }
              
              blaceyB 1 Reply Last reply
              0
              • derksuhD derksuh

                @blacey

                I did not get it working the way i would like. I now used a different sketch.
                here i had the same problem but i just set the relay_OFF from 0 to 1, and the Relay_ON from 1 to 0
                And with this sketch it worked fine.

                
                #define MY_NODE_ID 1
                // Enable debug prints
                #define MY_DEBUG
                
                // Enable and select radio type attached
                #define MY_RADIO_NRF24
                //#define MY_RADIO_RFM69
                
                #include <SPI.h>
                #include <MySensors.h>  
                #include <DHT.h>  
                
                #define CHILD_ID_HUM 1
                #define CHILD_ID_TEMP 2
                #define HUMIDITY_SENSOR_DIGITAL_PIN 6
                unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds)
                unsigned long lastRefreshTime = 0; // Use this to implement a non-blocking delay function
                
                #define RELAY_1  3  // Arduino Digital I/O pin number for first relay (second on pin+1 etc)
                #define NUMBER_OF_RELAYS 1 // Total number of attached relays
                #define RELAY_ON 0  // GPIO value to write to turn on attached relay
                #define RELAY_OFF 1 // GPIO value to write to turn off attached relay
                
                
                
                DHT dht;
                float lastTemp;
                float lastHum;
                boolean metric = true; 
                MyMessage msgHum(CHILD_ID_HUM, V_HUM);
                MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
                
                
                void setup()  
                { 
                  dht.setup(HUMIDITY_SENSOR_DIGITAL_PIN); 
                
                  metric = getConfig().isMetric;
                
                  for (int sensor=1, pin=RELAY_1; 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);
                  }
                }
                
                void presentation()  
                { 
                  // Send the Sketch Version Information to the Gateway
                  sendSketchInfo("Badkamer", "1.3");
                
                  // Register all sensors to gw (they will be created as child devices)
                  present(CHILD_ID_HUM, S_HUM);
                  present(CHILD_ID_TEMP, S_TEMP);
                
                  for (int sensor=1, pin=RELAY_1; sensor<=NUMBER_OF_RELAYS;sensor++, pin++) {
                    // Register all sensors to gw (they will be created as child devices)
                    present(sensor, S_LIGHT);
                  }
                }
                
                
                void loop()      
                { 
                  boolean needRefresh = (millis() - lastRefreshTime) > SLEEP_TIME;
                  if (needRefresh)
                  {
                      lastRefreshTime = millis();
                      
                      float temperature = dht.getTemperature();
                      if (isnan(temperature)) {
                          Serial.println("Failed reading temperature from DHT");
                      } else if (temperature != lastTemp) {
                        lastTemp = temperature;
                        if (!metric) {
                          temperature = dht.toFahrenheit(temperature);
                        }
                        send(msgTemp.set(temperature, 1));
                        Serial.print("T: ");
                        Serial.println(temperature);
                      }
                      
                      float humidity = dht.getHumidity();
                      if (isnan(humidity)) {
                          Serial.println("Failed reading humidity from DHT");
                      } else if (humidity != lastHum) {
                          lastHum = humidity;
                          send(msgHum.set(humidity, 1));
                          Serial.print("H: ");
                          Serial.println(humidity);
                      }
                
                  }
                  
                }
                
                void receive(const MyMessage &message) {
                  // We only expect one type of message from controller. But we better check anyway.
                  if (message.type==V_LIGHT) {
                     // Change relay state
                     digitalWrite(message.sensor-1+RELAY_1, 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(message.sensor);
                     Serial.print(", New status: ");
                     Serial.println(message.getBool());
                   } 
                }
                
                blaceyB Offline
                blaceyB Offline
                blacey
                Admin
                wrote on last edited by
                #14

                @derksuh said:

                I did not get it working the way i would like. I now used a different sketch.
                here i had the same problem but i just set the relay_OFF from 0 to 1, and the Relay_ON from 1 to 0
                And with this sketch it worked fine.

                Your new sketch looks much better, glad you figured it out! :+1: You might want to remove the saveState() from your receive() method because the "saved -state" is not being used and this will prevent unnecessary writes to EEPROM which has a limited lifespan. Also, you might want to request the relay status from the gateway in setup() so the node will set the relay status to that of they gateway (i.e. the response to a request() sent in setup() will be handled by your existing receive() method).

                1 Reply Last reply
                0
                • derksuhD Offline
                  derksuhD Offline
                  derksuh
                  wrote on last edited by
                  #15

                  @blacey You mean like this?

                  /**
                   * The MySensors Arduino library handles the wireless radio link and protocol
                   * between your home built sensors/actuators and HA controller of choice.
                   * The sensors forms a self healing radio network with optional repeaters. Each
                   * repeater and gateway builds a routing tables in EEPROM which keeps track of the
                   * network topology allowing messages to be routed to nodes.
                   *
                   * Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
                   * Copyright (C) 2013-2015 Sensnology AB
                   * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
                   *
                   * Documentation: http://www.mysensors.org
                   * Support Forum: http://forum.mysensors.org
                   *
                   * This program is free software; you can redistribute it and/or
                   * modify it under the terms of the GNU General Public License
                   * version 2 as published by the Free Software Foundation.
                   *
                   *******************************
                   *
                   * REVISION HISTORY
                   * Version 1.0 - Henrik EKblad
                   * 
                   * DESCRIPTION
                   * This sketch provides an example how to implement a humidity/temperature
                   * sensor using DHT11/DHT-22 
                   * http://www.mysensors.org/build/humidity
                   */
                  
                  #define MY_NODE_ID 1
                  // Enable debug prints
                  #define MY_DEBUG
                  
                  // Enable and select radio type attached
                  #define MY_RADIO_NRF24
                  //#define MY_RADIO_RFM69
                  
                  #include <SPI.h>
                  #include <MySensors.h>  
                  #include <DHT.h>  
                  
                  #define CHILD_ID_HUM 1
                  #define CHILD_ID_TEMP 2
                  #define HUMIDITY_SENSOR_DIGITAL_PIN 6
                  unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds)
                  unsigned long lastRefreshTime = 0; // Use this to implement a non-blocking delay function
                  
                  #define RELAY_1  3  // Arduino Digital I/O pin number for first relay (second on pin+1 etc)
                  #define NUMBER_OF_RELAYS 1 // Total number of attached relays
                  #define RELAY_ON 0  // GPIO value to write to turn on attached relay
                  #define RELAY_OFF 1 // GPIO value to write to turn off attached relay
                  
                  
                  
                  DHT dht;
                  float lastTemp;
                  float lastHum;
                  boolean metric = true; 
                  MyMessage msgHum(CHILD_ID_HUM, V_HUM);
                  MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
                  
                  
                  void setup()  
                  { 
                    dht.setup(HUMIDITY_SENSOR_DIGITAL_PIN); 
                  
                    metric = getConfig().isMetric;
                  
                    for (int sensor=1, pin=RELAY_1; 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);
                    }
                      // Request the latest relay status from the gateway 
                    Serial.println("Requesting initial value from controller");
                    request(RELAY_1, V_STATUS);
                  }
                  
                  void presentation()  
                  { 
                    // Send the Sketch Version Information to the Gateway
                    sendSketchInfo("Badkamer", "1.3");
                  
                    // Register all sensors to gw (they will be created as child devices)
                    present(CHILD_ID_HUM, S_HUM);
                    present(CHILD_ID_TEMP, S_TEMP);
                  
                    for (int sensor=1, pin=RELAY_1; sensor<=NUMBER_OF_RELAYS;sensor++, pin++) {
                      // Register all sensors to gw (they will be created as child devices)
                      present(sensor, S_LIGHT);
                    }
                  }
                  
                  
                  void loop()      
                  { 
                    boolean needRefresh = (millis() - lastRefreshTime) > SLEEP_TIME;
                    if (needRefresh)
                    {
                        lastRefreshTime = millis();
                        
                        float temperature = dht.getTemperature();
                        if (isnan(temperature)) {
                            Serial.println("Failed reading temperature from DHT");
                        } else if (temperature != lastTemp) {
                          lastTemp = temperature;
                          if (!metric) {
                            temperature = dht.toFahrenheit(temperature);
                          }
                          send(msgTemp.set(temperature, 1));
                          Serial.print("T: ");
                          Serial.println(temperature);
                        }
                        
                        float humidity = dht.getHumidity();
                        if (isnan(humidity)) {
                            Serial.println("Failed reading humidity from DHT");
                        } else if (humidity != lastHum) {
                            lastHum = humidity;
                            send(msgHum.set(humidity, 1));
                            Serial.print("H: ");
                            Serial.println(humidity);
                        }
                  
                    }
                    
                  }
                  
                  void receive(const MyMessage &message) {
                    // We only expect one type of message from controller. But we better check anyway.
                    if (message.type==V_LIGHT) {
                       // Change relay state
                       digitalWrite(message.sensor-1+RELAY_1, message.getBool()?RELAY_ON:RELAY_OFF);
                       // Store state in eeprom
                       Serial.print("Incoming change for sensor:");
                       Serial.print(message.sensor);
                       Serial.print(", New status: ");
                       Serial.println(message.getBool());
                     } 
                  }
                  
                  
                  blaceyB 1 Reply Last reply
                  0
                  • derksuhD derksuh

                    @blacey You mean like this?

                    /**
                     * The MySensors Arduino library handles the wireless radio link and protocol
                     * between your home built sensors/actuators and HA controller of choice.
                     * The sensors forms a self healing radio network with optional repeaters. Each
                     * repeater and gateway builds a routing tables in EEPROM which keeps track of the
                     * network topology allowing messages to be routed to nodes.
                     *
                     * Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
                     * Copyright (C) 2013-2015 Sensnology AB
                     * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
                     *
                     * Documentation: http://www.mysensors.org
                     * Support Forum: http://forum.mysensors.org
                     *
                     * This program is free software; you can redistribute it and/or
                     * modify it under the terms of the GNU General Public License
                     * version 2 as published by the Free Software Foundation.
                     *
                     *******************************
                     *
                     * REVISION HISTORY
                     * Version 1.0 - Henrik EKblad
                     * 
                     * DESCRIPTION
                     * This sketch provides an example how to implement a humidity/temperature
                     * sensor using DHT11/DHT-22 
                     * http://www.mysensors.org/build/humidity
                     */
                    
                    #define MY_NODE_ID 1
                    // Enable debug prints
                    #define MY_DEBUG
                    
                    // Enable and select radio type attached
                    #define MY_RADIO_NRF24
                    //#define MY_RADIO_RFM69
                    
                    #include <SPI.h>
                    #include <MySensors.h>  
                    #include <DHT.h>  
                    
                    #define CHILD_ID_HUM 1
                    #define CHILD_ID_TEMP 2
                    #define HUMIDITY_SENSOR_DIGITAL_PIN 6
                    unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds)
                    unsigned long lastRefreshTime = 0; // Use this to implement a non-blocking delay function
                    
                    #define RELAY_1  3  // Arduino Digital I/O pin number for first relay (second on pin+1 etc)
                    #define NUMBER_OF_RELAYS 1 // Total number of attached relays
                    #define RELAY_ON 0  // GPIO value to write to turn on attached relay
                    #define RELAY_OFF 1 // GPIO value to write to turn off attached relay
                    
                    
                    
                    DHT dht;
                    float lastTemp;
                    float lastHum;
                    boolean metric = true; 
                    MyMessage msgHum(CHILD_ID_HUM, V_HUM);
                    MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
                    
                    
                    void setup()  
                    { 
                      dht.setup(HUMIDITY_SENSOR_DIGITAL_PIN); 
                    
                      metric = getConfig().isMetric;
                    
                      for (int sensor=1, pin=RELAY_1; 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);
                      }
                        // Request the latest relay status from the gateway 
                      Serial.println("Requesting initial value from controller");
                      request(RELAY_1, V_STATUS);
                    }
                    
                    void presentation()  
                    { 
                      // Send the Sketch Version Information to the Gateway
                      sendSketchInfo("Badkamer", "1.3");
                    
                      // Register all sensors to gw (they will be created as child devices)
                      present(CHILD_ID_HUM, S_HUM);
                      present(CHILD_ID_TEMP, S_TEMP);
                    
                      for (int sensor=1, pin=RELAY_1; sensor<=NUMBER_OF_RELAYS;sensor++, pin++) {
                        // Register all sensors to gw (they will be created as child devices)
                        present(sensor, S_LIGHT);
                      }
                    }
                    
                    
                    void loop()      
                    { 
                      boolean needRefresh = (millis() - lastRefreshTime) > SLEEP_TIME;
                      if (needRefresh)
                      {
                          lastRefreshTime = millis();
                          
                          float temperature = dht.getTemperature();
                          if (isnan(temperature)) {
                              Serial.println("Failed reading temperature from DHT");
                          } else if (temperature != lastTemp) {
                            lastTemp = temperature;
                            if (!metric) {
                              temperature = dht.toFahrenheit(temperature);
                            }
                            send(msgTemp.set(temperature, 1));
                            Serial.print("T: ");
                            Serial.println(temperature);
                          }
                          
                          float humidity = dht.getHumidity();
                          if (isnan(humidity)) {
                              Serial.println("Failed reading humidity from DHT");
                          } else if (humidity != lastHum) {
                              lastHum = humidity;
                              send(msgHum.set(humidity, 1));
                              Serial.print("H: ");
                              Serial.println(humidity);
                          }
                    
                      }
                      
                    }
                    
                    void receive(const MyMessage &message) {
                      // We only expect one type of message from controller. But we better check anyway.
                      if (message.type==V_LIGHT) {
                         // Change relay state
                         digitalWrite(message.sensor-1+RELAY_1, message.getBool()?RELAY_ON:RELAY_OFF);
                         // Store state in eeprom
                         Serial.print("Incoming change for sensor:");
                         Serial.print(message.sensor);
                         Serial.print(", New status: ");
                         Serial.println(message.getBool());
                       } 
                    }
                    
                    
                    blaceyB Offline
                    blaceyB Offline
                    blacey
                    Admin
                    wrote on last edited by
                    #16

                    @derksuh Exactly - good job! So, is it working as expected? For example, if you turn the relay on and then reboot the node, does the node come up, ask for the relay status, receive relay on and then try to turn the relay on? You should be able to see this in the messaging sequence on the node.

                    1 Reply Last reply
                    0
                    • derksuhD Offline
                      derksuhD Offline
                      derksuh
                      wrote on last edited by
                      #17

                      No it doesn't do that. If i switch on the relay in pimatic then it goes on.
                      if i then rebot the node the relay stays off but the status in pimatic also changes to off.

                      blaceyB 1 Reply Last reply
                      0
                      • derksuhD derksuh

                        No it doesn't do that. If i switch on the relay in pimatic then it goes on.
                        if i then rebot the node the relay stays off but the status in pimatic also changes to off.

                        blaceyB Offline
                        blaceyB Offline
                        blacey
                        Admin
                        wrote on last edited by
                        #18

                        @derksuh Sorry to hear but your sketch looks good. Are you using the MySensors development branch? If not, doing so will probably fix the behavior because there was a bug in the 2.0 release that prevented messages from being sent (i.e. the request()) in the setup() method of a sketch.

                        Once you upgrade to the MySensors development branch, if it still doesn't behave properly, please post the messages logged by the node, with #MY_DEBUG enabled.

                        1 Reply Last reply
                        0
                        Reply
                        • Reply as topic
                        Log in to reply
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes


                        19

                        Online

                        11.7k

                        Users

                        11.2k

                        Topics

                        113.1k

                        Posts


                        Copyright 2025 TBD   |   Forum Guidelines   |   Privacy Policy   |   Terms of Service
                        • Login

                        • Don't have an account? Register

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • MySensors
                        • OpenHardware.io
                        • Categories
                        • Recent
                        • Tags
                        • Popular