How to add another relay



  • Hello,

    Sorry for the question, I still do not understand much programming.

    How to add more relay in the code below:

    #define MY_REPEATER_FEATURE
    
    #include <MySensors.h>
    
    #define RELAY_PIN 4  // 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
    
    
    void before()
    {
        for (int sensor=1, pin=RELAY_PIN; 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("Relay", "1.0");
    
        for (int sensor=1, pin=RELAY_PIN; 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_PIN, 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());
        }
    }
    

    I'm using an ESP8266.



  • @alexandre The code already supports more relays, so there is not much you need to do.

    1. Change the line #define NUMBER_OF_RELAYS 1 to #define NUMBER_OF_RELAYS 2/3/4 etc. Until you run out of pins!

    The rest of the code will automatically be handled within the 'for' loops.


  • Mod

    A caveat with esp8266: gpio 6 is not exposed externally, so a maximum of 2 relays can be used (gpio 4 and 5).
    Gpio 12, 13 and 14 can also be used but will require modification of the sketch.



  • Thank you very much.


 

331
Online

7.9k
Users

8.8k
Topics

93.8k
Posts