Anyone help with 4 relays please?



  • I have a pro mini set with nrf24l01+ and a 4 relay board. GW and controller both see the set up but it is unreliable (does not always respond to state changes sent from the controller) Seems pretty random as to if it will change or not...

    I tried 2 different methods, here they are......

    1. Take the latest code from dev branch (examples/actuator/relay) and change that to make a 4 relay board work. - It does switch 'sometimes' but is not reliable enough to use...
    /**
       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
       Example sketch showing how to control physical relays.
       This example will remember relay state after power failure.
       http://www.mysensors.org/build/relay
    */
    
    // Enable debug prints to serial monitor
    #define MY_DEBUG
    
    // Enable and select radio type attached
    #define MY_RADIO_NRF24
    //#define MY_RADIO_NRF5_ESB
    //#define MY_RADIO_RFM69
    //#define MY_RADIO_RFM95
    #define MY_NODE_ID 140
    // Enable repeater functionality for this node
    //#define MY_REPEATER_FEATURE
    
    #include <MySensors.h>
    MyMessage relay_msg;
    //#define RELAY_PIN 4  // Arduino Digital I/O pin number for first relay (second on pin+1 etc)
    const int RELAY_PIN[]  {4, 5, 6, 7}; // Array for relay pins.
    #define NUMBER_OF_RELAYS 4 // 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
    
    
    void before()
    {
      for (int sensor = 1, pin = RELAY_PIN[sensor - 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);
        digitalWrite(pin, LOW);
      }
    }
    
    void setup()
    {
    
    }
    
    void presentation()
    {
      // Send the sketch version information to the gateway and Controller
      sendSketchInfo("4Relay", "1.0a");
    
      for (int sensor = 1, pin = RELAY_PIN[sensor - 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)
    {
      // Handle incoming relay commands
      if (message.type == V_STATUS) {
        // Change relay state
        if (RELAY_PIN[message.sensor - 1]) {
          digitalWrite(RELAY_PIN[message.sensor - 1], message.getBool() ? RELAY_ON : RELAY_OFF);
    
          // Store state in eeprom
          saveState(message.sensor - 1, message.getBool());
          // Write some debug info
          Serial.print("Incoming change for sensor:");
          Serial.print(message.sensor);
          Serial.print(", New status: ");
          Serial.println(message.getBool());
        }
      }
    }
    
    void relay_msg_constructor(int sensor, uint8_t type)
    {
      relay_msg.setSensor(sensor);
      relay_msg.setType(type);
    }
    

    Second attempt was to look in the forums and try an update an old thread with mys 1.x code to work with 2.2.0-rc.1 - Here is that code with alarming similar results..... 😉

    /**
           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
           Version 1.1 - HenryWhite
    
           DESCRIPTION
           Example sketch showing how to control physical relays.
           This example will remember relay state after power failure.
           Optional attachment of motion sensor to control the relays is possible.
           Notes:
              -- The Child-IDs of the attached relays range from 1 up to (1-(NUMBER_OF_RELAYS))
              -- Make sure to adjust the potentiometer for triggertime on your motion sensor as leftmost as possible,
                 because the countdown will not start until the motion sensor reports back a "0" (no movement)
    
    */
    #include <Bounce2.h>
    //----------------------- Library Configuration ---------------------
    //#define MY_DEBUG                          // uncomment to enable debug prints to serial monitor
    //#define MY_REPEATER_FEATURE               // uncomment to enable repeater functionality for this node
    #define MY_NODE_ID 140                   // uncomment to define static node ID
    
    // Enable and uncomment attached radio type
    #define MY_RADIO_NRF24
    
    //----------------------- Relay and Motion Sensor Configuration -----------------------
    #define NUMBER_OF_RELAYS  4                                       // Total number of attached relays. Must be equal to total number of elements in array below!
    #define NUMBER_OF_SWITCHES 4                                      //Total of local manual override switches.
    const int sw[]                      =     {14, 15, 16, 17};        //switches connected to a0-a3.
    const int RELAYS[]   {4, 5, 6, 7};             // digital pins of attached relays
    int value = -1;  
    #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
    bool ack = 1;                                                     // set this to 1 if you want destination node to send ack back to this node
    int oldValue = 0;
    bool state;
    //----------------------- DO NOT CHANGE -----------------------------
    #include <MySensors.h>
    MyMessage relay_msg;                                // Initialize relay message
    
    void before()
    {
    
      for (int i = 1; i <= NUMBER_OF_RELAYS; i++)
      {
        // set relay pins to output mode
        pinMode(RELAYS[i-1], OUTPUT);
        digitalWrite(RELAYS[i-1], LOW);
        // Restore relay to last known state (using eeprom storage)
        //  digitalWrite(RELAYS[i], loadState(sensor) ? RELAY_ON : RELAY_OFF);
      }
      for (int i = 14; i <= (NUMBER_OF_SWITCHES + 13); i++)
      {
        pinMode(sw[i], INPUT_PULLUP);
      }
    }
    
    void setup()
    {
    
    }
    
    void presentation()
    {
      // Send the sketch version information to the gateway and Controller
      sendSketchInfo("Relay/Motion", "1.0");
    
      // Register all sensors to gw (they will be created as child devices)
      for (int i = 1; i <= NUMBER_OF_RELAYS; i++) {
        present(i, S_BINARY, "Relay");
      }
    
    }
    
    void loop()
    {
    
    
      if (value == 0) {
        for (int i = 14; i < (NUMBER_OF_SWITCHES + 14); i++) {
          digitalRead(i);
          send(relay_msg.set(state ? false : true)); // Send new state and request ack back
        }
        oldValue = value;
    
      }
    }
    
    void receive(const MyMessage & message)
    {
      // Handle incoming relay commands
      if (message.type == V_STATUS) {
        // Change relay state
        if (RELAYS[message.sensor - 1]) {
          digitalWrite(RELAYS[message.sensor - 1], message.getBool() ? RELAY_ON : RELAY_OFF);
    
          // Store state in eeprom
          saveState(message.sensor - 1, message.getBool());
          // Write some debug info
          Serial.print("Incoming change for sensor:");
          Serial.print(message.sensor);
          Serial.print(", New status: ");
          Serial.println(message.getBool());
        }
      }
    }
    
    void relay_msg_constructor(int sensor, uint8_t type)
    {
      relay_msg.setSensor(sensor);
      relay_msg.setType(type);
    }
    

    I have reached the limit of my current understanding of this and could really do with some help to get this working before I even try and add buttons for local emergency override 😉


  • Mod

    You need to monitor the logs, check if you get any NACKs on gateway and check if the node is really receiving the message. As a test I'd try to put a wait(500) at the end of loop just to see if you get any changes.



  • @gohan,

    Thanks for the idea and moral support!

    With due respect to all involved I found this thread from last year.....

    https://forum.mysensors.org/topic/1299/array-relay-button-actuator

    The code didn't compile at first due to a typo and then when loaded it didn't work due to deprecated sensor-type and variable-type. I updated it for compatibility with 2.2.0-rc.1 and it nearly all works.

    It compiles and loads.
    The gw and controller see it and buttons made in the controller switch the relays fine.
    The local physical buttons also toggle the relays just fine.
    But when the physical buttons are used to toggle the relays, the controller does not update the status on the screen so any changes made locally are not known by the controller.

    Here is the updated code, if anyone can see an issue in the void loop() then might be causeing this I would love to hear about it!

    #define MY_RADIO_NRF24
    #define MY_RF24_PA_LEVEL   RF24_PA_LOW
    //#define MY_REPEATER_FEATURE
    
    #include <MySensors.h>
    #define MY_NODE_ID 140
    #include <SPI.h>
    #include <Bounce2.h>
    #define RELAY_ON 0                      // switch around for relay HIGH/LOW state
    #define RELAY_OFF 1
    //
    
    #define noRelays 4                     //2-4
    const int relayPin[] = {4,5,6,7};          //  switch around pins to your desire
    const int buttonPin[] = {A0,A1,A2,A3};      //  switch around pins to your desire
    
    class Relay             // relay class, store all relevant data (equivalent to struct)
    {
    public:                                      
      int buttonPin;                   // physical pin number of button
      int relayPin;             // physical pin number of relay
      byte oldValue;                    // last Values for key (debounce)
      boolean relayState;               // relay status (also stored in EEPROM)
    };
    
    Relay Relays[noRelays]; 
    Bounce debouncer[noRelays];
    MyMessage msg[noRelays];
    
    void setup(){
        sendHeartbeat();
        wait(250);
        // Initialize Relays with corresponding buttons
        for (int i = 0; i < noRelays; i++){
        Relays[i].buttonPin = buttonPin[i];              // assign physical pins
        Relays[i].relayPin = relayPin[i];
        msg[i].sensor = i;                                   // initialize messages
        msg[i].type = V_STATUS;
        debouncer[i] = Bounce();                        // initialize debouncer
        debouncer[i].attach(buttonPin[i]);
        debouncer[i].interval(5);
        pinMode(Relays[i].buttonPin, INPUT_PULLUP);
        //digitalWrite(Relays[i].relayPin, RELAY_OFF);
        wait(250);
        pinMode(Relays[i].relayPin, OUTPUT);
        Relays[i].relayState = loadState(i);                               // retrieve last values from EEPROM
        digitalWrite(Relays[i].relayPin, Relays[i].relayState? RELAY_ON:RELAY_OFF);   // and set relays accordingly
        send(msg[i].set(Relays[i].relayState? true : false));                  // make controller aware of last status  
        wait(250);
        }
    }
    void presentation()  {
          sendSketchInfo("MYS-4-Relay", "0.1");
          wait(250);
          for (int i = 0; i < noRelays; i++)
          present(i, S_BINARY);                               // present sensor to gateway
    }
    void loop()
        {
        for (byte i = 0; i < noRelays; i++){
        debouncer[i].update();
        byte value = debouncer[i].read();
        if (value != Relays[i].oldValue && value==0){
        Relays[i].relayState = !Relays[i].relayState;
        digitalWrite(Relays[i].relayPin, Relays[i].relayState?RELAY_ON:RELAY_OFF);
        send(msg[i].set(Relays[i].relayState? true : false));
        saveState( i, Relays[i].relayState );}                 // save sensor state in EEPROM (location == sensor number)
        
            Relays[i].oldValue = value;      
        }
    }
    // process incoming message 
    void receive(const MyMessage &message){        
       if (message.type == V_STATUS){ 
       if (message.sensor <noRelays){            // check if message is valid for relays..... previous line  [[[ if (message.sensor <=noRelays){ ]]]
       Relays[message.sensor].relayState = message.getBool(); 
       digitalWrite(Relays[message.sensor].relayPin, Relays[message.sensor].relayState? RELAY_ON:RELAY_OFF); // and set relays accordingly
       saveState( message.sensor, Relays[message.sensor].relayState ); // save sensor state in EEPROM (location == sensor number)
       }
      }
    }
    


  • If anyone is interested this now works perfectly with mycontroller, local buttons and remote buttons too.....



  • @skywatch Hi, I was trying to follow your findings as I have exactly the same issue, but unfortunately, although I basically used the same setup as you did, it still misbehaves. Sometimes is reacts immediately, 5 times in a row, and sometimes it simply does not work for 10 attempts. My 8 relay sketch is so simple that it can not be simpler. Also using the capacitor - still no effect. Other relay sketch - same code, same everything - works as expected 😞 Really no idea.



  • @skywatch said in Anyone help with 4 relays please?:

    If anyone is interested this now works perfectly with mycontroller, local buttons and remote buttons too.....

    Any modification to the above code? This could be very handy for me!

    EDIT: does each button pin correspond to a relay? So in your example A0 relates to 4?

    Or can I use the rules in MC to dynamically assign buttons to operations?



  • @petr nosek

    You can only compare the one that works with the one that doesn't and see if you can figure out what is different and causing the problems.

    @ZachFlem

    Yes pins A0-A3 are button inputs for relay 1-4.
    Yes, works from mycontroller and buttons - I am re-learning all this again now as my controller sd card died and I lost a lot of settings - still it will be worth it.



  • @skywatch thanks for the answer. I did compare all and they all share teh same code. Pretty much. Some work for year or two without being touched and they are even further away from the gateway. I do think, that there is either HW problem with the arduino or the radio module. Before I touch it - which of those two determine what ID is the sensor? Is it the Radio module or arduino? I ask because when I change the one which delivers the ID, all the relays on the controller will be lost and I will have to rewrite all related dependencies etc.

    Regarding your further not on the lost configuration. I found somewhere a piece of code - a script, which does upload daily the current full database and configuration to dropbox - so in case I loose the raspberry Pi or SD card, I can restore it in a minute with the history. If you ned I can find it and send it.


  • Mod

    Node id is stored in Arduino eeprom


 

309
Online

7.4k
Users

8.3k
Topics

89.6k
Posts