Irrigation Controller (up to 16 valves with Shift Registers)



  • @AWI
    I'll try it.

    @Ngwpower
    Don't drop the towel. Just install the library from the libraries manager.



  • @Sergio-Rius Really confused found these in AVR libraries on my computer. 0_1469044384924_upload-b0e77311-082b-4d33-9473-c59ef1302d37
    Am I looking in the wrong place?
    Thank You for the help!



  • @Ngwpower
    ArduinoIDE Menu->Program->Include Library->Library manager
    0_1469044814353_upload-bdb3d59c-30bb-4c2e-8345-9aa060d3d67e

    I'm currently looking at converting the sketch to v2.0



  • This post is deleted!


  • Hello, is there anyone who can explain to me step by step how to deal with these libraries ? I received this error when compiling :

    "C:\Users\witkowski.med\Downloads\IrrigationController\IrrigationController\IrrigationController.ino:85:22: fatal error: MySensor.h: No such file or directory

    #include <MySensor.h>

                      ^
    

    compilation terminated.

    exit status 1"

    I have installed the various library and it doesnt help. My IDE version is 1.6.10.



  • @PaweMed
    If you've done a new installation, perhaps you installed Mysensors libraries from the IDE lib manager. In that case you could have installed v2.0.
    In the newer version the library has changed to Mysensors.h, please read the documentation carefully as this is not a minor upgrade:
    https://forum.mysensors.org/topic/4276/converting-a-sketch-from-1-5-x-to-2-0-x



  • This post is deleted!


  • @rechin304 - that's a great case/box. Where did you purchase it?





  • I am in the process of building this controller and in reading the comments here where some were asking about a master valve and how to control it. This is the concept that I am going to try with my setup.
    alt text
    I only have 4 zones to control, so with the 8 channel relay board that I have, I am going to use channel 8 as my pump start relay control. The idea is that when any one channel is on, the diodes will activate the master valve, but keep the signal from back-feeding into another relay channel.

    Hope that helps some people out there.



  • So I figured I would share my progress with my version of this project. The majority of the build was done to the schematic from the build section of the site. The only changes I am making are eliminating the use of Q0 on the shift register, and wiring in diodes like I mentioned in my previous post to control my pump start relay using relay channel 8 when any zone is turned on. I may even add a connection for one more digital line for a pump only startup, but will have to see about the code mods to do that.

    One of my hurdles that I wanted to overcome was what kind of case I would be building this in. I searched on ebay a bit, but couldn't find what I wanted. I was digging through some old stuff one day and found an old composite video A/V switcher that I no longer use.
    A/V switcher front
    A/V switcher back
    Rather than recycling it, I figured, why not up-cycle it. The case was the perfect size for the 8 channel relay board. I even kept the back portion of the original circuit board to re-use the old DC in jack and build my regulator circuit on using an AMS1117 3.3v regulator. The output of the power board is Ground (black), +5V (red) and +3.3V (yellow).
    relay/power boards
    AMS1117 regulator
    I cut a slot in the front of the case to allow access to the relay connections.
    front cutout
    The connections came out just enough to allow access to the screw terminals. You can also see the mouning of the LCD, push button and status LED.
    screw terminals
    main board
    I designed the circuit board so that it could plug directly on top of the 8 channel relay board. Notice the header connector strip between the pro mini and the shift register. There is just enough room above the blue 3 input power connector to attach the FTDI cable for programming the pro mini. The last thing I need to add to the board is the 8 diodes to control the pump start relay which will be channel 8 on the relay board. Currently the code uses outputs Q0 thru Q7 of the shift register to control relays 1 thru 8. I will need to make a slight change to the code to use Q1 thru Q7 as the first 7 relays as it was easier to connect it that way to the header connector. I am eliminating the use of Q0 in the circuit.

    I am having a few issues with compiling the code to upload to the pro mini. It is telling me that it can't find the LiquidCrystal.h file, and I have the library in my arduino library folder. The folder has both the LiquidCrystal.h and LiquidCrystal_I2C.h files, so I am not sure what is up there. I hope to have it figured out soon so I can test the assembly.

    Thanks for reviewing.



  • I am trying to use this controller with Domoticz and I am wondering how to set the valve times. Is there anyone that is using this controller with Domoticz that can help?



  • Hi, in original code is written to work with Vera - this is similar to Domoticz. But I same like you have Domoticz on my RPi0. Some time ago I changed some lines in this code that it is working now with Domoticz.

    /*
    MySprinkler for MySensors
    
    Arduino Multi-Zone Sprinkler Control
    
    May 31, 2015
    
    *** Version 2.0
    
    *** Upgraded to http://MySensors.org version 1.4.1
    *** Expanded for up to 16 Valves
    *** Setup for active low relay board or comment out #define ACTIVE_LOW to switch to active high
    *** Switch to bitshift method vs byte arrays
    *** Changed RUN_ALL_ZONES Vera device to 0 (was highest valve)
    *** Added optional LCD display featuring remaining time, date last ran & current time
    *** Features 'raindrop' and 'clock' icons which indicate sensor is updating valve data and clock respectively
    *** Added single pushbutton menu to manually select which program to run (All Zones or a Single Zone)
    *** Added option of naming your Zones programmatically or with Vera (V_VAR3 used to store names)
    
    Utilizing your Vera home automation controller and the MySensors.org gateway you can
    control up to a sixteen zone irrigation system with only three digital pins.  This sketch
    will create NUMBER_OF_VALVES + 1 devices on your Vera controller
    
    This sketch features the following:
    
    * Allows you to cycle through All zones (RUN_ALL_ZONES) or individual zone (RUN_SINGLE_ZONE) control.
    * Use the 0th controller to activate RUN_ALL_ZONES (each zone in numeric sequence 1 to n)
      using Variable1 as the "ON" time in minutes in each of the vera devices created.
    * Use the individual zone controller to activate a single zone.  This feature uses
      Variable2 as the "ON" time for each individual device/zone.
    * Connect according to pinout below and uses Shift Registers as to allow the MySensors
      standard radio configuration and still leave available digital pins
    * Turning on any zone will stop the current process and begin that particular process.
    * Turning off any zone will stop the current process and turn off all zones.
    * To push your new time intervals for your zones, simply change the variable on your Vera and
      your arduino will call to Vera once a minute and update accordingly.  Variables will also be
      requested when the device is first powered on.
    * Pushbutton activation to RUN_ALL_ZONES, RUN_SINGLE_ZONE or halt the current program
    * LED status indicator
    
    PARTS LIST:
    Available from the MySensors store - http://www.mysensors.org/store/
    * Relays (8 channel)
    * Female Pin Header Connector Strip
    * Prototype Universal Printed Circuit Boards (PCB)
    * NRF24L01 Radio
    * Arduino (I used a Pro Mini)
    * FTDI USB to TTL Serial Adapter
    * Capacitors (10uf and .1uf)
    * 3.3v voltage regulator
    * Resistors (270 & 10K)
    * Female Dupont Cables
    * 1602 LCD (with I2C Interface)
    * LED
    * Push button
    * Shift Register (SN74HC595)
    * 2 Pole 5mm Pitch PCB Mount Screw Terminal Block
    * 3 Pole 5mm Pitch PCB Mount Screw Terminal Block
    * 22-24 gauge wire or similar (I used Cat5/Cat6 cable)
    * 18 gauge wire (for relay)
    * Irrigation Power Supply (24-Volt/750 mA Transformer)
    
    
    INSTRUCTIONS:
    
    * A step-by-step setup video is available here: http://youtu.be/l4GPRTsuHkI
    * After assembling your arduino, radio, decoupling capacitors, shift register(s), status LED, pushbutton LCD (I2C connected to
      A4 and A5) and relays, and load the sketch.
    * Following the instructions at https://MySensors.org include the device to your MySensors Gateway.
    * Verify that each new device has a Variable1, Variable2 and Variable3. Populate data accordingly with whole minutes for
      the RUN_ALL_ZONES routine (Variable1) and the RUN_SINGLE_ZONE routines (Variable 2).  The values entered for times may be zero and
      you may use the defaulet zone names by leaving Variable3 blank.
    * Once you have entered values for each zone and each variable, save the settings by pressing the red save button on your Vera.
    * Restart your arduino; verify the settings are loaded into your arduino with the serial monitor; the array will be printed
      on the serial monitor.
    * Your arduino should slow-flash, indicating that it is in ready mode.
    * There are multiple debug serial prints that can be monitored to assure that it is operating properly.
    * ***THIS SHOULD NO LONGER BE NEEDED*** The standard MySensors library now works. https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads for the I2C library, or use yours
    
    Contributed by Jim (BulldogLowell@gmail.com) with much contribution from Pete (pete.will@mysensors.org) and is released to the public domain
    */
    //
    #include <Wire.h>
    #include <Time.h>
    #include <MySensor.h>
    #include <SPI.h>
    #include <LiquidCrystal.h>
    #include <LiquidCrystal_I2C.h>
    
    
    //
    #define NUMBER_OF_VALVES 8  // Change this to set your valve count up to 16.
    #define VALVE_RESET_TIME 7500UL   // Change this (in milliseconds) for the time you need your valves to hydraulically reset and change state
    #define RADIO_ID AUTO  // Change this to fix your Radio ID or use Auto
    
    #define SKETCH_NAME "MySprinkler"
    #define SKETCH_VERSION "2.0"
    //
    #define CHILD_ID_SPRINKLER 0
    //
    #define ACTIVE_LOW // comment out this line if your relays are active high
    //
    #define DEBUG_ON   // comment out to supress serial monitor output
    //
    #ifdef ACTIVE_LOW
    #define BITSHIFT_VALVE_NUMBER ~(1U << (valveNumber-1))
    #define ALL_VALVES_OFF 0xFFFF
    #else
    #define BITSHIFT_VALVE_NUMBER (1U << (valveNumber-1))
    #define ALL_VALVES_OFF 0U
    #endif
    //
    #ifdef DEBUG_ON
    #define DEBUG_PRINT(x)   Serial.print(x)
    #define DEBUG_PRINTLN(x) Serial.println(x)
    #define SERIAL_START(x)  Serial.begin(x)
    #else
    #define DEBUG_PRINT(x)
    #define DEBUG_PRINTLN(x)
    #define SERIAL_START(x)
    #endif
    //
    typedef enum {
      STAND_BY_ALL_OFF, RUN_SINGLE_ZONE, RUN_ALL_ZONES, CYCLE_COMPLETE, ZONE_SELECT_MENU
    }
    SprinklerStates;
    //
    SprinklerStates state = STAND_BY_ALL_OFF;
    SprinklerStates lastState;
    byte menuState = 0;
    unsigned long menuTimer;
    byte countDownTime = 10;
    //
    int allZoneTime [NUMBER_OF_VALVES + 1];
    int valveSoloTime [NUMBER_OF_VALVES + 1];
    int valveNumber;
    int lastValve;
    unsigned long startMillis;
    const int ledPin = 5;
    const int waterButtonPin = 3;
    boolean buttonPushed = false;
    boolean showTime = true;
    boolean clockUpdating = false;
    boolean recentUpdate = true;
    const char *dayOfWeek[] = {
      "Null", "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "
    };
    // Name your Zones here or use Vera to edit them by adding a name in Variable3...
    String valveNickName[17] = {
      "All Zones", "Zone 1", "Podlewanie 1", "Podlewanie 2", "Podlewanie 3", "Podlewanie 4", "Zone 6", "Zone 7", "Zone 8", "Zone 9", "Zone 10", "Zone 11", "Zone 12", "Zone 13", "Zone 14", "Zone 15", "Zone 16"
    };
    //
    time_t lastTimeRun = 0;
    //Setup Shift Register...
    const int latchPin = 8;
    const int clockPin = 4;
    const int dataPin  = 7;
    //
    byte clock[8] = {0x0, 0xe, 0x15, 0x17, 0x11, 0xe, 0x0}; // fetching time indicator
    byte raindrop[8] = {0x4, 0x4, 0xA, 0xA, 0x11, 0xE, 0x0,}; // fetching Valve Data indicator
    // Set the pins on the I2C chip used for LCD connections:
    //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address to 0x27
    MySensor gw;
    //
    MyMessage msg1valve(CHILD_ID_SPRINKLER, V_LIGHT);
    MyMessage var1valve(CHILD_ID_SPRINKLER, V_VAR1);
    MyMessage var2valve(CHILD_ID_SPRINKLER, V_VAR2);
    //
    void setup()
    {
      SERIAL_START(115200);
      DEBUG_PRINTLN(F("Initialising..."));
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(ledPin, OUTPUT);
      pinMode(waterButtonPin, INPUT_PULLUP);
      //pinMode(waterButtonPin, INPUT);
      attachInterrupt(1, PushButton, RISING); //May need to change for your Arduino model
      digitalWrite (ledPin, HIGH);
      DEBUG_PRINTLN(F("Turning All Valves Off..."));
      updateRelays(ALL_VALVES_OFF);
      //delay(5000);
      lcd.begin(16, 2); //(16 characters and 2 line display)
      lcd.clear();
      lcd.backlight();
      lcd.createChar(0, clock);
      lcd.createChar(1, raindrop);
      //
      //check for saved date in EEPROM
      DEBUG_PRINTLN(F("Checking EEPROM for stored date:"));
      delay(500);
      if (gw.loadState(0) == 0xFF); // EEPROM flag
      {
        DEBUG_PRINTLN(F("Retreiving last run time from EEPROM..."));
        for (int i = 0; i < 4 ; i++)
        {
          lastTimeRun = lastTimeRun << 8;
          lastTimeRun = lastTimeRun | gw.loadState(i + 1); // assemble 4 bytes into an ussigned long epoch timestamp
        }
      }
      gw.begin(getVariables, RADIO_ID, false); // Change 'false' to 'true' to create a Radio repeating node
      gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION);
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        gw.present(i, S_LIGHT);
      }
      DEBUG_PRINTLN(F("Sensor Presentation Complete"));
      //
      digitalWrite (ledPin, LOW);
      DEBUG_PRINTLN(F("Ready..."));
      //
      lcd.setCursor(0, 0);
      lcd.print(F(" Syncing Time  "));
      lcd.setCursor(15, 0);
      lcd.write(byte(0));
      lcd.setCursor(0, 1);
      int clockCounter = 0;
      while (timeStatus() == timeNotSet && clockCounter < 21)
      {
        gw.process();
        gw.requestTime(receiveTime);
        DEBUG_PRINTLN(F("Requesting time from Gateway:"));
        delay(1000);
        lcd.print(".");
        clockCounter++;
        if (clockCounter > 16)
        {
          DEBUG_PRINTLN(F("Failed initial clock synchronization!"));
          lcd.clear();
          lcd.print(F("  Failed Clock  "));
          lcd.setCursor(0, 1);
          lcd.print(F(" Syncronization "));
          delay(2000);
          break;
        }
      }
      //
      lcd.clear();
      //Update valve data when first powered on
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        lcd.print(F(" Updating  "));
        lcd.setCursor(0, 1);
        lcd.print(F(" Valve Data: "));
        lcd.print(i);
        boolean flashIcon = false;
        DEBUG_PRINT(F("Calling for Valve "));
        DEBUG_PRINT(i);
        DEBUG_PRINTLN(F(" Data..."));
        while (gw.process() == false)
        {
          lcd.setCursor(15, 0);
          flashIcon = !flashIcon;
          flashIcon ? lcd.write(byte(1)) : lcd.print(F(" "));
          gw.request(i, V_VAR1);
          delay(100);
        }
        while (gw.process() == false)
        {
          lcd.setCursor(15, 0);
          flashIcon = !flashIcon;
          flashIcon ? lcd.write(byte(1)) : lcd.print(F(" "));
          gw.request(i, V_VAR2);
          delay(100);
        }
        while (gw.process() == false)
        {
          lcd.setCursor(15, 0);
          flashIcon = !flashIcon;
          flashIcon ? lcd.write(byte(1)) : lcd.print(F(" "));
          gw.request(i, V_VAR3);
          delay(100);
        }
      }
      lcd.clear();
    }
    //
    void loop()
    {
      gw.process();
      updateClock();
      updateDisplay();
      goGetValveTimes();
      //
      if (buttonPushed)
      {
        menuTimer = millis();
        DEBUG_PRINTLN(F("Button Pressed"));
        if (state == STAND_BY_ALL_OFF)
        {
          state = ZONE_SELECT_MENU;
          menuState = 0;
        }
        else if (state == ZONE_SELECT_MENU)
        {
          menuState++;
          if (menuState > NUMBER_OF_VALVES)
          {
            menuState = 0;
          }
        }
        else
        {
          state = STAND_BY_ALL_OFF;
        }
        buttonPushed = false;
      }
      if (state == STAND_BY_ALL_OFF)
      {
        slowToggleLED ();
        if (state != lastState)
        {
          updateRelays(ALL_VALVES_OFF);
          DEBUG_PRINTLN(F("State Changed... all Zones off"));
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            delay(50);
            gw.send(msg1valve.setSensor(i).set(false), false);
          }
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print(F("** Irrigation **"));
          lcd.setCursor(0,1);
          lcd.print(F("**   Halted   **"));
          delay(2000);
          lastValve = -1;
        }
      }
      //
      else if (state == RUN_ALL_ZONES)
      {
        if (lastValve != valveNumber)
        {
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            if (i == 0 || i == valveNumber)
            {
              gw.send(msg1valve.setSensor(i).set(true), false);
            }
            else
            {
              gw.send(msg1valve.setSensor(i).set(false), false);
            }
          }
        }
        lastValve = valveNumber;
        fastToggleLed();
        if (state != lastState)
        {
          valveNumber = 1;
          updateRelays(ALL_VALVES_OFF);
          DEBUG_PRINTLN(F("State Changed, Running All Zones..."));
        }
        unsigned long nowMillis = millis();
        if (nowMillis - startMillis < VALVE_RESET_TIME)
        {
          updateRelays(ALL_VALVES_OFF);
        }
        else if (nowMillis - startMillis < (allZoneTime[valveNumber] * 60000UL))
        {
          updateRelays(BITSHIFT_VALVE_NUMBER);
        }
        else
        {
          DEBUG_PRINTLN(F("Changing Valves..."));
          updateRelays(ALL_VALVES_OFF);
          startMillis = millis();
          valveNumber++;
          if (valveNumber > NUMBER_OF_VALVES)
          {
            state = CYCLE_COMPLETE;
            startMillis = millis();
            lastValve = -1;
            lastTimeRun = now();
            saveDateToEEPROM(lastTimeRun);
            for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
            {
              gw.send(msg1valve.setSensor(i).set(false), false);
            }
            DEBUG_PRINT(F("State = "));
            DEBUG_PRINTLN(state);
          }
        }
      }
      //
      else if (state == RUN_SINGLE_ZONE)
      {
        fastToggleLed();
        if (state != lastState)
        {
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            if (i == 0 || i == valveNumber)
            {
              gw.send(msg1valve.setSensor(i).set(true), false);
            }
            else
            {
              gw.send(msg1valve.setSensor(i).set(false), false);
            }
          }
          DEBUG_PRINTLN(F("State Changed, Single Zone Running..."));
          DEBUG_PRINT(F("Zone: "));
          DEBUG_PRINTLN(valveNumber);
        }
        unsigned long nowMillis = millis();
        if (nowMillis - startMillis < VALVE_RESET_TIME)
        {
          updateRelays(ALL_VALVES_OFF);
        }
        else if (nowMillis - startMillis < (valveSoloTime [valveNumber] * 60000UL))
        {
          updateRelays(BITSHIFT_VALVE_NUMBER);
        }
        else
        {
          updateRelays(ALL_VALVES_OFF);
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            gw.send(msg1valve.setSensor(i).set(false), false);
          }
          state = CYCLE_COMPLETE;
          startMillis = millis();
          DEBUG_PRINT(F("State = "));
          DEBUG_PRINTLN(state);
        }
        lastTimeRun = now();
      }
      else if (state == CYCLE_COMPLETE)
      {
        if (millis() - startMillis < 30000UL)
        {
          fastToggleLed();
        }
        else
        {
          state = STAND_BY_ALL_OFF;
        }
      }
      else if (state = ZONE_SELECT_MENU)
      {
        displayMenu();
      }
      lastState = state;
    }
    //
    void displayMenu(void)
    {
      static byte lastMenuState = -1;
      static int lastSecond;
      if (menuState != lastMenuState)
      {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(valveNickName[menuState]);
        lcd.setCursor(0, 1);
        lcd.print(F("Starting"));
        DEBUG_PRINT(valveNickName[menuState]);
        Serial.print(F(" Starting Shortly"));
      }
      int thisSecond = (millis() - menuTimer) / 1000UL;
      if (thisSecond != lastSecond && thisSecond < 8)
      {
        lcd.print(F("."));
        Serial.print(".");
      }
      lastSecond = thisSecond;
      if (millis() - menuTimer > 10000UL)
      {
        startMillis = millis();
        if (menuState == 0)
        {
          valveNumber = 1;
          state = RUN_ALL_ZONES;
        }
        else
        {
          valveNumber = menuState;
          state = RUN_SINGLE_ZONE;
        }
      }
      else
      {
    
      }
      lastMenuState = menuState;
    }
    //
    void updateRelays(int value)
    {
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, MSBFIRST, highByte(value));
      shiftOut(dataPin, clockPin, MSBFIRST, lowByte(value));
      digitalWrite(latchPin, HIGH);
    }
    //
    void PushButton() //interrupt with debounce
    {
      static unsigned long last_interrupt_time = 0;
      unsigned long interrupt_time = millis();
      if (interrupt_time - last_interrupt_time > 200)
      {
        buttonPushed = true;
      }
      last_interrupt_time = interrupt_time;
    }
    //
    void fastToggleLed()
    {
      static unsigned long fastLedTimer;
      if (millis() - fastLedTimer >= 100UL)
      {
        digitalWrite(ledPin, !digitalRead(ledPin));
        fastLedTimer = millis ();
      }
    }
    //
    void slowToggleLED ()
    {
      static unsigned long slowLedTimer;
      if (millis() - slowLedTimer >= 1250UL)
      {
        digitalWrite(ledPin, !digitalRead(ledPin));
        slowLedTimer = millis ();
      }
    }
    //
    void getVariables(const MyMessage &message)
    {
      boolean zoneTimeUpdate = false;
      if (message.isAck())
      {
        DEBUG_PRINTLN(F("This is an ack from gateway"));
      }
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        if (message.sensor == i)
        {
          if (message.type == V_LIGHT)
          {
            int switchState = atoi(message.data);
            if (switchState == 0)
            {
              state = STAND_BY_ALL_OFF;
              DEBUG_PRINTLN(F("Recieved Instruction to Cancel..."));
            }
            else
            {
              if (i == 0)
              {
                state = RUN_ALL_ZONES;
                valveNumber = 1;
                DEBUG_PRINTLN(F("Recieved Instruction to Run All Zones..."));
              }
              else
              {
                state = RUN_SINGLE_ZONE;
                valveNumber = i;
                DEBUG_PRINT(F("Recieved Instruction to Activate Zone: "));
                DEBUG_PRINTLN(i);
              }
            }
            startMillis = millis();
          }
          else if (message.type == V_VAR1)
          {
            int variable1 = 15; // atoi(message.data);// RUN_ALL_ZONES time
            DEBUG_PRINT(F("Recieved variable1 valve:"));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" = "));
            DEBUG_PRINTLN(variable1);
            if (variable1 != allZoneTime[i])
            {
              allZoneTime[i] = variable1;
    
              zoneTimeUpdate = true;
            }
          }
          else if (message.type == V_VAR2)
          {
            int variable2 = 10; //atoi(message.data);// RUN_SINGLE_ZONE time
            DEBUG_PRINT(F("Recieved variable2 valve:"));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" = "));
            DEBUG_PRINTLN(variable2);
            if (variable2 != valveSoloTime[i])
            {
              valveSoloTime[i] = variable2;
              zoneTimeUpdate = true;
            }
          }
          else if (message.type == V_VAR3)
          {
            String newMessage = String(message.data);
            if (newMessage.length() == 0) 
            {
              DEBUG_PRINT(F("No Name Recieved for zone "));
              DEBUG_PRINTLN(i);
              break;
            }
            if (newMessage.length() > 16)
            {
              newMessage.substring(0, 16);
            }
            valveNickName[i] = "";
            valveNickName[i] += newMessage;
            DEBUG_PRINT(F("Recieved new name for zone "));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" and it is now called: "));
            DEBUG_PRINTLN(valveNickName[i]);
          }
        }
      }
      if (zoneTimeUpdate)
      {
        //
        DEBUG_PRINTLN(F("New Zone Times Recieved..."));
        for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
        {
          if (i != 0)
          {
            DEBUG_PRINT(F("Zone "));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" individual time: "));
            DEBUG_PRINT(valveSoloTime[i]);
            DEBUG_PRINT(F(" group time: "));
            DEBUG_PRINTLN(allZoneTime[i]);
            recentUpdate = true;
          }
        }
      }
      else
      {
        recentUpdate = false;
      }
    }
    //
    void updateDisplay()
    {
      static unsigned long lastUpdateTime;
      static boolean displayToggle = false;
      //static byte toggleCounter = 0;
      static SprinklerStates lastDisplayState;
      if (state != lastDisplayState || millis() - lastUpdateTime >= 3000UL)
      {
        displayToggle = !displayToggle;
        switch (state) {
          case STAND_BY_ALL_OFF:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F("  System Ready "));
              if (clockUpdating)
              {
                lcd.setCursor(15, 0);
                lcd.write(byte(0));
              }
              lcd.setCursor(0, 1);
              lcd.print(hour() < 10 ? F(" ") : F(""));
              lcd.print(hour());
              lcd.print(minute() < 10 ? F(":0") : F(":"));
              lcd.print(minute());
              //lcd.print(isAM() ? F("am") : F("pm"));
              lcd.setCursor(7, 1);
              lcd.print(day() < 10 ? F(" 0") : F(" "));
              lcd.print(day());
              lcd.print(month() < 10 ? F("/0") : F("/"));
              lcd.print(month());
              lcd.print(F("/"));
              lcd.print(year() % 100);
            }
            else
            {
              lcd.print(F("  Last Watered "));
              if (clockUpdating)
              {
                lcd.setCursor(15, 0);
                lcd.write(byte(0));
              }
              lcd.setCursor(0, 1);
              lcd.print(dayOfWeek[weekday(lastTimeRun)]);
              lcd.setCursor(10, 1);
              lcd.print(day(lastTimeRun) < 10 ? F(" 0") : F(""));
              lcd.print(day(lastTimeRun));
              lcd.print(month(lastTimeRun) < 10 ? F("/0") : F("/"));
              lcd.print(month(lastTimeRun));
            }
            break;
          case RUN_SINGLE_ZONE:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F("Single Zone Mode"));
              lcd.setCursor(0, 1);
              lcd.print(F(" Zone:"));
              if (valveNumber < 10) lcd.print(F("0"));
              lcd.print(valveNumber);
              lcd.print(F(" Active"));
            }
            else
            {
              lcd.print(F(" Time Remaining "));
              lcd.setCursor(0, 1);
              if (valveSoloTime[valveNumber] == 0)
              {
                lcd.print(F(" No Valve Time "));
              }
              else
              {
                unsigned long timeRemaining = (valveSoloTime[valveNumber] * 60) - ((millis() - startMillis) / 1000);
                lcd.print(timeRemaining / 60 < 10 ? "   0" : "   ");
                lcd.print(timeRemaining / 60);
                lcd.print("min");
                lcd.print(timeRemaining % 60 < 10 ? " 0" : " ");
                lcd.print(timeRemaining % 60);
                lcd.print("sec  ");
              }
            }
            break;
          case RUN_ALL_ZONES:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F(" All-Zone  Mode "));
              lcd.setCursor(0, 1);
              lcd.print(F(" Zone:"));
              if (valveNumber < 10) lcd.print(F("0"));
              lcd.print(valveNumber);
              lcd.print(F(" Active "));
            }
            else
            {
              lcd.print(F(" Time Remaining "));
              lcd.setCursor(0, 1);
              int timeRemaining = (allZoneTime[valveNumber] * 60) - ((millis() - startMillis) / 1000);
              lcd.print((timeRemaining / 60) < 10 ? "   0" : "   ");
              lcd.print(timeRemaining / 60);
              lcd.print("min");
              lcd.print(timeRemaining % 60 < 10 ? " 0" : " ");
              lcd.print(timeRemaining % 60);
              lcd.print("sec  ");
            }
            break;
          case CYCLE_COMPLETE:
            //
            if (displayToggle)
            {
              lcd.setCursor(0, 0);
              lcd.print(F(" Watering Cycle "));
              lcd.setCursor(0, 1);
              lcd.print(F("    Complete    "));
            }
            else
            {
              int totalTimeRan = 0;
              for (int i = 1; i < NUMBER_OF_VALVES + 1; i++)
              {
                totalTimeRan += allZoneTime[i];
              }
              lcd.setCursor(0, 0);
              lcd.print(F(" Total Time Run "));
              lcd.setCursor(0, 1);
              lcd.print(totalTimeRan < 10 ? "   0" : "   ");
              lcd.print(totalTimeRan);
              lcd.print(" Minutes   ");
            }
        }
        lastUpdateTime = millis();
      }
      lastDisplayState = state;
    }
    void receiveTime(time_t newTime)
    {
      DEBUG_PRINTLN(F("Time value received and updated..."));
      int lastSecond = second();
      int lastMinute = minute();
      int lastHour = hour();
      setTime(newTime);
      if (((second() != lastSecond) || (minute() != lastMinute) || (hour() != lastHour)) || showTime)
      {
        DEBUG_PRINTLN(F("Clock updated...."));
        DEBUG_PRINT(F("Sensor's time currently set to:"));
        DEBUG_PRINT(hourFormat12() < 10 ? F(" 0") : F(" "));
        DEBUG_PRINT(hourFormat12());
        DEBUG_PRINT(minute() < 10 ? F(":0") : F(":"));
        DEBUG_PRINT(minute());
        DEBUG_PRINTLN(isAM() ? F("am") : F("pm"));
        DEBUG_PRINT(month());
        DEBUG_PRINT(F("/"));
        DEBUG_PRINT(day());
        DEBUG_PRINT(F("/"));
        DEBUG_PRINTLN(year());
        DEBUG_PRINTLN(dayOfWeek[weekday()]);
        showTime = false;
      }
      else
      {
        DEBUG_PRINTLN(F("Sensor's time did NOT need adjustment greater than 1 second."));
      }
      clockUpdating = false;
    }
    void fastClear()
    {
      lcd.setCursor(0, 0);
      lcd.print(F("                "));
      lcd.setCursor(0, 1);
      lcd.print(F("                "));
    }
    //
    void updateClock()
    {
      static unsigned long lastVeraGetTime;
      if (millis() - lastVeraGetTime >= 3600000UL) // updates clock time and gets zone times from vera once every hour
      {
        DEBUG_PRINTLN(F("Requesting time and valve data from Gateway..."));
        lcd.setCursor(15, 0);
        lcd.write(byte(0));
        clockUpdating = true;
        gw.requestTime(receiveTime);
        lastVeraGetTime = millis();
      }
    }
    //
    void saveDateToEEPROM(unsigned long theDate)
    {
      DEBUG_PRINTLN(F("Saving Last Run date"));
      if (gw.loadState(0) != 0xFF)
      {
        gw.saveState(0, 0xFF); // EEPROM flag for last date saved stored in EEPROM (location zero)
      }
      //
      for (int i = 1; i < 5; i++)
      {
        gw.saveState(5 - i, byte(theDate >> 8 * (i - 1))); // store epoch datestamp in 4 bytes of EEPROM starting in location one
      }
    }
    //
    void goGetValveTimes()
    {
      static unsigned long valveUpdateTime;
      static byte valveIndex = 1;
      if (millis() - valveUpdateTime >= 300000UL / NUMBER_OF_VALVES)// update each valve once every 5 mins (distributes the traffic)
      {
        DEBUG_PRINTLN(F("Calling for Valve Data..."));
        lcd.setCursor(15, 0);
        lcd.write(byte(1)); //lcd.write(1);
        gw.request(valveIndex, V_VAR1);
        gw.request(valveIndex, V_VAR2);
        gw.request(valveIndex, V_VAR3);
        valveUpdateTime = millis();
        valveIndex++;
        if (valveIndex > NUMBER_OF_VALVES + 1)
        {
          valveIndex = 1;
        }
      }
    }
    

    Ok, originally time - how long relay is triggered was downloaded from Vera, I commented out this two lines and specify time there. When you power on arduino - program is trying to connect to Vera and download all data but it obviously fail at it. After a while it's just get date and time from Domoticz. So no names of zones or how long water them. All is hard coded in Arduino.

    int variable1 = 15; // atoi(message.data);// RUN_ALL_ZONES time
    int variable2 = 10; //atoi(message.data);// RUN_SINGLE_ZONE time
    

    Now there is 15 minutes if you trigger all zones and 10 minutes if you choose specific single zone.

    If you want change it you need burn it again on Arduino - so it is not the best solution, but it works 🙂 And it is about 1 week with testing all with laptop and FTDI connected to this controller. After that - you can leave it forever.

    PS, also I changed date and time - it is 24h and DD/MM/YY - so more European friendly 🙂



  • @Huczas One of the main things I wanted with this project was the ability to change the watering times in the automation software using a script. If I have to reprogram the arduino every time I want to change a time it seems pointless . I am looking into a few ideas with this to make it work in Domoticz. If I come up with something, it is most likely going to be a hack workaround.

    I have a post also in the Domoticz forum on a more generalized solution that would cover this situation. Seems though that this is something that the Domoticz team will need to implement. Hopefully I can figure out some kind of workaround to get this going for now.



  • @dbemowsk Hmm if you set 1 hour or more and start watering in Domoticz, then you can manually (or by script) turn off wathering during that time - this is my simple solution to your problem 🙂

    But remember - RPi isn't that reliable for me, it can freeze and then you get swamp instead of nice grass.



  • @Huczas That is all the more reason to have it on the sprinkler controller node. I am trying what I think might be a workable solution. I need to do more testing with it tonight to see if it's going to work, but I think it will. Once I test it I will post my code.



  • @dbemowsk

    While domoticz devs implement a way of better managing variables, perhaps you can implement a text sensor in the sketch and use it like a "times array". You could then populate it from Domoticz and send to the node as it was some text to show on a display.

    I was porting this sketch to mysensors v2 but the changes on this version are so deep that I discarded it.



  • @Sergio-Rius That is the exact thing I am working on. In Domoticz it shows up as devices, but I can live with that for now until they can do something.



  • domoticz i don't think have plans to support this, they took out the ability to use free text variables.

    I plan on doing 1 minute cycles for irrigation and using a moisture sensor to evaluate how much longer the cycles need to run for.




  • Admin

    @Mark-Jefford said:

    domoticz i don't think have plans to support this, they took out the ability to use free text variables.
    😞 that's unfortunate. Do they have any other way to store and retrieve variables? Has anyone reached out to them with this need?



  • @Mark-Jefford said:

    domoticz i don't think have plans to support this, they took out the ability to use free text variables.

    I plan on doing 1 minute cycles for irrigation and using a moisture sensor to evaluate how much longer the cycles need to run for.

    Can you elaborate a little more? What do you mean when you say free text variables?



  • Now that I read it twice... Just see that I writed "text sensor" not text or custom variables. That was what I first thought as a solution when I read about the the custom variable sending was dropped.

    And yes, it's so unfortunate that Domoticz doesn't foresees the need to have "intelligent" nodes. That's so limiting. I would like to build, for example, a garage door opener or a central heating controller. Those things must continue working even if domoticz loses connection. And they must have standalone routines that must be preconfigured without being a programmer.
    What if someone wants to sell an easy to use kit? In my language we say this is "andar con burreras", walking the path with those flaps horses and donkeys wear so they can't see sidewise.



  • @Sergio-Rius said:

    it's so unfortunate that Domoticz doesn't foresees the need to have "intelligent" nodes. That's so limiting.

    I agree. That's a big part of automation.



  • I am very close to having this working. The hardest part so far is sorting out all the text devices in Domoticz. I needed to use JSON calls to set the data for each of the text devices, but once they are set I shouldn't have to change them. But being JSON calls I should be able to easily change them with a script if needed.

    So I have the node present S_INFO devices for each of the 3 variables (all zones time, individual zone time, and zone name). I have 4 zones, so that presents 12 new devices to Domoticz. I have set zone names and they display correctly on the irrigation controller, I just need to figure out some of the zone time variables and what devices they are attached to.

    I should have this working in the next couple days and once I get it I will post the code with some notes on configuring it all.



  • Just an idea I was considering for my project, but haven't got around implementing yet so I don't know how viable it is.
    Wouldn't it be possible to use a S_Dimmer type of device instead of an S_Light?
    That way you can set the "dimmer" value in the UI between 0-100, and use this as the minutes in the sketch (I doubt I will water any part of my garden more than 100 mn). Granted it does not allow to have 2 different settings for manual and automatic, but I don't see this as a real limitation (actually, S_Dimmer also has a V_Watt variable, so theoretically you could also use that one).



  • So I think I have this figured out.One of the things that I had to contend with was running out of memory on my 5V Pro Mini 328. To fix this I had to comment out and shorten some of the DEBUG PRINTLN statements which didn't impede functionality.

    The key to making this work is presenting 3 new sensors for each zone. The sensors are S_INFO sensors that use V_TEXT variables. Because these are new to 2.0 and our sketch is for 1.5, we need to define them to be able to use them.

    const int V_TEXT = 47;
    // new S_INFO sensor type (development 20150905)
    const int S_INFO = 36 ;
    

    Here is how I present the new sensors. The S_LIGHT sensor is the valve control. The next 3 S_INFO sensors are the replacements for V_VAR1 - V_VAR3. They are defined as follows;
    All zones time
    Individual zone time
    Zone display name

     for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        gw.present((i * 4), S_LIGHT);
        gw.present(((i * 4) + 1), S_INFO);
        gw.present(((i * 4) + 2), S_INFO);
        gw.present(((i * 4) + 3), S_INFO);
      }
    

    The hardest part in this was figuring out the V_TEXT values on the Domoticz side. What I found was the easiest was to set each to a numeric value from 1 to whatever number of sensors are presented. To set the values type this into the address bar of your web browser:

    http://{your_domoticz_ip_address}:8080/json.htm?type=command&param=udevice&idx=41&nvalue=0&svalue=1
    

    Replace the 41 in idx=41 wit the idx value in the setup>devices list, and change the 1 in svalue=1 to the number next number. Once those are set, start all zones using the button on the controller. You will see one of the numbers on the display. Match that number with it's index (idx) value and re-run the above json command changing the idx to the matched index, and the svalue to the name of the zone:

    http://{your_domoticz_ip_address}:8080/json.htm?type=command&param=udevice&idx=36&nvalue=0&svalue=Run all zones
    

    Repeat this for all zone names. Then repeat the process by letting a zone start and matching a zone time to it's index. That is the reason for setting each V_TEXT variable to a unique number. When testing each zone on an "All Zones" run, it is best to find the first zone and set the time to 1 minute. Then run "All Zones" again and let the first zone run its 1 minute to hit the zone 2 time. Continue this through all zones changing the Domoticz names and values for each to identify them all.

    I have not been able to fully test this as my controller is set up slightly different than the one presented. I have done the steps above and have all of that set, but my zone 1 is my master valve, and zones 2 through 5 are my zones 1 through 4. Because of this I need to figure out the changes in my sketch. If someone can test this as I have it so far, that would help. Once I know this works, I will make my needed changes.

    Here is the complete modified sketch:

    /*
    MySprinkler for MySensors
    
    Arduino Multi-Zone Sprinkler Control
    
    May 31, 2015
    
    *** Version 2.0
    
    *** Upgraded to http://MySensors.org version 1.4.1
    *** Expanded for up to 16 Valves
    *** Setup for active low relay board or comment out #define ACTIVE_LOW to switch to active high
    *** Switch to bitshift method vs byte arrays
    *** Changed RUN_ALL_ZONES Vera device to 0 (was highest valve)
    *** Added optional LCD display featuring remaining time, date last ran & current time
    *** Features 'raindrop' and 'clock' icons which indicate sensor is updating valve data and clock respectively
    *** Added single pushbutton menu to manually select which program to run (All Zones or a Single Zone)
    *** Added option of naming your Zones programmatically or with Vera (V_VAR3 used to store names)
    
    Utilizing your Vera home automation controller and the MySensors.org gateway you can
    control up to a sixteen zone irrigation system with only three digital pins.  This sketch
    will create NUMBER_OF_VALVES + 1 devices on your Vera controller
    
    This sketch features the following:
    
    * Allows you to cycle through All zones (RUN_ALL_ZONES) or individual zone (RUN_SINGLE_ZONE) control.
    * Use the 0th controller to activate RUN_ALL_ZONES (each zone in numeric sequence 1 to n)
      using Variable1 as the "ON" time in minutes in each of the vera devices created.
    * Use the individual zone controller to activate a single zone.  This feature uses
      Variable2 as the "ON" time for each individual device/zone.
    * Connect according to pinout below and uses Shift Registers as to allow the MySensors
      standard radio configuration and still leave available digital pins
    * Turning on any zone will stop the current process and begin that particular process.
    * Turning off any zone will stop the current process and turn off all zones.
    * To push your new time intervals for your zones, simply change the variable on your Vera and
      your arduino will call to Vera once a minute and update accordingly.  Variables will also be
      requested when the device is first powered on.
    * Pushbutton activation to RUN_ALL_ZONES, RUN_SINGLE_ZONE or halt the current program
    * LED status indicator
    
    PARTS LIST:
    Available from the MySensors store - http://www.mysensors.org/store/
    * Relays (8 channel)
    * Female Pin Header Connector Strip
    * Prototype Universal Printed Circuit Boards (PCB)
    * NRF24L01 Radio
    * Arduino (I used a Pro Mini)
    * FTDI USB to TTL Serial Adapter
    * Capacitors (10uf and .1uf)
    * 3.3v voltage regulator
    * Resistors (270 & 10K)
    * Female Dupont Cables
    * 1602 LCD (with I2C Interface)
    * LED
    * Push button
    * Shift Register (SN74HC595)
    * 2 Pole 5mm Pitch PCB Mount Screw Terminal Block
    * 3 Pole 5mm Pitch PCB Mount Screw Terminal Block
    * 22-24 gauge wire or similar (I used Cat5/Cat6 cable)
    * 18 gauge wire (for relay)
    * Irrigation Power Supply (24-Volt/750 mA Transformer)
    
    
    INSTRUCTIONS:
    
    * A step-by-step setup video is available here: http://youtu.be/l4GPRTsuHkI
    * After assembling your arduino, radio, decoupling capacitors, shift register(s), status LED, pushbutton LCD (I2C connected to
      A4 and A5) and relays, and load the sketch.
    * Following the instructions at https://MySensors.org include the device to your MySensors Gateway.
    * Verify that each new device has a Variable1, Variable2 and Variable3. Populate data accordingly with whole minutes for
      the RUN_ALL_ZONES routine (Variable1) and the RUN_SINGLE_ZONE routines (Variable 2).  The values entered for times may be zero and
      you may use the defaulet zone names by leaving Variable3 blank.
    * Once you have entered values for each zone and each variable, save the settings by pressing the red save button on your Vera.
    * Restart your arduino; verify the settings are loaded into your arduino with the serial monitor; the array will be printed
      on the serial monitor.
    * Your arduino should slow-flash, indicating that it is in ready mode.
    * There are multiple debug serial prints that can be monitored to assure that it is operating properly.
    * ***THIS SHOULD NO LONGER BE NEEDED*** The standard MySensors library now works. https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads for the I2C library, or use yours
    
    Contributed by Jim (BulldogLowell@gmail.com) with much contribution from Pete (pete.will@mysensors.org) and is released to the public domain
    */
    //
    #include <Wire.h>
    #include <Time.h>
    #include <MySensor.h>
    #include <SPI.h>
    #include <LiquidCrystal.h>
    #include <LiquidCrystal_I2C.h>
    
    
    //
    #define NUMBER_OF_VALVES 4  // Change this to set your valve count up to 16.
    #define VALVE_RESET_TIME 7500UL   // Change this (in milliseconds) for the time you need your valves to hydraulically reset and change state
    #define RADIO_ID AUTO  // Change this to fix your Radio ID or use Auto
    
    #define SKETCH_NAME "MySprinkler"
    #define SKETCH_VERSION "2.0"
    //
    #define CHILD_ID_SPRINKLER 0
    #define CHILD_ID_SPRINKLER_ALL 1
    #define CHILD_ID_SPRINKLER_IND 2
    //
    #define ACTIVE_LOW // comment out this line if your relays are active high
    //
    #define DEBUG_ON   // comment out to supress serial monitor output
    //
    #ifdef ACTIVE_LOW
    #define BITSHIFT_VALVE_NUMBER ~(1U << (valveNumber-1))
    #define ALL_VALVES_OFF 0xFFFF
    #else
    #define BITSHIFT_VALVE_NUMBER (1U << (valveNumber-1))
    #define ALL_VALVES_OFF 0U
    #endif
    //
    #ifdef DEBUG_ON
    #define DEBUG_PRINT(x)   Serial.print(x)
    #define DEBUG_PRINTLN(x) Serial.println(x)
    #define SERIAL_START(x)  Serial.begin(x)
    #else
    #define DEBUG_PRINT(x)
    #define DEBUG_PRINTLN(x)
    #define SERIAL_START(x)
    #endif
    
    // new V_TEXT variable type (development 20150905)
    const int V_TEXT = 47;
    // new S_INFO sensor type (development 20150905)
    const int S_INFO = 36 ;
    
    //
    typedef enum {
      STAND_BY_ALL_OFF, RUN_SINGLE_ZONE, RUN_ALL_ZONES, CYCLE_COMPLETE, ZONE_SELECT_MENU
    }
    SprinklerStates;
    //
    SprinklerStates state = STAND_BY_ALL_OFF;
    SprinklerStates lastState;
    byte menuState = 0;
    unsigned long menuTimer;
    byte countDownTime = 10;
    //
    int allZoneTime [NUMBER_OF_VALVES + 1];
    int valveSoloTime [NUMBER_OF_VALVES + 1];
    int valveNumber;
    int lastValve;
    unsigned long startMillis;
    const int ledPin = 5;
    const int waterButtonPin = 3;
    boolean buttonPushed = false;
    boolean showTime = true;
    boolean clockUpdating = false;
    boolean recentUpdate = true;
    const char *dayOfWeek[] = {
      "Null", "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "
    };
    // Name your Zones here or use Vera to edit them by adding a name in Variable3...
    String valveNickName[17] = {
      "All Zones", "Zone 1", "Zone 2", "Zone 3", "Zone 4", "Zone 5", "Zone 6", "Zone 7", "Zone 8", "Zone 9", "Zone 10", "Zone 11", "Zone 12", "Zone 13", "Zone 14", "Zone 15", "Zone 16"
    };
    //
    time_t lastTimeRun = 0;
    //Setup Shift Register...
    const int latchPin = 8;
    const int clockPin = 4;
    const int dataPin  = 7;
    //
    byte clock[8] = {0x0, 0xe, 0x15, 0x17, 0x11, 0xe, 0x0}; // fetching time indicator
    byte raindrop[8] = {0x4, 0x4, 0xA, 0xA, 0x11, 0xE, 0x0,}; // fetching Valve Data indicator
    // Set the pins on the I2C chip used for LCD connections:
    //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
    LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address to 0x27
    MySensor gw;
    //
    MyMessage msg1valve(CHILD_ID_SPRINKLER, V_LIGHT);
    MyMessage var1valve(CHILD_ID_SPRINKLER_ALL, V_TEXT);
    MyMessage var2valve(CHILD_ID_SPRINKLER_IND, V_TEXT);
    
    bool receivedInitialValue = false;
    //
    void setup()
    {
      SERIAL_START(115200);
      DEBUG_PRINTLN(F("Initialising..."));
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(ledPin, OUTPUT);
      pinMode(waterButtonPin, INPUT_PULLUP);
      //pinMode(waterButtonPin, INPUT);
      attachInterrupt(1, PushButton, RISING); //May need to change for your Arduino model
      digitalWrite (ledPin, HIGH);
      DEBUG_PRINTLN(F("Turning All Valves Off..."));
      updateRelays(ALL_VALVES_OFF);
      //delay(5000);
      lcd.begin(16, 2); //(16 characters and 2 line display)
      lcd.clear();
      lcd.backlight();
      lcd.createChar(0, clock);
      lcd.createChar(1, raindrop);
      //
      //check for saved date in EEPROM
      //DEBUG_PRINTLN(F("Checking EEPROM for stored date:"));
      delay(500);
      if (gw.loadState(0) == 0xFF); // EEPROM flag
      {
        //``DEBUG_PRINTLN(F("Retreiving last run time from EEPROM..."));
        for (int i = 0; i < 4 ; i++)
        {
          lastTimeRun = lastTimeRun << 8;
          lastTimeRun = lastTimeRun | gw.loadState(i + 1); // assemble 4 bytes into an ussigned long epoch timestamp
        }
      }
      gw.begin(getVariables, RADIO_ID, false); // Change 'false' to 'true' to create a Radio repeating node
      gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION);
    
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        gw.present((i * 4), S_LIGHT);
        gw.present(((i * 4) + 1), S_INFO);
        gw.present(((i * 4) + 2), S_INFO);
        gw.present(((i * 4) + 3), S_INFO);
      }
      DEBUG_PRINTLN(F("Presentation Complete"));
      //
      digitalWrite (ledPin, LOW);
      DEBUG_PRINTLN(F("Ready..."));
      //
      lcd.setCursor(0, 0);
      lcd.print(F(" Syncing Time  "));
      lcd.setCursor(15, 0);
      lcd.write(byte(0));
      lcd.setCursor(0, 1);
      int clockCounter = 0;
      while (timeStatus() == timeNotSet && clockCounter < 21)
      {
        gw.process();
        gw.requestTime(receiveTime);
        DEBUG_PRINTLN(F("Requesting time:"));
        delay(1000);
        lcd.print(".");
        clockCounter++;
        if (clockCounter > 16)
        {
          DEBUG_PRINTLN(F("Failed synchronization!"));
          lcd.clear();
          lcd.print(F("  Failed Clock  "));
          lcd.setCursor(0, 1);
          lcd.print(F(" Syncronization "));
          delay(2000);
          break;
        }
      }
      //
      lcd.clear();
      //Update valve data when first powered on
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        lcd.print(F(" Updating  "));
        lcd.setCursor(0, 1);
        lcd.print(F(" Valve Data: "));
        lcd.print(i);
        boolean flashIcon = false;
        DEBUG_PRINT(F("Calling for Valve "));
        DEBUG_PRINT(i);
        DEBUG_PRINTLN(F(" Data..."));
        while (gw.process() == false)
        {
          lcd.setCursor(15, 0);
          flashIcon = !flashIcon;
          flashIcon ? lcd.write(byte(1)) : lcd.print(F(" "));
          gw.request((i * 4) + 1, V_TEXT);
          delay(100);
        }
        while (gw.process() == false)
        {
          lcd.setCursor(15, 0);
          flashIcon = !flashIcon;
          flashIcon ? lcd.write(byte(1)) : lcd.print(F(" "));
          gw.request((i * 4) + 2, V_TEXT);
          delay(100);
        }
        while (gw.process() == false)
        {
          lcd.setCursor(15, 0);
          flashIcon = !flashIcon;
          flashIcon ? lcd.write(byte(1)) : lcd.print(F(" "));
          gw.request((i * 4) + 3, V_TEXT);
          delay(100);
        }
      }
      lcd.clear();
    }
    //
    void loop()
    {
      gw.process();
      updateClock();
      updateDisplay();
      goGetValveTimes();
      //
      if (buttonPushed)
      {
        menuTimer = millis();
        DEBUG_PRINTLN(F("Button Pressed"));
        if (state == STAND_BY_ALL_OFF)
        {
          state = ZONE_SELECT_MENU;
          menuState = 0;
        }
        else if (state == ZONE_SELECT_MENU)
        {
          menuState++;
          if (menuState > NUMBER_OF_VALVES)
          {
            menuState = 0;
          }
        }
        else
        {
          state = STAND_BY_ALL_OFF;
        }
        buttonPushed = false;
      }
      if (state == STAND_BY_ALL_OFF)
      {
        slowToggleLED ();
        if (state != lastState)
        {
          updateRelays(ALL_VALVES_OFF);
          DEBUG_PRINTLN(F("State all Zones off"));
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            delay(50);
            gw.send(msg1valve.setSensor(i * 4).set(false), false);
          } 
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print(F("** Irrigation **"));
          lcd.setCursor(0,1);
          lcd.print(F("**   Halted   **"));
          delay(2000);
          lastValve = -1;
        }
      }
      //
      else if (state == RUN_ALL_ZONES)
      {
        if (lastValve != valveNumber)
        {
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            if (i == 0 || i == valveNumber)
            {
              gw.send(msg1valve.setSensor(i * 4).set(true), false);
            }
            else
            {
              gw.send(msg1valve.setSensor(i * 4).set(false), false);
            }
          }
        }
        lastValve = valveNumber;
        fastToggleLed();
        if (state != lastState)
        {
          valveNumber = 1;
          updateRelays(ALL_VALVES_OFF);
          DEBUG_PRINTLN(F("State Changed, Running All Zones..."));
        }
        unsigned long nowMillis = millis();
        if (nowMillis - startMillis < VALVE_RESET_TIME)
        {
          updateRelays(ALL_VALVES_OFF);
        }
        else if (nowMillis - startMillis < (allZoneTime[valveNumber] * 60000UL))
        {
          updateRelays(BITSHIFT_VALVE_NUMBER);
        }
        else
        {
          DEBUG_PRINTLN(F("Changing Valves..."));
          updateRelays(ALL_VALVES_OFF);
          startMillis = millis();
          valveNumber++;
          if (valveNumber > NUMBER_OF_VALVES)
          {
            state = CYCLE_COMPLETE;
            startMillis = millis();
            lastValve = -1;
            lastTimeRun = now();
            saveDateToEEPROM(lastTimeRun);
            for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
            {
              gw.send(msg1valve.setSensor(i * 4).set(false), false);
            }
            DEBUG_PRINT(F("State = "));
            DEBUG_PRINTLN(state);
          }
        }
      }
      //
      else if (state == RUN_SINGLE_ZONE)
      {
        fastToggleLed();
        if (state != lastState)
        {
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            if (i == 0 || i == valveNumber)
            {
              gw.send(msg1valve.setSensor(i * 4).set(true), false);
            }
            else
            {
              gw.send(msg1valve.setSensor(i * 4).set(false), false);
            }
          }
          DEBUG_PRINTLN(F("State Changed, Single Zone Running..."));
          DEBUG_PRINT(F("Zone: "));
          DEBUG_PRINTLN(valveNumber);
        }
        unsigned long nowMillis = millis();
        if (nowMillis - startMillis < VALVE_RESET_TIME)
        {
          updateRelays(ALL_VALVES_OFF);
        }
        else if (nowMillis - startMillis < (valveSoloTime [valveNumber] * 60000UL))
        {
          updateRelays(BITSHIFT_VALVE_NUMBER);
        }
        else
        {
          updateRelays(ALL_VALVES_OFF);
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            gw.send(msg1valve.setSensor(i * 4).set(false), false);
          }
          state = CYCLE_COMPLETE;
          startMillis = millis();
          DEBUG_PRINT(F("State = "));
          DEBUG_PRINTLN(state);
        }
        lastTimeRun = now();
      }
      else if (state == CYCLE_COMPLETE)
      {
        if (millis() - startMillis < 30000UL)
        {
          fastToggleLed();
        }
        else
        {
          state = STAND_BY_ALL_OFF;
        }
      }
      else if (state = ZONE_SELECT_MENU)
      {
        displayMenu();
      }
      lastState = state;
    }
    //
    void displayMenu(void)
    {
      static byte lastMenuState = -1;
      static int lastSecond;
      if (menuState != lastMenuState)
      {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(valveNickName[menuState]);
        lcd.setCursor(0, 1);
        lcd.print(F("Starting"));
        DEBUG_PRINT(valveNickName[menuState]);
        Serial.print(F(" Starting Shortly"));
      }
      int thisSecond = (millis() - menuTimer) / 1000UL;
      if (thisSecond != lastSecond && thisSecond < 8)
      {
        lcd.print(F("."));
        Serial.print(".");
      }
      lastSecond = thisSecond;
      if (millis() - menuTimer > 10000UL)
      {
        startMillis = millis();
        if (menuState == 0)
        {
          valveNumber = 1;
          state = RUN_ALL_ZONES;
        }
        else
        {
          valveNumber = menuState;
          state = RUN_SINGLE_ZONE;
        }
      }
      else
      {
    
      }
      lastMenuState = menuState;
    }
    //
    void updateRelays(int value)
    {
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, MSBFIRST, highByte(value));
      shiftOut(dataPin, clockPin, MSBFIRST, lowByte(value));
      digitalWrite(latchPin, HIGH);
    }
    //
    void PushButton() //interrupt with debounce
    {
      static unsigned long last_interrupt_time = 0;
      unsigned long interrupt_time = millis();
      if (interrupt_time - last_interrupt_time > 200)
      {
        buttonPushed = true;
      }
      last_interrupt_time = interrupt_time;
    }
    //
    void fastToggleLed()
    {
      static unsigned long fastLedTimer;
      if (millis() - fastLedTimer >= 100UL)
      {
        digitalWrite(ledPin, !digitalRead(ledPin));
        fastLedTimer = millis ();
      }
    }
    //
    void slowToggleLED ()
    {
      static unsigned long slowLedTimer;
      if (millis() - slowLedTimer >= 1250UL)
      {
        digitalWrite(ledPin, !digitalRead(ledPin));
        slowLedTimer = millis ();
      }
    }
    //
    void getVariables(const MyMessage &message)
    {
      boolean zoneTimeUpdate = false;
      if (message.isAck())
      {
        DEBUG_PRINTLN(F("This is an ack from gateway"));
      }
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        if (message.sensor == (i * 4))
        {
          if (message.type == V_LIGHT)
          {
            int switchState = atoi(message.data);
            if (switchState == 0)
            {
              state = STAND_BY_ALL_OFF;
              DEBUG_PRINTLN(F("Recieved Instruction to Cancel..."));
            }
            else
            {
              if (i == 0)
              {
                state = RUN_ALL_ZONES;
                valveNumber = 1;
                DEBUG_PRINTLN(F("Recieved Instruction to Run All Zones..."));
              }
              else
              {
                state = RUN_SINGLE_ZONE;
                valveNumber = i;
                DEBUG_PRINT(F("Recieved Instruction to Activate Zone: "));
                DEBUG_PRINTLN(i);
              }
            }
            startMillis = millis();
          }
        }
        if (message.sensor == ((i * 4) + 1))
        {
          if (message.type == V_TEXT)
          {
            int variable1 = atoi(message.data);// RUN_ALL_ZONES time
            DEBUG_PRINT(F("Recieved variable1 valve:"));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" = "));
            DEBUG_PRINTLN(variable1);
            if (variable1 != allZoneTime[i])
            {
              allZoneTime[i] = variable1;
    
              zoneTimeUpdate = true;
            }
          }
        }
        if (message.sensor == ((i * 4) + 2))
        {
          if (message.type == V_TEXT)
          {
            int variable2 = atoi(message.data);// RUN_SINGLE_ZONE time
            DEBUG_PRINT(F("Recieved variable1 valve:"));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" = "));
            DEBUG_PRINTLN(variable2);
            if (variable2 != valveSoloTime[i])
            {
              valveSoloTime[i] = variable2;
    
              zoneTimeUpdate = true;
            }
          }
        }
        if (message.sensor == ((i * 4) + 3))
        {
          if (message.type == V_TEXT)
          {
            String newMessage = String(message.data);
            if (newMessage.length() == 0) 
            {
              DEBUG_PRINT(F("No Name for "));
              DEBUG_PRINTLN(i);
              break;
            }
            if (newMessage.length() > 16)
            {
              newMessage.substring(0, 16);
            }
            valveNickName[i] = "";
            valveNickName[i] += newMessage;
            DEBUG_PRINT(F("Recieved name "));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" called: "));
            DEBUG_PRINTLN(valveNickName[i]);
          }
          receivedInitialValue = true;
        }
      }
      if (zoneTimeUpdate)
      {
        //
        DEBUG_PRINTLN(F("New Zone Times..."));
        for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
        {
          if (i != 0)
          {
            DEBUG_PRINT(F("Zone "));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" individual time: "));
            DEBUG_PRINT(valveSoloTime[i]);
            DEBUG_PRINT(F(" group time: "));
            DEBUG_PRINTLN(allZoneTime[i]);
            recentUpdate = true;
          }
        }
      }
      else
      {
        recentUpdate = false;
      }
    }
    //
    void updateDisplay()
    {
      static unsigned long lastUpdateTime;
      static boolean displayToggle = false;
      //static byte toggleCounter = 0;
      static SprinklerStates lastDisplayState;
      if (state != lastDisplayState || millis() - lastUpdateTime >= 3000UL)
      {
        displayToggle = !displayToggle;
        switch (state) {
          case STAND_BY_ALL_OFF:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F("  System Ready "));
              if (clockUpdating)
              {
                lcd.setCursor(15, 0);
                lcd.write(byte(0));
              }
              lcd.setCursor(0, 1);
              lcd.print(hourFormat12() < 10 ? F(" ") : F(""));
              lcd.print(hourFormat12());
              lcd.print(minute() < 10 ? F(":0") : F(":"));
              lcd.print(minute());
              lcd.print(isAM() ? F("am") : F("pm"));
              lcd.print(month() < 10 ? F(" 0") : F(" "));
              lcd.print(month());
              lcd.print(day() < 10 ? F("/0") : F("/"));
              lcd.print(day());
              lcd.print(F("/"));
              lcd.print(year() % 100);
            }
            else
            {
              lcd.print(F("  Last Watered "));
              if (clockUpdating)
              {
                lcd.setCursor(15, 0);
                lcd.write(byte(0));
              }
              lcd.setCursor(0, 1);
              lcd.print(dayOfWeek[weekday(lastTimeRun)]);
              lcd.setCursor(11, 1);
              lcd.print(month(lastTimeRun) < 10 ? F(" ") : F(""));
              lcd.print(month(lastTimeRun));
              lcd.print(day(lastTimeRun) < 10 ? F("/0") : F("/"));
              lcd.print(day(lastTimeRun));
            }
            break;
          case RUN_SINGLE_ZONE:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F("Single Zone Mode"));
              lcd.setCursor(0, 1);
              lcd.print(F(" Zone:"));
              if (valveNumber < 10) lcd.print(F("0"));
              lcd.print(valveNumber);
              lcd.print(F(" Active"));
            }
            else
            {
              lcd.print(F(" Time Remaining "));
              lcd.setCursor(0, 1);
              if (valveSoloTime[valveNumber] == 0)
              {
                lcd.print(F(" No Valve Time "));
              }
              else
              {
                unsigned long timeRemaining = (valveSoloTime[valveNumber] * 60) - ((millis() - startMillis) / 1000);
                lcd.print(timeRemaining / 60 < 10 ? "   0" : "   ");
                lcd.print(timeRemaining / 60);
                lcd.print("min");
                lcd.print(timeRemaining % 60 < 10 ? " 0" : " ");
                lcd.print(timeRemaining % 60);
                lcd.print("sec  ");
              }
            }
            break;
          case RUN_ALL_ZONES:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F(" All-Zone  Mode "));
              lcd.setCursor(0, 1);
              lcd.print(F(" Zone:"));
              if (valveNumber < 10) lcd.print(F("0"));
              lcd.print(valveNumber);
              lcd.print(F(" Active "));
            }
            else
            {
              lcd.print(F(" Time Remaining "));
              lcd.setCursor(0, 1);
              int timeRemaining = (allZoneTime[valveNumber] * 60) - ((millis() - startMillis) / 1000);
              lcd.print((timeRemaining / 60) < 10 ? "   0" : "   ");
              lcd.print(timeRemaining / 60);
              lcd.print("min");
              lcd.print(timeRemaining % 60 < 10 ? " 0" : " ");
              lcd.print(timeRemaining % 60);
              lcd.print("sec  ");
            }
            break;
          case CYCLE_COMPLETE:
            //
            if (displayToggle)
            {
              lcd.setCursor(0, 0);
              lcd.print(F(" Watering Cycle "));
              lcd.setCursor(0, 1);
              lcd.print(F("    Complete    "));
            }
            else
            {
              int totalTimeRan = 0;
              for (int i = 1; i <= NUMBER_OF_VALVES + 1; i++)
              {
                totalTimeRan += allZoneTime[i];
              }
              lcd.setCursor(0, 0);
              lcd.print(F(" Total Time Run "));
              lcd.setCursor(0, 1);
              lcd.print(totalTimeRan < 10 ? "   0" : "   ");
              lcd.print(totalTimeRan);
              lcd.print(" Minutes   ");
            }
        }
        lastUpdateTime = millis();
      }
      lastDisplayState = state;
    }
    void receiveTime(time_t newTime)
    {
      DEBUG_PRINTLN(F("Time value received and updated..."));
      int lastSecond = second();
      int lastMinute = minute();
      int lastHour = hour();
      setTime(newTime);
      if (((second() != lastSecond) || (minute() != lastMinute) || (hour() != lastHour)) || showTime)
      {
        DEBUG_PRINTLN(F("Clock updated...."));
        DEBUG_PRINT(F("Sensor's time currently set to:"));
        DEBUG_PRINT(hourFormat12() < 10 ? F(" 0") : F(" "));
        DEBUG_PRINT(hourFormat12());
        DEBUG_PRINT(minute() < 10 ? F(":0") : F(":"));
        DEBUG_PRINT(minute());
        DEBUG_PRINTLN(isAM() ? F("am") : F("pm"));
        DEBUG_PRINT(month());
        DEBUG_PRINT(F("/"));
        DEBUG_PRINT(day());
        DEBUG_PRINT(F("/"));
        DEBUG_PRINTLN(year());
        DEBUG_PRINTLN(dayOfWeek[weekday()]);
        showTime = false;
      }
      else
      {
        DEBUG_PRINTLN(F("Sensor's time did NOT need adjustment greater than 1 second."));
      }
      clockUpdating = false;
    }
    void fastClear()
    {
      lcd.setCursor(0, 0);
      lcd.print(F("                "));
      lcd.setCursor(0, 1);
      lcd.print(F("                "));
    }
    //
    void updateClock()
    {
      static unsigned long lastVeraGetTime;
      if (millis() - lastVeraGetTime >= 3600000UL) // updates clock time and gets zone times from vera once every hour
      {
        DEBUG_PRINTLN(F("Requesting time and valve data from Gateway..."));
        lcd.setCursor(15, 0);
        lcd.write(byte(0));
        clockUpdating = true;
        gw.requestTime(receiveTime);
        lastVeraGetTime = millis();
      }
    }
    //
    void saveDateToEEPROM(unsigned long theDate)
    {
      DEBUG_PRINTLN(F("Saving Last Run date"));
      if (gw.loadState(0) != 0xFF)
      {
        gw.saveState(0, 0xFF); // EEPROM flag for last date saved stored in EEPROM (location zero)
      }
      //
      for (int i = 1; i < 5; i++)
      {
        gw.saveState(5 - i, byte(theDate >> 8 * (i - 1))); // store epoch datestamp in 4 bytes of EEPROM starting in location one
      }
    }
    //
    void goGetValveTimes()
    {
      static unsigned long valveUpdateTime;
      static byte valveIndex = 1;
      if (millis() - valveUpdateTime >= 300000UL / NUMBER_OF_VALVES)// update each valve once every 5 mins (distributes the traffic)
      {
        DEBUG_PRINTLN(F("Calling for Valve Data..."));
        lcd.setCursor(15, 0);
        lcd.write(byte(1)); //lcd.write(1);
        gw.request((valveIndex * 4) + 1, V_TEXT);
        gw.request((valveIndex * 4) + 2, V_TEXT);
        gw.request((valveIndex * 4) + 3, V_TEXT);
        valveUpdateTime = millis();
        valveIndex++;
        if (valveIndex > NUMBER_OF_VALVES + 1)
        {
          valveIndex = 1;
        }
      }
    }
    

    Curious to see how this works for people.



  • @dbemowsk

    Just a hint on memory: Why creating three sensors for each valve? Why not creating a unique sensor with array contents for all valves? 😉



  • @Sergio-Rius I hadn't thought of the array. I've never dealt with a S_INFO/V_TEXT as an array. Do you have an example of this? It does sound like an easier approach.


  • Hero Member

    @dbemowsk I would suggest to take @PierreSt advice and go for a V_PERCENTAGE device. From my perspective you wil mostly deal with "a scale of fixed values' for more or less intensive irrigation. As you are working with Domoticz you can use a "Selector switch" to select the diiferent options.

    I am currently using this for selecting patterns in my Wall mounted mood light and it works like a charm.

    If anyone is intrested I will publish a "how-to" (in the Domoticz section)



  • @AWI
    While that would be a logical approach, the the dimmer control in Domoticz it's complex and sometimes requires more than one click to activate. In other interfaces (Android, etc) that could be worse, and should change in the future.

    @dbemowsk
    I did not use S_INFO in my sketch, but I managed to use an array for valves configuration and may be pretty interesting if we mix the two of them.

    Note that this is a version 2.0 sketch, and that I removed all the remote management stuff. Due to the flow change in v2, the display menu was so difficult to do.
    Perhaps you can adapt it back and get back to the original idea.

    ///// Mysensors options /////
    //#define MY_DEBUG
    #define MY_RADIO_NRF24
    #define MY_NODE_ID 1 // Having some problems with auto Id on my installation.
    
    #include <Time.h>
    #include <Wire.h>
    #include <SPI.h>
    
    #include <LiquidCrystal_I2C.h>
    #include <MySensors.h>
    
    #define SKETCH_NAME "GardenController"
    #define SKETCH_VERSION "1.0"
    
    /////// Display output options /////
    //#define USING_DISPLAY
    //boolean showTime = true;
    //#ifdef USING_DISPLAY
    //	LiquidCrystal_I2C lcd(0x27, 16, 2);
    //	//#define LCDINIT (DEBUG_PRINTLN("Setting up LCD..."); lcd.init(); lcd.clear(); lcd.backlight();)
    //#else
    //	#define LCDINIT
    //#endif
    
    const int latchPin = 8;
    const int clockPin = 4;
    const int dataPin = 7;
    
    unsigned char bitStatus;
    
    #define ACTIVE_LOW // comment out this line if your relays are active high
    #ifdef ACTIVE_LOW
    	#define ALL_ELEMENTS_OFF 0xFFFF
    	#define myShiftOut (shiftOut(dataPin, clockPin, MSBFIRST, ~bitStatus))
    #else
    	#define ALL_ELEMENTS_OFF 0U
    	#define myShiftOut (shiftOut(dataPin, clockPin, MSBFIRST, bitStatus))
    #endif
    
    boolean clockSetup = false;
    
    ///// Serial interface options /////
    #define DEBUG_ON   // comment out to supress serial monitor output
    #ifdef DEBUG_ON
    	#define DEBUG_PRINT(x)   Serial.print(x)
    	#define DEBUG_PRINTLN(x) Serial.println(x)
    	#define SERIAL_START(x)  Serial.begin(x)
    #else
    	#define DEBUG_PRINT(x)
    	#define DEBUG_PRINTLN(x)
    	#define SERIAL_START(x)
    #endif
    
    ///// Control elements /////
    class myElement {
    public:
    	myElement(char* name, int runningTime, unsigned long Started);
    	char* Name;
    	int RunningTime;
    	unsigned long Started;
    };
    
    myElement::myElement(char* Name, int RunningTime, unsigned long Started = 0)
    {
    	this->Name = Name;
    	this->RunningTime = RunningTime;
    	this->Started = Started;
    };
    
    myElement myElements[] =
    {
    	{ "Irrigation Zone 1", 1 },
    	{ "Irrigation Zone 2", 1 },
    	{ "Pond Pump", 0 },
    	{ "Pond Lights", 0 },
    	{ "Front way lights", 0 },
    	{ "Acc1", 0 },
    	{ "Acc2", 0 },
    	{ "Acc3", 0 },
    };
    
    int NUMBER_OF_ELEMENTS = sizeof(myElements) / sizeof(*myElements);
    
    MyMessage msg1valve(0, V_STATUS);
    
    void setup()
    {
    	SERIAL_START(9600);
    	DEBUG_PRINTLN("Initialising...");
    
    	pinMode(latchPin, OUTPUT);
    	pinMode(clockPin, OUTPUT);
    	pinMode(dataPin, OUTPUT);
    
    	//LCDINIT;
    	//DEBUG_PRINTLN("Setting up LCD..."); lcd.init(); lcd.clear(); lcd.backlight();
    
    	//DEBUG_PRINTLN("Requesting time from Gateway");
    	//requestTime();
    
    	//DEBUG_PRINTLN("Ready!");
    }
    
    void presentation() 
    {
    	sendSketchInfo(SKETCH_NAME, SKETCH_VERSION);
    	for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
    		myElement Elm = myElements[i];
    		present(i, S_BINARY, Elm.Name);
    		wait(50);
    		DEBUG_PRINT("Presented element (id/name/preset time): "); DEBUG_PRINT(i); DEBUG_PRINT("/");  DEBUG_PRINT(Elm.Name); DEBUG_PRINT("/"); DEBUG_PRINTLN(Elm.RunningTime);
    		request(i, V_STATUS);
    		wait(50);
    	}
    }
    
    void loop()
    {
    	//Check if there are some timer lights to shutdown
    	for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
    		//DEBUG_PRINT(myElements[i].Name); DEBUG_PRINT("/"); DEBUG_PRINT(myElements[i].RunningTime); DEBUG_PRINT("/"); DEBUG_PRINTLN(myElements[i].Started);
    		if (myElements[i].Started > 0) {
    			DEBUG_PRINT("Running element ("); DEBUG_PRINT(i); DEBUG_PRINTLN(")");
    			if ((millis() - myElements[i].Started) >= (myElements[i].RunningTime * 60000)){
    				DEBUG_PRINT("ELEMENT TIMEOUT! ("); DEBUG_PRINT(i); DEBUG_PRINTLN(")");
    				updateRelay(i, 0);
    				send(msg1valve.setSensor(i).set(false), false);
    			}
    		}
    		wait(500);
    	}
    }
    
    //void receiveTime(time_t newTime)
    //{
    //	DEBUG_PRINTLN("Received time value, updating...");
    //	int lastSecond = second();
    //	int lastMinute = minute();
    //	int lastHour = hour();
    //	setTime(newTime);
    //	if (((second() != lastSecond) || (minute() != lastMinute) || (hour() != lastHour)) )|| showTime)
    //	{
    //		DEBUG_PRINT("Node's time currently set to: ");
    //		DEBUG_PRINT(day());
    //		DEBUG_PRINT("/");
    //		DEBUG_PRINT(month());
    //		DEBUG_PRINT(F("/"));
    //		DEBUG_PRINT(year());
    //		DEBUG_PRINT(hour() < 10 ? F(" 0") : F(" "));
    //		DEBUG_PRINT(hour());
    //		DEBUG_PRINT(minute() < 10 ? F(":0") : F(":"));
    //		DEBUG_PRINTLN(minute());
    //		showTime = false;
    //	}
    //	else
    //	{
    //		DEBUG_PRINTLN("Node's time did NOT need adjustment greater than 1 second.");
    //	}
    //	clockSetup = true;
    //}
    
    void receive(const MyMessage &message) {
    	// We only expect one type of message from controller. But we better check anyway.
    	switch (message.type)
    	{
    	case V_STATUS:
    		DEBUG_PRINT("Received: Position "); DEBUG_PRINT(message.sensor); DEBUG_PRINT(" Value "); DEBUG_PRINTLN(message.getBool());
    		//DEBUG_PRINT("Before status: "); DEBUG_PRINTLN(bitStatus);
    		updateRelay(message.sensor, message.getBool());
    		break;
    	default:
    		break;
    	}
    }
    
    //void RESET() {
    //	digitalWrite(latchPin, LOW);
    //	shiftOut(dataPin, clockPin, MSBFIRST, ALL_ELEMENTS_OFF);
    //	digitalWrite(latchPin, HIGH);
    //}
    
    void updateRelay(int whichPin, byte whichState) {
    	if (myElements[whichPin].RunningTime > 0){
    		if (whichState == 1){
    			myElements[whichPin].Started = millis();
    			DEBUG_PRINT("Stored start time ("); DEBUG_PRINT(myElements[whichPin].Started); DEBUG_PRINT(") for "); DEBUG_PRINTLN(whichPin);
    		}
    		else
    		{
    			myElements[whichPin].Started = 0;
    			DEBUG_PRINT("Reset start time for "); DEBUG_PRINTLN(whichPin);
    		}
    	}
    
    	digitalWrite(latchPin, LOW);
    	bitWrite(bitStatus, whichPin, whichState);
    	//DEBUG_PRINT("updateRelay: bitStatus -> "); DEBUG_PRINTLN(bitStatus);
    	myShiftOut;
    	digitalWrite(latchPin, HIGH);
    }
    

    As you may noticed, it can control up to 32 valves and you only have to populate the array. It'll be nice to request this data to domoticz and after a timer or received it, store in eeprom and populate the sub-nodes. Then in subsequent starts, boot with the info on eeprom and ask for changes.
    The sensor shuts itself the "valves" and if time is set to zero runs them without limit.

    That's not my irrigation controller, but my whole garden controller. (thaks the op for the idea)



  • @Sergio-Rius Just a few things. I am assuming that the array you are talking about is "myElement". I am fairly new to MySensors and Domoticz. How do you use this array with Domoticz to send the zone times to the controller? It looks like you are setting the valve names and times within the sketch as if they are permanently set on the controller. I am a little confused about the presentation of the S_BINARY, Elm.Name:

            myElement Elm = myElements[i];
            present(i, S_BINARY, Elm.Name);
    

    My understanding is that S_BINARY is just for on/off which I am guessing is the on/off control for the zone. What does the Elm.Name do though? Do yoy have a way to set valve times from within Domoticz?

    I also noticed that you removed the time sync with the receiveTime() function. This tells me that you are not sending the current time to the controller. Any reason for this?

    As for my sketch, I am thinking of another route to go with this where I can send the valve times and names using a single S_INFO sensor. I plan to use some of the information from this forum post: Splitting a string. The idea is to use a separator character such as ":" or "|" to create a pseudo array using a single string. Doing this will eliminate 2 S_INFO sensors for each zone, and also make it easier to configure. I am going to work on this tonight and see where I get with it.



  • @AWI I am still not a big fan of the V_PERCENTAGE route. I like the flexibility of the all zones time as well as the individual zone times. I suppose from a scripting sense it wouldn't matter too much, but I still think it's easier and more flexible the other way.



  • OK, so I've modified my sketch making the change to only use a single S_INFO sensor. The idea is to send a pipe delimited string of all the config data for a zone in the following format:
    {all zone time}|{individual time}|{zone name}

    45|60|Garden/pond 
    

    So all zones call uses 45 minutes, individual zone time is 60 minutes, and the zone name is "Garden/pond"

    Well without further adieu, here is the sketch.

    /*
    MySprinkler for MySensors
    
    Arduino Multi-Zone Sprinkler Control
    
    May 31, 2015
    
    *** Version 2.0
    
    *** Upgraded to http://MySensors.org version 1.4.1
    *** Expanded for up to 16 Valves
    *** Setup for active low relay board or comment out #define ACTIVE_LOW to switch to active high
    *** Switch to bitshift method vs byte arrays
    *** Changed RUN_ALL_ZONES Vera device to 0 (was highest valve)
    *** Added optional LCD display featuring remaining time, date last ran & current time
    *** Features 'raindrop' and 'clock' icons which indicate sensor is updating valve data and clock respectively
    *** Added single pushbutton menu to manually select which program to run (All Zones or a Single Zone)
    *** Added option of naming your Zones programmatically or with Vera (V_VAR3 used to store names)
    
    Utilizing your Vera home automation controller and the MySensors.org gateway you can
    control up to a sixteen zone irrigation system with only three digital pins.  This sketch
    will create NUMBER_OF_VALVES + 1 devices on your Vera controller
    
    This sketch features the following:
    
    * Allows you to cycle through All zones (RUN_ALL_ZONES) or individual zone (RUN_SINGLE_ZONE) control.
    * Use the 0th controller to activate RUN_ALL_ZONES (each zone in numeric sequence 1 to n)
      using Variable1 as the "ON" time in minutes in each of the vera devices created.
    * Use the individual zone controller to activate a single zone.  This feature uses
      Variable2 as the "ON" time for each individual device/zone.
    * Connect according to pinout below and uses Shift Registers as to allow the MySensors
      standard radio configuration and still leave available digital pins
    * Turning on any zone will stop the current process and begin that particular process.
    * Turning off any zone will stop the current process and turn off all zones.
    * To push your new time intervals for your zones, simply change the variable on your Vera and
      your arduino will call to Vera once a minute and update accordingly.  Variables will also be
      requested when the device is first powered on.
    * Pushbutton activation to RUN_ALL_ZONES, RUN_SINGLE_ZONE or halt the current program
    * LED status indicator
    
    PARTS LIST:
    Available from the MySensors store - http://www.mysensors.org/store/
    * Relays (8 channel)
    * Female Pin Header Connector Strip
    * Prototype Universal Printed Circuit Boards (PCB)
    * NRF24L01 Radio
    * Arduino (I used a Pro Mini)
    * FTDI USB to TTL Serial Adapter
    * Capacitors (10uf and .1uf)
    * 3.3v voltage regulator
    * Resistors (270 & 10K)
    * Female Dupont Cables
    * 1602 LCD (with I2C Interface)
    * LED
    * Push button
    * Shift Register (SN74HC595)
    * 2 Pole 5mm Pitch PCB Mount Screw Terminal Block
    * 3 Pole 5mm Pitch PCB Mount Screw Terminal Block
    * 22-24 gauge wire or similar (I used Cat5/Cat6 cable)
    * 18 gauge wire (for relay)
    * Irrigation Power Supply (24-Volt/750 mA Transformer)
    
    
    INSTRUCTIONS:
    
    * A step-by-step setup video is available here: http://youtu.be/l4GPRTsuHkI
    * After assembling your arduino, radio, decoupling capacitors, shift register(s), status LED, pushbutton LCD (I2C connected to
      A4 and A5) and relays, and load the sketch.
    * Following the instructions at https://MySensors.org include the device to your MySensors Gateway.
    * Verify that each new device has a Variable1, Variable2 and Variable3. Populate data accordingly with whole minutes for
      the RUN_ALL_ZONES routine (Variable1) and the RUN_SINGLE_ZONE routines (Variable 2).  The values entered for times may be zero and
      you may use the defaulet zone names by leaving Variable3 blank.
    * Once you have entered values for each zone and each variable, save the settings by pressing the red save button on your Vera.
    * Restart your arduino; verify the settings are loaded into your arduino with the serial monitor; the array will be printed
      on the serial monitor.
    * Your arduino should slow-flash, indicating that it is in ready mode.
    * There are multiple debug serial prints that can be monitored to assure that it is operating properly.
    * ***THIS SHOULD NO LONGER BE NEEDED*** The standard MySensors library now works. https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads for the I2C library, or use yours
    
    Contributed by Jim (BulldogLowell@gmail.com) with much contribution from Pete (pete.will@mysensors.org) and is released to the public domain
    */
    //
    #include <Wire.h>
    #include <Time.h>
    #include <MySensor.h>
    #include <SPI.h>
    #include <LiquidCrystal.h>
    #include <LiquidCrystal_I2C.h>
    
    
    //
    #define NUMBER_OF_VALVES 4  // Change this to set your valve count up to 16.
    #define VALVE_RESET_TIME 7500UL   // Change this (in milliseconds) for the time you need your valves to hydraulically reset and change state
    #define RADIO_ID AUTO  // Change this to fix your Radio ID or use Auto
    
    #define SKETCH_NAME "MySprinkler"
    #define SKETCH_VERSION "2.0"
    //
    #define CHILD_ID_SPRINKLER 0
    #define CHILD_ID_SPRINKLER_ALL 1
    #define CHILD_ID_SPRINKLER_IND 2
    //
    #define ACTIVE_LOW // comment out this line if your relays are active high
    //
    #define DEBUG_ON   // comment out to supress serial monitor output
    //
    #ifdef ACTIVE_LOW
    #define BITSHIFT_VALVE_NUMBER ~(1U << (valveNumber-1))
    #define ALL_VALVES_OFF 0xFFFF
    #else
    #define BITSHIFT_VALVE_NUMBER (1U << (valveNumber-1))
    #define ALL_VALVES_OFF 0U
    #endif
    //
    #ifdef DEBUG_ON
    #define DEBUG_PRINT(x)   Serial.print(x)
    #define DEBUG_PRINTLN(x) Serial.println(x)
    #define SERIAL_START(x)  Serial.begin(x)
    #else
    #define DEBUG_PRINT(x)
    #define DEBUG_PRINTLN(x)
    #define SERIAL_START(x)
    #endif
    
    // new V_TEXT variable type (development 20150905)
    const int V_TEXT = 47;
    // new S_INFO sensor type (development 20150905)
    const int S_INFO = 36 ;
    
    //
    typedef enum {
      STAND_BY_ALL_OFF, RUN_SINGLE_ZONE, RUN_ALL_ZONES, CYCLE_COMPLETE, ZONE_SELECT_MENU
    }
    SprinklerStates;
    //
    SprinklerStates state = STAND_BY_ALL_OFF;
    SprinklerStates lastState;
    byte menuState = 0;
    unsigned long menuTimer;
    byte countDownTime = 10;
    //
    int allZoneTime [NUMBER_OF_VALVES + 1];
    int valveSoloTime [NUMBER_OF_VALVES + 1];
    int valveNumber;
    int lastValve;
    unsigned long startMillis;
    const int ledPin = 5;
    const int waterButtonPin = 3;
    boolean buttonPushed = false;
    boolean showTime = true;
    boolean clockUpdating = false;
    boolean recentUpdate = true;
    const char *dayOfWeek[] = {
      "Null", "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "
    };
    // Name your Zones here or use Vera to edit them by adding a name in Variable3...
    String valveNickName[17] = {
      "All Zones", "Zone 1", "Zone 2", "Zone 3", "Zone 4", "Zone 5", "Zone 6", "Zone 7", "Zone 8", "Zone 9", "Zone 10", "Zone 11", "Zone 12", "Zone 13", "Zone 14", "Zone 15", "Zone 16"
    };
    //
    time_t lastTimeRun = 0;
    //Setup Shift Register...
    const int latchPin = 8;
    const int clockPin = 4;
    const int dataPin  = 7;
    //
    byte clock[8] = {0x0, 0xe, 0x15, 0x17, 0x11, 0xe, 0x0}; // fetching time indicator
    byte raindrop[8] = {0x4, 0x4, 0xA, 0xA, 0x11, 0xE, 0x0,}; // fetching Valve Data indicator
    // Set the pins on the I2C chip used for LCD connections:
    //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
    LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address to 0x27
    MySensor gw;
    //
    MyMessage msg1valve(CHILD_ID_SPRINKLER, V_LIGHT);
    MyMessage var1valve(CHILD_ID_SPRINKLER_ALL, V_TEXT);
    MyMessage var2valve(CHILD_ID_SPRINKLER_IND, V_TEXT);
    
    bool receivedInitialValue = false;
    //
    void setup()
    {
      SERIAL_START(115200);
      DEBUG_PRINTLN(F("Initialising..."));
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(ledPin, OUTPUT);
      pinMode(waterButtonPin, INPUT_PULLUP);
      //pinMode(waterButtonPin, INPUT);
      attachInterrupt(1, PushButton, RISING); //May need to change for your Arduino model
      digitalWrite (ledPin, HIGH);
      DEBUG_PRINTLN(F("Turning All Valves Off..."));
      updateRelays(ALL_VALVES_OFF);
      //delay(5000);
      lcd.begin(16, 2); //(16 characters and 2 line display)
      lcd.clear();
      lcd.backlight();
      lcd.createChar(0, clock);
      lcd.createChar(1, raindrop);
      //
      //check for saved date in EEPROM
      //DEBUG_PRINTLN(F("Checking EEPROM for stored date:"));
      delay(500);
      if (gw.loadState(0) == 0xFF); // EEPROM flag
      {
        //``DEBUG_PRINTLN(F("Retreiving last run time from EEPROM..."));
        for (int i = 0; i < 4 ; i++)
        {
          lastTimeRun = lastTimeRun << 8;
          lastTimeRun = lastTimeRun | gw.loadState(i + 1); // assemble 4 bytes into an ussigned long epoch timestamp
        }
      }
      gw.begin(getVariables, RADIO_ID, false); // Change 'false' to 'true' to create a Radio repeating node
      gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION);
    
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        gw.present((i * 2), S_LIGHT);
        gw.present(((i * 2) + 1), S_INFO);
        delay(100);
      }
      DEBUG_PRINTLN(F("Presentation Complete"));
      //
      digitalWrite (ledPin, LOW);
      DEBUG_PRINTLN(F("Ready..."));
      //
      lcd.setCursor(0, 0);
      lcd.print(F(" Syncing Time  "));
      lcd.setCursor(15, 0);
      lcd.write(byte(0));
      lcd.setCursor(0, 1);
      int clockCounter = 0;
      while (timeStatus() == timeNotSet && clockCounter < 21)
      {
        gw.process();
        gw.requestTime(receiveTime);
        DEBUG_PRINTLN(F("Requesting time:"));
        delay(1000);
        lcd.print(".");
        clockCounter++;
        if (clockCounter > 16)
        {
          DEBUG_PRINTLN(F("Failed synchronization!"));
          lcd.clear();
          lcd.print(F("  Failed Clock  "));
          lcd.setCursor(0, 1);
          lcd.print(F(" Syncronization "));
          delay(2000);
          break;
        }
      }
      //
      lcd.clear();
      //Update valve data when first powered on
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        lcd.print(F(" Updating  "));
        lcd.setCursor(0, 1);
        lcd.print(F(" Valve Data: "));
        lcd.print(i);
        boolean flashIcon = false;
        DEBUG_PRINT(F("Calling for Valve "));
        DEBUG_PRINT(i);
        DEBUG_PRINTLN(F(" Data..."));
        while (gw.process() == false)
        {
          lcd.setCursor(15, 0);
          flashIcon = !flashIcon;
          flashIcon ? lcd.write(byte(1)) : lcd.print(F(" "));
          gw.request((i * 2) + 1, V_TEXT);
          delay(100);
        }
      }
      lcd.clear();
    }
    //
    void loop()
    {
      gw.process();
      updateClock();
      updateDisplay();
      goGetValveTimes();
      //
      if (buttonPushed)
      {
        menuTimer = millis();
        DEBUG_PRINTLN(F("Button Pressed"));
        if (state == STAND_BY_ALL_OFF)
        {
          state = ZONE_SELECT_MENU;
          menuState = 0;
        }
        else if (state == ZONE_SELECT_MENU)
        {
          menuState++;
          if (menuState > NUMBER_OF_VALVES)
          {
            menuState = 0;
          }
        }
        else
        {
          state = STAND_BY_ALL_OFF;
        }
        buttonPushed = false;
      }
      if (state == STAND_BY_ALL_OFF)
      {
        slowToggleLED ();
        if (state != lastState)
        {
          updateRelays(ALL_VALVES_OFF);
          DEBUG_PRINTLN(F("State all Zones off"));
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            delay(50);
            gw.send(msg1valve.setSensor(i * 2).set(false), false);
          } 
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print(F("** Irrigation **"));
          lcd.setCursor(0,1);
          lcd.print(F("**   Halted   **"));
          delay(2000);
          lastValve = -1;
        }
      }
      //
      else if (state == RUN_ALL_ZONES)
      {
        if (lastValve != valveNumber)
        {
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            if (i == 0 || i == valveNumber)
            {
              gw.send(msg1valve.setSensor(i * 2).set(true), false);
            }
            else
            {
              gw.send(msg1valve.setSensor(i * 2).set(false), false);
            }
          }
        }
        lastValve = valveNumber;
        fastToggleLed();
        if (state != lastState)
        {
          valveNumber = 1;
          updateRelays(ALL_VALVES_OFF);
          DEBUG_PRINTLN(F("State Changed, Running All Zones..."));
        }
        unsigned long nowMillis = millis();
        if (nowMillis - startMillis < VALVE_RESET_TIME)
        {
          updateRelays(ALL_VALVES_OFF);
        }
        else if (nowMillis - startMillis < (allZoneTime[valveNumber] * 60000UL))
        {
          updateRelays(BITSHIFT_VALVE_NUMBER);
        }
        else
        {
          DEBUG_PRINTLN(F("Changing Valves..."));
          updateRelays(ALL_VALVES_OFF);
          startMillis = millis();
          valveNumber++;
          if (valveNumber > NUMBER_OF_VALVES)
          {
            state = CYCLE_COMPLETE;
            startMillis = millis();
            lastValve = -1;
            lastTimeRun = now();
            saveDateToEEPROM(lastTimeRun);
            for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
            {
              gw.send(msg1valve.setSensor(i * 2).set(false), false);
            }
            DEBUG_PRINT(F("State = "));
            DEBUG_PRINTLN(state);
          }
        }
      }
      //
      else if (state == RUN_SINGLE_ZONE)
      {
        fastToggleLed();
        if (state != lastState)
        {
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            if (i == 0 || i == valveNumber)
            {
              gw.send(msg1valve.setSensor(i * 2).set(true), false);
            }
            else
            {
              gw.send(msg1valve.setSensor(i * 2).set(false), false);
            }
          }
          DEBUG_PRINTLN(F("State Changed, Single Zone Running..."));
          DEBUG_PRINT(F("Zone: "));
          DEBUG_PRINTLN(valveNumber);
        }
        unsigned long nowMillis = millis();
        if (nowMillis - startMillis < VALVE_RESET_TIME)
        {
          updateRelays(ALL_VALVES_OFF);
        }
        else if (nowMillis - startMillis < (valveSoloTime [valveNumber] * 60000UL))
        {
          updateRelays(BITSHIFT_VALVE_NUMBER);
        }
        else
        {
          updateRelays(ALL_VALVES_OFF);
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            gw.send(msg1valve.setSensor(i * 2).set(false), false);
          }
          state = CYCLE_COMPLETE;
          startMillis = millis();
          DEBUG_PRINT(F("State = "));
          DEBUG_PRINTLN(state);
        }
        lastTimeRun = now();
      }
      else if (state == CYCLE_COMPLETE)
      {
        if (millis() - startMillis < 30000UL)
        {
          fastToggleLed();
        }
        else
        {
          state = STAND_BY_ALL_OFF;
        }
      }
      else if (state = ZONE_SELECT_MENU)
      {
        displayMenu();
      }
      lastState = state;
    }
    //
    void displayMenu(void)
    {
      static byte lastMenuState = -1;
      static int lastSecond;
      if (menuState != lastMenuState)
      {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(valveNickName[menuState]);
        lcd.setCursor(0, 1);
        lcd.print(F("Starting"));
        DEBUG_PRINT(valveNickName[menuState]);
        Serial.print(F(" Starting Shortly"));
      }
      int thisSecond = (millis() - menuTimer) / 1000UL;
      if (thisSecond != lastSecond && thisSecond < 8)
      {
        lcd.print(F("."));
        Serial.print(".");
      }
      lastSecond = thisSecond;
      if (millis() - menuTimer > 10000UL)
      {
        startMillis = millis();
        if (menuState == 0)
        {
          valveNumber = 1;
          state = RUN_ALL_ZONES;
        }
        else
        {
          valveNumber = menuState;
          state = RUN_SINGLE_ZONE;
        }
      }
      else
      {
    
      }
      lastMenuState = menuState;
    }
    //
    void updateRelays(int value)
    {
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, MSBFIRST, highByte(value));
      shiftOut(dataPin, clockPin, MSBFIRST, lowByte(value));
      digitalWrite(latchPin, HIGH);
    }
    //
    void PushButton() //interrupt with debounce
    {
      static unsigned long last_interrupt_time = 0;
      unsigned long interrupt_time = millis();
      if (interrupt_time - last_interrupt_time > 200)
      {
        buttonPushed = true;
      }
      last_interrupt_time = interrupt_time;
    }
    //
    void fastToggleLed()
    {
      static unsigned long fastLedTimer;
      if (millis() - fastLedTimer >= 100UL)
      {
        digitalWrite(ledPin, !digitalRead(ledPin));
        fastLedTimer = millis ();
      }
    }
    //
    void slowToggleLED ()
    {
      static unsigned long slowLedTimer;
      if (millis() - slowLedTimer >= 1250UL)
      {
        digitalWrite(ledPin, !digitalRead(ledPin));
        slowLedTimer = millis ();
      }
    }
    //
    //void getVariables(const MyMessage &message)
    void getVariables(const MyMessage &message)
    {
      boolean zoneTimeUpdate = false;
      if (message.isAck())
      {
        DEBUG_PRINTLN(F("This is an ack from gateway"));
      }
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        if (message.sensor == (i * 2))
        {
          if (message.type == V_LIGHT)
          {
            int switchState = atoi(message.data);
            if (switchState == 0)
            {
              state = STAND_BY_ALL_OFF;
              DEBUG_PRINTLN(F("Recieved Instruction to Cancel..."));
            }
            else
            {
              if (i == 0)
              {
                state = RUN_ALL_ZONES;
                valveNumber = 1;
                DEBUG_PRINTLN(F("Recieved Instruction to Run All Zones..."));
              }
              else
              {
                state = RUN_SINGLE_ZONE;
                valveNumber = i;
                DEBUG_PRINT(F("Recieved Instruction to Activate Zone: "));
                DEBUG_PRINTLN(i);
              }
            }
            startMillis = millis();
          }
        }
        if (message.sensor == ((i * 2) + 1))
        {
          if (message.type == V_TEXT)
          {
            String valveMessage = String(message.data);
            char* valveData = &valveMessage[0]; //.c_str();
            DEBUG_PRINT(F("Recieved valve data:"));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" = "));
            DEBUG_PRINTLN(valveMessage);
    
            char* var = strtok(valveData, "|");
    
            int variable1 = atoi(var); // RUN_ALL_ZONES time
            
            if (variable1 != allZoneTime[i])
            {
              allZoneTime[i] = variable1;
    
              zoneTimeUpdate = true;
            }
            
            var = strtok(NULL, "|");
            
            int variable2 = atoi(var);// RUN_SINGLE_ZONE time
            
            if (variable2 != valveSoloTime[i])
            {
              valveSoloTime[i] = variable2;
    
              zoneTimeUpdate = true;
            }
            
            var = strtok(NULL, "|");
            
            String newMessage = String(var);
            if (newMessage.length() == 0) 
            {
              DEBUG_PRINT(F("No Name for "));
              DEBUG_PRINTLN(i);
              break;
            }
            if (newMessage.length() > 16)
            {
              newMessage.substring(0, 16);
            }
            valveNickName[i] = "";
            valveNickName[i] += newMessage;
            DEBUG_PRINT(F("Recieved name "));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" called: "));
            DEBUG_PRINTLN(valveNickName[i]);
          }
          receivedInitialValue = true;
        }
      }
      if (zoneTimeUpdate)
      {
        //
        DEBUG_PRINTLN(F("New Zone Times..."));
        for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
        {
          if (i != 0)
          {
            DEBUG_PRINT(F("Zone "));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" individual time: "));
            DEBUG_PRINT(valveSoloTime[i]);
            DEBUG_PRINT(F(" group time: "));
            DEBUG_PRINTLN(allZoneTime[i]);
            recentUpdate = true;
          }
        }
      }
      else
      {
        recentUpdate = false;
      }
    }
    //
    void updateDisplay()
    {
      static unsigned long lastUpdateTime;
      static boolean displayToggle = false;
      //static byte toggleCounter = 0;
      static SprinklerStates lastDisplayState;
      if (state != lastDisplayState || millis() - lastUpdateTime >= 3000UL)
      {
        displayToggle = !displayToggle;
        switch (state) {
          case STAND_BY_ALL_OFF:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F("  System Ready "));
              if (clockUpdating)
              {
                lcd.setCursor(15, 0);
                lcd.write(byte(0));
              }
              lcd.setCursor(0, 1);
              lcd.print(hourFormat12() < 10 ? F(" ") : F(""));
              lcd.print(hourFormat12());
              lcd.print(minute() < 10 ? F(":0") : F(":"));
              lcd.print(minute());
              lcd.print(isAM() ? F("am") : F("pm"));
              lcd.print(month() < 10 ? F(" 0") : F(" "));
              lcd.print(month());
              lcd.print(day() < 10 ? F("/0") : F("/"));
              lcd.print(day());
              lcd.print(F("/"));
              lcd.print(year() % 100);
            }
            else
            {
              lcd.print(F("  Last Watered "));
              if (clockUpdating)
              {
                lcd.setCursor(15, 0);
                lcd.write(byte(0));
              }
              lcd.setCursor(0, 1);
              lcd.print(dayOfWeek[weekday(lastTimeRun)]);
              lcd.setCursor(11, 1);
              lcd.print(month(lastTimeRun) < 10 ? F(" ") : F(""));
              lcd.print(month(lastTimeRun));
              lcd.print(day(lastTimeRun) < 10 ? F("/0") : F("/"));
              lcd.print(day(lastTimeRun));
            }
            break;
          case RUN_SINGLE_ZONE:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F("Single Zone Mode"));
              lcd.setCursor(0, 1);
              lcd.print(F(" Zone:"));
              if (valveNumber < 10) lcd.print(F("0"));
              lcd.print(valveNumber);
              lcd.print(F(" Active"));
            }
            else
            {
              lcd.print(F(" Time Remaining "));
              lcd.setCursor(0, 1);
              if (valveSoloTime[valveNumber] == 0)
              {
                lcd.print(F(" No Valve Time "));
              }
              else
              {
                unsigned long timeRemaining = (valveSoloTime[valveNumber] * 60) - ((millis() - startMillis) / 1000);
                lcd.print(timeRemaining / 60 < 10 ? "   0" : "   ");
                lcd.print(timeRemaining / 60);
                lcd.print("min");
                lcd.print(timeRemaining % 60 < 10 ? " 0" : " ");
                lcd.print(timeRemaining % 60);
                lcd.print("sec  ");
              }
            }
            break;
          case RUN_ALL_ZONES:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F(" All-Zone  Mode "));
              lcd.setCursor(0, 1);
              lcd.print(F(" Zone:"));
              if (valveNumber < 10) lcd.print(F("0"));
              lcd.print(valveNumber);
              lcd.print(F(" Active "));
            }
            else
            {
              lcd.print(F(" Time Remaining "));
              lcd.setCursor(0, 1);
              int timeRemaining = (allZoneTime[valveNumber] * 60) - ((millis() - startMillis) / 1000);
              lcd.print((timeRemaining / 60) < 10 ? "   0" : "   ");
              lcd.print(timeRemaining / 60);
              lcd.print("min");
              lcd.print(timeRemaining % 60 < 10 ? " 0" : " ");
              lcd.print(timeRemaining % 60);
              lcd.print("sec  ");
            }
            break;
          case CYCLE_COMPLETE:
            //
            if (displayToggle)
            {
              lcd.setCursor(0, 0);
              lcd.print(F(" Watering Cycle "));
              lcd.setCursor(0, 1);
              lcd.print(F("    Complete    "));
            }
            else
            {
              int totalTimeRan = 0;
              for (int i = 1; i <= NUMBER_OF_VALVES + 1; i++)
              {
                totalTimeRan += allZoneTime[i];
              }
              lcd.setCursor(0, 0);
              lcd.print(F(" Total Time Run "));
              lcd.setCursor(0, 1);
              lcd.print(totalTimeRan < 10 ? "   0" : "   ");
              lcd.print(totalTimeRan);
              lcd.print(" Minutes   ");
            }
        }
        lastUpdateTime = millis();
      }
      lastDisplayState = state;
    }
    void receiveTime(time_t newTime)
    {
      DEBUG_PRINTLN(F("Time value received and updated..."));
      int lastSecond = second();
      int lastMinute = minute();
      int lastHour = hour();
      setTime(newTime);
      if (((second() != lastSecond) || (minute() != lastMinute) || (hour() != lastHour)) || showTime)
      {
        DEBUG_PRINTLN(F("Clock updated...."));
        DEBUG_PRINT(F("Sensor's time currently set to:"));
        DEBUG_PRINT(hourFormat12() < 10 ? F(" 0") : F(" "));
        DEBUG_PRINT(hourFormat12());
        DEBUG_PRINT(minute() < 10 ? F(":0") : F(":"));
        DEBUG_PRINT(minute());
        DEBUG_PRINTLN(isAM() ? F("am") : F("pm"));
        DEBUG_PRINT(month());
        DEBUG_PRINT(F("/"));
        DEBUG_PRINT(day());
        DEBUG_PRINT(F("/"));
        DEBUG_PRINTLN(year());
        DEBUG_PRINTLN(dayOfWeek[weekday()]);
        showTime = false;
      }
      else
      {
        DEBUG_PRINTLN(F("Sensor's time did NOT need adjustment greater than 1 second."));
      }
      clockUpdating = false;
    }
    void fastClear()
    {
      lcd.setCursor(0, 0);
      lcd.print(F("                "));
      lcd.setCursor(0, 1);
      lcd.print(F("                "));
    }
    //
    void updateClock()
    {
      static unsigned long lastVeraGetTime;
      if (millis() - lastVeraGetTime >= 3600000UL) // updates clock time and gets zone times from vera once every hour
      {
        DEBUG_PRINTLN(F("Requesting time and valve data from Gateway..."));
        lcd.setCursor(15, 0);
        lcd.write(byte(0));
        clockUpdating = true;
        gw.requestTime(receiveTime);
        lastVeraGetTime = millis();
      }
    }
    //
    void saveDateToEEPROM(unsigned long theDate)
    {
      DEBUG_PRINTLN(F("Saving Last Run date"));
      if (gw.loadState(0) != 0xFF)
      {
        gw.saveState(0, 0xFF); // EEPROM flag for last date saved stored in EEPROM (location zero)
      }
      //
      for (int i = 1; i < 5; i++)
      {
        gw.saveState(5 - i, byte(theDate >> 8 * (i - 1))); // store epoch datestamp in 4 bytes of EEPROM starting in location one
      }
    }
    //
    void goGetValveTimes()
    {
      static unsigned long valveUpdateTime;
      static byte valveIndex = 1;
      if (millis() - valveUpdateTime >= 300000UL / NUMBER_OF_VALVES)// update each valve once every 5 mins (distributes the traffic)
      {
        DEBUG_PRINTLN(F("Calling for Valve Data..."));
        lcd.setCursor(15, 0);
        lcd.write(byte(1)); //lcd.write(1);
        gw.request((valveIndex * 4) + 1, V_TEXT);
        gw.request((valveIndex * 4) + 2, V_TEXT);
        gw.request((valveIndex * 4) + 3, V_TEXT);
        valveUpdateTime = millis();
        valveIndex++;
        if (valveIndex > NUMBER_OF_VALVES + 1)
        {
          valveIndex = 1;
        }
      }
    }
    

  • Hero Member

    @Sergio-Rius said:

    the dimmer control in Domoticz it's complex and sometimes requires more than one click to activate

    Can you elaborate on this? In my setup the Dimmer is as reliable as any other control. Main limitation is that the standard dimmer can only assume 16 "states"/ values.


  • Hero Member

    @dbemowsk said:

    I am still not a big fan of the V_PERCENTAGE route

    While introducing the V_TEXT/S_INFO type we were aware that this would be a would open up the route to many "non standard" applications. I personally try to keep everything in the standard types or to have a standard defined for it. (like in the V_ORIENTATION suggestion in the Orientation actuator ).
    Sometimes the choice is limited as with the V_PERCENTAGE/ DIMMER implementation in Domoticz as there is no "generic" type to represent just a value (int/float) or date/time (y/m/d hⓂs).



  • @dbemowsk said:

    How do you use this array with Domoticz to send the zone times to the controller? It looks like you are setting the valve names and times within the sketch as if they are permanently set on the controller.

    Yes, that was the part where we supposedly had to join our sketches. Just getting all the array contents from an S_INFO. Perhaps using some Json to array conversion. Should be some library for conversions there.

    I am a little confused about the presentation of the S_BINARY, Elm.Name:

            myElement Elm = myElements[i];
            present(i, S_BINARY, Elm.Name);
    

    My understanding is that S_BINARY is just for on/off which I am guessing is the on/off control for the zone. What does the Elm.Name do though?

    Elm.Name assigns a name to the valve. And presents to Domoticz. Still doesn't exists a way to get from domoticz.

    Do yoy have a way to set valve times from within Domoticz?

    Again, still doesn't....

    I also noticed that you removed the time sync with the receiveTime() function. This tells me that you are not sending the current time to the controller. Any reason for this?

    Yes. as I said it was so complicated for me to integrate the "stand-alone functions" that use loop cycles for running the menu. I planned to make dedicated functions for it, but didn't have time.

    As for my sketch, I am thinking of another route to go with this where I can send the valve times and names using a single S_INFO sensor. I plan to use some of the information from this forum post: Splitting a string. The idea is to use a separator character such as ":" or "|" to create a pseudo array using a single string. Doing this will eliminate 2 S_INFO sensors for each zone, and also make it easier to configure. I am going to work on this tonight and see where I get with it.

    And why not using this approach on a single S_INFO, that could feed the array I have in my sketch?



  • @AWI said:

    Can you elaborate on this? In my setup the Dimmer is as reliable as any other control. Main limitation is that the standard dimmer can only assume 16 "states"/ values.

    The dimmer is reliable. I was talking of interface widget being complex. In Domoticz, to activate one zone you would have to first click, and when the popup appears, click again on the blue (sphere?) for it to start.
    In Imperihome, you would have up to 32 rgb dial indicators on your page and still don't get the current set value, and when you set it on, most of times it doesn't respect the current intensity value.

    And that doesn't solve the double timing setup nor the naming.
    I always like to apply the KISS rule to my developments and avoid to depend on other systems. Specially if they don't walk in the same direction. Imagine that in the future the dimmer system changes, for example, into a hue pallete.

    And it's true that mysensors and domoticz is lacking a sensors configuration system.


  • Hero Member

    @Sergio-Rius Think I understand 😉 and keep my systems as autonomous and simple as possible.
    The route with S_INFO/V_TEXT won't bring you any luck, regarding the customization to be done in Domoticz to get values in V_TEXT (LUA / JSON).
    btw. Like your sketch 👍



  • @AWI
    You'r right, that's not the best route. But until we have sensors configuration routines... 😉
    Will we have? 😬


  • Hero Member

    @Sergio-Rius Don't expect too much in either MySensors/ Domoticz unless you know of a "industry standard" approach which can be implemented with reasonable efforts by the community..



  • @AWI said:

    @Sergio-Rius Don't expect too much in either MySensors/ Domoticz unless you know of a "industry standard" approach which can be implemented with reasonable efforts by the community..

    Are you saying that Domoticz primary focus is to follow existing industry standards? Some times you need to shift away from the standards. Giving users more options will only increase the software's user base. If it were me, I'd rather become the standard than chase it.



  • @Sergio-Rius said:

    And why not using this approach on a single S_INFO, that could feed the array I have in my sketch?

    The main part of my new approach is this bit here:

          if (message.type == V_TEXT)
          {
            String valveMessage = String(message.data);
            char* valveData = &valveMessage[0]; //.c_str();
            DEBUG_PRINT(F("Recieved valve data:"));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" = "));
            DEBUG_PRINTLN(valveMessage);
    
            char* var = strtok(valveData, "|");
    
            int variable1 = atoi(var); // RUN_ALL_ZONES time
            
            if (variable1 != allZoneTime[i])
            {
              allZoneTime[i] = variable1;
    
              zoneTimeUpdate = true;
            }
            
            var = strtok(NULL, "|");
            
            int variable2 = atoi(var);// RUN_SINGLE_ZONE time
            
            if (variable2 != valveSoloTime[i])
            {
              valveSoloTime[i] = variable2;
    
              zoneTimeUpdate = true;
            }
            
            var = strtok(NULL, "|");
            
            String newMessage = String(var);
            if (newMessage.length() == 0) 
            {
              DEBUG_PRINT(F("No Name for "));
              DEBUG_PRINTLN(i);
              break;
            }
            if (newMessage.length() > 16)
            {
              newMessage.substring(0, 16);
            }
            valveNickName[i] = "";
            valveNickName[i] += newMessage;
            DEBUG_PRINT(F("Recieved name "));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" called: "));
            DEBUG_PRINTLN(valveNickName[i]);
          }
          receivedInitialValue = true;
        }
      }
    

    The key is using strtok() to split the incoming string into it's parts. The code that I posted from my tests seems to work, at least from what I have tested so far. It uses one S_INFO sensor for each zone to carry the 3 parts that would be the V_VAR1 - V_VAR3 info in the original sketch. Granted it is only for 1.5, but if you can use anything from my 1.5 sketch in your 2.0 sketch, feel free.



  • Hi first Great projekt. All the things is Just ordred from eBay. But i Wonder what the yellow component is.

    And mayby a tuturial have to make a complete HA kontroller. And have to set i Up. Rigtig now i have a raspberry pi with calaos. But i Dont know have to the it Up with the system.

    Hope there is some help in here 🙂



  • @BulldogLowell

    I love your programming skills, it is superb. Haven gone through your video, l was happy and l needed a modification to your setup. I want to use the arduino to power my irrigation with the following function.

    Arduino with soil moisture sensor check. once the soil is dry, arduino to switch on the electric 1horse power pumping machine and at the same time open the solenoid valve to irrigate at a specified timing.

    As per powering the pumping machine, arduino should check if there is public electricity supply before switching on the pump and if there is no public power supply then it should switch on the power generating set to power the pumping machine and solenoid valve.

    After the sensor has confirmed that the soil is wet and moist, then arduino stops the pumping machine and then closes the electric 220v solenoid valve.

    Second task.

    Overhead Mist Sprayer (uses a different AC 1horse power pump)

    A sensor to check when the sun temperature is 35 or 40 degrees or any programmed temperature and switch on the pumping machine to power the sprayer for a specified timing. Also arduino should should check if there is public electricity supply before switching on the pump and if there is no public power supply then it should switch on the power generating set to power the pumping machine.

    Also irrigation records of time and dates and other function will be added up in the setup.

    I like to know the hardwares l will need for this project, a guide and codes. I appreciate this .

    Thanks


  • Contest Winner

    @wasam

    There are several examples out there (either here or in the Arduino forum) of how to combine sketches for added functionality. Fortunately, you are starting with my code that is already non-blocking and uses little in the way of system resources so it should be straightforward from here.

    The community here (including me) can assist in giving you what you want.

    first thing is the hardware... assuming your using metric means you are 220VAC... you need a person familiar with mains switching to help you out there!



  • @impertus said:

    Hi first Great projekt. All the things is Just ordred from eBay. But i Wonder what the yellow component is.

    And mayby a tuturial have to make a complete HA kontroller. And have to set i Up. Rigtig now i have a raspberry pi with calaos. But i Dont know have to the it Up with the system.

    Hope there is some help in here 🙂
    @BulldogLowell


  • Admin

    @impertus said:

    But i Wonder what the yellow component is.

    Where are you seeing the yellow component? Maybe it's the LED? Can you post a picture?



  • @petewill this One. 0_1476216631327_Screenshot_20161011-220800.png


  • Admin

    @impertus Ah, ok. That is a .1uf capacitor.


  • Contest Winner

    @petewill

    which can be easily substituted by a flux capacitor.

    😉



  • @BulldogLowell Thx 🙂

    Is this the rigth setup.

    Irrigationcontroller <-----> Radio + ethernet (Gateaway) ------> Router + Wifi ------> RaspB with (Calaos HA controller)

    Wifi -----> Calaos Mobile app

    How does the HA controller detects the signal from the irrigation controller? some mystisk setup 🙂 or plug an play..

    What HA will you use (Opensouce)(With mobil function)


  • Admin

    @BulldogLowell Ha! Unfortunately I'm fresh out of those...

    @impertus Both @BulldogLowell and I use Vera as our home automation controller (not open source). My setup looks like: Irrigation Controller <> Ethernet Gateway <> Vera <> Vera Mobile App (usually AutHomationHD). I haven't tested any other controllers with this device but reading up a little in this forum post it appears that some people have got it to work with Domoticz.



  • @petewill yeahh i did a little bit of surfing on the forum. And felt over Domoticz. I see that also can run on RaspBerryPi. So think i will give that at try. It will be nice with a newbie guide how to setup my sensors to Domo. step by step..

    now im waiting for the mailman with all my components 🙂



  • Hi, I've done recently this setup - it works greate with domoticz and Raspberry Pi 0.
    After some tests I findout that when I plug in power - sometimes all, sometimes 3 or 4 relays are turning ON for 1second.
    If that happend my 24V power adapter will be in trash. How to prevent that? Do I need to add something in code (I'm not a programmer)?

    0_1477417969901_photo_2016-10-25_19-50-49.jpg


  • Contest Winner

    @Huczas

    try adding a delay in various places in setup() start with 5 or even 10 seconds.



  • ok, I just get back from Hackerspace. Some people fix this issue:
    SN74HC595 - 13 pin (OE from datascheet) - remove GND and then add pull up 1k resistor and wire it to Arduino pin 6

    and software, added three lines in code:

      const int outputEnablePin = 6;
    
      pinMode(outputEnablePin, OUTPUT);
      digitalWrite (outputEnablePin, LOW);
    
    

    put them after 190 line https://github.com/mysensors/MySensorsArduinoExamples/blob/master/examples/IrrigationController/IrrigationController.ino

    should be like that:

    <some code>
     //Setup Shift Register...
    const int latchPin = 8;
    const int clockPin = 4;
    const int dataPin  = 7;
    const int outputEnablePin = 6;
    //
    byte clock[8] = {0x0, 0xe, 0x15, 0x17, 0x11, 0xe, 0x0}; // fetching time indicator
    byte raindrop[8] = {0x4, 0x4, 0xA, 0xA, 0x11, 0xE, 0x0,}; // fetching Valve Data indicator
    // Set the pins on the I2C chip used for LCD connections:
    //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
    LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address to 0x27
    MySensor gw;
    //
    MyMessage msg1valve(CHILD_ID_SPRINKLER, V_LIGHT);
    MyMessage var1valve(CHILD_ID_SPRINKLER, V_VAR1);
    MyMessage var2valve(CHILD_ID_SPRINKLER, V_VAR2);
    //
    void setup()
    {
      SERIAL_START(115200);
      DEBUG_PRINTLN(F("Initialising..."));
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(ledPin, OUTPUT);
      pinMode(waterButtonPin, INPUT_PULLUP);
      //pinMode(waterButtonPin, INPUT);
      attachInterrupt(1, PushButton, RISING); //May need to change for your Arduino model
      digitalWrite (ledPin, HIGH);
      DEBUG_PRINTLN(F("Turning All Valves Off..."));
      updateRelays(ALL_VALVES_OFF);
      pinMode(outputEnablePin, OUTPUT);
      digitalWrite (outputEnablePin, LOW);
    <some code>
    

    If somebody can update this project in github and that fritzling draw - would be super nice.


  • Admin

    @Huczas Great, thanks! Have you tested these updates? Also, can you post a link the info on hackerspace?



  • @petewill
    Yes, I've tested this and it's working well!
    Link to the hackerspace - HackerSpace Warsaw, they are on irc - where I talk with them, #hackerspace-pl at freenode servers.


  • Admin

    @Huczas Oh, ok. I thought it was a forum post. Thanks for the update. I will work to get this updated.


  • Admin

    @Huczas the code has been updated in the 2.0 GitHub branch. The wiring diagram has also been updated. Thanks for the fix!



  • @petewill as I sad before - pull up 1k resistor and wire it to Arduino pin 6 - I mean

    pull up - connect to power,
    so should be 1k resistor connected with power source(that make sence with pull up) and also with pin 6. Like below:
    0_1477751319151_Przechwytywanie.PNG


  • Admin

    @Huczas Ah, missed that. I fixed it.



  • I just finished building this but when I go to upload the code to my arduino i get this error

    'byte clock [8]' redeclared as different kind of symbol

    what does this mean ?

    thanks


  • Admin

    @bsivley Are you using the libraries from the MySensors github page (https://github.com/mysensors/MySensorsArduinoExamples/tree/master/libraries)? I just compiled it without any errors. What version of the Arduino IDE are you using? What version of MySensors are you using?



  • @petewill Hi, Please can you advise what version Arduino IDE you are using for this sketch?



  • This post is deleted!


  • Hi, Maybe somebody can help me with this issue? Managed to upload code for irrigation controller with Arduino IDE 1.6.12 but can't pair with Vera controller.


  • Admin

    @Andrej_AB I'm using 1.6.12 but I haven't changed my node to 2.0 yet.
    What is the issue you are having with pairing? Do you see the presentation messages on your gateway? Do you have other nodes successfully paired with your Vera?



  • @petewill Hi, All my other nodes have successfully paired with Vera, but irrigation controller node can't pair with Vera, I have started inclusion mode on Vera, one minute passed 0 devices found.
    Please see attached picture.
    0_1480325874006_Vera inclusion.png

    0_1480325904307_irrigation node.png


  • Admin

    @Andrej_AB It looks like it's communicating ok because it's getting the time. Have you ever had a mysenors node #5 in your Vera previously and deleted it? Could it be that the Vera thinks it's already there? What happens if you clear your eeprom on your irrigation controller then manually assign a different ID and then try to pair it again?



  • @petewill said:

    @Andrej_AB It looks like it's communicating ok because it's getting the time. Have you ever had a mysenors node #5 in your Vera previously and deleted it? Could it be that the Vera thinks it's already there? What happens if you clear your eeprom on your irrigation controller then manually assign a different ID and then try to pair it again?

    Also thinking about it, eprom was cleaned and manually assigned new ID but still can't pair with Vera.
    Today I tried upload sketch from My sensors library 1.5.4 and node was successfully paired with Vera, then tried again last sketch and again can't pair.


  • Admin

    @Andrej_AB Can you post the full log from your sensor? The device is never getting presented in what you've posted so far. I don't have enough time to dig in to the code to know if this will help but can you try moving

    void presentation()  
    { 
      sendSketchInfo(SKETCH_NAME, SKETCH_VERSION);
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        present(i, S_LIGHT);
      }
    }
    

    so it's above

    void setup()
    

    I still haven't updated my irrigation controller to 2.0 yet so I haven't tested any of the code.



  • @petewill Finally managed to pair node with Vera controller, many thanks to @petewill for assistance with this issue.

    //
    #define NUMBER_OF_VALVES 6  // Change this to set your valve count up to 16.
    #define VALVE_RESET_TIME 7500UL   // Change this (in milliseconds) for the time you need your valves to hydraulically reset and change state
    #define RADIO_ID 7  // Set this to fix your Radio ID or use Auto```


  • hey @petewill

    finally i am done making the controller. but when i want to upload the code i get the error..

    
    C:\Users\crame\Desktop\Vanding\Vanding.ino: In function 'void setup()':
    
    Vanding:112: error: 'lcd' was not declared in this scope
    
       lcd.begin(16, 2); //(16 characters and 2 line display)
    
       ^
    
    C:\Users\crame\Desktop\Vanding\Vanding.ino: In function 'void loop()':
    
    Vanding:255: error: 'lcd' was not declared in this scope
    
           lcd.clear();
    
           ^
    
    C:\Users\crame\Desktop\Vanding\Vanding.ino: In function 'void displayMenu()':
    
    Vanding:388: error: 'lcd' was not declared in this scope
    
         lcd.clear();
    
         ^
    
    Vanding:399: error: 'lcd' was not declared in this scope
    
         lcd.print(F("."));
    
         ^
    
    C:\Users\crame\Desktop\Vanding\Vanding.ino: In function 'void updateDisplay()':
    
    Vanding:589: error: 'lcd' was not declared in this scope
    
             lcd.setCursor(0, 0);
    
             ^
    
    C:\Users\crame\Desktop\Vanding\Vanding.ino: In function 'void fastClear()':
    
    Vanding:750: error: 'lcd' was not declared in this scope
    
       lcd.setCursor(0, 0);
    
       ^
    
    C:\Users\crame\Desktop\Vanding\Vanding.ino: In function 'void updateClock()':
    
    Vanding:762: error: 'lcd' was not declared in this scope
    
         lcd.setCursor(15, 0);
    
         ^
    
    C:\Users\crame\Desktop\Vanding\Vanding.ino: In function 'void goGetValveTimes()':
    
    Vanding:791: error: 'lcd' was not declared in this scope
    
         lcd.setCursor(15, 0);
    
         ^
    
    exit status 1
    'lcd' was not declared in this scope
    

    do you have some help 4 me??



  • @impertus Can you post your entire sketch?



  • @impertus Those errors have to do with this line:

    
    // Set the pins on the I2C chip used for LCD connections:
    //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address to 0x27
    

    This is where the declaration happens. If this is commented or fails, you will get the errors you described. Do you have the correct LCD libraries installed for this?



  • @dbemowsk i just copy/paste from the site.

    witch library should i use?

    i have added mysensors-master to IDE

    edit i could see i have out comment the line. Now i get this error

    Vanding:92: error: 'POSITIVE' was not declared in this scope
    
     LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address to 0x27
    
                                                         ^
    
    C:\Users\crame\Desktop\Vanding\Vanding.ino: In function 'void setup()':
    
    Vanding:116: error: no matching function for call to 'LiquidCrystal_I2C::begin(int, int)'
    
       lcd.begin(16, 2); //(16 characters and 2 line display)
    
                      ^
    
    C:\Users\crame\Desktop\Vanding\Vanding.ino:116:18: note: candidate is:
    
    In file included from C:\Users\crame\Desktop\Vanding\Vanding.ino:1:0:
    
    C:\Program Files (x86)\Arduino\libraries\Arduino-LiquidCrystal-I2C-library-master/LiquidCrystal_I2C.h:76:7: note: void LiquidCrystal_I2C::begin()
    
      void begin();
    
           ^
    
    C:\Program Files (x86)\Arduino\libraries\Arduino-LiquidCrystal-I2C-library-master/LiquidCrystal_I2C.h:76:7: note:   candidate expects 0 arguments, 2 provided
    
    exit status 1
    'POSITIVE' was not declared in this scope
    

    the sketch.

    #include <LiquidCrystal_I2C.h>
    
    
    
    // Enable debug prints
    //#define MY_DEBUG
    
    // Enable and select radio type attached
    #define MY_RADIO_NRF24
    //#define MY_RADIO_RFM69
    
    //#define MY_NODE_ID 1  // Set this to fix your Radio ID or use Auto
    
    #include <Wire.h>
    #include <TimeLib.h>
    #include <SPI.h>
    #include <MySensors.h>
    #include <LiquidCrystal.h>
    #include <LiquidCrystal_I2C.h>
    
    
    #define NUMBER_OF_VALVES 8  // Change this to set your valve count up to 16.
    #define VALVE_RESET_TIME 7500UL   // Change this (in milliseconds) for the time you need your valves to hydraulically reset and change state
    
    #define SKETCH_NAME "MySprinkler"
    #define SKETCH_VERSION "2.0"
    //
    #define CHILD_ID_SPRINKLER 0
    //
    #define ACTIVE_LOW // comment out this line if your relays are active high
    //
    #define DEBUG_ON   // comment out to supress serial monitor output
    //
    #ifdef ACTIVE_LOW
    #define BITSHIFT_VALVE_NUMBER ~(1U << (valveNumber-1))
    #define ALL_VALVES_OFF 0xFFFF
    #else
    #define BITSHIFT_VALVE_NUMBER (1U << (valveNumber-1))
    #define ALL_VALVES_OFF 0U
    #endif
    //
    #ifdef DEBUG_ON
    #define DEBUG_PRINT(x)   Serial.print(x)
    #define DEBUG_PRINTLN(x) Serial.println(x)
    #else
    #define DEBUG_PRINT(x)
    #define DEBUG_PRINTLN(x)
    #define SERIAL_START(x)
    #endif
    //
    typedef enum {
      STAND_BY_ALL_OFF, RUN_SINGLE_ZONE, RUN_ALL_ZONES, CYCLE_COMPLETE, ZONE_SELECT_MENU
    }
    SprinklerStates;
    //
    SprinklerStates state = STAND_BY_ALL_OFF;
    SprinklerStates lastState;
    byte menuState = 0;
    unsigned long menuTimer;
    byte countDownTime = 10;
    //
    int allZoneTime [NUMBER_OF_VALVES + 1];
    int valveSoloTime [NUMBER_OF_VALVES + 1];
    int valveNumber;
    int lastValve;
    unsigned long startMillis;
    const int ledPin = 5;
    const int waterButtonPin = 3;
    bool buttonPushed = false;
    bool showTime = true;
    bool clockUpdating = false;
    bool recentUpdate = true;
    const char *dayOfWeek[] = {
      "Null", "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "
    };
    // Name your Zones here or use Vera to edit them by adding a name in Variable3...
    String valveNickName[17] = {
      "All Zones", "Zone 1", "Zone 2", "Zone 3", "Zone 4", "Zone 5", "Zone 6", "Zone 7", "Zone 8", "Zone 9", "Zone 10", "Zone 11", "Zone 12", "Zone 13", "Zone 14", "Zone 15", "Zone 16"
    };
    //
    time_t lastTimeRun = 0;
    //Setup Shift Register...
    const int latchPin = 8;
    const int clockPin = 4;
    const int dataPin  = 7;
    const int outputEnablePin = 6;
    //
    byte clock[8] = {0x0, 0xe, 0x15, 0x17, 0x11, 0xe, 0x0}; // fetching time indicator
    byte raindrop[8] = {0x4, 0x4, 0xA, 0xA, 0x11, 0xE, 0x0,}; // fetching Valve Data indicator
    // Set the pins on the I2C chip used for LCD connections:
    //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address to 0x27
    //
    MyMessage msg1valve(CHILD_ID_SPRINKLER, V_LIGHT);
    MyMessage var1valve(CHILD_ID_SPRINKLER, V_VAR1);
    MyMessage var2valve(CHILD_ID_SPRINKLER, V_VAR2);
    
    bool receivedInitialValue = false;
    //
    void setup()
    {
      DEBUG_PRINTLN(F("Initialising..."));
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(ledPin, OUTPUT);
      pinMode(outputEnablePin, OUTPUT);
      digitalWrite (outputEnablePin, LOW);
      pinMode(waterButtonPin, INPUT_PULLUP);
      //pinMode(waterButtonPin, INPUT);
      attachInterrupt(digitalPinToInterrupt(waterButtonPin), PushButton, RISING); //May need to change for your Arduino model
      digitalWrite (ledPin, HIGH);
      DEBUG_PRINTLN(F("Turning All Valves Off..."));
      updateRelays(ALL_VALVES_OFF);
      //delay(5000);
      lcd.begin(16, 2); //(16 characters and 2 line display)
      lcd.clear();
      lcd.backlight();
      lcd.createChar(0, clock);
      lcd.createChar(1, raindrop);
      //
      //check for saved date in EEPROM
      DEBUG_PRINTLN(F("Checking EEPROM for stored date:"));
      delay(500);
      if (loadState(0) == 0xFF) // EEPROM flag
      {
        DEBUG_PRINTLN(F("Retreiving last run time from EEPROM..."));
        for (int i = 0; i < 4 ; i++)
        {
          lastTimeRun = lastTimeRun << 8;
          lastTimeRun = lastTimeRun | loadState(i + 1); // assemble 4 bytes into an ussigned long epoch timestamp
        }
      }
    
      DEBUG_PRINTLN(F("Sensor Presentation Complete"));
      //
      digitalWrite (ledPin, LOW);
      DEBUG_PRINTLN(F("Ready..."));
      //
      lcd.setCursor(0, 0);
      lcd.print(F(" Syncing Time  "));
      lcd.setCursor(15, 0);
      lcd.write(byte(0));
      lcd.setCursor(0, 1);
      int clockCounter = 0;
      while (timeStatus() == timeNotSet && clockCounter < 21)
      {
        requestTime();
        DEBUG_PRINTLN(F("Requesting time from Gateway:"));
        wait(1000);
        lcd.print(".");
        clockCounter++;
        if (clockCounter > 16)
        {
          DEBUG_PRINTLN(F("Failed initial clock synchronization!"));
          lcd.clear();
          lcd.print(F("  Failed Clock  "));
          lcd.setCursor(0, 1);
          lcd.print(F(" Syncronization "));
          wait(2000);
          break;
        }
      }
      //
      lcd.clear();
      //Update valve data when first powered on
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        lcd.print(F(" Updating  "));
        lcd.setCursor(0, 1);
        lcd.print(F(" Valve Data: "));
        lcd.print(i);
        bool flashIcon = false;
        DEBUG_PRINT(F("Calling for Valve "));
        DEBUG_PRINT(i);
        DEBUG_PRINTLN(F(" Data..."));
        while (!receivedInitialValue)
        {
          lcd.setCursor(15, 0);
          flashIcon = !flashIcon;
          flashIcon ? lcd.write(byte(1)) : lcd.print(F(" "));
          request(i, V_VAR1);
          wait(500);
        }
        receivedInitialValue = false;
        while (!receivedInitialValue)
        {
          lcd.setCursor(15, 0);
          flashIcon = !flashIcon;
          flashIcon ? lcd.write(byte(1)) : lcd.print(F(" "));
          request(i, V_VAR2);
          wait(500);
        }
        receivedInitialValue = false;
        while (!receivedInitialValue)
        {
          lcd.setCursor(15, 0);
          flashIcon = !flashIcon;
          flashIcon ? lcd.write(byte(1)) : lcd.print(F(" "));
          request(i, V_VAR3);
          wait(500);
        }
      }
      lcd.clear();
    }
    
    
    void presentation()  
    { 
      sendSketchInfo(SKETCH_NAME, SKETCH_VERSION);
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        present(i, S_LIGHT);
      }
    }
    
    //
    void loop()
    {
      updateClock();
      updateDisplay();
      goGetValveTimes();
      //
      if (buttonPushed)
      {
        menuTimer = millis();
        DEBUG_PRINTLN(F("Button Pressed"));
        if (state == STAND_BY_ALL_OFF)
        {
          state = ZONE_SELECT_MENU;
          menuState = 0;
        }
        else if (state == ZONE_SELECT_MENU)
        {
          menuState++;
          if (menuState > NUMBER_OF_VALVES)
          {
            menuState = 0;
          }
        }
        else
        {
          state = STAND_BY_ALL_OFF;
        }
        buttonPushed = false;
      }
      if (state == STAND_BY_ALL_OFF)
      {
        slowToggleLED ();
        if (state != lastState)
        {
          updateRelays(ALL_VALVES_OFF);
          DEBUG_PRINTLN(F("State Changed... all Zones off"));
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            wait(50);
            send(msg1valve.setSensor(i).set(false), false);
          }
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print(F("** Irrigation **"));
          lcd.setCursor(0,1);
          lcd.print(F("**   Halted   **"));
          wait(2000);
          lastValve = -1;
        }
      }
      //
      else if (state == RUN_ALL_ZONES)
      {
        if (lastValve != valveNumber)
        {
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            if (i == 0 || i == valveNumber)
            {
              send(msg1valve.setSensor(i).set(true), false);
            }
            else
            {
              send(msg1valve.setSensor(i).set(false), false);
            }
          }
        }
        lastValve = valveNumber;
        fastToggleLed();
        if (state != lastState)
        {
          valveNumber = 1;
          updateRelays(ALL_VALVES_OFF);
          DEBUG_PRINTLN(F("State Changed, Running All Zones..."));
        }
        unsigned long nowMillis = millis();
        if (nowMillis - startMillis < VALVE_RESET_TIME)
        {
          updateRelays(ALL_VALVES_OFF);
        }
        else if (nowMillis - startMillis < (allZoneTime[valveNumber] * 60000UL))
        {
          updateRelays(BITSHIFT_VALVE_NUMBER);
        }
        else
        {
          DEBUG_PRINTLN(F("Changing Valves..."));
          updateRelays(ALL_VALVES_OFF);
          startMillis = millis();
          valveNumber++;
          if (valveNumber > NUMBER_OF_VALVES)
          {
            state = CYCLE_COMPLETE;
            startMillis = millis();
            lastValve = -1;
            lastTimeRun = now();
            saveDateToEEPROM(lastTimeRun);
            for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
            {
              send(msg1valve.setSensor(i).set(false), false);
            }
            DEBUG_PRINT(F("State = "));
            DEBUG_PRINTLN(state);
          }
        }
      }
      //
      else if (state == RUN_SINGLE_ZONE)
      {
        fastToggleLed();
        if (state != lastState)
        {
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            if (i == 0 || i == valveNumber)
            {
              send(msg1valve.setSensor(i).set(true), false);
            }
            else
            {
              send(msg1valve.setSensor(i).set(false), false);
            }
          }
          DEBUG_PRINTLN(F("State Changed, Single Zone Running..."));
          DEBUG_PRINT(F("Zone: "));
          DEBUG_PRINTLN(valveNumber);
        }
        unsigned long nowMillis = millis();
        if (nowMillis - startMillis < VALVE_RESET_TIME)
        {
          updateRelays(ALL_VALVES_OFF);
        }
        else if (nowMillis - startMillis < (valveSoloTime [valveNumber] * 60000UL))
        {
          updateRelays(BITSHIFT_VALVE_NUMBER);
        }
        else
        {
          updateRelays(ALL_VALVES_OFF);
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            send(msg1valve.setSensor(i).set(false), false);
          }
          state = CYCLE_COMPLETE;
          startMillis = millis();
          DEBUG_PRINT(F("State = "));
          DEBUG_PRINTLN(state);
        }
        lastTimeRun = now();
      }
      else if (state == CYCLE_COMPLETE)
      {
        if (millis() - startMillis < 30000UL)
        {
          fastToggleLed();
        }
        else
        {
          state = STAND_BY_ALL_OFF;
        }
      }
      else if (state == ZONE_SELECT_MENU)
      {
        displayMenu();
      }
      lastState = state;
    }
    //
    void displayMenu(void)
    {
      static byte lastMenuState = -1;
      static int lastSecond;
      if (menuState != lastMenuState)
      {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(valveNickName[menuState]);
        lcd.setCursor(0, 1);
        lcd.print(F("Starting"));
        DEBUG_PRINT(valveNickName[menuState]);
        Serial.print(F(" Starting Shortly"));
      }
      int thisSecond = (millis() - menuTimer) / 1000UL;
      if (thisSecond != lastSecond && thisSecond < 8)
      {
        lcd.print(F("."));
        Serial.print(".");
      }
      lastSecond = thisSecond;
      if (millis() - menuTimer > 10000UL)
      {
        startMillis = millis();
        if (menuState == 0)
        {
          valveNumber = 1;
          state = RUN_ALL_ZONES;
        }
        else
        {
          valveNumber = menuState;
          state = RUN_SINGLE_ZONE;
        }
      }
      else
      {
    
      }
      lastMenuState = menuState;
    }
    //
    void updateRelays(int value)
    {
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, MSBFIRST, highByte(value));
      shiftOut(dataPin, clockPin, MSBFIRST, lowByte(value));
      digitalWrite(latchPin, HIGH);
    }
    //
    void PushButton() //interrupt with debounce
    {
      static unsigned long last_interrupt_time = 0;
      unsigned long interrupt_time = millis();
      if (interrupt_time - last_interrupt_time > 200)
      {
        buttonPushed = true;
      }
      last_interrupt_time = interrupt_time;
    }
    //
    void fastToggleLed()
    {
      static unsigned long fastLedTimer;
      if (millis() - fastLedTimer >= 100UL)
      {
        digitalWrite(ledPin, !digitalRead(ledPin));
        fastLedTimer = millis ();
      }
    }
    //
    void slowToggleLED ()
    {
      static unsigned long slowLedTimer;
      if (millis() - slowLedTimer >= 1250UL)
      {
        digitalWrite(ledPin, !digitalRead(ledPin));
        slowLedTimer = millis ();
      }
    }
    //
    void receive(const MyMessage &message)
    {
      bool zoneTimeUpdate = false;
      if (message.isAck())
      {
        DEBUG_PRINTLN(F("This is an ack from gateway"));
      }
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        if (message.sensor == i)
        {
          if (message.type == V_LIGHT)
          {
            int switchState = atoi(message.data);
            if (switchState == 0)
            {
              state = STAND_BY_ALL_OFF;
              DEBUG_PRINTLN(F("Recieved Instruction to Cancel..."));
            }
            else
            {
              if (i == 0)
              {
                state = RUN_ALL_ZONES;
                valveNumber = 1;
                DEBUG_PRINTLN(F("Recieved Instruction to Run All Zones..."));
              }
              else
              {
                state = RUN_SINGLE_ZONE;
                valveNumber = i;
                DEBUG_PRINT(F("Recieved Instruction to Activate Zone: "));
                DEBUG_PRINTLN(i);
              }
            }
            startMillis = millis();
          }
          else if (message.type == V_VAR1)
          {
            int variable1 = atoi(message.data);// RUN_ALL_ZONES time
            DEBUG_PRINT(F("Recieved variable1 valve:"));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" = "));
            DEBUG_PRINTLN(variable1);
            if (variable1 != allZoneTime[i])
            {
              allZoneTime[i] = variable1;
    
              zoneTimeUpdate = true;
            }
            receivedInitialValue = true;
          }
          else if (message.type == V_VAR2)
          {
            int variable2 = atoi(message.data);// RUN_SINGLE_ZONE time
            DEBUG_PRINT(F("Recieved variable2 valve:"));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" = "));
            DEBUG_PRINTLN(variable2);
            if (variable2 != valveSoloTime[i])
            {
              valveSoloTime[i] = variable2;
              zoneTimeUpdate = true;
            }
            receivedInitialValue = true;
          }
          else if (message.type == V_VAR3)
          {
            String newMessage = String(message.data);
            if (newMessage.length() == 0) 
            {
              DEBUG_PRINT(F("No Name Recieved for zone "));
              DEBUG_PRINTLN(i);
              break;
            }
            if (newMessage.length() > 16)
            {
              newMessage.substring(0, 16);
            }
            valveNickName[i] = "";
            valveNickName[i] += newMessage;
            DEBUG_PRINT(F("Recieved new name for zone "));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" and it is now called: "));
            DEBUG_PRINTLN(valveNickName[i]);
          }
          receivedInitialValue = true;
        }
      }
      if (zoneTimeUpdate)
      {
        //
        DEBUG_PRINTLN(F("New Zone Times Recieved..."));
        for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
        {
          if (i != 0)
          {
            DEBUG_PRINT(F("Zone "));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" individual time: "));
            DEBUG_PRINT(valveSoloTime[i]);
            DEBUG_PRINT(F(" group time: "));
            DEBUG_PRINTLN(allZoneTime[i]);
            recentUpdate = true;
          }
        }
      }
      else
      {
        recentUpdate = false;
      }
    }
    //
    void updateDisplay()
    {
      static unsigned long lastUpdateTime;
      static bool displayToggle = false;
      //static byte toggleCounter = 0;
      static SprinklerStates lastDisplayState;
      if (state != lastDisplayState || millis() - lastUpdateTime >= 3000UL)
      {
        displayToggle = !displayToggle;
        switch (state) {
          case STAND_BY_ALL_OFF:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F("  System Ready "));
              if (clockUpdating)
              {
                lcd.setCursor(15, 0);
                lcd.write(byte(0));
              }
              lcd.setCursor(0, 1);
              lcd.print(hourFormat12() < 10 ? F(" ") : F(""));
              lcd.print(hourFormat12());
              lcd.print(minute() < 10 ? F(":0") : F(":"));
              lcd.print(minute());
              lcd.print(isAM() ? F("am") : F("pm"));
              lcd.print(month() < 10 ? F(" 0") : F(" "));
              lcd.print(month());
              lcd.print(day() < 10 ? F("/0") : F("/"));
              lcd.print(day());
              lcd.print(F("/"));
              lcd.print(year() % 100);
            }
            else
            {
              lcd.print(F("  Last Watered "));
              if (clockUpdating)
              {
                lcd.setCursor(15, 0);
                lcd.write(byte(0));
              }
              lcd.setCursor(0, 1);
              lcd.print(dayOfWeek[weekday(lastTimeRun)]);
              lcd.setCursor(11, 1);
              lcd.print(month(lastTimeRun) < 10 ? F(" ") : F(""));
              lcd.print(month(lastTimeRun));
              lcd.print(day(lastTimeRun) < 10 ? F("/0") : F("/"));
              lcd.print(day(lastTimeRun));
            }
            break;
          case RUN_SINGLE_ZONE:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F("Single Zone Mode"));
              lcd.setCursor(0, 1);
              lcd.print(F(" Zone:"));
              if (valveNumber < 10) lcd.print(F("0"));
              lcd.print(valveNumber);
              lcd.print(F(" Active"));
            }
            else
            {
              lcd.print(F(" Time Remaining "));
              lcd.setCursor(0, 1);
              if (valveSoloTime[valveNumber] == 0)
              {
                lcd.print(F(" No Valve Time "));
              }
              else
              {
                unsigned long timeRemaining = (valveSoloTime[valveNumber] * 60) - ((millis() - startMillis) / 1000);
                lcd.print(timeRemaining / 60 < 10 ? "   0" : "   ");
                lcd.print(timeRemaining / 60);
                lcd.print("min");
                lcd.print(timeRemaining % 60 < 10 ? " 0" : " ");
                lcd.print(timeRemaining % 60);
                lcd.print("sec  ");
              }
            }
            break;
          case RUN_ALL_ZONES:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F(" All-Zone  Mode "));
              lcd.setCursor(0, 1);
              lcd.print(F(" Zone:"));
              if (valveNumber < 10) lcd.print(F("0"));
              lcd.print(valveNumber);
              lcd.print(F(" Active "));
            }
            else
            {
              lcd.print(F(" Time Remaining "));
              lcd.setCursor(0, 1);
              int timeRemaining = (allZoneTime[valveNumber] * 60) - ((millis() - startMillis) / 1000);
              lcd.print((timeRemaining / 60) < 10 ? "   0" : "   ");
              lcd.print(timeRemaining / 60);
              lcd.print("min");
              lcd.print(timeRemaining % 60 < 10 ? " 0" : " ");
              lcd.print(timeRemaining % 60);
              lcd.print("sec  ");
            }
            break;
          case CYCLE_COMPLETE:
            //
            if (displayToggle)
            {
              lcd.setCursor(0, 0);
              lcd.print(F(" Watering Cycle "));
              lcd.setCursor(0, 1);
              lcd.print(F("    Complete    "));
            }
            else
            {
              int totalTimeRan = 0;
              for (int i = 1; i < NUMBER_OF_VALVES + 1; i++)
              {
                totalTimeRan += allZoneTime[i];
              }
              lcd.setCursor(0, 0);
              lcd.print(F(" Total Time Run "));
              lcd.setCursor(0, 1);
              lcd.print(totalTimeRan < 10 ? "   0" : "   ");
              lcd.print(totalTimeRan);
              lcd.print(" Minutes   ");
            }
          default:
            // what of ZONE_SELECT_MENU?
            break;
        }
        lastUpdateTime = millis();
      }
      lastDisplayState = state;
    }
    void receiveTime(time_t newTime)
    {
      DEBUG_PRINTLN(F("Time value received and updated..."));
      int lastSecond = second();
      int lastMinute = minute();
      int lastHour = hour();
      setTime(newTime);
      if (((second() != lastSecond) || (minute() != lastMinute) || (hour() != lastHour)) || showTime)
      {
        DEBUG_PRINTLN(F("Clock updated...."));
        DEBUG_PRINT(F("Sensor's time currently set to:"));
        DEBUG_PRINT(hourFormat12() < 10 ? F(" 0") : F(" "));
        DEBUG_PRINT(hourFormat12());
        DEBUG_PRINT(minute() < 10 ? F(":0") : F(":"));
        DEBUG_PRINT(minute());
        DEBUG_PRINTLN(isAM() ? F("am") : F("pm"));
        DEBUG_PRINT(month());
        DEBUG_PRINT(F("/"));
        DEBUG_PRINT(day());
        DEBUG_PRINT(F("/"));
        DEBUG_PRINTLN(year());
        DEBUG_PRINTLN(dayOfWeek[weekday()]);
        showTime = false;
      }
      else
      {
        DEBUG_PRINTLN(F("Sensor's time did NOT need adjustment greater than 1 second."));
      }
      clockUpdating = false;
    }
    void fastClear()
    {
      lcd.setCursor(0, 0);
      lcd.print(F("                "));
      lcd.setCursor(0, 1);
      lcd.print(F("                "));
    }
    //
    void updateClock()
    {
      static unsigned long lastVeraGetTime;
      if (millis() - lastVeraGetTime >= 3600000UL) // updates clock time and gets zone times from vera once every hour
      {
        DEBUG_PRINTLN(F("Requesting time and valve data from Gateway..."));
        lcd.setCursor(15, 0);
        lcd.write(byte(0));
        clockUpdating = true;
        requestTime();
        lastVeraGetTime = millis();
      }
    }
    //
    void saveDateToEEPROM(unsigned long theDate)
    {
      DEBUG_PRINTLN(F("Saving Last Run date"));
      if (loadState(0) != 0xFF)
      {
        saveState(0, 0xFF); // EEPROM flag for last date saved stored in EEPROM (location zero)
      }
      //
      for (int i = 1; i < 5; i++)
      {
        saveState(5 - i, byte(theDate >> 8 * (i - 1))); // store epoch datestamp in 4 bytes of EEPROM starting in location one
      }
    }
    //
    void goGetValveTimes()
    {
      static unsigned long valveUpdateTime;
      static byte valveIndex = 1;
      if (millis() - valveUpdateTime >= 300000UL / NUMBER_OF_VALVES)// update each valve once every 5 mins (distributes the traffic)
      {
        DEBUG_PRINTLN(F("Calling for Valve Data..."));
        lcd.setCursor(15, 0);
        lcd.write(byte(1)); //lcd.write(1);
        request(valveIndex, V_VAR1);
        request(valveIndex, V_VAR2);
        request(valveIndex, V_VAR3);
        valveUpdateTime = millis();
        valveIndex++;
        if (valveIndex > NUMBER_OF_VALVES + 1)
        {
          valveIndex = 1;
        }
      }
    }
    


  • Hello,

    Can some one help me with a working sketch for Domoticz.
    I have it a little working, only Domoticz give not the childs.
    I get from the gate way the time and then is searching for the name from the zone.
    If some one can give me a working sketch than i can see what is wrong.

    Thanks in advance Ton



  • This post is deleted!


  • This post is deleted!


  • Hello,
    first off all : thank you for your job.

    I'm trying to make this sketch, but i have some problems.
    Around the line 619 with V_VAR3
    In the sensor console i have this

    0 MCO:BGN:INIT REPEATER,CP=RNNRA--,VER=2.1.0
    3 TSM:INIT
    4 TSF:WUR:MS=0
    11 TSM:INIT:TSP OK
    13 TSF:SID:OK,ID=1
    15 TSM:FPAR
    51 TSF:MSG:SEND,1-1-255-255,s=255,c=3,t=7,pt=0,l=0,sg=0,ft=0,st=OK:
    144 TSF:MSG:READ,0-0-1,s=255,c=3,t=8,pt=1,l=1,sg=0:0
    149 TSF:MSG:FPAR OK,ID=0,D=1
    2058 TSM:FPAR:OK
    2059 TSM:ID
    2060 TSM:ID:OK
    2062 TSM:UPL
    2065 TSF:MSG:SEND,1-1-0-0,s=255,c=3,t=24,pt=1,l=1,sg=0,ft=0,st=OK:1
    2072 TSF:MSG:READ,0-0-1,s=255,c=3,t=25,pt=1,l=1,sg=0:1
    2077 TSF:MSG:PONG RECV,HP=1
    2080 TSM:UPL:OK
    2081 TSM:READY:ID=1,PAR=0,DIS=1
    2086 TSF:MSG:SEND,1-1-0-0,s=255,c=3,t=15,pt=6,l=2,sg=0,ft=0,st=OK:0100
    2096 TSF:MSG:READ,0-0-1,s=255,c=3,t=15,pt=6,l=2,sg=0:0100
    2103 TSF:MSG:SEND,1-1-0-0,s=255,c=0,t=18,pt=0,l=5,sg=0,ft=0,st=OK:2.1.0
    2111 TSF:MSG:SEND,1-1-0-0,s=255,c=3,t=6,pt=1,l=1,sg=0,ft=0,st=OK:0
    2129 TSF:MSG:READ,0-0-1,s=255,c=3,t=6,pt=0,l=1,sg=0:M
    2137 TSF:MSG:SEND,1-1-0-0,s=255,c=3,t=11,pt=0,l=11,sg=0,ft=0,st=OK:MySprinkler
    2146 TSF:MSG:SEND,1-1-0-0,s=255,c=3,t=12,pt=0,l=3,sg=0,ft=0,st=OK:2.0
    2154 TSF:MSG:SEND,1-1-0-0,s=0,c=0,t=3,pt=0,l=0,sg=0,ft=0,st=OK:
    2161 TSF:MSG:SEND,1-1-0-0,s=1,c=0,t=3,pt=0,l=0,sg=0,ft=0,st=OK:
    2168 TSF:MSG:SEND,1-1-0-0,s=2,c=0,t=3,pt=0,l=0,sg=0,ft=0,st=OK:
    2177 TSF:MSG:SEND,1-1-0-0,s=3,c=0,t=3,pt=0,l=0,sg=0,ft=0,st=OK:
    2184 TSF:MSG:SEND,1-1-0-0,s=4,c=0,t=3,pt=0,l=0,sg=0,ft=0,st=OK:
    2190 MCO:REG:REQ
    2193 TSF:MSG:SEND,1-1-0-0,s=255,c=3,t=26,pt=1,l=1,sg=0,ft=0,st=OK:2
    2199 TSF:MSG:READ,0-0-1,s=255,c=3,t=27,pt=1,l=1,sg=0:1
    2204 MCO:PIM:NODE REG=1
    2207 MCO:BGN:STP
    Initialisation...
    Mise des Vannes sur Off...
    Checking EEPROM for stored date:
    Retreiving last run time from EEPROM...
    Sensor Presentation Complete
    Ready...
    2864 TSF:MSG:SEND,1-1-0-0,s=255,c=3,t=1,pt=0,l=0,sg=0,ft=0,st=OK:
    Requesting time from Gateway:
    2882 TSF:MSG:READ,0-0-1,s=255,c=3,t=1,pt=0,l=10,sg=0:1484768469
    Time value received and updated...
    Horloge mise à jour....
    Sensor's time currently set to: 07:41pm
    18/1/2017
    Mercredi 
    Calling for Valve 0 Data...
    3902 TSF:MSG:SEND,1-1-0-0,s=0,c=2,t=24,pt=0,l=0,sg=0,ft=0,st=OK:
    3913 TSF:MSG:READ,0-0-1,s=0,c=2,t=24,pt=0,l=0,sg=0:
    Recieved variable1 valve:0 = 0
    4410 TSF:MSG:SEND,1-1-0-0,s=0,c=2,t=25,pt=0,l=0,sg=0,ft=0,st=OK:
    4431 TSF:MSG:READ,0-0-1,s=0,c=2,t=25,pt=0,l=0,sg=0:
    Recieved variable2 valve:0 = 0
    4919 TSF:MSG:SEND,1-1-0-0,s=0,c=2,t=26,pt=0,l=0,sg=0,ft=0,st=OK:
    4939 TSF:MSG:READ,0-0-1,s=0,c=2,t=26,pt=0,l=0,sg=0:
    No Name Recieved for zone 0
    5428 TSF:MSG:SEND,1-1-0-0,s=0,c=2,t=26,pt=0,l=0,sg=0,ft=0,st=OK:
    5447 TSF:MSG:READ,0-0-1,s=0,c=2,t=26,pt=0,l=0,sg=0:
    No Name Recieved for zone 0
    

    In my domoticz GW i have a node MySprinkler 2.0 with 6 childs : 0 to 4 S_LIGHT/S_BINARY, 255 REPREATER

    It's seems that the communication between gateway and sensors failed with V_VAR3, V_VAR1 and V_VAR2 are ok.

    Can somebody help me, please ?

    EDIT : according to the instructions inside this skecth :

    * Verify that each new device has a Variable1, Variable2 and Variable3. Populate data accordingly with whole minutes for
      the RUN_ALL_ZONES routine (Variable1) and the RUN_SINGLE_ZONE routines (Variable 2).  The values entered for times may be zero and
      you may use the defaulet zone names by leaving Variable3 blank.
    

    I can't find any Variable in my domoticz Controller, only S_LIGHT childs of Sprinkler Node :
    0_1484781045078_image.png

    Where is my mistake ?



  • I reply to myself...
    Like Huczas say before, you have to modify this Sketch for Domoticz. 😞

    Domoticz don't receive and manage V_VAR1, V_VAR2, V_VAR3, so you have to fixe them in code.

    But i have another question :
    is there a possibility to declare a supplementary sensor wich can manage this variables ?



  • Hi I looking to do My 1st MySensors Project an hoping to use this one I have a 3.2" Nextion. Will it be hard to use a nextion as a Display. Will there be help so I can get it working as I think the nextion Display will be good .... with weather updates and maybe senses to tell if the plants has to much water or no water. but thats down the trake...



  • Hi, this is my first MySensors project having been inspired to jump in after finding @petewill great Youtube video. Thanks to @BulldogLowell for the code. After much perseverance I have everything working... kinda'.
    My last persistent issue is the system halting zone 2, ie, cycle starts and ~10 seconds in the irrigation is halted. This only happens for Zone 2 (pin 1 on the shift register). This issue only occurs when either starting Zone 2 singularly from the controller or as part of the All Zones from the controller - Zone 1 will complete, Zone 2 will start then stop after ~10 seconds. Zone 2 WILL complete fine when selected manually from the pushbutton. All Zones from the pushbutton or controller will both fail.
    I've checked and re-checked solder joints, wire connections, put the 10k external pullup resistor in and swapped out shift registers with no luck so far.
    Would appreciate any help to resolve. Thanks.

    I am using Domoticz and @Huczas modified sketch.

    /*
    
    Arduino Multi-Zone Sprinkler Control
    
    May 31, 2015
    
    *** Version 2.0
    
    *** Upgraded to http://MySensors.org version 1.4.1
    *** Expanded for up to 16 Valves
    *** Setup for active low relay board or comment out #define ACTIVE_LOW to switch to active high
    *** Switch to bitshift method vs byte arrays
    *** Changed RUN_ALL_ZONES Vera device to 0 (was highest valve)
    *** Added optional LCD display featuring remaining time, date last ran & current time
    *** Features 'raindrop' and 'clock' icons which indicate sensor is updating valve data and clock respectively
    *** Added single pushbutton menu to manually select which program to run (All Zones or a Single Zone)
    *** Added option of naming your Zones programmatically or with Vera (V_VAR3 used to store names)
    
    Utilizing your Vera home automation controller and the MySensors.org gateway you can
    control up to a sixteen zone irrigation system with only three digital pins.  This sketch
    will create NUMBER_OF_VALVES + 1 devices on your Vera controller
    
    This sketch features the following:
    
    * Allows you to cycle through All zones (RUN_ALL_ZONES) or individual zone (RUN_SINGLE_ZONE) control.
    * Use the 0th controller to activate RUN_ALL_ZONES (each zone in numeric sequence 1 to n)
      using Variable1 as the "ON" time in minutes in each of the vera devices created.
    * Use the individual zone controller to activate a single zone.  This feature uses
      Variable2 as the "ON" time for each individual device/zone.
    * Connect according to pinout below and uses Shift Registers as to allow the MySensors
      standard radio configuration and still leave available digital pins
    * Turning on any zone will stop the current process and begin that particular process.
    * Turning off any zone will stop the current process and turn off all zones.
    * To push your new time intervals for your zones, simply change the variable on your Vera and
      your arduino will call to Vera once a minute and update accordingly.  Variables will also be
      requested when the device is first powered on.
    * Pushbutton activation to RUN_ALL_ZONES, RUN_SINGLE_ZONE or halt the current program
    * LED status indicator
    
    PARTS LIST:
    Available from the MySensors store - http://www.mysensors.org/store/
    * Relays (8 channel)
    * Female Pin Header Connector Strip
    * Prototype Universal Printed Circuit Boards (PCB)
    * NRF24L01 Radio
    * Arduino (I used a Pro Mini)
    * FTDI USB to TTL Serial Adapter
    * Capacitors (10uf and .1uf)
    * 3.3v voltage regulator
    * Resistors (270 & 10K)
    * Female Dupont Cables
    * 1602 LCD (with I2C Interface)
    * LED
    * Push button
    * Shift Register (SN74HC595)
    * 2 Pole 5mm Pitch PCB Mount Screw Terminal Block
    * 3 Pole 5mm Pitch PCB Mount Screw Terminal Block
    * 22-24 gauge wire or similar (I used Cat5/Cat6 cable)
    * 18 gauge wire (for relay)
    * Irrigation Power Supply (24-Volt/750 mA Transformer)
    
    
    INSTRUCTIONS:
    
    * A step-by-step setup video is available here: http://youtu.be/l4GPRTsuHkI
    * After assembling your arduino, radio, decoupling capacitors, shift register(s), status LED, pushbutton LCD (I2C connected to
      A4 and A5) and relays, and load the sketch.
    * Following the instructions at https://MySensors.org include the device to your MySensors Gateway.
    * Verify that each new device has a Variable1, Variable2 and Variable3. Populate data accordingly with whole minutes for
      the RUN_ALL_ZONES routine (Variable1) and the RUN_SINGLE_ZONE routines (Variable 2).  The values entered for times may be zero and
      you may use the defaulet zone names by leaving Variable3 blank.
    * Once you have entered values for each zone and each variable, save the settings by pressing the red save button on your Vera.
    * Restart your arduino; verify the settings are loaded into your arduino with the serial monitor; the array will be printed
      on the serial monitor.
    * Your arduino should slow-flash, indicating that it is in ready mode.
    * There are multiple debug serial prints that can be monitored to assure that it is operating properly.
    * ***THIS SHOULD NO LONGER BE NEEDED*** The standard MySensors library now works. https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads for the I2C library, or use yours
    
    Contributed by Jim (BulldogLowell@gmail.com) with much contribution from Pete (pete.will@mysensors.org) and is released to the public domain
    */
    //
    #include <Wire.h>
    #include <Time.h>
    #include <MySensor.h>
    #include <SPI.h>
    #include <LiquidCrystal.h>
    #include <LiquidCrystal_I2C.h>
    //
    #define NUMBER_OF_VALVES 5  // Change this to set your valve count up to 16.
    #define VALVE_RESET_TIME 4500UL   // Change this (in milliseconds) for the time you need your valves to hydraulically reset and change state
    #define RADIO_ID AUTO  // Change this to fix your Radio ID or use Auto
    
    #define SKETCH_NAME "MySprinkler Domoticz"
    #define SKETCH_VERSION "2.0"
    //
    #define CHILD_ID_SPRINKLER 0
    //
    #define ACTIVE_LOW // comment out this line if your relays are active high
    //
    #define DEBUG_ON   // comment out to supress serial monitor output
    //
    #ifdef ACTIVE_LOW
    #define BITSHIFT_VALVE_NUMBER ~(1U << (valveNumber-1))
    #define ALL_VALVES_OFF 0xFFFF
    #else
    #define BITSHIFT_VALVE_NUMBER (1U << (valveNumber-1))
    #define ALL_VALVES_OFF 0U
    #endif
    //
    #ifdef DEBUG_ON
    #define DEBUG_PRINT(x)   Serial.print(x)
    #define DEBUG_PRINTLN(x) Serial.println(x)
    #define SERIAL_START(x)  Serial.begin(x)
    #else
    #define DEBUG_PRINT(x)
    #define DEBUG_PRINTLN(x)
    #define SERIAL_START(x)
    #endif
    //
    typedef enum {
      STAND_BY_ALL_OFF, RUN_SINGLE_ZONE, RUN_ALL_ZONES, CYCLE_COMPLETE, ZONE_SELECT_MENU
    }
    SprinklerStates;
    //
    SprinklerStates state = STAND_BY_ALL_OFF;
    SprinklerStates lastState;
    byte menuState = 0;
    unsigned long menuTimer;
    byte countDownTime = 10;
    //
    int allZoneTime [NUMBER_OF_VALVES + 1]= {0, 1, 1, 1, 1, 1};     // Insert values in min, 0 = all zone (always 0) this is a 5 chan relay
    int valveSoloTime [NUMBER_OF_VALVES + 1]= {0, 1, 1, 1, 1, 1};   // Insert values in min, 0 = all zone (always 0) this is a 5 chan relay
    int valveNumber;
    int lastValve;
    unsigned long startMillis;
    const int ledPin = 5;
    const int waterButtonPin = 3;
    boolean buttonPushed = false;
    boolean showTime = true;
    boolean clockUpdating = false;
    boolean recentUpdate = true;
    const char *dayOfWeek[] = {
      "Null", "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "
    };
    // Name your Zones here or use Vera to edit them by adding a name in Variable3...
    String valveNickName[17] = {
      "All Zones", "Zone 1", "Zone 2", "Zone 3", "Zone 4", "Zone 5", "Zone 6", "Zone 7", "Zone 8", "Zone 9", "Zone 10", "Zone 11", "Zone 12", "Zone 13", "Zone 14", "Zone 15", "Zone 16"
    };
    //
    time_t lastTimeRun = 0;
    //Setup Shift Register...
    const int latchPin = 8;
    const int clockPin = 4;
    const int dataPin  = 7;
    //extra for 1k resistor
    //const int outputEnablePin = 6;
    //end extra 1k
    //
    byte clock[8] = {0x0, 0xe, 0x15, 0x17, 0x11, 0xe, 0x0}; // fetching time indicator
    byte raindrop[8] = {0x4, 0x4, 0xA, 0xA, 0x11, 0xE, 0x0,}; // fetching Valve Data indicator
    // Set the pins on the I2C chip used for LCD connections:
    //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address to 0x27
    MySensor gw;
    //
    MyMessage msg1valve(CHILD_ID_SPRINKLER, V_LIGHT);
    MyMessage var1valve(CHILD_ID_SPRINKLER, V_VAR1);
    MyMessage var2valve(CHILD_ID_SPRINKLER, V_VAR2);
    //
    void setup()
    {
      SERIAL_START(115200);
      DEBUG_PRINTLN(F("Initialising..."));
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(ledPin, OUTPUT);
      //internal pullup use next line
      //pinMode(waterButtonPin, INPUT_PULLUP);
      //external pullup use next line
      pinMode(waterButtonPin, INPUT);
      attachInterrupt(1, PushButton, RISING); //May need to change for your Arduino model
      digitalWrite (ledPin, HIGH);
      DEBUG_PRINTLN(F("Turning All Valves Off..."));
      updateRelays(ALL_VALVES_OFF);
      //extra for 1k resistor
      //pinMode(outputEnablePin, OUTPUT);
      //digitalWrite (outputEnablePin, LOW);
      //end extra 1k  
      //delay(5000);
      //delay(5000);
      lcd.begin(16, 2); //(16 characters and 2 line display)
      lcd.clear();
      lcd.backlight();
      lcd.createChar(0, clock);
      lcd.createChar(1, raindrop);
      //
      //check for saved date in EEPROM
      DEBUG_PRINTLN(F("Checking EEPROM for stored date:"));
      delay(500);
      if (gw.loadState(0) == 0xFF); // EEPROM flag
      {
        DEBUG_PRINTLN(F("Retreiving last run time from EEPROM..."));
        for (int i = 0; i < 4 ; i++)
        {
          lastTimeRun = lastTimeRun << 8;
          lastTimeRun = lastTimeRun | gw.loadState(i + 1); // assemble 4 bytes into an ussigned long epoch timestamp
        }
      }
      gw.begin(getVariables, RADIO_ID, false); // Change 'false' to 'true' to create a Radio repeating node
      gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION);
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        gw.present(i, S_LIGHT);
      }
      DEBUG_PRINTLN(F("Sensor Presentation Complete"));
      //
      digitalWrite (ledPin, LOW);
      DEBUG_PRINTLN(F("Ready..."));
      //
      lcd.setCursor(0, 0);
      lcd.print(F(" Syncing Time  "));
      lcd.setCursor(15, 0);
      lcd.write(byte(0));
      lcd.setCursor(0, 1);
      int clockCounter = 0;
      while (timeStatus() == timeNotSet && clockCounter < 21)
      {
        gw.process();
        gw.requestTime(receiveTime);
        DEBUG_PRINTLN(F("Requesting time from Gateway:"));
        delay(1000);
        lcd.print(".");
        clockCounter++;
        if (clockCounter > 16)
        {
          DEBUG_PRINTLN(F("Failed initial clock synchronization!"));
          lcd.clear();
          lcd.print(F("  Failed Clock  "));
          lcd.setCursor(0, 1);
          lcd.print(F(" Syncronization "));
          delay(2000);
          break;
        }
      }
      //
      lcd.clear();
    
      /*
      //Update valve data when first powered on
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        lcd.print(F(" Updating  "));
        lcd.setCursor(0, 1);
        lcd.print(F(" Valve Data: "));
        lcd.print(i);
        boolean flashIcon = false;
        DEBUG_PRINT(F("Calling for Valve "));
        DEBUG_PRINT(i);
        DEBUG_PRINTLN(F(" Data..."));
        while (gw.process() == false)
        {
          lcd.setCursor(15, 0);
          flashIcon = !flashIcon;
          flashIcon ? lcd.write(byte(1)) : lcd.print(F(" "));
          gw.request(i, V_VAR1);
          delay(100);
        }
        while (gw.process() == false)
        {
          lcd.setCursor(15, 0);
          flashIcon = !flashIcon;
          flashIcon ? lcd.write(byte(1)) : lcd.print(F(" "));
          gw.request(i, V_VAR2);
          delay(100);
        }
        while (gw.process() == false)
        {
          lcd.setCursor(15, 0);
          flashIcon = !flashIcon;
          flashIcon ? lcd.write(byte(1)) : lcd.print(F(" "));
          gw.request(i, V_VAR3);
          delay(100);
        }
      }
      */
      lcd.clear();
    }
    //
    void loop()
    {
      gw.process();
      updateClock();
      updateDisplay();
      //goGetValveTimes();
      //
      if (buttonPushed)
      {
        menuTimer = millis();
        DEBUG_PRINTLN(F("Button Pressed"));
        if (state == STAND_BY_ALL_OFF)
        {
          state = ZONE_SELECT_MENU;
          menuState = 0;
        }
        else if (state == ZONE_SELECT_MENU)
        {
          menuState++;
          if (menuState > NUMBER_OF_VALVES)
          {
            menuState = 0;
          }
        }
        else
        {
          state = STAND_BY_ALL_OFF;
        }
        buttonPushed = false;
      }
      if (state == STAND_BY_ALL_OFF)
      {
        slowToggleLED ();
        if (state != lastState)
        {
          updateRelays(ALL_VALVES_OFF);
          DEBUG_PRINTLN(F("State Changed... all Zones off"));
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            delay(50);
            gw.send(msg1valve.setSensor(i).set(false), false);
          }
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print(F("** Irrigation **"));
          lcd.setCursor(0,1);
          lcd.print(F("**   Halted   **"));
          delay(2000);
          lastValve = -1;
        }
      }
      //
      else if (state == RUN_ALL_ZONES)
      {
        if (lastValve != valveNumber)
        {
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            if (i == 0 || i == valveNumber)
            {
              gw.send(msg1valve.setSensor(i).set(true), false);
            }
            else
            {
              gw.send(msg1valve.setSensor(i).set(false), false);
            }
          }
        }
        lastValve = valveNumber;
        fastToggleLed();
        if (state != lastState)
        {
          valveNumber = 1;
          updateRelays(ALL_VALVES_OFF);
          DEBUG_PRINTLN(F("State Changed, Running All Zones..."));
        }
        unsigned long nowMillis = millis();
        if (nowMillis - startMillis < VALVE_RESET_TIME)
        {
          updateRelays(ALL_VALVES_OFF);
        }
        else if (nowMillis - startMillis < (allZoneTime[valveNumber] * 60000UL))
        {
          updateRelays(BITSHIFT_VALVE_NUMBER);
        }
        else
        {
          DEBUG_PRINTLN(F("Changing Valves..."));
          updateRelays(ALL_VALVES_OFF);
          startMillis = millis();
          valveNumber++;
          if (valveNumber > NUMBER_OF_VALVES)
          {
            state = CYCLE_COMPLETE;
            startMillis = millis();
            lastValve = -1;
            lastTimeRun = now();
            saveDateToEEPROM(lastTimeRun);
            for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
            {
              gw.send(msg1valve.setSensor(i).set(false), false);
            }
            DEBUG_PRINT(F("State = "));
            DEBUG_PRINTLN(state);
          }
        }
      }
      //
      else if (state == RUN_SINGLE_ZONE)
      {
        fastToggleLed();
        if (state != lastState)
        {
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            if (i == 0 || i == valveNumber)
            {
              gw.send(msg1valve.setSensor(i).set(true), false);
            }
            else
            {
              gw.send(msg1valve.setSensor(i).set(false), false);
            }
          }
          DEBUG_PRINTLN(F("State Changed, Single Zone Running..."));
          DEBUG_PRINT(F("Zone: "));
          DEBUG_PRINTLN(valveNumber);
        }
        unsigned long nowMillis = millis();
        if (nowMillis - startMillis < VALVE_RESET_TIME)
        {
          updateRelays(ALL_VALVES_OFF);
        }
        else if (nowMillis - startMillis < (valveSoloTime [valveNumber] * 60000UL))
        {
          updateRelays(BITSHIFT_VALVE_NUMBER);
        }
        else
        {
          updateRelays(ALL_VALVES_OFF);
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            gw.send(msg1valve.setSensor(i).set(false), false);
          }
          state = CYCLE_COMPLETE;
          startMillis = millis();
          DEBUG_PRINT(F("State = "));
          DEBUG_PRINTLN(state);
        }
        lastTimeRun = now();
      }
      else if (state == CYCLE_COMPLETE)
      {
        if (millis() - startMillis < 30000UL)
        {
          fastToggleLed();
        }
        else
        {
          state = STAND_BY_ALL_OFF;
        }
      }
      else if (state = ZONE_SELECT_MENU)
      {
        displayMenu();
      }
      lastState = state;
    }
    //
    void displayMenu(void)
    {
      static byte lastMenuState = -1;
      static int lastSecond;
      if (menuState != lastMenuState)
      {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(valveNickName[menuState]);
        lcd.setCursor(0, 1);
        lcd.print(F("Starting"));
        DEBUG_PRINT(valveNickName[menuState]);
        Serial.print(F(" Starting Shortly"));
      }
      int thisSecond = (millis() - menuTimer) / 1000UL;
      if (thisSecond != lastSecond && thisSecond < 8)
      {
        lcd.print(F("."));
        Serial.print(".");
      }
      lastSecond = thisSecond;
      if (millis() - menuTimer > 10000UL)
      {
        startMillis = millis();
        if (menuState == 0)
        {
          valveNumber = 1;
          state = RUN_ALL_ZONES;
        }
        else
        {
          valveNumber = menuState;
          state = RUN_SINGLE_ZONE;
        }
      }
      else
      {
    
      }
      lastMenuState = menuState;
    }
    //
    void updateRelays(int value)
    {
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, MSBFIRST, highByte(value));
      shiftOut(dataPin, clockPin, MSBFIRST, lowByte(value));
      digitalWrite(latchPin, HIGH);
    }
    //
    void PushButton() //interrupt with debounce
    {
      static unsigned long last_interrupt_time = 0;
      unsigned long interrupt_time = millis();
      if (interrupt_time - last_interrupt_time > 200)
      {
        buttonPushed = true;
      }
      last_interrupt_time = interrupt_time;
    }
    //
    void fastToggleLed()
    {
      static unsigned long fastLedTimer;
      if (millis() - fastLedTimer >= 100UL)
      {
        digitalWrite(ledPin, !digitalRead(ledPin));
        fastLedTimer = millis ();
      }
    }
    //
    void slowToggleLED ()
    {
      static unsigned long slowLedTimer;
      if (millis() - slowLedTimer >= 1250UL)
      {
        digitalWrite(ledPin, !digitalRead(ledPin));
        slowLedTimer = millis ();
      }
    }
    //
    void getVariables(const MyMessage &message)
    {
      boolean zoneTimeUpdate = false;
      if (message.isAck())
      {
        DEBUG_PRINTLN(F("This is an ack from gateway"));
      }
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        if (message.sensor == i)
        {
          if (message.type == V_LIGHT)
          {
            int switchState = atoi(message.data);
            if (switchState == 0)
            {
              state = STAND_BY_ALL_OFF;
              DEBUG_PRINTLN(F("Recieved Instruction to Cancel..."));
            }
            else
            {
              if (i == 0)
              {
                state = RUN_ALL_ZONES;
                valveNumber = 1;
                DEBUG_PRINTLN(F("Recieved Instruction to Run All Zones..."));
              }
              else
              {
                state = RUN_SINGLE_ZONE;
                valveNumber = i;
                DEBUG_PRINT(F("Recieved Instruction to Activate Zone: "));
                DEBUG_PRINTLN(i);
              }
            }
            startMillis = millis();
          }
          else if (message.type == V_VAR1)
          {
            int variable1 = atoi(message.data);// RUN_ALL_ZONES time
            DEBUG_PRINT(F("Recieved variable1 valve:"));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" = "));
            DEBUG_PRINTLN(variable1);
            if (variable1 != allZoneTime[i])
            {
              allZoneTime[i] = variable1;
    
              zoneTimeUpdate = true;
            }
          }
          else if (message.type == V_VAR2)
          {
            int variable2 = atoi(message.data);// RUN_SINGLE_ZONE time
            DEBUG_PRINT(F("Recieved variable2 valve:"));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" = "));
            DEBUG_PRINTLN(variable2);
            if (variable2 != valveSoloTime[i])
            {
              valveSoloTime[i] = variable2;
              zoneTimeUpdate = true;
            }
          }
          else if (message.type == V_VAR3)
          {
            String newMessage = String(message.data);
            if (newMessage.length() == 0) 
            {
              DEBUG_PRINT(F("No Name Recieved for zone "));
              DEBUG_PRINTLN(i);
              break;
            }
            if (newMessage.length() > 16)
            {
              newMessage.substring(0, 16);
            }
            valveNickName[i] = "";
            valveNickName[i] += newMessage;
            DEBUG_PRINT(F("Recieved new name for zone "));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" and it is now called: "));
            DEBUG_PRINTLN(valveNickName[i]);
          }
        }
      }
      if (zoneTimeUpdate)
      {
        //
        DEBUG_PRINTLN(F("New Zone Times Recieved..."));
        for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
        {
          if (i != 0)
          {
            DEBUG_PRINT(F("Zone "));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" individual time: "));
            DEBUG_PRINT(valveSoloTime[i]);
            DEBUG_PRINT(F(" group time: "));
            DEBUG_PRINTLN(allZoneTime[i]);
            recentUpdate = true;
          }
        }
      }
      else
      {
        recentUpdate = false;
      }
    }
    //
    void updateDisplay()
    {
      static unsigned long lastUpdateTime;
      static boolean displayToggle = false;
      //static byte toggleCounter = 0;
      static SprinklerStates lastDisplayState;
      if (state != lastDisplayState || millis() - lastUpdateTime >= 3000UL)
      {
        displayToggle = !displayToggle;
        switch (state) {
          case STAND_BY_ALL_OFF:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F("  System Ready "));
              if (clockUpdating)
              {
                lcd.setCursor(15, 0);
                lcd.write(byte(0));
              }
              lcd.setCursor(0, 1);
              lcd.print(hourFormat12() < 10 ? F(" ") : F(""));
              lcd.print(hourFormat12());
              lcd.print(minute() < 10 ? F(":0") : F(":"));
              lcd.print(minute());
              lcd.print(isAM() ? F("am") : F("pm"));
              lcd.print(month() < 10 ? F(" 0") : F(" "));
              lcd.print(month());
              lcd.print(day() < 10 ? F("/0") : F("/"));
              lcd.print(day());
              lcd.print(F("/"));
              lcd.print(year() % 100);
            }
            else
            {
              lcd.print(F("  Last Watered "));
              if (clockUpdating)
              {
                lcd.setCursor(15, 0);
                lcd.write(byte(0));
              }
              lcd.setCursor(0, 1);
              lcd.print(dayOfWeek[weekday(lastTimeRun)]);
              lcd.setCursor(11, 1);
              lcd.print(day(lastTimeRun) < 10 ? F("0") : F("/"));
              lcd.print(day(lastTimeRun));
              lcd.print(month(lastTimeRun) < 10 ? F(" ") : F(""));
              lcd.print(month(lastTimeRun));
              
            }
            break;
          case RUN_SINGLE_ZONE:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F("Single Zone Mode"));
              lcd.setCursor(0, 1);
              lcd.print(F(" Zone:"));
              if (valveNumber < 10) lcd.print(F("0"));
              lcd.print(valveNumber);
              lcd.print(F(" Active"));
            }
            else
            {
              lcd.print(F(" Time Remaining "));
              lcd.setCursor(0, 1);
              if (valveSoloTime[valveNumber] == 0)
              {
                lcd.print(F(" No Valve Time "));
              }
              else
              {
                unsigned long timeRemaining = (valveSoloTime[valveNumber] * 60) - ((millis() - startMillis) / 1000);
                lcd.print(timeRemaining / 60 < 10 ? "   0" : "   ");
                lcd.print(timeRemaining / 60);
                lcd.print("min");
                lcd.print(timeRemaining % 60 < 10 ? " 0" : " ");
                lcd.print(timeRemaining % 60);
                lcd.print("sec  ");
              }
            }
            break;
          case RUN_ALL_ZONES:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F(" All-Zone  Mode "));
              lcd.setCursor(0, 1);
              lcd.print(F(" Zone:"));
              if (valveNumber < 10) lcd.print(F("0"));
              lcd.print(valveNumber);
              lcd.print(F(" Active "));
            }
            else
            {
              lcd.print(F(" Time Remaining "));
              lcd.setCursor(0, 1);
              int timeRemaining = (allZoneTime[valveNumber] * 60) - ((millis() - startMillis) / 1000);
              lcd.print((timeRemaining / 60) < 10 ? "   0" : "   ");
              lcd.print(timeRemaining / 60);
              lcd.print("min");
              lcd.print(timeRemaining % 60 < 10 ? " 0" : " ");
              lcd.print(timeRemaining % 60);
              lcd.print("sec  ");
            }
            break;
          case CYCLE_COMPLETE:
            //
            if (displayToggle)
            {
              lcd.setCursor(0, 0);
              lcd.print(F(" Watering Cycle "));
              lcd.setCursor(0, 1);
              lcd.print(F("    Complete    "));
            }
            else
            {
              int totalTimeRan = 0;
              for (int i = 1; i < NUMBER_OF_VALVES + 1; i++)
              {
                totalTimeRan += allZoneTime[i];
              }
              lcd.setCursor(0, 0);
              lcd.print(F(" Total Time Run "));
              lcd.setCursor(0, 1);
              lcd.print(totalTimeRan < 10 ? "   0" : "   ");
              lcd.print(totalTimeRan);
              lcd.print(" Minutes   ");
            }
        }
        lastUpdateTime = millis();
      }
      lastDisplayState = state;
    }
    void receiveTime(time_t newTime)
    {
      DEBUG_PRINTLN(F("Time value received and updated..."));
      int lastSecond = second();
      int lastMinute = minute();
      int lastHour = hour();
      setTime(newTime);
      if (((second() != lastSecond) || (minute() != lastMinute) || (hour() != lastHour)) || showTime)
      {
        DEBUG_PRINTLN(F("Clock updated...."));
        DEBUG_PRINT(F("Sensor's time currently set to:"));
        DEBUG_PRINT(hourFormat12() < 10 ? F(" 0") : F(" "));
        DEBUG_PRINT(hourFormat12());
        DEBUG_PRINT(minute() < 10 ? F(":0") : F(":"));
        DEBUG_PRINT(minute());
        DEBUG_PRINTLN(isAM() ? F("am") : F("pm"));
        DEBUG_PRINT(month());
        DEBUG_PRINT(F("/"));
        DEBUG_PRINT(day());
        DEBUG_PRINT(F("/"));
        DEBUG_PRINTLN(year());
        DEBUG_PRINTLN(dayOfWeek[weekday()]);
        showTime = false;
      }
      else
      {
        DEBUG_PRINTLN(F("Sensor's time did NOT need adjustment greater than 1 second."));
      }
      clockUpdating = false;
    }
    void fastClear()
    {
      lcd.setCursor(0, 0);
      lcd.print(F("                "));
      lcd.setCursor(0, 1);
      lcd.print(F("                "));
    }
    //
    void updateClock()
    {
      static unsigned long lastVeraGetTime;
      if (millis() - lastVeraGetTime >= 3600000UL) // updates clock time and gets zone times from vera once every hour
      {
        DEBUG_PRINTLN(F("Requesting time and valve data from Gateway..."));
        lcd.setCursor(15, 0);
        lcd.write(byte(0));
        clockUpdating = true;
        gw.requestTime(receiveTime);
        lastVeraGetTime = millis();
      }
    }
    //
    void saveDateToEEPROM(unsigned long theDate)
    {
      DEBUG_PRINTLN(F("Saving Last Run date"));
      if (gw.loadState(0) != 0xFF)
      {
        gw.saveState(0, 0xFF); // EEPROM flag for last date saved stored in EEPROM (location zero)
      }
      //
      for (int i = 1; i < 5; i++)
      {
        gw.saveState(5 - i, byte(theDate >> 8 * (i - 1))); // store epoch datestamp in 4 bytes of EEPROM starting in location one
      }
    }
    //
    void goGetValveTimes()
    {
      static unsigned long valveUpdateTime;
      static byte valveIndex = 1;
      if (millis() - valveUpdateTime >= 300000UL / NUMBER_OF_VALVES)// update each valve once every 5 mins (distributes the traffic)
      {
        DEBUG_PRINTLN(F("Calling for Valve Data..."));
        lcd.setCursor(15, 0);
        lcd.write(byte(1)); //lcd.write(1);
        gw.request(valveIndex, V_VAR1);
        gw.request(valveIndex, V_VAR2);
        gw.request(valveIndex, V_VAR3);
        valveUpdateTime = millis();
        valveIndex++;
        if (valveIndex > NUMBER_OF_VALVES + 1)
        {
          valveIndex = 1;
        }
      }
    }```


  • @Paulb After more troubleshooting I finally narrowed down the problem to an external factor. It seems the old desk lamp I was using on my workbench interfered with the radio signal. It is a fluorescent tube which I understand can be quite 'noisy'. Replicated the conditions several times, stopped using the lamp - presto! everything works as it should.



  • Do anyone has a working solution to connect this project to a main valve who has to open when running the zones ?


  • Mod

    Do you mean that you need to open a main valve while any of the others are open and close it whenever the others are all closed?



  • @gohan exactly what I meant.



  • @pettib I started this project last summer but have not fully finished it. My setup has a pump start relay, which is essentially the same as a main valve control.

    One way to do this is to connect one more data line to a relay and in your sketch, change it so that any time a zone is triggered, turn on the main valve data line. Shouldn't be that difficult to code.

    I was originally planning to do this with hardware where I had diodes from each output of the shift register feeding to one central point which would be the main valve relay, but I had some trouble with that. Could have been that I was doing something wrong. None the less, the approach above should work without issue if programmed correctly.


  • Mod

    You could make a function that recursively checks if any of the valves pin is high it sets the main valve pin HIGH, if all the valve pins are LOW then it sets the main valve pin LOW



  • I have the irrigation controller all setup and working. I have one problem though as soon as I power it up with 5 volts for the pro mini sometimes one sometimes all the relays come on. If I am not home the water runs all day is there a programing change or a wire change I need to make to stop this. I was using the old wire diagram without the pull up on pin 13 of the 74hc I changed to the new version and added the lines off code but it still does not help.


  • Mod

    Are you setting all pins to low during setup?



  • So I had started this build going on a year ago but never finished it. That was before I found the easy newbie boards which is what I plan on using to resurrect this build. My question is, can this be built using a 3.3V pro mini, or should I be using a 5V one. I am just wondering if I need to set up my newbie board with a 3.3V regulator or not. My other question is on the resistors. I have a bunch of 1/8 watt resistors and was wondering if they would work or if I should go to 1/4 watt. I have all of the parts in my parts bin and with the newbie board it shouldn't take long to put it together, just need direction on those couple things.


  • Mod

    It's hard to answer since you aren't providing many details like is it battery powered? What kind of valves are you using? What are you using those resistors for?



  • @gohan Sorry, I am talking about the schematic for the irrigation controller in the build section of the site. That is why I posted the question here.

    One other thing that I just noticed, and I will post this in the easy newbie board thread also for @sundberg84, I noticed that there is a change in the pins that are broken out on the header on the left side of the board. This is the board that I am using for the build, and I was going to point out here that the schematic below shows to connect D7 and D8 to the shift register, but the REV 8 board that I am using does not break out D8. After looking at the site on the new REV 9 boards, which I have a batch of, he doesn't break out D7 or D8.. The wiring of the pins is completely different between the REV 8 and REV 9 boards. The reason I mention this is that I was going to write something up here explaining the build with a newbie board, but I think I will hold off as it might be confusing to many depending what REV of the board people have.

    Another thing that I just notices is on the schematic. I have a copy of the schematic that I printed last year when I started this build. There has since been a change. In the old schematic that I have it shows the output enable (OE) pin of the shift register grounded, where in the one below, it showsit connected to D6 through a 1K resistor. I can understand that the change is to give arduino control to the output enable line, but because in the other schematic it didn't show D6 connected, and I didn't have D8 broken out, I used D6 in it's place. I may need to rethink some of this. In any case, I will need to make some changes to the sketch prior to uploading it.
    0_1496074195604_upload-c4616651-6dc5-47bb-a4c6-ff77a1936257



  • OK, so I have this built this and have it mostly working with my Vera Plus. Below is a link to a video of a problem I am having.

    http://www.dan.bemowski.info/videos/20170601_004213.mp4

    So my sprinkler system has a pump start relay which gets turned on any time a valve is turned on. Because of this I made a slight hardware modification which thus required a software modification. For the hardware, I ended up using relay number 1 of my 8 channel relay board as my pump start relay control. This I have wired to pin A1. Relays 2 through 8 are connected to the shift register on Qb through Qh (outputs 2-8) skipping output 1. Because of this I had to change how the code defined which valve to start on. To do this, I changed the commented lines removing the (-1) on the bit shift. I made the assumption that in code, the relay numbers start with 0.

    #ifdef ACTIVE_LOW
    //#define BITSHIFT_VALVE_NUMBER ~(1U << (valveNumber-1))
    #define BITSHIFT_VALVE_NUMBER ~(1U << (valveNumber))
    #define ALL_VALVES_OFF 0xFFFF
    #else
    //#define BITSHIFT_VALVE_NUMBER (1U << (valveNumber-1))
    #define BITSHIFT_VALVE_NUMBER (1U << (valveNumber))
    #define ALL_VALVES_OFF 0U
    #endif
    

    Then I needed to define the pump start relay.

    const int pumpStart = A1;
    

    and then in setup I have this:

      pinMode(pumpStart, OUTPUT);
      digitalWrite (pumpStart, HIGH);
    

    Lastly, to operate the pump start relay whenever a zone is triggered, this is the updateRelays() function:

    void updateRelays(int value)
    {
      if (value == ALL_VALVES_OFF) 
      {
        digitalWrite(pumpStart, HIGH);
      }
      else
      {
        digitalWrite(pumpStart, LOW);
      }
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, MSBFIRST, highByte(value));
      shiftOut(dataPin, clockPin, MSBFIRST, lowByte(value));
      digitalWrite(latchPin, HIGH);
    }
    

    All of this seems to work. When I trigger a zone, I see the pump start relay kick on as well as the triggered zone relay. The only problem I have is that the screen keeps cycling valve data: (1-4) on the screen, as can be seen in the video clip.

    Here is my entire modified sketch that I have uploaded:

    /*
    MySprinkler for MySensors
    
    Arduino Multi-Zone Sprinkler Control
    
    May 31, 2015
    
    *** Version 2.0
    
    *** Upgraded to http://MySensors.org version 1.4.1
    *** Expanded for up to 16 Valves
    *** Setup for active low relay board or comment out #define ACTIVE_LOW to switch to active high
    *** Switch to bitshift method vs byte arrays
    *** Changed RUN_ALL_ZONES Vera device to 0 (was highest valve)
    *** Added optional LCD display featuring remaining time, date last ran & current time
    *** Features 'raindrop' and 'clock' icons which indicate sensor is updating valve data and clock respectively
    *** Added single pushbutton menu to manually select which program to run (All Zones or a Single Zone)
    *** Added option of naming your Zones programmatically or with Vera (V_VAR3 used to store names)
    
    Utilizing your Vera home automation controller and the MySensors.org gateway you can
    control up to a sixteen zone irrigation system with only three digital pins.  This sketch
    will create NUMBER_OF_VALVES + 1 devices on your Vera controller
    
    This sketch features the following:
    
    * Allows you to cycle through All zones (RUN_ALL_ZONES) or individual zone (RUN_SINGLE_ZONE) control.
    * Use the 0th controller to activate RUN_ALL_ZONES (each zone in numeric sequence 1 to n)
      using Variable1 as the "ON" time in minutes in each of the vera devices created.
    * Use the individual zone controller to activate a single zone.  This feature uses
      Variable2 as the "ON" time for each individual device/zone.
    * Connect according to pinout below and uses Shift Registers as to allow the MySensors
      standard radio configuration and still leave available digital pins
    * Turning on any zone will stop the current process and begin that particular process.
    * Turning off any zone will stop the current process and turn off all zones.
    * To push your new time intervals for your zones, simply change the variable on your Vera and
      your arduino will call to Vera once a minute and update accordingly.  Variables will also be
      requested when the device is first powered on.
    * Pushbutton activation to RUN_ALL_ZONES, RUN_SINGLE_ZONE or halt the current program
    * LED status indicator
    
    PARTS LIST:
    Available from the MySensors store - http://www.mysensors.org/store/
    * Relays (8 channel)
    * Female Pin Header Connector Strip
    * Prototype Universal Printed Circuit Boards (PCB)
    * NRF24L01 Radio
    * Arduino (I used a Pro Mini)
    * FTDI USB to TTL Serial Adapter
    * Capacitors (10uf and .1uf)
    * 3.3v voltage regulator
    * Resistors (270, 1K & 10K)
    * Female Dupont Cables
    * 1602 LCD (with I2C Interface)
    * LED
    * Push button
    * Shift Register (SN74HC595)
    * 2 Pole 5mm Pitch PCB Mount Screw Terminal Block
    * 3 Pole 5mm Pitch PCB Mount Screw Terminal Block
    * 22-24 gauge wire or similar (I used Cat5/Cat6 cable)
    * 18 gauge wire (for relay)
    * Irrigation Power Supply (24-Volt/750 mA Transformer)
    
    
    INSTRUCTIONS:
    
    * A step-by-step setup video is available here: http://youtu.be/l4GPRTsuHkI
    * After assembling your arduino, radio, decoupling capacitors, shift register(s), status LED, pushbutton LCD (I2C connected to
      A4 and A5) and relays, and load the sketch.
    * Following the instructions at https://MySensors.org include the device to your MySensors Gateway.
    * Verify that each new device has a Variable1, Variable2 and Variable3. Populate data accordingly with whole minutes for
      the RUN_ALL_ZONES routine (Variable1) and the RUN_SINGLE_ZONE routines (Variable 2).  The values entered for times may be zero and
      you may use the defaulet zone names by leaving Variable3 blank.
    * Once you have entered values for each zone and each variable, save the settings by pressing the red save button on your Vera.
    * Restart your arduino; verify the settings are loaded into your arduino with the serial monitor; the array will be printed
      on the serial monitor.
    * Your arduino should slow-flash, indicating that it is in ready mode.
    * There are multiple debug serial prints that can be monitored to assure that it is operating properly.
    * ***THIS SHOULD NO LONGER BE NEEDED*** The standard MySensors library now works. https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads for the I2C library, or use yours
    
    Contributed by Jim (BulldogLowell@gmail.com) with much contribution from Pete (pete.will@mysensors.org) and is released to the public domain
    */
    //
    
    // Enable debug prints
    #define MY_DEBUG
    
    // Enable and select radio type attached
    #define MY_RADIO_NRF24
    //#define MY_RADIO_RFM69
    
    //#define MY_NODE_ID 1  // Set this to fix your Radio ID or use Auto
    
    #include <Wire.h>
    #include <TimeLib.h>
    #include <SPI.h>
    #include <MySensors.h>
    #include <LiquidCrystal.h>
    #include <LiquidCrystal_I2C.h>
    
    
    #define NUMBER_OF_VALVES 4  // Change this to set your valve count up to 16.
    #define VALVE_RESET_TIME 7500UL   // Change this (in milliseconds) for the time you need your valves to hydraulically reset and change state
    #define VALVE_TIMES_RELOAD 300000UL  // Change this (in milliseconds) for how often to update all valves data from the controller (Loops at value/number valves)
                                         // ie: 300000 for 8 valves produces requests 37.5seconds with all valves updated every 5mins 
    
    #define SKETCH_NAME "MySprinkler"
    #define SKETCH_VERSION "2.2"
    //
    #define CHILD_ID_SPRINKLER 0
    //
    #define ACTIVE_LOW // comment out this line if your relays are active high
    //
    #define DEBUG_ON   // comment out to supress serial monitor output
    //
    #ifdef ACTIVE_LOW
    //#define BITSHIFT_VALVE_NUMBER ~(1U << (valveNumber-1))
    #define BITSHIFT_VALVE_NUMBER ~(1U << (valveNumber))
    #define ALL_VALVES_OFF 0xFFFF
    #else
    //#define BITSHIFT_VALVE_NUMBER (1U << (valveNumber-1))
    #define BITSHIFT_VALVE_NUMBER (1U << (valveNumber))
    #define ALL_VALVES_OFF 0U
    #endif
    //
    #ifdef DEBUG_ON
    #define DEBUG_PRINT(x)   Serial.print(x)
    #define DEBUG_PRINTLN(x) Serial.println(x)
    #else
    #define DEBUG_PRINT(x)
    #define DEBUG_PRINTLN(x)
    #define SERIAL_START(x)
    #endif
    //
    typedef enum {
      STAND_BY_ALL_OFF, RUN_SINGLE_ZONE, RUN_ALL_ZONES, CYCLE_COMPLETE, ZONE_SELECT_MENU
    }
    SprinklerStates;
    //
    SprinklerStates state = STAND_BY_ALL_OFF;
    SprinklerStates lastState;
    byte menuState = 0;
    unsigned long menuTimer;
    byte countDownTime = 10;
    //
    int allZoneTime [NUMBER_OF_VALVES + 1];
    int valveSoloTime [NUMBER_OF_VALVES + 1];
    int valveNumber;
    int lastValve;
    unsigned long startMillis;
    const int ledPin = 5;
    const int waterButtonPin = 3;
    bool buttonPushed = false;
    bool showTime = true;
    bool clockUpdating = false;
    bool recentUpdate = true;
    int allVars[] = {V_VAR1, V_VAR2, V_VAR3};
    const char *dayOfWeek[] = {
      "Null", "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "
    };
    // Name your Zones here or use Vera to edit them by adding a name in Variable3...
    String valveNickName[17] = {
      "All Zones", "Zone 1", "Zone 2", "Zone 3", "Zone 4", "Zone 5", "Zone 6", "Zone 7", "Zone 8", "Zone 9", "Zone 10", "Zone 11", "Zone 12", "Zone 13", "Zone 14", "Zone 15", "Zone 16"
    };
    //
    time_t lastTimeRun = 0;
    //Setup Shift Register...
    const int latchPin = 6;
    const int clockPin = 4;
    const int dataPin  = 7;
    const int outputEnablePin = A0;
    const int pumpStart = A1;
    //
    byte clock[8] = {0x0, 0xe, 0x15, 0x17, 0x11, 0xe, 0x0}; // fetching time indicator
    byte raindrop[8] = {0x4, 0x4, 0xA, 0xA, 0x11, 0xE, 0x0,}; // fetching Valve Data indicator
    // Set the pins on the I2C chip used for LCD connections:
    //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
    LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address to 0x27. Mine was actually 0x3F
    //
    MyMessage msg1valve(CHILD_ID_SPRINKLER, V_LIGHT);
    MyMessage var1valve(CHILD_ID_SPRINKLER, V_VAR1);
    MyMessage var2valve(CHILD_ID_SPRINKLER, V_VAR2);
    
    bool receivedInitialValue = false;
    bool inSetup = true;
    //
    void setup()
    {
      DEBUG_PRINTLN(F("Initialising..."));
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(ledPin, OUTPUT);
      pinMode(outputEnablePin, OUTPUT);
      digitalWrite (outputEnablePin, LOW);
      pinMode(ledPin, OUTPUT);
      pinMode(pumpStart, OUTPUT);
      digitalWrite (pumpStart, HIGH);
      pinMode(waterButtonPin, INPUT_PULLUP);
      //pinMode(waterButtonPin, INPUT);
      attachInterrupt(digitalPinToInterrupt(waterButtonPin), PushButton, RISING); //May need to change for your Arduino model
      digitalWrite (ledPin, HIGH);
      DEBUG_PRINTLN(F("Turning All Valves Off..."));
      updateRelays(ALL_VALVES_OFF);
      //delay(5000);
      lcd.begin(16, 2); //(16 characters and 2 line display)
      lcd.clear();
      lcd.backlight();
      lcd.createChar(0, clock);
      lcd.createChar(1, raindrop);
      //
      //check for saved date in EEPROM
      DEBUG_PRINTLN(F("Checking EEPROM for stored date:"));
      delay(500);
      if (loadState(0) == 0xFF) // EEPROM flag
      {
        DEBUG_PRINTLN(F("Retreiving last run time from EEPROM..."));
        for (int i = 0; i < 4 ; i++)
        {
          lastTimeRun = lastTimeRun << 8;
          lastTimeRun = lastTimeRun | loadState(i + 1); // assemble 4 bytes into an ussigned long epoch timestamp
        }
      }
    
      DEBUG_PRINTLN(F("Sensor Presentation Complete"));
      //
      digitalWrite (ledPin, LOW);
      DEBUG_PRINTLN(F("Ready..."));
      //
      lcd.setCursor(0, 0);
      lcd.print(F(" Syncing Time  "));
      lcd.setCursor(15, 0);
      lcd.write(byte(0));
      lcd.setCursor(0, 1);
      int clockCounter = 0;
      while (timeStatus() == timeNotSet && clockCounter < 21)
      {
        requestTime();
        DEBUG_PRINTLN(F("Requesting time from Gateway:"));
        wait(1000);
        lcd.print(".");
        clockCounter++;
        if (clockCounter > 16)
        {
          DEBUG_PRINTLN(F("Failed initial clock synchronization!"));
          lcd.clear();
          lcd.print(F("  Failed Clock  "));
          lcd.setCursor(0, 1);
          lcd.print(F(" Syncronization "));
          wait(2000);
          break;
        }
      }
      //
      //Update valve data when first powered on 
      for (byte i = 1; i <= NUMBER_OF_VALVES; i++)
      {
        lcd.clear();
        goGetValveTimes();
      }
      lcd.clear();
    }
    
    
    void presentation()  
    { 
      sendSketchInfo(SKETCH_NAME, SKETCH_VERSION);
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        present(i, S_LIGHT);
      }
    }
    
    //
    void loop()
    {
      updateClock();
      updateDisplay();
      goGetValveTimes();
      //
      if (buttonPushed)
      {
        menuTimer = millis();
        DEBUG_PRINTLN(F("Button Pressed"));
        if (state == STAND_BY_ALL_OFF)
        {
          state = ZONE_SELECT_MENU;
          menuState = 0;
        }
        else if (state == ZONE_SELECT_MENU)
        {
          menuState++;
          if (menuState > NUMBER_OF_VALVES)
          {
            menuState = 0;
          }
        }
        else
        {
          state = STAND_BY_ALL_OFF;
        }
        buttonPushed = false;
      }
      if (state == STAND_BY_ALL_OFF)
      {
        slowToggleLED ();
        if (state != lastState)
        {
          updateRelays(ALL_VALVES_OFF);
          DEBUG_PRINTLN(F("State Changed... all Zones off"));
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            wait(50);
            send(msg1valve.setSensor(i).set(false), false);
          }
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print(F("** Irrigation **"));
          lcd.setCursor(0,1);
          lcd.print(F("**   Halted   **"));
          wait(2000);
          lastValve = -1;
        }
      }
      //
      else if (state == RUN_ALL_ZONES)
      {
        if (lastValve != valveNumber)
        {
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            if (i == 0 || i == valveNumber)
            {
              send(msg1valve.setSensor(i).set(true), false);
            }
            else
            {
              send(msg1valve.setSensor(i).set(false), false);
            }
            wait(50);
          }
        }
        lastValve = valveNumber;
        fastToggleLed();
        if (state != lastState)
        {
          valveNumber = 1;
          updateRelays(ALL_VALVES_OFF);
          DEBUG_PRINTLN(F("State Changed, Running All Zones..."));
        }
        unsigned long nowMillis = millis();
        if (nowMillis - startMillis < VALVE_RESET_TIME)
        {
          updateRelays(ALL_VALVES_OFF);
        }
        else if (nowMillis - startMillis < (allZoneTime[valveNumber] * 60000UL))
        {
          updateRelays(BITSHIFT_VALVE_NUMBER);
        }
        else
        {
          DEBUG_PRINTLN(F("Changing Valves..."));
          updateRelays(ALL_VALVES_OFF);
          startMillis = millis();
          valveNumber++;
          if (valveNumber > NUMBER_OF_VALVES)
          {
            state = CYCLE_COMPLETE;
            startMillis = millis();
            lastValve = -1;
            lastTimeRun = now();
            saveDateToEEPROM(lastTimeRun);
            for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
            {
              send(msg1valve.setSensor(i).set(false), false);
              wait(50);
            }
            DEBUG_PRINT(F("State = "));
            DEBUG_PRINTLN(state);
          }
        }
      }
      //
      else if (state == RUN_SINGLE_ZONE)
      {
        fastToggleLed();
        if (state != lastState)
        {
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            if (i == 0 || i == valveNumber)
            {
              send(msg1valve.setSensor(i).set(true), false);
            }
            else
            {
              send(msg1valve.setSensor(i).set(false), false);
            }
            wait(50);
          }
          DEBUG_PRINTLN(F("State Changed, Single Zone Running..."));
          DEBUG_PRINT(F("Zone: "));
          DEBUG_PRINTLN(valveNumber);
        }
        unsigned long nowMillis = millis();
        if (nowMillis - startMillis < VALVE_RESET_TIME)
        {
          updateRelays(ALL_VALVES_OFF);
        }
        else if (nowMillis - startMillis < (valveSoloTime [valveNumber] * 60000UL))
        {
          updateRelays(BITSHIFT_VALVE_NUMBER);
        }
        else
        {
          updateRelays(ALL_VALVES_OFF);
          for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
          {
            send(msg1valve.setSensor(i).set(false), false);
          }
          state = CYCLE_COMPLETE;
          startMillis = millis();
          DEBUG_PRINT(F("State = "));
          DEBUG_PRINTLN(state);
        }
        lastTimeRun = now();
      }
      else if (state == CYCLE_COMPLETE)
      {
        if (millis() - startMillis < 30000UL)
        {
          fastToggleLed();
        }
        else
        {
          state = STAND_BY_ALL_OFF;
        }
      }
      if (state == ZONE_SELECT_MENU)
      {
        displayMenu();
      } 
      else 
      {
        lastState = state;
      }
    }
    //
    void displayMenu(void)
    {
      static byte lastMenuState = -1;
      static int lastSecond;
      if (menuState != lastMenuState)
      {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(valveNickName[menuState]);
        lcd.setCursor(0, 1);
        lcd.print(F("Starting"));
        DEBUG_PRINT(valveNickName[menuState]);
        Serial.print(F(" Starting Shortly"));
      }
      int thisSecond = (millis() - menuTimer) / 1000UL;
      if (thisSecond != lastSecond && thisSecond < 8)
      {
        lcd.print(F("."));
        Serial.print(".");
      }
      lastSecond = thisSecond;
      if (millis() - menuTimer > 10000UL)
      {
        startMillis = millis();
        if (menuState == 0)
        {
          valveNumber = 1;
          state = RUN_ALL_ZONES;
        }
        else
        {
          valveNumber = menuState;
          state = RUN_SINGLE_ZONE;
        }
      }
      else
      {
    
      }
      lastMenuState = menuState;
    }
    //
    void updateRelays(int value)
    {
      if (value == ALL_VALVES_OFF) 
      {
        digitalWrite(pumpStart, HIGH);
      }
      else
      {
        digitalWrite(pumpStart, LOW);
      }
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, MSBFIRST, highByte(value));
      shiftOut(dataPin, clockPin, MSBFIRST, lowByte(value));
      digitalWrite(latchPin, HIGH);
    }
    //
    void PushButton() //interrupt with debounce
    {
      static unsigned long last_interrupt_time = 0;
      unsigned long interrupt_time = millis();
      if (interrupt_time - last_interrupt_time > 200)
      {
        buttonPushed = true;
      }
      last_interrupt_time = interrupt_time;
    }
    //
    void fastToggleLed()
    {
      static unsigned long fastLedTimer;
      if (millis() - fastLedTimer >= 100UL)
      {
        digitalWrite(ledPin, !digitalRead(ledPin));
        fastLedTimer = millis ();
      }
    }
    //
    void slowToggleLED ()
    {
      static unsigned long slowLedTimer;
      if (millis() - slowLedTimer >= 1250UL)
      {
        digitalWrite(ledPin, !digitalRead(ledPin));
        slowLedTimer = millis ();
      }
    }
    //
    void receive(const MyMessage &message)
    {
      bool zoneTimeUpdate = false;
      if (message.isAck())
      {
        DEBUG_PRINTLN(F("This is an ack from gateway"));
      }
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        if (message.sensor == i)
        {
          if (message.type == V_LIGHT)
          {
            int switchState = atoi(message.data);
            if (switchState == 0)
            {
              state = STAND_BY_ALL_OFF;
              DEBUG_PRINTLN(F("Recieved Instruction to Cancel..."));
            }
            else
            {
              if (i == 0)
              {
                state = RUN_ALL_ZONES;
                valveNumber = 1;
                DEBUG_PRINTLN(F("Recieved Instruction to Run All Zones..."));
              }
              else
              {
                state = RUN_SINGLE_ZONE;
                valveNumber = i;
                DEBUG_PRINT(F("Recieved Instruction to Activate Zone: "));
                DEBUG_PRINTLN(i);
              }
            }
            startMillis = millis();
          }
          else if (message.type == V_VAR1)
          {
            int variable1 = atoi(message.data);// RUN_ALL_ZONES time
            DEBUG_PRINT(F("Recieved variable1 valve:"));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" = "));
            DEBUG_PRINTLN(variable1);
            if (variable1 != allZoneTime[i])
            {
              allZoneTime[i] = variable1;
    
              zoneTimeUpdate = true;
            }
            receivedInitialValue = true;
          }
          else if (message.type == V_VAR2)
          {
            int variable2 = atoi(message.data);// RUN_SINGLE_ZONE time
            DEBUG_PRINT(F("Recieved variable2 valve:"));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" = "));
            DEBUG_PRINTLN(variable2);
            if (variable2 != valveSoloTime[i])
            {
              valveSoloTime[i] = variable2;
              zoneTimeUpdate = true;
            }
            receivedInitialValue = true;
          }
          else if (message.type == V_VAR3)
          {
            String newMessage = String(message.data);
            if (newMessage.length() == 0) 
            {
              DEBUG_PRINT(F("No Name Recieved for zone "));
              DEBUG_PRINTLN(i);
              break;
            }
            if (newMessage.length() > 16)
            {
              newMessage.substring(0, 16);
            }
            valveNickName[i] = "";
            valveNickName[i] += newMessage;
            DEBUG_PRINT(F("Recieved variable3 valve: "));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" = "));
            DEBUG_PRINTLN(valveNickName[i]);
          }
          receivedInitialValue = true;
        }
      }
      if (zoneTimeUpdate)
      {
        //
        DEBUG_PRINTLN(F("New Zone Times Recieved..."));
        for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
        {
          if (i != 0)
          {
            DEBUG_PRINT(F("Zone "));
            DEBUG_PRINT(i);
            DEBUG_PRINT(F(" individual time: "));
            DEBUG_PRINT(valveSoloTime[i]);
            DEBUG_PRINT(F(" group time: "));
            DEBUG_PRINT(allZoneTime[i]);
            DEBUG_PRINT(F(" name: "));
            DEBUG_PRINTLN(valveNickName[i]);
            recentUpdate = true;
          }
        }
      }
      else
      {
        recentUpdate = false;
      }
    }
    //
    void updateDisplay()
    {
      static unsigned long lastUpdateTime;
      static bool displayToggle = false;
      //static byte toggleCounter = 0;
      static SprinklerStates lastDisplayState;
      if (state != lastDisplayState || millis() - lastUpdateTime >= 3000UL)
      {
        displayToggle = !displayToggle;
        switch (state) {
          case STAND_BY_ALL_OFF:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F("  System Ready "));
              if (clockUpdating)
              {
                lcd.setCursor(15, 0);
                lcd.write(byte(0));
              }
              lcd.setCursor(0, 1);
              lcd.print(hourFormat12() < 10 ? F(" ") : F(""));
              lcd.print(hourFormat12());
              lcd.print(minute() < 10 ? F(":0") : F(":"));
              lcd.print(minute());
              lcd.print(isAM() ? F("am") : F("pm"));
              lcd.print(month() < 10 ? F(" 0") : F(" "));
              lcd.print(month());
              lcd.print(day() < 10 ? F("/0") : F("/"));
              lcd.print(day());
              lcd.print(F("/"));
              lcd.print(year() % 100);
            }
            else
            {
              lcd.print(F("  Last Watered "));
              if (clockUpdating)
              {
                lcd.setCursor(15, 0);
                lcd.write(byte(0));
              }
              lcd.setCursor(0, 1);
              lcd.print(dayOfWeek[weekday(lastTimeRun)]);
              lcd.setCursor(11, 1);
              lcd.print(month(lastTimeRun) < 10 ? F(" ") : F(""));
              lcd.print(month(lastTimeRun));
              lcd.print(day(lastTimeRun) < 10 ? F("/0") : F("/"));
              lcd.print(day(lastTimeRun));
            }
            break;
          case RUN_SINGLE_ZONE:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F("Single Zone Mode"));
              lcd.setCursor(0, 1);
              lcd.print(F(" Zone:"));
              if (valveNumber < 10) lcd.print(F("0"));
              lcd.print(valveNumber);
              lcd.print(F(" Active"));
            }
            else
            {
              lcd.print(F(" Time Remaining "));
              lcd.setCursor(0, 1);
              if (valveSoloTime[valveNumber] == 0)
              {
                lcd.print(F(" No Valve Time "));
              }
              else
              {
                unsigned long timeRemaining = (valveSoloTime[valveNumber] * 60) - ((millis() - startMillis) / 1000);
                lcd.print(timeRemaining / 60 < 10 ? "   0" : "   ");
                lcd.print(timeRemaining / 60);
                lcd.print("min");
                lcd.print(timeRemaining % 60 < 10 ? " 0" : " ");
                lcd.print(timeRemaining % 60);
                lcd.print("sec  ");
              }
            }
            break;
          case RUN_ALL_ZONES:
            //
            fastClear();
            lcd.setCursor(0, 0);
            if (displayToggle)
            {
              lcd.print(F(" All-Zone  Mode "));
              lcd.setCursor(0, 1);
              lcd.print(F(" Zone:"));
              if (valveNumber < 10) lcd.print(F("0"));
              lcd.print(valveNumber);
              lcd.print(F(" Active "));
            }
            else
            {
              lcd.print(F(" Time Remaining "));
              lcd.setCursor(0, 1);
              int timeRemaining = (allZoneTime[valveNumber] * 60) - ((millis() - startMillis) / 1000);
              lcd.print((timeRemaining / 60) < 10 ? "   0" : "   ");
              lcd.print(timeRemaining / 60);
              lcd.print("min");
              lcd.print(timeRemaining % 60 < 10 ? " 0" : " ");
              lcd.print(timeRemaining % 60);
              lcd.print("sec  ");
            }
            break;
          case CYCLE_COMPLETE:
            //
            if (displayToggle)
            {
              lcd.setCursor(0, 0);
              lcd.print(F(" Watering Cycle "));
              lcd.setCursor(0, 1);
              lcd.print(F("    Complete    "));
            }
            else
            {
              int totalTimeRan = 0;
              for (int i = 1; i < NUMBER_OF_VALVES + 1; i++)
              {
                totalTimeRan += allZoneTime[i];
              }
              lcd.setCursor(0, 0);
              lcd.print(F(" Total Time Run "));
              lcd.setCursor(0, 1);
              lcd.print(totalTimeRan < 10 ? "   0" : "   ");
              lcd.print(totalTimeRan);
              lcd.print(" Minutes   ");
            }
          default:
            // what of ZONE_SELECT_MENU?
            break;
        }
        lastUpdateTime = millis();
      }
      lastDisplayState = state;
    }
    void receiveTime(time_t newTime)
    {
      DEBUG_PRINTLN(F("Time value received and updated..."));
      int lastSecond = second();
      int lastMinute = minute();
      int lastHour = hour();
      setTime(newTime);
      if (((second() != lastSecond) || (minute() != lastMinute) || (hour() != lastHour)) || showTime)
      {
        DEBUG_PRINTLN(F("Clock updated...."));
        DEBUG_PRINT(F("Sensor's time currently set to:"));
        DEBUG_PRINT(hourFormat12() < 10 ? F(" 0") : F(" "));
        DEBUG_PRINT(hourFormat12());
        DEBUG_PRINT(minute() < 10 ? F(":0") : F(":"));
        DEBUG_PRINT(minute());
        DEBUG_PRINTLN(isAM() ? F("am") : F("pm"));
        DEBUG_PRINT(month());
        DEBUG_PRINT(F("/"));
        DEBUG_PRINT(day());
        DEBUG_PRINT(F("/"));
        DEBUG_PRINTLN(year());
        DEBUG_PRINTLN(dayOfWeek[weekday()]);
        showTime = false;
      }
      else
      {
        DEBUG_PRINTLN(F("Sensor's time did NOT need adjustment greater than 1 second."));
      }
      clockUpdating = false;
    }
    void fastClear()
    {
      lcd.setCursor(0, 0);
      lcd.print(F("                "));
      lcd.setCursor(0, 1);
      lcd.print(F("                "));
    }
    //
    void updateClock()
    {
      static unsigned long lastVeraGetTime;
      if (millis() - lastVeraGetTime >= 3600000UL) // updates clock time and gets zone times from vera once every hour
      {
        DEBUG_PRINTLN(F("Requesting time and valve data from Gateway..."));
        lcd.setCursor(15, 0);
        lcd.write(byte(0));
        clockUpdating = true;
        requestTime();
        lastVeraGetTime = millis();
      }
    }
    //
    void saveDateToEEPROM(unsigned long theDate)
    {
      DEBUG_PRINTLN(F("Saving Last Run date"));
      if (loadState(0) != 0xFF)
      {
        saveState(0, 0xFF); // EEPROM flag for last date saved stored in EEPROM (location zero)
      }
      //
      for (int i = 1; i < 5; i++)
      {
        saveState(5 - i, byte(theDate >> 8 * (i - 1))); // store epoch datestamp in 4 bytes of EEPROM starting in location one
      }
    }
    //
    void goGetValveTimes()
    {
      static unsigned long valveUpdateTime;
      static byte valveIndex = 1;
      if (inSetup || millis() - valveUpdateTime >= VALVE_TIMES_RELOAD / NUMBER_OF_VALVES) // update each valve once every 5 mins (distributes the traffic)
      {
        if (inSetup) {
          lcd.print(F(" Updating  "));
          lcd.setCursor(0, 1);
          lcd.print(F(" Valve Data: "));
          lcd.print(valveIndex);
        }
        bool flashIcon = false;
        DEBUG_PRINT(F("Calling for Valve "));
        DEBUG_PRINT(valveIndex);
        DEBUG_PRINTLN(F(" Data..."));
        for (int a = 0; a < (sizeof(allVars)/sizeof(int)); a++) {
          receivedInitialValue = false;
          byte timeout = 10;
          while (!receivedInitialValue && timeout > 0)
          {
            lcd.setCursor(15, 0);
            flashIcon = !flashIcon;
            flashIcon ? lcd.write(byte(1)) : lcd.print(F(" "));
            request(valveIndex, allVars[a]);
            wait(50);
            timeout--;
          }
        }
        valveUpdateTime = millis();
        valveIndex++;
        if (valveIndex > NUMBER_OF_VALVES)
        {
          valveIndex = 1;
        }
      }
    }
    

    As always, any help is appreciated.


  • Contest Winner

    @dbemowsk

    what's happening in the Serial debug?



  • I'll look later and report. Got company at the moment. The odd thing is that I can turn my zones on and they seem to run for the specified time just fine. It's only what I see on the display that is messed up.



  • I've just started playing with a Z-Uno and was looking at ways to use for a project like this.
    I'm a believer in not re-inventing the wheel and it seem that all I would need to do is to delete the radio and re-code the sketch for the extra relays ( I have already built a 4 channel relay, it's just getting over the hurdle of learning about Shift Registers).
    Do you think this is possible or would I be better just starting from scratch?


Log in to reply
 

Suggested Topics

  • 8
  • 29
  • 1
  • 44
  • 1
  • 3

2
Online

11.2k
Users

11.1k
Topics

112.5k
Posts