Invert the relay in the sketch



  • Hello all,

    I used the sketch below to control a fan and to read the humidity and temperature from a sensor.
    Now when i start up the sensor in Pimatic it says it is off, but the relay is activated. Can i somehow invert it?

    #define MY_DEBUG
    #define MY_RADIO_NRF24
    #define MY_REPEATER_FEATURE
    #define MY_NODE_ID 1
    
     
    #include <SPI.h>
    #include <MySensors.h>
    #include <Bounce2.h>
    #include <DHT.h>
    
    // Set this to the pin you connected the DHT's data pin to
    #define DHT_DATA_PIN 6
    
    // Set this offset if the sensor has a permanent small offset to the real temperatures
    #define SENSOR_TEMP_OFFSET 0
    
    // Sleep time between sensor updates (in milliseconds)
    // Must be >1000ms for DHT22 and >2000ms for DHT11
    static const uint64_t UPDATE_INTERVAL = 60000;
    
    // Force sending an update of the temperature after n sensor reads, so a controller showing the
    // timestamp of the last update doesn't show something like 3 hours in the unlikely case, that
    // the value didn't change since;
    // i.e. the sensor would force sending an update every UPDATE_INTERVAL*FORCE_UPDATE_N_READS [ms]
    static const uint8_t FORCE_UPDATE_N_READS = 10;
    
    #define CHILD_ID_HUM 0
    #define CHILD_ID_TEMP 1
    #define CHILD_ID_RLAY 2
    
    #define RELAY_PIN  3
    #define RELAY_ON 1  
    #define RELAY_OFF 0
    
    Bounce debouncer = Bounce();
    bool state = false;
    bool initialValueSent = false;
    
    float lastTemp;
    float lastHum;
    uint8_t nNoUpdatesTemp;
    uint8_t nNoUpdatesHum;
    bool metric = true;
    
    MyMessage msgHum(CHILD_ID_HUM, V_HUM);
    MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
    MyMessage msgRlay(CHILD_ID_RLAY, V_STATUS);
    
    DHT dht;
    
    void presentation()   
    { 
      // Send the sketch version information to the gateway
      sendSketchInfo("TempHumidRelay", "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);
      present(CHILD_ID_RLAY, S_BINARY);
    
      metric = getConfig().isMetric;
    }
    
    void setup()
    {
      dht.setup(DHT_DATA_PIN); // set data pin of DHT sensor
      if (UPDATE_INTERVAL <= dht.getMinimumSamplingPeriod()) {
        Serial.println("Warning: UPDATE_INTERVAL is smaller than supported by the sensor!");
      }
      // Sleep for the time of the minimum sampling period to give the sensor time to power up
      // (otherwise, timeout errors might occure for the first reading)
      //sleep(dht.getMinimumSamplingPeriod());
      
      // Make sure relays are off when starting up
      digitalWrite(RELAY_PIN, RELAY_OFF);
      pinMode(RELAY_PIN, OUTPUT);
    }
    
    void loop()      
    {  
        if (!initialValueSent) {
        Serial.println("Sending initial value");
        send(msgRlay.set(state?RELAY_ON:RELAY_OFF),2);
        Serial.println("Requesting initial value from controller");
        request(CHILD_ID_RLAY, V_STATUS);
        wait(2000, C_SET, V_STATUS);
      }
      if (debouncer.update()) {
        if (debouncer.read()==LOW) {
          state = !state;
          // Send new state and request ack back
          send(msgRlay.set(state?RELAY_ON:RELAY_OFF), true);
        }
      }
      dht.readSensor(true);
      float temperature = dht.getTemperature();
      if (isnan(temperature)) {
        Serial.println("Failed reading temperature from DHT!");
      } 
      else if (temperature != lastTemp || nNoUpdatesTemp == FORCE_UPDATE_N_READS) {
        // Only send temperature if it changed since the last measurement or if we didn't send an update for n times
        lastTemp = temperature;
        if (!metric) {
          temperature = dht.toFahrenheit(temperature);
        }
        nNoUpdatesTemp = 0;
        temperature += SENSOR_TEMP_OFFSET;
        send(msgTemp.set(temperature, 1));
        
        #ifdef MY_DEBUG
        Serial.print("T: ");
        Serial.println(temperature);
        #endif
      } else {
        // Increase no update counter if the temperature stayed the same
        nNoUpdatesTemp++;
      }
    
      // Get humidity from DHT library
      float humidity = dht.getHumidity();
      if (isnan(humidity)) {
        Serial.println("Failed reading humidity from DHT");
      } else if (humidity != lastHum || nNoUpdatesHum == FORCE_UPDATE_N_READS) {
        // Only send humidity if it changed since the last measurement or if we didn't send an update for n times
        lastHum = humidity;
        // Reset no updates counter
        nNoUpdatesHum = 0;
        send(msgHum.set(humidity, 1));
        
        #ifdef MY_DEBUG
        Serial.print("H: ");
        Serial.println(humidity);
        #endif
      } else {
        // Increase no update counter if the humidity stayed the same
        nNoUpdatesHum++;
      }
     wait(2000);
    }
    
    void receive(const MyMessage &message) {
      if (message.isAck()) {
         Serial.println("This is an ack from gateway");
      }
    
      if (message.type == V_STATUS) {
        if (!initialValueSent) {
          Serial.println("Receiving initial value from controller");
          initialValueSent = true;
        }
        // Change relay state
        state = (bool)message.getInt();
        digitalWrite(RELAY_PIN, state?RELAY_ON:RELAY_OFF);
        send(msgRlay.set(state?RELAY_ON:RELAY_OFF,2));
      }
    }```

  • Mod

    @derksuh yes. Switch these two:

    #define RELAY_ON 1
    #define RELAY_OFF 0



  • @mfalkvidd is it nescessary to clear the eeprom before uploading the changef sketch?


  • Mod

    @derksuh no, no need to clear the eeprom


  • Admin

    @derksuh I see a couple of potential problems:

    1. In setup(), you are attempt to turn the relay off before setting the pin mode. You need to reverse the following two lines.
      // Make sure relays are off when starting up
      digitalWrite(RELAY_PIN, RELAY_OFF);
      pinMode(RELAY_PIN, OUTPUT);
    
    1. What are you debouncing()? You never attach debouncer to a pin to read (e.g. debouncer.attach())?

    2. I actually see a number of other issues but it would be better to understand your use case/requirements. Can you describe what you want to happen when you first power up the node and, while the node is in steady state, and any interactions/control with the relay on the node. For example (hypothetical).

    Startup:
    1. Set relay status to last known gateway state (on/off)
    2. Send current temperature and humidity to gateway

    Steady state:
    1. Send temperature and humidity to gateway ever xx seconds/minutes
    2. Allow gateway to turn fan on/off (e.g. scene to turn on fan when humidity is high, off when low, manual user control, etc.)

    I saw potential requirements conflicts hence my question regarding your view of the requirements/envisioned behavior.



  • @blacey

    I reversed the lines and changed the values of relay off and relay on but that did not do the trick.
    This sketch i copied from a other project so i don't really know why debouncing is implemented.

    The example you scribed is exactly how it should work.


  • Admin

    @derksuh Ok, I took a shot at refactoring your sketch. I didn't have much time and I only ensured that it compiles so your MMV... This could probably be simplified even more but you know the old saying, "If I had more time, I would write less code" 😉

    #define MY_DEBUG
    #define MY_RADIO_NRF24
    #define MY_REPEATER_FEATURE
    #define MY_NODE_ID 1
     
    #include <SPI.h>
    #include <MySensors.h>
    #include <DHT.h>
    
    // Set this to the pin you connected the DHT's data pin to
    #define DHT_DATA_PIN 6
    
    // Set this offset if the sensor has a permanent small offset to the real temperatures
    #define SENSOR_TEMP_OFFSET 0
    
    // Sleep time between sensor updates (in milliseconds)
    // Must be >1000ms for DHT22 and >2000ms for DHT11
    static const uint64_t UPDATE_INTERVAL = 60000;
    
    // Force sending an update of the temperature after n sensor reads, so a controller showing the
    // timestamp of the last update doesn't show something like 3 hours in the unlikely case, that
    // the value didn't change since;
    // i.e. the sensor would force sending an update every UPDATE_INTERVAL*FORCE_UPDATE_N_READS [ms]
    static const uint8_t FORCE_UPDATE_N_READS = 10;
    
    #define CHILD_ID_HUM 0
    #define CHILD_ID_TEMP 1
    #define CHILD_ID_RLAY 2
    
    #define RELAY_PIN  3
    #define RELAY_ON 1  
    #define RELAY_OFF 0
    
    #define TEMP 0
    #define HUMI 1
    
    byte state = 0;
    bool metric = true;
    
    MyMessage msgHum(CHILD_ID_HUM, V_HUM);
    MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
    MyMessage msgRlay(CHILD_ID_RLAY, V_STATUS);
    
    typedef struct {
      float last;
      uint8_t nNoUpdates;
    } sensorState_t;
    
    sensorState_t dhtState[2];
    
    DHT dht;
    
    void presentation()   
    { 
      // Send the sketch version information to the gateway
      sendSketchInfo("TempHumidRelay", "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);
      present(CHILD_ID_RLAY, S_BINARY);
    
      // Ask the gateway for the units of measure to use
      metric = getConfig().isMetric;
    }
    
    void setup()
    {
      // Make sure relays are off when starting up
      pinMode(RELAY_PIN, OUTPUT);
      digitalWrite(RELAY_PIN, RELAY_OFF);
    
      // Initialize the Temperature & Humidity sensor, first reading will be sent from loop()
      if (UPDATE_INTERVAL >= dht.getMinimumSamplingPeriod()) {
        dht.setup(DHT_DATA_PIN); // set data pin of DHT sensor and model (e.g. DHT_22, DHT_11)
      } else {
        Serial.println("Warning: UPDATE_INTERVAL is smaller than supported by the sensor!");
        Serial.println("Increase UPDATE_INTERVAL and re-upload sketch...");
      }
     
      // Request the latest relay status from the gateway 
      Serial.println("Requesting initial value from controller");
      request(CHILD_ID_RLAY, V_STATUS);
    }
    
    void loop()      
    { 
      // Sleep until next valid interal to read temperature and humidity
      wait(UPDATE_INTERVAL);
    
      // Read current temperature & humidity from DHT22
      dht.readSensor(true);
      float temperature = dht.getTemperature();
    
      // Only send temperature if it has changed since the last measurement or if we didn't send an update for n times
      if (temperature != dhtState[TEMP].last || dhtState[TEMP].nNoUpdates >= FORCE_UPDATE_N_READS) {
        dhtState[TEMP].last = temperature;
        temperature = metric ? temperature : dht.toFahrenheit(temperature);
        temperature += SENSOR_TEMP_OFFSET;
        send(msgTemp.set(temperature, 1));
        #ifdef MY_DEBUG
          Serial.print("T: ");
          Serial.println(temperature);
        #endif
        dhtState[TEMP].nNoUpdates = 0;
      }
      else if (isnan(temperature)) {
        Serial.println("Failed reading temperature from DHT!");
      } else {
        // Increase no update counter if the temperature stayed the same
        dhtState[TEMP].nNoUpdates++;
      }
    
      // Retrieve the current humidity
      float humidity = dht.getHumidity();
    
      // Only send humidity if it changed since the last measurement or if we didn't send an update for n times
      if (humidity != dhtState[HUMI].last || dhtState[HUMI].nNoUpdates >= FORCE_UPDATE_N_READS) {
        dhtState[HUMI].last = humidity;
        send(msgHum.set(humidity, 1));
        
        #ifdef MY_DEBUG
          Serial.print("H: ");
          Serial.println(humidity);
        #endif
        dhtState[HUMI].nNoUpdates = 0;
    
      } else if (isnan(humidity)) {
        Serial.println("Failed reading humidity from DHT");
      } else {
        // Increase no update counter if the humidity stayed the same
        dhtState[HUMI].nNoUpdates++;
      }
    }
    
    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));
      }
    }
    


  • @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


  • Admin

    @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) );
    


  • @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.



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


  • Admin

    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) );
       }
    }
    


  • @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());
       } 
    }
    

  • Admin

    @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! 👍 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).



  • @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());
       } 
    }
    
    

  • Admin

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



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


  • Admin

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


Log in to reply
 

Suggested Topics

  • 1
  • 3
  • 6
  • 1
  • 1
  • 3

0
Online

11.4k
Users

11.1k
Topics

112.7k
Posts