[SOLVED]Two nodes with relays interfering



  • As a noob I ran into a problem with two nodes.
    One (node 1) is running code to actuate 6 relays. the other one (node 2) has a relay and a pulse meter.
    Whenever I actuate the relay on node 2 (connected to pin 4), then relay 1 on node 1 (also connected to pin 4) is actuated too. When I actuate relay 1 on node 1 however, node 2 is not affected.
    Some how seems I'm overlooking something basic, but I can't figure it out 😞
    Node 1 is running the following code:

    
    #include <MySigningNone.h>
    #include <MyTransportNRF24.h>
    #include <MyTransportRFM69.h>
    #include <MyHwATMega328.h>
    #include <MySensor.h>
    #include <SPI.h>
    
    #define RELAY_1  3  // Arduino Digital I/O pin number for first relay (second on pin+1 etc)
    #define NUMBER_OF_RELAYS 6 // 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
    #define CHILD_ID 1
    
    // NRFRF24L01 radio driver (set low transmit power by default) 
    MyTransportNRF24 radio(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW);  
    //MyTransportRFM69 radio;
    // Message signing driver (none default)
    //MySigningNone signer;
    // Select AtMega328 hardware profile
    MyHwATMega328 hw;
    // Construct MySensors library
    MySensor gw(radio, hw);
    
    void setup()  
    {   
      // Initialize library and add callback for incoming messages
      gw.begin(incomingMessage, AUTO, true);
      // Send the sketch version information to the gateway and Controller
      gw.sendSketchInfo("Relay", "1.0");
    
      // Fetch relay status
      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)
        gw.present(CHILD_ID, S_LIGHT);
        // Then set relay pins in output mode
        pinMode(pin, OUTPUT);   
        // Set relay to last known state (using eeprom storage) 
        digitalWrite(pin, gw.loadState(sensor)?RELAY_ON:RELAY_OFF);
      }
    }
    
    
    void loop() 
    {
      // Alway process incoming messages whenever possible
      gw.process();
    }
    
    void incomingMessage(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
         gw.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());
       } 
    }
    
    

    Node 2 code:

    
    #include <MySensor.h>
    #include <SPI.h>
    
    
    #define DIGITAL_INPUT_SENSOR 3                  // The digital input you attached your sensor.  (Only 2 and 3 generates interrupt!)
    //#define PULSE_FACTOR 12500                       // Nummber of blinks per m3 of your meter (One rotation/liter)
    #define PULSE_FACTOR 1000
    #define SLEEP_MODE false                        // flowvalue can only be reported when sleep mode is false.
    #define MAX_WATT 10000                            // Max flow (l/min) value to report. This filetrs outliers.
    #define INTERRUPT DIGITAL_INPUT_SENSOR-2        // Usually the interrupt = pin -2 (on uno/nano anyway)
    #define CHILD_ID 3                              // Id of the sensor child
    #define RELAY_10  4  // Arduino Digital I/O pin number for first relay
    #define NUMBER_OF_RELAYS 1 
    #define RELAY_ON 0
    #define RELAY_OFF 1
    unsigned long SEND_FREQUENCY = 10000;              // Minimum time between send (in miliseconds). We don't want to spam the gateway.
    
    MySensor gw;
    
    double ppl = ((double)PULSE_FACTOR)/1000;        // Pulses per liter
    
    volatile unsigned long pulseCount = 0;   
    volatile unsigned long lastBlink = 0;
    volatile double watt = 0;
    boolean pcReceived = false;
    unsigned long oldPulseCount = 0;
    unsigned long newBlink = 0;   
    double oldwatt = 0;
    double oldKwh;
    double Kwh;                     
    unsigned long lastSend;
    unsigned long currentTime;
    unsigned long lastPulse;
    
    MyMessage wattMsg(CHILD_ID,V_WATT);
    MyMessage KwhMsg(CHILD_ID,V_KWH);
    MyMessage pcMsg(CHILD_ID,V_VAR1);
    
    void setup()  
    {  
      gw.begin(incomingMessage, AUTO, true);
      //gw.begin(incomingMessage, AUTO, false, AUTO, RF24_PA_LOW);
      //gw.begin(incomingMessage, AUTO, false, AUTO);
      //  gw.send(pcMsg.set(0));
      //  gw.send(volumeMsg.set(0.000, 3));
      //Water meter setup
      //Serial.print("PPL:");
      //Serial.print(ppl);
    
      // Send the sketch version information to the gateway and Controller
      gw.sendSketchInfo("power meter and actuator", "1.0");
    
      // Register this device as current sensor
      gw.present(CHILD_ID, S_POWER);      
    
      // Fetch last known pulse count value from gw
      gw.request(CHILD_ID, V_VAR1);
      //pulseCount = oldPulseCount = 0;
    
      //Serial.print("Last pulse count from gw:");
      //Serial.println(pulseCount);
    
      attachInterrupt(INTERRUPT, onPulse, RISING);
      lastSend = millis();
    
      //RELAY SETUP
      for (int sensor=1, pin=RELAY_10; sensor<=NUMBER_OF_RELAYS;sensor++, pin++) {
        // Register all sensors to gw (they will be created as child devices)
        gw.present(sensor, S_LIGHT);
        // Then set relay pins in output mode
        pinMode(pin, OUTPUT);   
        // Set relay to last known state (using eeprom storage) 
        digitalWrite(pin, gw.loadState(sensor)?RELAY_ON:RELAY_OFF);
      }
    
    }
    
    
    void loop()     
    { 
      gw.process();//////t
      currentTime = millis();
      bool sendTime = currentTime - lastSend > SEND_FREQUENCY;
      if (pcReceived && (SLEEP_MODE || sendTime)) {
        // New flow value has been calculated  
        if (!SLEEP_MODE && watt != oldwatt) {
          // Check that we dont get unresonable large flow value. 
          // could hapen when long wraps or false interrupt triggered
          if (watt<((unsigned long)MAX_WATT)) {
            gw.send(wattMsg.set(watt, 2));        // Send flow value to gw
          }
    
          //Serial.print("g/min:");
          // Serial.println(flow);
          oldwatt = watt;
        }
    
        // No Pulse count in 2min 
        if(currentTime - lastPulse > 20000){
          watt = 0;
        } 
    
    
        // Pulse count has changed
        if (pulseCount != oldPulseCount) {
          gw.send(pcMsg.set(pulseCount));                  // Send  volumevalue to gw VAR1
          double volume = ((double)pulseCount/((double)PULSE_FACTOR)*264.172);
          //double volume = ((double)pulseCount/((double)PULSE_FACTOR));     
          oldPulseCount = pulseCount;
          if (Kwh != oldKwh) {
            gw.send(KwhMsg.set(Kwh, 3));               // Send volume value to gw
            oldKwh = Kwh;
          } 
        }
        lastSend = currentTime;
      } 
      else if (sendTime) {
        // No count received. Try requesting it again
        gw.request(CHILD_ID, V_VAR1);
        lastSend=currentTime;
      }
    
      if (SLEEP_MODE) {
        gw.sleep(SEND_FREQUENCY);
      }     
    
    
    }
    
    
    void onPulse()     
    { 
      if (!SLEEP_MODE) {
        unsigned long newBlink = micros();   
        unsigned long interval = newBlink-lastBlink;
        lastPulse = millis();
        if (interval < 2080) {       // Sometimes we get interrupt on RISING,  500000 = 0.5sek debounce ( max 120 l/min)  WAS 2080
          return;   
        }
    
        watt = ((60000000.0 /interval) / ppl)*.264172;
        //flow = ((60000000.0 /interval) / ppl);
        // Serial.print("interval:");
        // Serial.println(interval);
        lastBlink = newBlink;
        // Serial.println(flow, 4);
      }
      pulseCount++;
    
    }
    
    void incomingMessage(const MyMessage &message) {
      if (message.type==V_VAR1) {  
        pulseCount = oldPulseCount = message.getLong();
        Serial.print("Received last pulse count from gw:");
        Serial.println(pulseCount);
        pcReceived = true;
      }
      if (message.type==V_LIGHT) {
        // Change relay state
        digitalWrite(message.sensor-1+RELAY_10, message.getBool()?RELAY_ON:RELAY_OFF);
        // Store state in eeprom
        gw.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());
      } 
    
    }
    

    Can somebody help me to figure this out?


  • Hero Member

    Do both nodes have different node ids? Maybe both nodes have stored the Same node id in eeprom and thus use it. Could you post serial output of both nodes, when it happens?



  • I just cleared the eeprom on node 2, but nothing changed.
    Output node 2:

    send: 1-1-0-0 s=255,c=0,t=18,pt=0,l=5,sg=0,st=ok:1.5.1
    send: 1-1-0-0 s=255,c=3,t=6,pt=1,l=1,sg=0,st=ok:0
    repeater started, id=1, parent=0, distance=1
    send: 1-1-0-0 s=255,c=3,t=11,pt=0,l=24,sg=0,st=ok:power meter and actuator
    send: 1-1-0-0 s=255,c=3,t=12,pt=0,l=3,sg=0,st=ok:1.0
    send: 1-1-0-0 s=3,c=0,t=13,pt=0,l=0,sg=0,st=ok:
    send: 1-1-0-0 s=3,c=2,t=24,pt=0,l=0,sg=0,st=ok:
    send: 1-1-0-0 s=1,c=0,t=3,pt=0,l=0,sg=0,st=ok:
    read: 0-0-1 s=3,c=2,t=24,pt=0,l=0,sg=0:
    Received last pulse count from gw:0
    read: 0-0-1 s=1,c=1,t=2,pt=0,l=1,sg=0:1
    send: 1-1-0-0 s=1,c=1,t=2,pt=0,l=1,sg=0,st=ok:1
    Incoming change for sensor:1, New status: 1
    read: 0-0-1 s=1,c=1,t=2,pt=0,l=1,sg=0:0
    send: 1-1-0-0 s=1,c=1,t=2,pt=0,l=1,sg=0,st=ok:0
    Incoming change for sensor:1, New status: 0
    

    Output node 1:

    send: 0-0-0-0 s=255,c=0,t=18,pt=0,l=5,sg=0,st=ok:1.5.1
    send: 0-0-0-0 s=255,c=3,t=6,pt=1,l=1,sg=0,st=ok:0
    repeater started, id=0, parent=0, distance=0
    send: 0-0-0-0 s=255,c=3,t=11,pt=0,l=5,sg=0,st=ok:Relay
    send: 0-0-0-0 s=255,c=3,t=12,pt=0,l=3,sg=0,st=ok:1.0
    send: 0-0-0-0 s=1,c=0,t=3,pt=0,l=0,sg=0,st=ok:
    send: 0-0-0-0 s=1,c=0,t=3,pt=0,l=0,sg=0,st=ok:
    send: 0-0-0-0 s=1,c=0,t=3,pt=0,l=0,sg=0,st=ok:
    send: 0-0-0-0 s=1,c=0,t=3,pt=0,l=0,sg=0,st=ok:
    send: 0-0-0-0 s=1,c=0,t=3,pt=0,l=0,sg=0,st=ok:
    send: 0-0-0-0 s=1,c=0,t=3,pt=0,l=0,sg=0,st=ok:
    read: 0-0-0 s=1,c=1,t=2,pt=0,l=1,sg=0:1
    send: 0-0-0-0 s=1,c=1,t=2,pt=0,l=1,sg=0,st=ok:1
    Incoming change for sensor:1, New status: 1
    read: 0-0-0 s=1,c=1,t=2,pt=0,l=1,sg=0:0
    send: 0-0-0-0 s=1,c=1,t=2,pt=0,l=1,sg=0,st=ok:0
    Incoming change for sensor:1, New status: 0
    read: 0-0-0 s=0,c=1,t=0,pt=7,l=5,sg=0:66.6
    

    Node 2 was not powered when I monitored this node 1 output.


  • Hardware Contributor

    The output on node 2 looks strange - ID 0 is (and should only be) the gateway!



  • @sundberg84 said:

    The output on node 2 looks strange - ID 0 is (and should only be) the gateway!

    I guess you mean node 1. And indeed, I really messed up the code somehow. Reloaded the original sketch and adapted it again, now everything works like a charm.
    Thanks everyone for thinking along!



  • Im having the same problem. But I'm not finding the solution from this thread really. Did you find it?

    I'm going to manually asign node_ids next.
    I get interference inside one node with two relays (mqtt gw + 2relay) and also across two nodes (dht+relay and 6relay node).
    I checked the mqtt traffic and it sends the same mqtt topic twice (both on and off commands).
    Controller is Domoticz.


  • Mod

    Have you tried with just leds instead of the relays, just to exclude some parts of the circuit.



  • @gohan I have the boards soldered with the relays attached (regreting that now) so that would be difficult.


  • Mod

    ok, so do you get issues either with or without load on relays? Are they optoisolated from the rest of the circuit?



  • I've tested with load only. The circuits are very basic so no opto. The relays are powered from the 5v transformer directly and not vcc off Promini.
    The problem is not global (affecting all relays in node) but only a few lights/relays seem to be "tandem".


  • Mod

    Try without load. I have seen to be a recurring problem that load causes interference on the board. I you see things getting better, you know that opto will be the way 😄



  • I will. But just out of curiosity, are relays always touchy or is it just something about certain loads? The loads are not heavy (10-15w fluorescent lamp per relay or 2-6w led bulb).


  • Mod

    You know when there are coils involved and circuits opening and closing (especially if there are inductive loads) there can be interference generated during switching. There are also solid state relays that should solve this issue, there are some projects already in the openhardware section



  • Back at this after a while... I changed code for all nodes and manually assigned node_ids to make sure nothing interferes.

    Currently the problem: when a remote nodes (number 4) relay is activated, it also causes the relay attached to gw-node to activate. The gw attached relay works well by itself (optocoupled).
    I checked MQTT traffic and there's nothing fishy (activation message "1"). I also checked the debug on the gw and that looks OK to me as well.
    The gw relays are optocoupled, the outside (it's a dht22+single relay node) light relay is not. GW receives power from car battery thru usb, so no interference should be possible.

    Any ideas?

    Conflicting relays code:

    // Enable debug prints
    #define MY_DEBUG
    #define MY_REPEATER_FEATURE
    
    // Enable and select radio type attached 
    #define MY_RADIO_NRF24
    //#define MY_RADIO_RFM69
    //#define MY_RS485
    #define MY_NODE_ID 4
    
    #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 4
    
    // 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
    
    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);
    DHT dht;
    
    #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 1  // GPIO value to write to turn on attached relay
    #define RELAY_OFF 0 // GPIO value to write to turn off attached relay
    #define CHILD_ID_RELAY 2
    
    void before()
    {
      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("TempHumRelUlko", "vMasi");
    
      // 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_RELAY, S_BINARY);
    
      metric = getControllerConfig().isMetric;
    
      //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_BINARY);
      //}
    }
    
    
    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(2000);
    }
    
    
    void loop()      
    {  
      // Force reading sensor, so it works also after sleep()
      dht.readSensor(true);
    
      // Get temperature from DHT library
      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);
        }
        // Reset no updates counter
        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++;
      }
    
      // Sleep for a while to save energy
      //sleep(UPDATE_INTERVAL); 
    
    wait(120000);
    }
    
    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_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());
      }
    }
    
    

    And the debug from GW:

    0;255;3;0;9;MCO:BGN:INIT GW,CP=RNNGA--,VER=2.1.1
    0;255;3;0;9;MCO:BGN:BFR
    0;255;3;0;9;TSM:INIT
    0;255;3;0;9;TSF:WUR:MS=0
    0;255;3;0;9;TSM:INIT:TSP OK
    0;255;3;0;9;TSM:INIT:GW MODE
    0;255;3;0;9;TSM:READY:ID=0,PAR=0,DIS=0
    0;255;3;0;9;MCO:REG:NOT NEEDED
    IP: 192.168.0.201
    0;255;3;0;9;MCO:BGN:STP
    0;255;3;0;9;MCO:BGN:INIT OK,TSP=1
    IP: 192.168.0.201
    0;255;3;0;9;Attempting MQTT connection...
    0;255;3;0;9;MQTT connected
    0;255;3;0;9;Sending message on topic: domoticz/in/MyMQTT/0/255/0/0/18
    0;255;3;0;9;Sending message on topic: domoticz/in/MyMQTT/0/255/3/0/11
    0;255;3;0;9;Sending message on topic: domoticz/in/MyMQTT/0/255/3/0/12
    0;255;3;0;9;Sending message on topic: domoticz/in/MyMQTT/0/1/0/0/3
    0;255;3;0;9;Sending message on topic: domoticz/in/MyMQTT/0/2/0/0/3
    0;255;3;0;9;Message arrived on topic: domoticz/out/MyMQTT/4/1/1/1/2
    0;255;3;0;9;TSF:MSG:SEND,0-0-4-4,s=1,c=1,t=2,pt=0,l=1,sg=0,ft=0,st=OK:0
    0;255;3;0;9;TSF:MSG:READ,4-4-0,s=1,c=1,t=2,pt=0,l=1,sg=0:0
    0;255;3;0;9;TSF:MSG:ACK
    0;255;3;0;9;Sending message on topic: domoticz/in/MyMQTT/4/1/1/1/2
    Incoming change for sensor:1, New status: 0
    0;255;3;0;9;Message arrived on topic: domoticz/out/MyMQTT/4/1/1/1/2
    0;255;3;0;9;TSF:MSG:SEND,0-0-4-4,s=1,c=1,t=2,pt=0,l=1,sg=0,ft=0,st=OK:0
    0;255;3;0;9;TSF:MSG:READ,4-4-0,s=1,c=1,t=2,pt=0,l=1,sg=0:0
    0;255;3;0;9;TSF:MSG:ACK
    0;255;3;0;9;Sending message on topic: domoticz/in/MyMQTT/4/1/1/1/2
    Incoming change for sensor:1, New status: 0
    0;255;3;0;9;Message arrived on topic: domoticz/out/MyMQTT/4/1/1/1/2
    0;255;3;0;9;TSF:MSG:SEND,0-0-4-4,s=1,c=1,t=2,pt=0,l=1,sg=0,ft=0,st=OK:1
    0;255;3;0;9;TSF:MSG:READ,4-4-0,s=1,c=1,t=2,pt=0,l=1,sg=0:1
    0;255;3;0;9;TSF:MSG:ACK
    0;255;3;0;9;Sending message on topic: domoticz/in/MyMQTT/4/1/1/1/2
    Incoming change for sensor:1, New status: 1
    
    

  • Mod

    @MasMat could you post the sketch for your gateway node as well?



  • Sure. Here it is. Slight mod from MQTT sketch with Relay sketch parts.

    #define MY_DEBUG
    
    // Enables and select radio type (if attached)
    #define MY_RADIO_NRF24
    //#define MY_RADIO_RFM69
    
    #define MY_GATEWAY_MQTT_CLIENT
    
    // Set this node's subscribe and publish topic prefix
    #define MY_MQTT_PUBLISH_TOPIC_PREFIX "domoticz/in/MyMQTT"
    #define MY_MQTT_SUBSCRIBE_TOPIC_PREFIX "domoticz/out/MyMQTT"
    
    // Set MQTT client id
    #define MY_MQTT_CLIENT_ID "mysensors-1"
    
    // W5100 Ethernet module SPI enable (optional if using a shield/module that manages SPI_EN signal)
    //#define MY_W5100_SPI_EN 4
    
    // Enable Soft SPI for NRF radio (note different radio wiring is required)
    // The W5100 ethernet module seems to have a hard time co-operate with
    // radio on the same spi bus.
    #if !defined(MY_W5100_SPI_EN) && !defined(ARDUINO_ARCH_SAMD)
    #define MY_SOFTSPI
    #define MY_SOFT_SPI_SCK_PIN 14
    #define MY_SOFT_SPI_MISO_PIN 16
    #define MY_SOFT_SPI_MOSI_PIN 15
    #endif
    
    // When W5100 is connected we have to move CE/CSN pins for NRF radio
    #ifndef MY_RF24_CE_PIN
    #define MY_RF24_CE_PIN 5
    #endif
    #ifndef MY_RF24_CS_PIN
    #define MY_RF24_CS_PIN 6
    #endif
    
    // Enable MY_IP_ADDRESS here if you want a static ip address (no DHCP)
    #define MY_IP_ADDRESS 192,168,0,201
    #define MY_MAC_ADDRESS 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
    
    // If using static ip you need to define Gateway and Subnet address as well
    #define MY_IP_GATEWAY_ADDRESS 192,168,0,254
    #define MY_IP_SUBNET_ADDRESS 255,255,255,0
    
    // MQTT broker ip address or url. Define one or the other.
    //#define MY_CONTROLLER_URL_ADDRESS "m20.cloudmqtt.com"
    #define MY_CONTROLLER_IP_ADDRESS 192, 168, 0, 200
    
    // The MQTT broker port to to open
    #define MY_PORT 1883
    
    /*
    // Enable inclusion mode
    #define MY_INCLUSION_MODE_FEATURE
    // Enable Inclusion mode button on gateway
    //#define MY_INCLUSION_BUTTON_FEATURE
    // Set inclusion mode duration (in seconds)
    #define MY_INCLUSION_MODE_DURATION 60
    // Digital pin used for inclusion mode button
    //#define MY_INCLUSION_MODE_BUTTON_PIN  3
    
    // Set blinking period
    #define MY_DEFAULT_LED_BLINK_PERIOD 300
    
    // Flash leds on rx/tx/err
    // Uncomment to override default HW configurations
    //#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 RELAY_1  3  // Arduino Digital I/O pin number for first relay (second on pin+1 etc)
    #define NUMBER_OF_RELAYS 2 // 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
    // #define CHILD_ID_RELAY1 1
    // #define CHILD_ID_RELAY2 2
    
    #include <Ethernet.h>
    #include <MySensors.h>
    
    void before()
    {
      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 setup()
    {
    
    }
    
    void presentation()
    {
      // Send the sketch version information to the gateway and Controller
      sendSketchInfo("MQTT_GWAndRelay", "vMasi");
    
      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_BINARY);
      }
    }
    
    
    void loop()
    {
    
    }
    
    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_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());
      }
    }
    
    

  • Mod

    @MasMat Looks like the gateway's receive function is called even when the gateway is the destination of the message. That results in the gateway updating its relay even though it shouldn't.

    I think you could do something like this:

    if (message.type==V_STATUS) {
        if (message.sensor == 0) { // Only switch the relay if the message is for myself
            Serial.print("Updating relay state");
            // 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
        }
        // Write some debug info
        Serial.print("Incoming change for sensor:");
        Serial.print(message.sensor);
        Serial.print(", New status: ");
        Serial.println(message.getBool());
    }
    


  • @mfalkvidd All this under "void loop"? Do I remove the "void receive"?

    I added (and commented out previous) under "void receive": the relay became unresponsive.
    debug:

    0;255;3;0;9;Message arrived on topic: domoticz/out/MyMQTT/0/2/1/0/2
    Incoming change for sensor:2, New status: 1
    0;255;3;0;9;Message arrived on topic: domoticz/out/MyMQTT/0/2/1/0/2
    Incoming change for sensor:2, New status: 0
    
    

  • Mod

    You need the receive, just replace the code



  • @gohan I did. Relay unresponsive but clearly the messages are coming thru. Went back, relay works so not mechanical/electrical.
    Current code:

    void receive(const MyMessage &message)
    {
    if (message.type==V_STATUS) {
        if (message.sensor == 0) { // Only switch the relay if the message is for myself
            Serial.print("Updating relay state");
            // 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
        }
        // Write some debug info
        Serial.print("Incoming change for sensor:");
        Serial.print(message.sensor);
        Serial.print(", New status: ");
        Serial.println(message.getBool());
    }
    


  • @mfalkvidd I've been reviewing this: I have two relays actually attached, so this code will ignore the other completely, right? I think that's why it's not working. Or the numbering for the sensors is different?

    Am I wrong or does the "message.sensor" actually refer to child_id rather than node_id? Or am I following this wrong?


  • Mod

    @MasMat I have trouble finding documentation explaining the details, but I think you are right. See if message.destination works better.



  • @mfalkvidd That fixed it right up and makes complete sense. I couldn't find docs either on message.sensor or message.destination...

    The problem now appears more complex...
    The GW (node 0) relay STILL follows the other nodes (node 4) commands (completely different circuits, so no electrical connection at all).

    GW debug (first a on & off test for gw-relay, then clicked the node4-relay, on comes OK (gwrelay follows) but off reboots gw)

    0;255;3;0;9;Message arrived on topic: domoticz/out/MyMQTT/0/1/1/0/2
    Updating relay stateIncoming change for sensor:1, New status: 1
    0;255;3;0;9;Message arrived on topic: domoticz/out/MyMQTT/0/1/1/0/2
    Updating relay stateIncoming change for sensor:1, New status: 0
    0;255;3;0;9;TSF:MSG:READ,4-4-0,s=1,c=1,t=0,pt=7,l=5,sg=0:16.6
    0;255;3;0;9;Sending message on topic: domoticz/in/MyMQTT/4/1/1/0/0
    0;255;3;0;9;TSF:MSG:READ,4-4-0,s=0,c=1,t=1,pt=7,l=5,sg=0:69.8
    0;255;3;0;9;Sending message on topic: domoticz/in/MyMQTT/4/0/1/0/1
    0;255;3;0;9;Message arrived on topic: domoticz/out/MyMQTT/4/1/1/1/2
    0;255;3;0;9;TSF:MSG:SEND,0-0-4-4,s=1,c=1,t=2,pt=0,l=1,sg=0,ft=0,st=OK:1
    0;255;3;0;9;TSF:MSG:READ,4-4-0,s=1,c=1,t=2,pt=0,l=1,sg=0:1
    0;255;3;0;9;TSF:MSG:ACK
    0;255;3;0;9;Sending message on topic: domoticz/in/MyMQTT/4/1/1/1/2
    Updating relay stateIncoming change for sensor:1, New status: 1
    0;255;3;0;9;Message arrived on topic: domoticz/out/MyMQTT/4/1/1/1/2
    0;255;3;0;9;!TSF:MSG:SEND,0-0-4-4,s=1,c=1,t=2,pt=0,l=1,sg=0,ft=0,st=NACK:1
    0;255;3;0;9;MCO:BGN:INIT GW,CP=RNNGA--,VER=2.1.1
    0;255;3;0;9;MCO:BGN:BFR```


  • Nevermind. Whined too soon.
    Completely worked over the node4 code, moved "include"s around and eventually changed the relay presentations and receive clauses. Hope this helps someone with their problems later:
    Thanks a millions!

    void before()
    {
        // Set relay pin in output mode
        pinMode(RELAY_1, OUTPUT);
        // Set relay to last known state (using eeprom storage)
        digitalWrite(RELAY_1, loadState(CHILD_ID_RELAY)?RELAY_ON:RELAY_OFF);
    }
    
    later this....
    
    present(CHILD_ID_RELAY, S_BINARY);
    
    
    ....and ending with this...
    
    void receive(const MyMessage &message)
    {
    if (message.type==V_STATUS) {
        if (message.destination == MY_NODE_ID) { // Only switch the relay if the message is for this node
            Serial.print("Updating relay state");
            // Change relay state
            digitalWrite(RELAY_1, message.getBool()?RELAY_ON:RELAY_OFF);
            // Store state in eeprom
            saveState(CHILD_ID_RELAY, message.getBool());
            // Write some debug info
        }
        // Write some debug info
        Serial.print("Incoming change for sensor:");
        Serial.print(message.sensor);
        Serial.print(", New status: ");
        Serial.println(message.getBool());
    }
     
    }
    
    

  • Mod

    @MasMat great work! Maybe change this to make the output more complete?

        // Write some debug info
        Serial.print("Incoming change for sensor:");
    

    to

        // Write some debug info
        Serial.print("Incoming change for node: ");
        Serial.print(message.destination);
        Serial.print(", sensor:");
    


  • @mfalkvidd That would definitely polish it up! 😄
    Cheers!!


Log in to reply
 

Suggested Topics

23
Online

11.2k
Users

11.1k
Topics

112.5k
Posts