relay not changing state when compiling two working sketchs



  • Hi all! i'm having problems with compiling two of my working sketches i am fairly new to this so it might be stupid mistake. Here is the thing one of my sketch is for 4x relay whith 4x button and the other is for dht22 and dallas temp sensor...this for a chicken coop im working on. The problem is that once compiled the relay doesn't change state when switching on and off in openhab2. I spent 2 days trying to figure out what is wrong...here is the code hope somebody can help me with that thanks!! in advance 🐔

    // MySensor Debug
    #define MY_DEBUG
    
    // Enables repeater functionality (relays messages from other nodes)
    //#define MY_REPEATER_FEATURE
    
    
    #define MY_NODE_ID 50
    
    #define MY_RF24_CE_PIN 40
    #define MY_RF24_CS_PIN 53
    #define MY_RF24_MOSI_PIN 51
    #define MY_RF24_MISO_PIN 50
    #define MY_RF24_SCK_PIN 52
    
    // Comment line below if you don't want to use the temperature sensor
    #define USE_TEMP_SENSOR
    
    #define MY_RADIO_NRF24
    #include <MySensors.h>
    #include <SPI.h>
    #include <Bounce2.h>
    #include <DHT.h>
    #include <DallasTemperature.h>
    #include <OneWire.h>
    
    #define RELAY_PIN    22  // Arduino Digital I/O pin number for relay 
    #define RELAY_PIN_2  23
    #define RELAY_PIN_3  24
    #define RELAY_PIN_4  25
    #define BUTTON_PIN   9  // Arduino Digital I/O pin number for button 
    #define BUTTON_PIN_2 10
    #define BUTTON_PIN_3 11
    #define BUTTON_PIN_4 12
    #define CHILD_ID 11 // Id of the sensor child for 1st relay
    #define CHILD_ID_2 12 // Id of the sensor child for 2nd relay
    #define CHILD_ID_3 13
    #define CHILD_ID_4 14
    #define CHILD_ID_HUM1 6
    #define CHILD_ID_TEMP1 7
    #define ONE_WIRE_BUS 3 // Pin where dallase sensor is connected 
    #define MAX_ATTACHED_DS18B20 1
    // Relay status
    #define RELAY_ON 1
    #define RELAY_OFF 0
    
    // Source of state change (used when printing debug information)
    #define CHANGE_STATE_SOURCE_RADIO 0
    #define CHANGE_STATE_SOURCE_SWITCH 1
    // Set this to the pin you connected the DHT's data pin to
    #define DHT1_DATA_PIN 2
    
    // 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 = 10000;
    
    // 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 = 100000;
    
    float lastTemp1;
    float lastHum1;
    uint8_t nNoUpdatesTemp1;
    uint8_t nNoUpdatesHum1;
    bool metric = true;
    
    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;
    
    
    Bounce debouncer = Bounce();
    int oldValue;
    bool state;
    Bounce debouncer2 = Bounce();
    int oldValue2;
    bool state2;
    Bounce debouncer3 = Bounce();
    int oldValue3;
    bool state3;
    Bounce debouncer4 = Bounce();
    int oldValue4;
    bool state4;
    
    MyMessage msg(CHILD_ID, V_LIGHT);
    MyMessage msg2(CHILD_ID_2, V_LIGHT);
    MyMessage msg3(CHILD_ID_3, V_LIGHT);
    MyMessage msg4(CHILD_ID_4, V_LIGHT);
    MyMessage msgDallas(0,V_TEMP);
    MyMessage msgHum1(CHILD_ID_HUM1, V_HUM);
    MyMessage msgTemp1(CHILD_ID_TEMP1, V_TEMP);
    DHT dht;
    
    void before()
    {
      // Startup up the OneWire library
      sensors.begin();
    }
    
    void presentation() {
      // Send the sketch version information to the gateway and Controller
      sendSketchInfo("Double Relay & Button", "0.2");
      // Register all sensors to gw (they will be created as child devices)
      present(CHILD_ID, S_LIGHT);
      present(CHILD_ID_2, S_LIGHT);
      present(CHILD_ID_3, S_LIGHT);
      present(CHILD_ID_4, S_LIGHT);
    
    }
    
    void setup()
    {
    // Send the sketch version information to the gateway
      sendSketchInfo("DHTandDallas", "1.1");
      
      // Register all sensors to gw (they will be created as child devices)
      present(CHILD_ID_HUM1, S_HUM);
      present(CHILD_ID_TEMP1, S_TEMP);
      
      metric = getControllerConfig().isMetric;
    
       // Fetch the number of attached temperature sensors  
      numSensors = sensors.getDeviceCount();
    //numSensors = 1;
      // Present all sensors to controller
      for (int i=0; i<numSensors && i<MAX_ATTACHED_DS18B20; i++) {   
         present(i, S_TEMP);
    }
      
      // Setup the button
      pinMode(BUTTON_PIN, INPUT);
      // Activate internal pull-up
      digitalWrite(BUTTON_PIN, HIGH);
    
      // Setup the button
      pinMode(BUTTON_PIN_2, INPUT);
      // Activate internal pull-up
      digitalWrite(BUTTON_PIN_2, HIGH);
    
       // Setup the button
      pinMode(BUTTON_PIN_3, INPUT);
      // Activate internal pull-up
      digitalWrite(BUTTON_PIN_3, HIGH);
    
       // Setup the button
      pinMode(BUTTON_PIN_4, INPUT);
      // Activate internal pull-up
      digitalWrite(BUTTON_PIN_4, HIGH);
    
      // After setting up the button, setup debouncer
      debouncer.attach(BUTTON_PIN);
      debouncer.interval(5);
    
      debouncer2.attach(BUTTON_PIN_2);
      debouncer2.interval(5);
    
      debouncer3.attach(BUTTON_PIN_3);
      debouncer3.interval(5);
    
      debouncer4.attach(BUTTON_PIN_4);
      debouncer4.interval(5);
    
      // Set the initial values of oldValue/oldValue2 variables from status of physical switches
      //  if this is not done the loop() will detect status change and switch the relays on or off
      debouncer.update();
      debouncer2.update();
      debouncer3.update();
      debouncer4.update();
      oldValue = debouncer.read();
      oldValue2 = debouncer2.read();
      oldValue3 = debouncer3.read();
      oldValue4 = debouncer4.read();
    
      // Make sure relays are off when starting up
      setRelayState(RELAY_PIN, RELAY_OFF);
      // Then set relay pins in output mode
      pinMode(RELAY_PIN, OUTPUT);
    
      digitalWrite(RELAY_PIN_2, RELAY_OFF);
      // Then set relay pins in output mode
      pinMode(RELAY_PIN_2, OUTPUT);
      
       digitalWrite(RELAY_PIN_3, RELAY_OFF);
      // Then set relay pins in output mode
      pinMode(RELAY_PIN_3, OUTPUT);
    
       digitalWrite(RELAY_PIN_4, RELAY_OFF);
      // Then set relay pins in output mode
      pinMode(RELAY_PIN_4, OUTPUT);
    
      // Set relay to last known state (using eeprom storage)
      state = loadState(CHILD_ID);
      setRelayState(RELAY_PIN, state);
     state2 = loadState(CHILD_ID_2);
      setRelayState(RELAY_PIN_2, state2);
    state3 = loadState(CHILD_ID_3);
      setRelayState(RELAY_PIN_3, state3);
    state4 = loadState(CHILD_ID_4);
      setRelayState(RELAY_PIN_4, state4);
      
    }
    
    void loop()
    {
      // Fetch temperatures from Dallas sensors
      sensors.requestTemperatures();
    
      // 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)
      sleep(conversionTime);
    
      // 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) {
       // #else
       // if (temperature != -127.00 && temperature != 85.00) {
        //#endif
     
          // Send in the new temperature
          send(msgDallas.setSensor(i).set(temperature,1));
          Serial.print("Dallas");
          Serial.println(i);
          Serial.println(" :");
        Serial.println(temperature);
          // Save new temperatures for next compare
          lastTemperature[i]=temperature;
        //}
      }
    
    // Sleep for a while to save energy
      sleep(UPDATE_INTERVAL);
    
       
      dht.setup(DHT1_DATA_PIN); // set data pin of DHT1 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());
      
      // Force reading sensor, so it works also after sleep()
      dht.readSensor(true);
      
      // Get temperature from DHT library
      float temperature1 = dht.getTemperature();
      if (isnan(temperature1)) {
        Serial.println("Failed reading temperature from DHT!");
      } else if (temperature1 != lastTemp1 || nNoUpdatesTemp1 == 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
        lastTemp1 = temperature1;
        if (!metric) {
          temperature1 = dht.toFahrenheit(temperature1);
        }
        // Reset no updates counter
        nNoUpdatesTemp1 = 0;
        temperature1 += SENSOR_TEMP_OFFSET;
        send(msgTemp1.set(temperature1, 1));
    
        //#ifdef MY_DEBUG
        //Serial.print("T1: ");
        //Serial.println(temperature1);
        //#endif
      } else {
        // Increase no update counter if the temperature stayed the same
        nNoUpdatesTemp1++;
      }
    
      // Get humidity from DHT library
      float humidity1 = dht.getHumidity();
      if (isnan(humidity1)) {
        Serial.println("Failed reading humidity from DHT");
      } else if (humidity1 != lastHum1 || nNoUpdatesHum1 == 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
        lastHum1 = humidity1;
        // Reset no updates counter
        nNoUpdatesHum1 = 0;
        send(msgHum1.set(humidity1, 1));
        
        #ifdef MY_DEBUG
        Serial.print("H1: ");
        Serial.println(humidity1);
        #endif
      } else {
        // Increase no update counter if the humidity stayed the same
        nNoUpdatesHum1++;
      }
    
      // Sleep for a while to save energy
      sleep(UPDATE_INTERVAL); 
    
    
      debouncer.update();
      debouncer2.update();
      debouncer3.update();
      debouncer4.update();
      // Get the update value
      int value = debouncer.read();
      int value2 = debouncer2.read();
      int value3 = debouncer3.read();
      int value4 = debouncer4.read(); 
    
      if (value != oldValue) {
        send(msg.set(state ? false : true), true); // Send new state and request ack back
        // Write some debug info
        printStateChangedDebug(CHANGE_STATE_SOURCE_SWITCH, CHILD_ID, value);
      }
      oldValue = value;
    
      if (value2 != oldValue2) {
        send(msg2.set(state2 ? false : true), true); // Send new state and request ack back
        // Write some debug info
        printStateChangedDebug(CHANGE_STATE_SOURCE_SWITCH, CHILD_ID_2, value2);
      }
      oldValue2 = value2;
     if (value3 != oldValue3) {
        send(msg3.set(state3 ? false : true), true); // Send new state and request ack back
        // Write some debug info
        printStateChangedDebug(CHANGE_STATE_SOURCE_SWITCH, CHILD_ID_3, value3);
      }
      oldValue3 = value3;
    
      if (value4 != oldValue4) {
        send(msg4.set(state4 ? false : true), true); // Send new state and request ack back
        // Write some debug info
        printStateChangedDebug(CHANGE_STATE_SOURCE_SWITCH, CHILD_ID_4, value4);
      }
      oldValue4 = value4;
    
     }
    
    void receive(const MyMessage &message) {
      // We only expect one type of message from controller. But we better check anyway.
      if (message.isAck()) {
    #ifdef MY_DEBUG
        Serial.println(F("This is an ack from gateway"));
    #endif
      }
      else if (message.type == V_LIGHT && message.sensor == CHILD_ID) {
        // Change relay state
        state = message.getBool();
        setRelayState(RELAY_PIN, state);
        // Store state in eeprom
        saveState(CHILD_ID, state);
        // Write some debug info
        printStateChangedDebug(CHANGE_STATE_SOURCE_RADIO, CHILD_ID, state);
      }
      else if (message.type == V_LIGHT && message.sensor == CHILD_ID_2) {
        state2 = message.getBool();
        setRelayState(RELAY_PIN_2, state2);
        // Store state in eeprom
        saveState(CHILD_ID_2, state2);
        // Write some debug info
        printStateChangedDebug(CHANGE_STATE_SOURCE_RADIO, CHILD_ID_2, state2);
      }
      else if (message.type == V_LIGHT && message.sensor == CHILD_ID_3) {
       state3 = message.getBool();
        setRelayState(RELAY_PIN_3, state3);
        // Store state in eeprom
        saveState(CHILD_ID_3, state3);
        // Write some debug info
        printStateChangedDebug(CHANGE_STATE_SOURCE_RADIO, CHILD_ID_3, state3);
      }
      else if (message.type == V_LIGHT && message.sensor == CHILD_ID_4) {
        state4 = message.getBool();
        setRelayState(RELAY_PIN_4, state4);
        // Store state in eeprom
        saveState(CHILD_ID_4, state4);
        // Write some debug info
        printStateChangedDebug(CHANGE_STATE_SOURCE_RADIO, CHILD_ID_4, state4);
      }
    }
    
    // Set status of a relay pin
    void setRelayState(byte relayPin, bool value) {
      digitalWrite(relayPin, value ? RELAY_ON : RELAY_OFF);
    }
    
    // Print debug info, centralized in one place to minimize memory usage and have only one #ifdef MY_DEBUG for all state change messages
    void printStateChangedDebug(int source, int sensorID, bool value) {
    #ifdef MY_DEBUG
      Serial.print(F("Sensor value changed, source="));
      Serial.print(source == CHANGE_STATE_SOURCE_RADIO ? F("Radio") : F("Physical switch"));
      Serial.print(F(", Sensor="));
      Serial.print(sensorID);
      Serial.print(F(", New status: "));
      Serial.println(value);
    #endif
    }```

  • Hero Member

    Try changin all your sleep() to wait(). Your node can not receive commans while sleeping.



  • Thank you for quick response works perfect 👍


Log in to reply
 

Suggested Topics

  • 3
  • 3
  • 2
  • 4
  • 10
  • 2

1
Online

11.2k
Users

11.1k
Topics

112.5k
Posts