More relay and push botton

  • Hi!

    I need to control 15 relay with 15 push button (one click on, another click off) on a mega 2560 and w5100.

    I want integrate remotexy to control them.

    What is the easiest way for that?

    Can You help me with the code?

    With one button e one relay it's ok (button+remotexy), i dont know how duplicate the code for 15 times with a matrix.


  • You may have a look at this example here to avoid redundancies in your code:

  • Yes, i have try it but unsuccesfull.. this is my sketch

      RemoteXY example. 
      Smartphone Ethernet connect over W5100 Ethernet shield or module 
      (hardware serial connected).
      This shows an example of using the library RemoteXY.
      In the example you can control the pin 2 using the button on the 
      smartphone. You need to connect W5100 Ethernet shield or module. 
      W5100 used SPI interface.
      Download the mobile app from the 
      website: for connect this sketch.
      Use the website to create your own management 
      interface your arduino with your smartphone or tablet.
      You can create different management interfaces. Use buttons, 
      switches, sliders, joysticks (g-sensor) all colors and sizes 
      in its interface. Next, you will be able to get the sample 
      code for arduino to use your interface for control from a 
      smartphone or tablet. You will not need to re-install the 
      android app, as it will determine which interface you have 
      downloaded the arduino.
    //        RemoteXY include library         // 
    /* RemoteXY select connection mode and include library */ 
    // Enable debug prints to serial monitor
    #define MY_DEBUG
    // Enable and select radio type attached
    #define MY_RADIO_NRF24
    //#define MY_RADIO_RFM69
    // Enabled repeater feature for this node
    #include <Ethernet.h>
    #include <SPI.h>
    #include <RemoteXY.h>
    #include <SPI.h>
    #include <MySensors.h>
    #include <Bounce2.h>
    /* RemoteXY connection settings */
    #define REMOTEXY_SERVER_PORT 6377
    // RemoteXY configurate   
    #pragma pack(push, 1) 
    uint8_t RemoteXY_CONF[] = 
      { 255,3,0,2,0,48,0,8,13,1,
      2,31,79,78,0 }; 
    // this structure defines all the variables of your control interface  
    struct { 
        // input variable
      uint8_t button_2; // =1 if button pressed, else =0 
      uint8_t button_1; // =1 if button pressed, else =0 
      uint8_t button_all; // =1 if button pressed, else =0
        // output variable
      uint8_t led_1_r; // =0..255 LED Red brightness 
      uint8_t led_2_r; // =0..255 LED Red brightness 
        // other variable
      uint8_t connect_flag;  // =1 if wire connected, else =0 
    } RemoteXY; 
    #pragma pack(pop) 
    //           END RemoteXY include          // 
       Based on the RelayWithButtonActuator sketch
    // Enable debug prints to serial monitor
    #define MY_DEBUG
    // Enabled repeater feature for this node
    #define RELAY_ON 1
    #define RELAY_OFF 0
    #define SSR_A_ID 1   // Id of the sensor child
    #define SSR_B_ID 2   // Id of the sensor child
    const int buttonPinA = 28;
    const int buttonPinB = 29;
    const int relayPinA = 30;
    const int relayPinB = 31;
    int oldValueA = 0;
    int oldValueB = 0;
    bool stateA = false;
    bool stateB = false;
    Bounce debouncerA = Bounce();
    Bounce debouncerB = Bounce();
    MyMessage msgA(SSR_A_ID, V_STATUS);
    MyMessage msgB(SSR_B_ID, V_STATUS);
    void setup()
      pinMode(buttonPinA, INPUT_PULLUP); // Setup the button Activate internal pull-up
      pinMode(buttonPinB, INPUT_PULLUP); // Setup the button Activate internal pull-up
    // Then set relay pins in output mode
      pinMode(relayPinA, OUTPUT);
      pinMode(relayPinB, OUTPUT);
      // After setting up the buttons, setup debouncer
      // Make sure relays are off when starting up
      digitalWrite(relayPinA, RELAY_OFF);
      digitalWrite(relayPinB, RELAY_OFF);
    void presentation()  {
      // Send the sketch version information to the gateway and Controller
      sendSketchInfo("Mains Controller", "1.0");
      // Register all sensors to gw (they will be created as child devices)
      present(SSR_A_ID, S_LIGHT);
      present(SSR_B_ID, S_LIGHT);
       Example on how to asynchronously check for new messages from gw
    void loop()
      // Get the update value
      int valueA =;
      if (valueA != oldValueA && valueA == 0) {
        send(msgA.set(stateA ? false : true), true); // Send new state and request ack back
      oldValueA = valueA;
      // Get the update value
      int valueB =;
      if (valueB != oldValueB && valueB == 0) {
        send(msgB.set(stateB ? false : true), true); // Send new state and request ack back
      oldValueB = valueB;
    void receive(const MyMessage &message) {
      // We only expect one type of message from controller. But we better check anyway.
      if (message.type == V_STATUS) {
        switch (message.sensor) {
          case 1:
            stateA = message.getBool();
            digitalWrite(message.sensor + 4, stateA ? RELAY_ON : RELAY_OFF);
          case 2:
            stateB = message.getBool();
            digitalWrite(message.sensor + 4, stateB ? RELAY_ON : RELAY_OFF);
          // Write some debug info
        Serial.print("Incoming change for sensor:");
        Serial.print("from node:");
        Serial.print(", New status: ");

  • @gabriele-cirillo Can you please reformat your post using code tags (</>-button above the editing field)?
    Wrt. to your sketch: Why do you use different childIDs in the receiving part than in the header?
    Did you have a look at the sketch in the above link? You will have to learn a little, how to use arrays, so please first try to understand how it works. I agree, this is not a very simple example, but as you asked for one...
    Don't really expect me (or somebody else) to deliever completed code - in the end it's up to you to connect your buttons and SSR's to the arduino, so you should know, what you are doing 😀 .

  • sorry for tag! 🙂

    this is pratically the code of your link... with some adjustement of my pin configuration... but the output remain LOW...

    i know that is not simply 😛

  • @gabriele-cirillo Sorry, but the one you posted may be the sketch of the first post in the linked thread, but my link (at least on my computer here 😉 ) leads to a very different sketch using arrays for assinging PINs and buttons. See post #33 by @korttoma in the linked thread.

  • uh ok, sorry, i use the first, your right!

    now... i have tried this, but always unsuccesfully (i just change the pin)

    // Enable debug prints to serial monitor
    #define MY_DEBUG
    // Enable and select radio type attached
    #define MY_RADIO_NRF24
    #define SN "RelayButtonArray"
    #define SV "1.0"
    #include <MySensors.h>
    #include <SPI.h>
    #include <Bounce2.h>
    #define RELAY_ON 0                      // switch around for ACTIVE LOW / ACTIVE HIGH relay
    #define RELAY_OFF 1
    #define noRelays 4                     //2-4
    const int relayPin[] = {30, 31, 32, 33};       //  switch around pins to your desire
    const int buttonPin[] = {28, 29, 27, 26};   //  switch around pins to your desire
    class Relay             // relay class, store all relevant data (equivalent to struct)
        int buttonPin;                   // physical pin number of button
        int relayPin;             // physical pin number of relay
        boolean relayState;               // relay status (also stored in EEPROM)
    Relay Relays[noRelays];
    Bounce debouncer[noRelays];
    MyMessage msg[noRelays];
      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() {
      // 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_LIGHT;
        pinMode(Relays[i].buttonPin, INPUT_PULLUP);
        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
        debouncer[i] = Bounce();                        // initialize debouncer
    void presentation()
      // Send the sketch version information to the gateway and Controller
      sendSketchInfo(SN, SV);
      for (int i = 0; i < noRelays; i++)
        present(i, S_LIGHT);                               // present sensor to gateway
    void loop()
      for (byte i = 0; i < noRelays; i++) {
        if (debouncer[i].update()) {
          int value = debouncer[i].read();
          if ( value == LOW) {
            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));
            // save sensor state in EEPROM (location == sensor number)
            saveState( i, Relays[i].relayState );
    void receive(const MyMessage &message) {
      if (message.type == V_LIGHT) {
        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)

  • @gabriele-cirillo Can you please be a little more specific: What exactly is not working? What's the serial output?
    I have to admit, I never directly used @korttoma's sketch directly, but used the principles he applied to make own things happen. So if you want to dig into this a little more in depth, you may have a look at these here and here (the later not yet finisched, but button+relay-wise working).

  • If i trigger the input pin, the output still to LOW

    this is the serial code

    T NODE,CP=RNNNA---,VER=2.2.0
    25 TSM:INIT
    26 TSF:WUR:MS=0
    35 TSM:FAIL:CNT=1
    38 TSF:TDI:TSL
    &"⸮q_⸮⸮!⸮D⸮⸮⸮s⸮ ⸮⸮ED⸮⸮A

  • OK, this is a different topic: as long as there is no uplink to the controller, your sketch will never enter loop() and so on.
    Sounds like there is no radio module attached? Please see hints in troubleshooting, especially: log parser.
    As a workaround you may get node starting without radio by using


    But some remark wrt applying fixes like that: It's kind of frustrating to discuss basic things when beeing asked for help on really advanced features. Imo, you might get some more basic examples to work first before starting projects like the one here.

    Just my2ct...

  • you are right and sorry

    But I search for a simply code for x input and for x relay asking the best method for the code...

    now i start from 0 and try simply code! ty

  • @rejoe2 ok, i try with succesfully to make a sketch like my initial requests with array function 🙂

    for you is so simply, but for me no! 😛

    all is ok, only a problem: at boot, at the first pression of one button (pin 27, 28 or 29) put high all 3 output... with another pression of button, all go ok... you see something that i can't see? 🙂 ty

    int buttPin[3] = {27,28,29};// you do not want to use digital pins 0 or 1
    int relayPin[3] = {30,31,32};
    int lastButtState[3];
    int buttState[3];
    int debounceDelay = 50;
    int ledState[3];
    int reading[3];
    unsigned long lastDebounceTime[3];
    void setup() 
      for (int i = 0; i < 3; i++)
        pinMode(relayPin[i], OUTPUT);
        pinMode(buttPin[i], INPUT_PULLUP); 
    void loop() 
      for (int i = 0; i < 3; i++)
        reading[i] = digitalRead(buttPin[i]);
        if (reading[i] != lastButtState[i]) 
          lastDebounceTime[i] = millis();
          lastButtState[i] = reading[i];
        if ((millis() - lastDebounceTime[i]) > debounceDelay) {
           if (buttState[i] != lastButtState[i]) {
               buttState[i] = lastButtState[i];
               if (buttState[i] == HIGH) {
                     ledState[i] = !ledState[i];
                     digitalWrite(relayPin[i], ledState[i]);

  • To me, these things are also quite close to magic, don't worry 😄 .
    I don't know, what is going on at bootup, but my assumption wold be the PINs are somehow floating, as you didn't do some kind of initialisation in setup() or comparable.

    Add. remark:
    You also deleted the original debouncing function - that's possible, but as you seem to be quite good in adopting things (imo you made a big step forward). So you may review your code once more wrt that; could be the debouncer-function does a little more than just wait some time 😉 .

  • @rejoe2 i use the pullup input and i try in setup to write relayPin to LOW, to put LOW the variable but with no success...

    ps: i deleted what??!?!? 😛

  • @gabriele-cirillo said in More relay and push botton:

    ps: i deleted what??!?!? 😛

    Your code was to some extend very close to @korttoma's. So I thougt you started with a "cleaner" version ot this base and let out some parts - especially things related to

    #include <Bounce2.h>

  • ahhhhh! no, I start from 0 with an example found on the web, the @korttoma sketch is too complicated for me 😛

Log in to reply

Suggested Topics