Irrigation Controller (up to 16 valves with Shift Registers)


  • Contest Winner

    I put together an extension of the multi-Relay controller for use as a controller for your irrigation project if you have more zones than available pins on your Arduino.

    This sketch features the following:

    • Allows you to cycle through All zones or individual zone control.
    • Use the (n+1)th device to activate each zone in numeric sequence (zero 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 in the sketch and uses an 74HC595 (or equiv) Shift Register as to
      allow the MySensors standard radio configuration and still leave available digital pins
    • Compiles to ~12,000 Bytes, so will run on any Arduino
    • 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.
    • Sketch must collect your desired intervals so it takes several minutes to startup.
    • If you change your desired time intervals for your zones, simply restart your arduino
      and it will self update to reflect those changes.

    Example, I am using with 8 relays:

    This will create 9 devices. Zero through 7 are the individual relays. Eight is the Sequencer, so to speak (refer to attachment).

    Once you create this and add it using the gateway, go to each of zero through 7 and edit Variable1 and Variable2 for what time you want to use for the Sequencer or Zone respectively. Then save the settings. Then, restart your arduino; your arduino will extract these settings and save them to an array.

    When you turn on device 8 (aka the Sequencer) the relays will actuate in order from zero to seven, each one staying on for the period entered in the Variable1 field. There is a 5 second delay at the start of a new zone to allow for the valves to hydraulically reset.

    When you turn on any of devices zero through 7, it will run that zone only for the period of time entered in Variable2.

    Selecting any new zone (0-8) will stop the current process and start as per above.

    Hope you have a use for it. If you see any opportunity to improve, or find a bug, let me know.

    Jim
    modified. Attached wrong file, whoops!

    Sprinkler.ino


  • Admin

    Great thanks!



  • Looking at the sketch, there seems to be a fair bit of logic and processing that happens in the Arduino. A lot more than a simple on/off command for the zone. Any reason for this logic not to be controlled by the gateway?


  • Contest Winner

    @mikeones said:

    Looking at the sketch, there seems to be a fair bit of logic and processing that happens in the Arduino. A lot more than a simple on/off command for the zone. Any reason for this logic not to be controlled by the gateway?

    I didn't think I had that much happening on the Arduino side, it is turning on and off up to 8 relays based on times stored server side. IMHO, this saves a lot of work creating the functionality to progress through the zones within Vera. You would need eight scenes to turn on and off each relay, or one scene with delays. Either way, if you happened to have a vera restart in the middle, then you would have interrupted one of the cycles or even more, depending how you connected the scenes. You could program it in PLEG, but that won't be easy either, especially not wanting to overlap your single zone actions. Then you are also inside your PLEG editor every time you want to tweak the time in a zone.

    You need to control 8 relays with three wires, so a lot of the code is about pushing the little byte into the shift register (with all of the install comments, debug assists, etc. this is less than 100 LOC as is and i admit its too flabby at that).

    I have an EtherRain8 and it was a bear to get that working this easily.

    This is a set-it and forget-it approach; push the variables to the Arduino and run it whenever you want.

    I'm going to add an update toggle that will push out new variables if you make a change server side. Look for a V2.0 coming soon. I'm going to play with this for a while, and look for comments from others using it (there were a couple folks in the Vera forum looking for this).


  • Hero Member

    Hello,

    Can you describe your installation (what kind of relay you used) and whether you use a moisture sensor ? I'm looking for one that would last, more than those basic we have here for Arduino, and/or a water evaporation system (as I actually have).

    I'd really love to have an intelligent irrigation system that would handle wind, temp, moisture per zone... and not globally as I actually have, for grass and growing plants do not have the same needs...


  • Contest Winner

    @epierre said:

    Hello,

    Can you describe your installation (what kind of relay you used) and whether you use a moisture sensor ? I'm looking for one that would last, more than those basic we have here for Arduino, and/or a water evaporation system (as I actually have).

    I'd really love to have an intelligent irrigation system that would handle wind, temp, moisture per zone... and not globally as I actually have, for grass and growing plants do not have the same needs...

    I have been using two of these moisture sensors for some large pots. They are the real deal, while quite expensive versus the stuff I've seen for arduino. The pots drain quickly so I have to water them on a different schedule.

    I also updated the sketch to add pushbutton activation and a status LED

    Sprinkler.ino


  • Hero Member

    Yes I thought it would be something like that, unfortunatly from Europe it is quite expensive, although the Davis is more affordable from here...


  • Admin

    @BulldogLowell thanks for making this! I have bookmarked this post and I'll be back when I get a chance to assemble this.


  • Contest Winner

    @petewill, well, I hope you like it. I wired together with my relays and damn if it didn't work on one zone. It turns out I have a bad optocoupler on the bank of 8 relays I bought. 😞

    But no despair, I'll have a replacement shortly.

    Please be critical. Any way to make it work better is an idea worth pursuing.

    Thanks!


  • Contest Winner

    can anyone take a whack at updating my sketch for the latest IDE?

    I have someone on the vera forum waiting for an update but I haven't updated my net yet.

    this setback will cost me a week or so to update, ask I'm looking for help...

    SprinklerActiveLow.ino




  • Contest Winner

    I updated the Irrigation Controller to 1.4.1 and added some more functionality. It will control up to 16 valves now, controls an LCD display and some fun new things.

    Screen Shot 2014-11-30 at 5.00.56 PM.png

    Video of the communications icons

    Take a look and I'll update when I get it all in a box:

    /*
    MySprinkler for MySensors
    
    Arduino Multi-Zone Sprinkler Control
    
    November, 2014
    
    *** 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 times and clock respectively
    
    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.
    * Pushbutton activation to RUN_ALL_ZONES
    * LED status indicator
    
    INSTRUCTIONS:
    
    * 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 and Variable2. Populate data accordingly with whole minutes for 
    the RUN_ALL_ZONES routine and the RUN_SINGLE_ZONE routines.  The values entered may be zero.  
    * 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.
    * https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads for the I2C library, or use yours
    
    Contributed by Jim (BulldogLowell@gmail.com) and is released to the public domain
    */
    // 
    #include <Wire.h>
    #include <Time.h>
    #include <MySensor.h>
    #include <SPI.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 9 // AUTO  // Change this to fix your Radio ID or use Auto
    //
    #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}
    SprinklerStates;
    //
    SprinklerStates state = STAND_BY_ALL_OFF;
    SprinklerStates lastState;
    //
    int allZoneTime [NUMBER_OF_VALVES + 1];
    int valveSoloTime [NUMBER_OF_VALVES + 1];
    int valveNumber;
    int lastValve;
    unsigned long startMillis;
    const int ledPin = 5;
    boolean buttonPushed = false;
    boolean showTime = true;
    boolean clockUpdating = false;
    boolean recentUpdate = true;
    const char *dayOfWeek[] = {
     "Null","Sunday ","Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "};
    //
    time_t lastTimeRun = 0;
    //Setup Shift Register...
    const int latchPin = 8;
    const int clockPin = 4;
    const int dataPin  = 7;
    // 
    uint8_t clock[8] = {0x0,0xe,0x15,0x17,0x11,0xe,0x0}; // fetching time indicator
    uint8_t raindrop[8] = {0x4,0x4,0xA,0xA,0x11,0xE,0x0,}; // fetching Valve Data indicator
    //
    LiquidCrystal_I2C lcd(0x27, 16, 2);  // set the LCD I2C address to 0x27 (16 characters and 2 line display)
    MySensor gw;
    //
    MyMessage msg1valve(0,V_LIGHT);
    MyMessage var1valve(0,V_VAR1);
    MyMessage var2valve(0,V_VAR2);
    //
    void setup() 
    { 
     Serial.begin(115200);
     delay(5000);
     lcd.init();
     lcd.clear();
     lcd.backlight();
     lcd.createChar(0, clock);
     lcd.createChar(1, raindrop);
     DEBUG_PRINTLN(F("Initialising..."));
     pinMode(latchPin, OUTPUT);
     pinMode(clockPin, OUTPUT);
     pinMode(dataPin, OUTPUT);
     pinMode(ledPin, OUTPUT);
     attachInterrupt(2, PushButton, CHANGE);
     digitalWrite (ledPin, HIGH);
     // 
     //check for saved date in EEPROM
     DEBUG_PRINTLN(F("Checking EEPROM for stored date:"));
     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("MySprinkler", "2.0");
     for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
     {
    	gw.present(i, S_LIGHT);
     }
     DEBUG_PRINTLN(F("Sensor Presentation Complete"));
     //
     DEBUG_PRINTLN(F("Turning All Valves Off..."));
     updateRelays(ALL_VALVES_OFF);
     digitalWrite (ledPin, LOW);
     DEBUG_PRINTLN(F("Ready..."));
     //
     lcd.setCursor(0, 0);
     lcd.print(F(" Syncing Time  "));
     lcd.setCursor(15, 0);
     lcd.write(0);  //lcd.print(0, BYTE);
     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(".");
    	DEBUG_PRINT(F("."));
    	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();
    }
    //
    void loop()
    {
     gw.process();
     updateClock();
     updateDisplay();
     goGetValveTimes();
     //
     if (buttonPushed)
     {
    	DEBUG_PRINTLN(F("Button Pressed"));
    	if (state != RUN_ALL_ZONES);
    	{
         state = RUN_ALL_ZONES;
         valveNumber = 1;
         gw.send(msg1valve.setSensor(0).set(true), false);
         startMillis = millis();
         for (byte i = 0; i < 5; i++)  // flash lcd backlight on button press
         {
    		lcd.noBacklight(); 
    		delay(25);
    		lcd.backlight();
         }
         delay(50);
         fastClear();
         lcd.setCursor(0,0);
         lcd.print(F("*AllZone Active*"));
         lcd.setCursor(0,0);
         lcd.print(F(" Cycling  Zones "));
         delay(1000);
         DEBUG_PRINT(F("State = "));
         DEBUG_PRINTLN(state);
    	}
    	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);
         }
         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;
    	}
     }
     lastState = state;
    }
    //
    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;
    		}
         }
    	}
     }
     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(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(F(" "));
    		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(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);
    		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 >= 60000UL) // updates clock time and gets zone times from vera once every 10 minutes
     {
    	DEBUG_PRINTLN(F("Requesting time and valve data from Gateway..."));
    	lcd.setCursor(15,0);
    	lcd.write(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 Times..."));
    	lcd.setCursor(15, 0);
    	lcd.write(1);
    	gw.request(valveIndex, V_VAR1);
    	gw.request(valveIndex, V_VAR2);
    	valveUpdateTime = millis();
    	valveIndex++;
    	if (valveIndex > NUMBER_OF_VALVES+1)
    	{
         valveIndex = 1;
    	}
     }
    }


  • @BulldogLowell What valves did you use? Have you had any issues with a valve not closing all the way, thus, boom goes the dynamite.


  • Contest Winner

    @NotYetRated

    My valves were there already, it was controlled by simple timer. The valves are 24V like these.

    Really impossible to get that kind of failure...


  • Admin

    @BulldogLowell I am finally getting ready to make this. Thanks and great job as usual! I was waiting for what seemed like forever for the LCD to come in and when it did it was missing the I2C interface. DANG IT!! I think I'm going to see if I can wire it without I2C and then change it back when it comes in.

    I did have one thought as I was going through the code... What do you think of the idea of requesting the run time variables from Vera just before the relay is turned on instead of every 5 minutes? That might help minimize communication on the network as well as ensure the most up to date run times are received from Vera.


  • Contest Winner

    On a plane to china, working on the Rain Gauge!!!

    Thanks for the kind words, this is the one I'm most happy with of all the Mysensors I've done so far!!!

    @petewill said:

    What do you think of the idea of requesting the run time variables from Vera just before the relay is turned on instead of every 5 minutes?

    So, I've been using it for several months, along with the rain gauge. I use PLEG to send updates to the Vera Device Files each season (remember I'm in Florida). It updates the times (longer in the winter) and number of days (twice a week during Winter, once a week Spring and Autumn, and never on during Summer, lots of rain) .

    So, because I am never 'manually' updating the times, I never thought about the 5 minute update. since I started it up!!! I have from time to time updated the Single Zone times. If I need to push them, I just restart the arduino.

    So, you can certainly look to update whenever you prefer, it is in a nice little function for you.

    I personally don't mind at all the calls every five minutes, each call is a few milliseconds and it has the side benefit of updating the device last updated time on vera's device, so I know it's in contact with the gateway. I haven't had a traffic problem on my system yet.

    Screen Shot 2015-05-14 at 3.52.58 PM.png

    I can mail you an I2C LCD if you need it, you just have to wait until I'm back from China. Email or PM me an address to send it! I'm back on the 29th. You only need to send one back when you get the chance!


  • Admin

    @BulldogLowell said:

    On a plane to china, working on the Rain Gauge!!!

    Awesome! I should have some time this weekend to test if you have something by then.

    I personally don't mind at all the calls every five minutes, each call is a few milliseconds and it has the side benefit of updating the device last updated time on vera's device, so I know it's in contact with the gateway. I haven't had a traffic problem on my system yet.

    Good to know. I have around 80 MySensors devices so I'm always thinking about keeping communication to a minimum. I may just run it as is and if I notice any issues I can look into adjusting the code.

    I can mail you an I2C LCD if you need it, you just have to wait until I'm back from China.

    Wow, thanks for the offer! I have already ordered a replacement so hopefully it will arrive right around the time you get back. This is my first time working with LCDs so I didn't even think to look for the I2C connectivity. I just read the description and took their word for it. That will teach me...

    Oh yeah... that's cool you're going to China! Are you stocking up on a whole bunch of parts while you're there? 🙂


  • Contest Winner

    @petewill

    I think waiting for the I2C piggyback will be worth the time, but you can debug with the Serial connection, I have all that in there.

    I would think that retrieving the latest times for the sprinklers could be brought back to once a day even, if you are that worried about traffic.

    Just curious, but how many valves will you end up controlling?

    PS my factory is in the north, and I won't be getting to the south this trip. Shenzhen is really the epicenter of hobby electronics plus, it is never a good thing to bring a lot of small electronic components, wires and sensors in your bags through airport security!


  • Admin

    @BulldogLowell said:

    I think waiting for the I2C piggyback will be worth the time, but you can debug with the Serial connection, I have all that in there.

    Yeah, I'm thinking I can still get it partially working this weekend (hopefully) but I wish I could see the LCD. That is such a cool feature!

    I would think that retrieving the latest times for the sprinklers could be brought back to once a day even, if you are that worried about traffic.

    I still need to think through the PLEG but I was hoping to do something like this...

    • If there has been rain in the past 5 days adjust the irrigation timing based on the amount.

    • Also, factor in the past high temperatures as well as the upcoming forecast.

    • If it is currently raining, stop the irrigation.

    I still need to think through it a little more but calculations like that would require the variables to be updated to the irrigation controller more than once a day (at least I think). That's why I was thinking it would be cool if it pulled the values before it ran each zone. It could still update every 5 hours or so though for the heartbeat. I really like that benefit!

    Just curious, but how many valves will you end up controlling?

    Currently only 5 but I will probably add 2 more in the next year or so.

    it is never a good thing to bring a lot of small electronic components, wires and sensors in your bags through airport security!

    Haha, very true!


  • Admin

    @BulldogLowell is there a reason you're using pin 2 for the button/interrupt? That is normally wired up with the radio (although not currently used I believe). Is there a reason I shouldn't switch it to pin 3?


  • Admin

    Never mind. I forgot that interrupt numbers aren't pin numbers. I changed it to a 1 for pin 3 on my pro mini. What Arduino are you using?


  • Contest Winner

    @petewill said:

    What Arduino are you using?

    I cannot recall, but think I probably used a nano.


  • Admin

    @BulldogLowell I'm getting an error when I try to compile the code (I am finally getting to the point of uploading it). There are a long string of errors but they seem to be related to this:

        IrrigationController.ino:122:34: error: invalid conversion from 'int' to 't_backlighPol' [-fpermissive]
    
        In file included from IrrigationController.ino:59:0:
    
        C:\Users\petewill\Documents\Arduino\libraries\LiquidCrystal/LiquidCrystal_I2C.h:53:4: error:   initializing argument 3 of 'LiquidCrystal_I2C::LiquidCrystal_I2C(uint8_t, uint8_t, t_backlighPol)' [-fpermissive]
    
        LiquidCrystal_I2C (uint8_t lcd_Addr, uint8_t backlighPin, t_backlighPol pol);
    

    Here is the Arduino code:

    LiquidCrystal_I2C lcd(0x27, 16, 2);  // set the LCD I2C address to 0x27 (16 characters and 2 line display)
    

    I downloaded the 1.2.1 library from here: https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads

    Is there something else I should be doing?

    Thanks,

    Pete


  • Contest Winner

    @petewill

    9:15am here in china!

    can you post what you are trying to compile? it looks like a library issue (as you figured out) but I want to make suer I can compile exactly what you have.


  • Admin

    @BulldogLowell 9am nice! I'm ready for bed 🙂

    Here is the code I'm trying to compile. I think it's pretty much what you have except a couple small additions like Child ID, Sketch Name etc.

    /*
    MySprinkler for MySensors
    
    Arduino Multi-Zone Sprinkler Control
    
    November, 2014
    
    *** 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 times and clock respectively
    
    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.
    * Pushbutton activation to RUN_ALL_ZONES
    * LED status indicator
    
    INSTRUCTIONS:
    
    * 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 and Variable2. Populate data accordingly with whole minutes for 
    the RUN_ALL_ZONES routine and the RUN_SINGLE_ZONE routines.  The values entered may be zero.  
    * 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.
    * https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads for the I2C library, or use yours
    
    Contributed by Jim (BulldogLowell@gmail.com) and is released to the public domain
    */
    // 
    #include <Wire.h>
    #include <Time.h>
    #include <MySensor.h>
    #include <SPI.h>
    #include <LiquidCrystal_I2C.h>
    //
    #define NUMBER_OF_VALVES 5  // 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 // AUTO  // Change this to fix your Radio ID or use Auto
    //*Added sketch name and version
    #define SKETCH_NAME "MySprinkler"
    #define SKETCH_VERSION "2.0"
    //
    //*Added Child ID definition
    #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}
    SprinklerStates;
    //
    SprinklerStates state = STAND_BY_ALL_OFF;
    SprinklerStates lastState;
    //
    int allZoneTime [NUMBER_OF_VALVES + 1];
    int valveSoloTime [NUMBER_OF_VALVES + 1];
    int valveNumber;
    int lastValve;
    unsigned long startMillis;
    const int ledPin = 5;
    boolean buttonPushed = false;
    boolean showTime = true;
    boolean clockUpdating = false;
    boolean recentUpdate = true;
    const char *dayOfWeek[] = {
     "Null","Sunday ","Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "};
    //
    time_t lastTimeRun = 0;
    //Setup Shift Register...
    const int latchPin = 8;
    const int clockPin = 4;
    const int dataPin  = 7;
    // 
    uint8_t clock[8] = {0x0,0xe,0x15,0x17,0x11,0xe,0x0}; // fetching time indicator
    uint8_t raindrop[8] = {0x4,0x4,0xA,0xA,0x11,0xE,0x0,}; // fetching Valve Data indicator
    //
    LiquidCrystal_I2C lcd(0x27, 16, 2);  // set the LCD I2C address to 0x27 (16 characters and 2 line display)
    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() 
    { 
     //*Not needed
     //Serial.begin(115200);
     delay(5000);
     lcd.init();
     lcd.clear();
     lcd.backlight();
     lcd.createChar(0, clock);
     lcd.createChar(1, raindrop);
     DEBUG_PRINTLN(F("Initialising..."));
     pinMode(latchPin, OUTPUT);
     pinMode(clockPin, OUTPUT);
     pinMode(dataPin, OUTPUT);
     pinMode(ledPin, OUTPUT);
     //*Changed for Pin 3 on the pro mini
     attachInterrupt(1, PushButton, CHANGE);
     digitalWrite (ledPin, HIGH);
     // 
     //check for saved date in EEPROM
     DEBUG_PRINTLN(F("Checking EEPROM for stored date:"));
     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"));
     //
     DEBUG_PRINTLN(F("Turning All Valves Off..."));
     updateRelays(ALL_VALVES_OFF);
     digitalWrite (ledPin, LOW);
     DEBUG_PRINTLN(F("Ready..."));
     //
     lcd.setCursor(0, 0);
     lcd.print(F(" Syncing Time  "));
     lcd.setCursor(15, 0);
     lcd.write(0);  //lcd.print(0, BYTE);
     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(".");
        DEBUG_PRINT(F("."));
        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();
    }
    //
    void loop()
    {
     gw.process();
     updateClock();
     updateDisplay();
     goGetValveTimes();
     //
     if (buttonPushed)
     {
        DEBUG_PRINTLN(F("Button Pressed"));
        if (state != RUN_ALL_ZONES);
        {
         state = RUN_ALL_ZONES;
         valveNumber = 1;
         gw.send(msg1valve.setSensor(0).set(true), false);
         startMillis = millis();
         for (byte i = 0; i < 5; i++)  // flash lcd backlight on button press
         {
            lcd.noBacklight(); 
            delay(25);
            lcd.backlight();
         }
         delay(50);
         fastClear();
         lcd.setCursor(0,0);
         lcd.print(F("*AllZone Active*"));
         lcd.setCursor(0,0);
         lcd.print(F(" Cycling  Zones "));
         delay(1000);
         DEBUG_PRINT(F("State = "));
         DEBUG_PRINTLN(state);
        }
        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);
         }
         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;
        }
     }
     lastState = state;
    }
    //
    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;
            }
         }
        }
     }
     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(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(F(" "));
            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(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);
            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 >= 60000UL) // updates clock time and gets zone times from vera once every 10 minutes
     {
        DEBUG_PRINTLN(F("Requesting time and valve data from Gateway..."));
        lcd.setCursor(15,0);
        lcd.write(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 Times..."));
        lcd.setCursor(15, 0);
        lcd.write(1);
        gw.request(valveIndex, V_VAR1);
        gw.request(valveIndex, V_VAR2);
        valveUpdateTime = millis();
        valveIndex++;
        if (valveIndex > NUMBER_OF_VALVES+1)
        {
         valveIndex = 1;
        }
     }
    }
    
    

  • Contest Winner

    @petewill

    meanwhile I tried to compile my old code with the latest Arduino IDE and get the same errors...

    It may take me some time, but meanwhile you can try Arduino board for I2C library for LCDs.

    sorry!


  • Hero Member

    @petewill said:

    Good to know. I have around 80 MySensors devices so I'm always thinking about keeping communication to a minimum. I may just run it as is and if I notice any issues I can look into adjusting the code.

    Holy cow, ~80 MySensor devices.. I'm surprised Vera handles all that traffic reliably... My Vera3 can't seem to handle my ~35 Z-Wave and ~ 15 MySensors devices reliably...

    I'm in the starting process of moving everything over to HomeSeer. I'm really hoping this solution works better.. The little I've done so far, I'm VERY impressed. I will not miss PLEG (It's a great plug-in but difficult to build and maintain for me), as the built in event system in HS3 Pro is amazing and I've only just scratch the surface...


  • Admin

    @ServiceXp said:

    I'm surprised Vera handles all that traffic reliably

    Depends on your definition of reliably 🙂 I'd say 98% of the time there are no issues but the other 2% can be annoying... I am continually amazed by how well MySensors works. I just keep adding devices and it keeps performing. Henrik and team are awesome!

    Vera can definitely be frustrating. The key for me is to limit the plugins. I am very careful what I install. I'm sure I'll have to switch from Vera one day (unless they start making more powerful hardware) but for now it works and it's cheap. What are you going to do with MySensors when you switch? I love MySensors too much!!


  • Admin

    @BulldogLowell said:

    It may take me some time, but meanwhile you can try Arduino board for I2C library for LCDs.

    Jim,

    I did some searching and modified the code a little. It will now compile but I haven't had time to figure out what the purpose of lcd.write(0) was for. I have to go to work so I won't be able to look into it until later. Here are the items of code I changed to get it to compile:

    //LiquidCrystal_I2C lcd(0x27, 16, 2);  // set the LCD I2C address to 0x27 
    LiquidCrystal_I2C lcd(0x27);  // set the LCD I2C address to 0x27
    
     //*Added
     lcd.begin(16, 2); //(16 characters and 2 line display)
    //*Removed 
    // lcd.init();
    
    //*Removed 3 instances of:
    // lcd.write(0);
    

    Interestingly lcd.write(1); will compile. I also don't have an LCD to test with so I don't know if it will work.


  • Hero Member

    @petewill There is a MySensors plug-in for HS3, At the moment it is a bit limited, and has some bugs but the developer is working on it.


  • Admin

    @ServiceXp Good to know. I'll keep that in mind. Thanks for passing that on!


  • Contest Winner

    @petewill

    lcd.write(0)

    Prints the '0' special character.

    There is a raindrop icon, which tells you times are downloading and a clock icon which designates clock updates.

    uint8_t clock[8] = {0x0,0xe,0x15,0x17,0x11,0xe,0x0}; // fetching time indicator
    uint8_t raindrop[8] = {0x4,0x4,0xA,0xA,0x11,0xE,0x0,}; // fetching Valve Data indicator
    

    convert the hex to binary you can see the shape (5 X 7 pixels, so disregard the first three bits):

    00000000
    00001110
    00010101
    00010111
    00010001
    00001110
    00000000
    

    can you see the clock face at 3:00?

    00000100
    00000100
    00001010
    00001010
    00010001
    00010001
    00001110
    00000000
    

    Can you see the raindrop?

    they are created here:

     lcd.createChar(0, clock);
     lcd.createChar(1, raindrop);
    

    if you look at the video above, they appear from time to time.

    cool right?


  • Admin

    @BulldogLowell said:

    Prints the '0' special character.

    Ok, good to know. I'll see if I can do a little searching on that. Maybe there is a different way to implement them now?? It will be hard to test without an LCD but hopefully it will come soon and I can post back 🙂

    Speaking of testing I was able to control my relays last night from Vera! SO COOL!! This is one of the devices I have been wanting to add for a long time. I can't wait to be able to turn on my valves from my phone when I'm turning on my sprinkler system. It sure will beat sprinting to/from the basement...

    Thanks again for the awesome work!


  • Contest Winner

    @petewill

    I edited above to give more detail...


  • Admin

    @BulldogLowell said:

    I edited above to give more detail...

    Ok, thanks. I did a little research and found this from the Arduino website:

    When referencing custom character "0", if it is not in a variable, you need to cast it as a byte, otherwise the compiler throws an error. See the example below.

    http://www.arduino.cc/en/Reference/LiquidCrystalCreateChar

    I changed the code to this:

    byte clock[8] = {0x0,0xe,0x15,0x17,0x11,0xe,0x0};
    

    and this

    lcd.write(byte(0));
    

    and now it's compiling. But, I don't know if it's working.

    I'm still working on a couple of other small things I found. I'll post the code when I get it to a point where it's ready for your review.


  • Admin

    @BulldogLowell

    Here is the code with some changes. I have also attached a document with the changes highlighted. The most notable thing is I added some code to update the valve times when the device is first powered on. I hope that's ok.

    One thing I can't figure out, but hopefully you can, is the button is always acting like it's "pressed" when the Arduino is first powered on. This could be a problem as the power seems to go off in my house a couple of times a year (I don't want my irrigation to run when it's not supposed to). Any idea how to fix it? I've tried everything I could think of (which isn't much) and nothing worked.

    Anyway, here is the PDF with the changes Irrigation Controller Changes.pdf

    And the code:

    /*
    MySprinkler for MySensors
    
    Arduino Multi-Zone Sprinkler Control
    
    November, 2014
    
    *** 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 times and clock respectively
    
    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.
    * Pushbutton activation to RUN_ALL_ZONES
    * LED status indicator
    
    INSTRUCTIONS:
    
    * 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 and Variable2. Populate data accordingly with whole minutes for 
    the RUN_ALL_ZONES routine and the RUN_SINGLE_ZONE routines.  The values entered may be zero.  
    * 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.
    * https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads for the I2C library, or use yours
    
    Contributed by Jim (BulldogLowell@gmail.com) and is released to the public domain
    */
    // 
    #include <Wire.h>
    #include <Time.h>
    #include <MySensor.h>
    #include <SPI.h>
    #include <LiquidCrystal_I2C.h>
    //
    #define NUMBER_OF_VALVES 5  // 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 // 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}
    SprinklerStates;
    //
    SprinklerStates state = STAND_BY_ALL_OFF;
    SprinklerStates lastState;
    //
    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 "};
    //
    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
    LiquidCrystal_I2C lcd(0x27);  // 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() 
    { 
      delay(5000);
     //*Added
     lcd.begin(16, 2); //(16 characters and 2 line display)
    //*Removed 
    // lcd.init();
     lcd.clear();
     lcd.backlight();
     lcd.createChar(0, clock);
     lcd.createChar(1, raindrop);
     DEBUG_PRINTLN(F("Initialising..."));
     pinMode(latchPin, OUTPUT);
     pinMode(clockPin, OUTPUT);
     pinMode(dataPin, OUTPUT);
     pinMode(ledPin, OUTPUT);
     pinMode(waterButtonPin, INPUT_PULLUP);
     attachInterrupt(1, PushButton, RISING); //May need to change for your Arduino model
     digitalWrite (ledPin, HIGH);
     // 
     //check for saved date in EEPROM
     DEBUG_PRINTLN(F("Checking EEPROM for stored date:"));
     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"));
     //
     DEBUG_PRINTLN(F("Turning All Valves Off..."));
     updateRelays(ALL_VALVES_OFF);
     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.print(0, BYTE);
     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(".");
        //DEBUG_PRINT(F("."));
        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 times when first powered on
     for(byte i = 0; i <= NUMBER_OF_VALVES; i++)
     {
       allZoneTime[i]=-1;
       valveSoloTime[i]=-1;
       int clockCounter = 0;
       while((valveSoloTime[i]==-1 || allZoneTime[i]==-1) && clockCounter < 10)
       {
         DEBUG_PRINTLN(F("Calling for Valve Times..."));
         lcd.setCursor(15, 0);
         lcd.write(byte(1)); //lcd.write(1);
         gw.request(i, V_VAR1);
         gw.request(i, V_VAR2);
         delay(1000);
         gw.process();
         clockCounter++;
         if (clockCounter > 10)
         {
            DEBUG_PRINTLN(F("Failed initial valve synchronization!"));
            lcd.clear();
            lcd.print(F("  Failed Valve  "));
            lcd.setCursor(0,1);
            lcd.print(F(" Syncronization "));
         }
       }
     }
     
    }
    //
    void loop()
    {
     gw.process();
     updateClock();
     updateDisplay();
     goGetValveTimes();
     //
     if (buttonPushed)
     {
        DEBUG_PRINTLN(F("Button Pressed"));
        if (state != RUN_ALL_ZONES)
        {
         state = RUN_ALL_ZONES;
         valveNumber = 1;
         gw.send(msg1valve.setSensor(0).set(true), false);
         startMillis = millis();
         for (byte i = 0; i < 5; i++)  // flash lcd backlight on button press
         {
            lcd.noBacklight(); 
            delay(25);
            lcd.backlight();
         }
         delay(50);
         fastClear();
         lcd.setCursor(0,0);
         lcd.print(F("*AllZone Active*"));
         lcd.setCursor(0,0);
         lcd.print(F(" Cycling  Zones "));
         delay(1000);
         DEBUG_PRINT(F("State = "));
         DEBUG_PRINTLN(state);
        }
        else
        {
          state = STAND_BY_ALL_OFF;
          //valveNumber = 1;
          gw.send(msg1valve.setSensor(0).set(false), false);
          startMillis = millis();
          for (byte i = 0; i < 5; i++)  // flash lcd backlight on button press
          {
            lcd.noBacklight(); 
            delay(25);
            lcd.backlight();
          }
          delay(50);
          fastClear();
          lcd.setCursor(0,0);
          lcd.print(F("*AllZone Off*"));
          lcd.setCursor(0,0);
          lcd.print(F(" Stopping  Zones "));
          delay(1000);
          DEBUG_PRINT(F("State = "));
          DEBUG_PRINTLN(state);
        }
        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);
         }
         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;
        }
     }
     lastState = state;
    }
    //
    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;
            }
         }
        }
     }
     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(F(" "));
            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);
            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 Times..."));
        lcd.setCursor(15, 0);
        lcd.write(byte(1)); //lcd.write(1);
        gw.request(valveIndex, V_VAR1);
        gw.request(valveIndex, V_VAR2);
        valveUpdateTime = millis();
        valveIndex++;
        if (valveIndex > NUMBER_OF_VALVES+1)
        {
         valveIndex = 1;
        }
     }
    }```

  • Contest Winner

    @petewill said:

    One thing I can't figure out, but hopefully you can, is the button is always acting like it's "pressed" when the Arduino is first powered on. This could be a problem as the power seems to go off in my house a couple of times a year (I don't want my irrigation to run when it's not supposed to).

    You could try a bigger pullup resistor, maybe the pin floats for a brief moment or it is somehow energized... I've read about others having a problem like that. Alternatively, reverse the logic and pull pull the pin down to ground. I'd expect that one or both can correct that issue.

    Glad to have the improvements in the code, that's great! Always better to have another set of eyes on a project.


  • Admin

    @BulldogLowell said:

    You could try a bigger pullup resistor, maybe the pin floats for a brief moment or it is somehow energized...

    Ok, I'll do some testing with that. I don't think I'll get the chance today but I should be able to do some tomorrow. It works perfectly after the first start up so hopefully a bigger resistor will help.


  • Contest Winner

    @petewill

    yeah, I see in the code that the pushbutton is using interrupt pin, but still needs to be set to input

    pinMode(PushButton, INPUT_PULLUP);
    

    start there, sorry!


  • Admin

    @BulldogLowell said:

    yeah, I see in the code that the pushbutton is using interrupt pin, but still needs to be set to input

    I thought I added it already with this:

    pinMode(waterButtonPin, INPUT_PULLUP);
    
    

    Is that correct? Maybe that's my problem...


  • Admin

    @BulldogLowell said:

    were you not getting a compile error? on the PushButton variable being undeclared?

    Ok, I still think I have some things to learn about interrupts. I thought PushButton was the method being called when the interrupt was triggered. I didn't think it was the pin. I thought the pin was the first item 1 in this case. But, I thought 1 isn't even the pin. It's the interrupt number which is pin 3 in the case of a Pro Mini. I also thought I needed to declare the pinMode even if it's already in the interrupt. So confusing... Am I totally off?


  • Contest Winner

    @petewill

    post deleted, my bad! your understanding is 100% correct!

    your PushButton is the ISR, so you are right

    Try the extra pullup or pull-down

    really sorry for confusing you! I'm mega jet lagged


  • Admin

    @BulldogLowell said:

    I'm mega jet lagged

    Totally understandable 🙂

    Ok, I'll try the other options discussed above and post back. Thanks.


  • Admin

    @BulldogLowell said:

    Try the extra pullup

    Well, I had almost no time to work on MySensors stuff this weekend. 😞 I did do a quick test last night and it seems the external pullup worked! I power cycled the node 3 times and each time it worked flawlessly. I'll continue to test but so far so good. Thank you!


  • Contest Winner

    @petewill

    glad to hear that worked!

    👍


  • Hero Member

    @BulldogLowell Thanks for posting this. A sprinkler controller to replace my Rainbird controller is next on my list of projects.

    For those looking for a good and relatively cheap soil moisture sensor, these ones are pretty good and use a capacitive sensor: http://www.ebay.com/itm/261675851824. They transmit on 433 MHz. I currently use them with RFXCom and HomeSeer, but for those that don't have RFXCom, the protocol should be relatively easy to reverse engineer and then use directly with MySensors and a 433MHz receiver. I've also bought a few from here: https://www.plantcaretools.com/en/webshop/wireless-moisture-sensor-en-detail. Both sellers were good to deal with. The only drawback to them is that the antenna (and therefore range) is not very good, but there is an easy mod to improve that: http://www.domoticz.com/forum/viewtopic.php?f=13&t=2712

    Cheers
    Al


  • Admin


  • Contest Winner

    Cool @hek!

    Well done @petewill So easy for folks to follow along your outstanding video!

    MySensors Community Rocks!


  • Admin

    @BulldogLowell said:

    MySensors Community Rocks!

    Agreed!!! Thanks to both @BulldogLowell and @hek for making this possible. I love seeing it hanging on my wall every time I go into the basement 🙂


  • Hero Member

    Great Work Guys!!



  • @Sparkman I like the sensors, I just built some and was dbating the way to make smaller, what kind of battery life do those moisture sensors have?

    @petewill Time to change my current 16 valve arduino sprinklers to a little smarter version like yours! I love this community.
    You have been coming on with some awesome videos and contributions!


  • Admin

    @DrJeff I agree this is a great community! So much fun!

    Thanks for the kind words! All credit for this project goes to @BulldogLowell though. I just made the video 🙂



  • @BulldogLowell Sorry For not giving the credit where it is due! Major Props @BulldogLowell !


  • Hero Member

    @DrJeff said:

    @Sparkman I like the sensors, I just built some and was dbating the way to make smaller, what kind of battery life do those moisture sensors have?

    They've been running for about 9 months on the first set of batteries (2xAAA) so far and are still going strong.

    Cheers
    Al


  • Contest Winner

    Thanks @DrJeff

    I just made an irrigation controller... @petewill made it for everyone!


  • Admin

    just for inspiration, here's another irrigation controller video (no, it's not mine.. but one of my friends that made it)

    Arduino controlled garden watering system – 01:04
    — Nikolaj Rahbek

    🙂



  • Wow 48 channels thats awesome


  • Admin

    @tbowmo WOW! What did he use that for??



  • @tbowmo Time for a Shower, Can you say body sprays! 🙂


  • Admin

    @petewill

    He recently planted a lot of trees, so instead of walking around and watering each one manually he made this

    Its a arduino with a nrf24 module, but not using the mysensors library (yet...)


  • Admin

    @tbowmo said:

    @petewill

    He recently planted a lot of trees

    I guess so 🙂

    Cool!


  • Contest Winner

    @treb0r

    here is a stab at modification for no shift register... not much changes.

    Not tested but it compiles...

    Let me know if you see anything in testing.

    /*
    MySprinkler for MySensors
    
    Arduino Multi-Zone Sprinkler Control
    
    June 30, 2015
    
    *** Version 2.0nsr //MODIFIED FOR NO SHIFT REGISTER
    
    *** 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.0nsr"
    //
    #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;
    //
    const int relayPin[NUMBER_OF_VALVES] = {5,6,7,8};//<<<<<<<<<<<<<<<<<<< YOUR DIGITAL PINS HERE
    //
    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 = 4;//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< CHANGED THIS TOO
    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...<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< COMMENTED OUT THIS BIT
    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..."));
      /*  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< COMMENTED OUT THIS BLOCK
      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++)
      {
        pinMode(relayPin[i], OUTPUT);//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ADDED PINMODE HERE
        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)
    {
      /*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<  COMMENTED OUT THIS BLOCK BELOW
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, MSBFIRST, highByte(value));
      shiftOut(dataPin, clockPin, MSBFIRST, lowByte(value));
      digitalWrite(latchPin, HIGH);
      */
      //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<   ADDED THIS BLOCK BELOW
      for (byte i = 0; i < NUMBER_OF_VALVES; i++)
      {
        digitalWrite(relayPin[i], bitRead(value, i));
      }
    }
    //
    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(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, V_VAR1);
        gw.request(valveIndex, V_VAR2);
        gw.request(valveIndex, V_VAR3);
        valveUpdateTime = millis();
        valveIndex++;
        if (valveIndex > NUMBER_OF_VALVES + 1)
        {
          valveIndex = 1;
        }
      }
    }
    


  • thank you for this modification. I will test it today. Shall it be working withou any problems with Domoticz on Raspberry Pi?


  • Contest Winner

    @treb0r said:

    Shall it be working withou any problems with Domoticz on Raspberry Pi?

    I assume so. It is using S_LIGHT, one of the most used device types. I am unsure however if Domoticz supports V_VAR1 & V_VAR2 for that device type, so you may have to check with other forum members who use Domoticz.


  • Hero Member

    Do you think I I could use that kind of design in parallel of a static watering controller, so I could have the basic program with the controller, and manage extras with the arduino/mysensors ?


  • Hero Member

    @epierre said:

    Do you think I I could use that kind of design in parallel of a static watering controller, so I could have the basic program with the controller, and manage extras with the arduino/mysensors ?

    Inspired by @BulldogLowell's controller, I've been working on a MySensors irrigation controller that works in parallel with my RainBird Controller. I'm using a double set of relays (one 5VDC set that's controlled by the Arduino and a 24VAC set that's controlled by the 5VDC relays and the RainBird). This way I can also sense in my HA system when the valves have been opened by the RainBird controller. I have the base functionality finished and working on some additional bells and whistles. Will post some details in a separate thread later today.

    Cheers
    Al



  • Regarding the Video presenting this irrigation project: is the 15 min time, which is counting down after starting the valve via pressing the button, programed somewhere in the arduino code? Or it is taken from timer set in the Vera (or Domoticz) controller?



  • @BulldogLowell said:

    @treb0r said:

    Shall it be working withou any problems with Domoticz on Raspberry Pi?

    I assume so. It is using S_LIGHT, one of the most used device types. I am unsure however if Domoticz supports V_VAR1 & V_VAR2 for that device type, so you may have to check with other forum members who use Domoticz.

    Well, it is not working. Domoticz finds 5 switches, but on LCD there is Message: Failed Clock Synchronisation, and the Updating Valves but still 0 😕 Is the problems with V_VAR1 & V_VAR2 variables?


  • Contest Winner

    @treb0r said:

    Regarding the Video presenting this irrigation project: is the 15 min time, which is counting down after starting the valve via pressing the button, programed somewhere in the arduino code? Or it is taken from timer set in the Vera (or Domoticz) controller?

    On my Vera controller (as demonstrated by @petewill ) you would edit the times under Variable1 and Variable2, which corresponds to V_VAR1 and V_VAR2 in the program.

    The video shows how to modify the values in the arduino by changing the values. I am not sure if Domoticz supports such dataflow. Does Domoticz support V_VAR1 and V_VAR2?

    @treb0r said:

    on LCD there is Message: Failed Clock Synchronisation, and the Updating Valves but still 0 😕 Is the problems with V_VAR1 & V_VAR2 variables?

    does Domoticz support MySensors time function? That I do not know.



  • @BulldogLowell
    I am afraid that Domoticz doesn't have such advanced options of configuration of devices. Or maybe I am wrong? Is there any chance to bypass the V_VAR1 variables?


  • Hero Member

    @treb0r This thread seems to imply that V_VAR1 etc are supported. I guess @AWI can say more about that.


  • Contest Winner

    thanks for your help, @Moshe-Livne

    Do you know if Domoticz supports returning Unix timestamp using requestTime()?


  • Hero Member

    @BulldogLowell Sorry, I don't know.


  • Contest Winner

    thanks @Moshe-Livne

    @treb0r said:

    @BulldogLowell
    I am afraid that Domoticz doesn't have such advanced options of configuration of devices. Or maybe I am wrong? Is there any chance to bypass the V_VAR1 variables?

    @treb0r,

    If you can find out if V_VAR1 & V_VAR2 can work you can try that. Otherwise we can hard code the watering times by zone into the programming.

    If requestTime() isn't supported, we can attach a Real Time Clock (RTC) device to gain back the clock functionality.

    You can then use the Domoticz devices to start the ALL_ZONE sequence or individual zones...

    Let me know what you would like to do and I can modify the program for you.



  • @BulldogLowell

    requestTime() seems not be supported. A have rtc ds3231 or ds1307. They can use the same commands and libraries. If you would change the code that would perfect 🙂 As you proposed you would also include in the code the timers for zones, instead of requesting them from Domoticz. As I understand these timers are only for manuals starts (via button) right?


  • Contest Winner

    @treb0r said:

    @BulldogLowell
    As I understand these timers are only for manuals starts (via button) right?

    Well, those times will be used when you activate the device using the Domoticz on/off controls (or activate using 'scene' in Domotocz.

    Give me a day or so and I will try to code for you.


  • Contest Winner

    @treb0r

    Would you like to try this, untested.

    Just to see if the RTC is working...

    /*
    MySprinkler for MySensors
    
    Arduino Multi-Zone Sprinkler Control
    
    June 30, 2015
    
    *** Version 2.0nsr //MODIFIED FOR NO SHIFT REGISTER
    
    *** 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 <DS1307RTC.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.0nsr"
    //
    #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;
    //
    const int relayPin[NUMBER_OF_VALVES] = {5, 6, 7, 8}; //<<<<<<<<<<<<<<<<<<< YOUR DIGITAL PINS HERE
    //
    byte menuState = 0;
    unsigned long menuTimer;
    byte countDownTime = 10;
    //
    int allZoneTime [NUMBER_OF_VALVES + 1] = {0, 1, 1, 1, 1}; //minutes
    int valveSoloTime [NUMBER_OF_VALVES + 1] = {0, 2, 2, 2, 2};
    int valveNumber;
    int lastValve;
    unsigned long startMillis;
    const int ledPin = 4;
    const int waterButtonPin = 3;
    boolean buttonPushed = false;
    boolean showTime = true;
    boolean clockUpdating = false;
    boolean recentUpdate = true;
    const char *verboseDayOfWeek[] = {
      /*"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...<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< COMMENTED OUT THIS BIT
    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(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);
      //
      // RTC setup
      setSyncProvider(RTC.get);   // the function to get the time from the RTC
      if(timeStatus()!= timeSet) 
         Serial.println("Unable to sync with the RTC");
      else
         Serial.println("RTC has set the system time"); 
      //
      //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.clear();
      //Update valve data when first powered on
      for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        pinMode(relayPin[i], OUTPUT);
        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();
      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)
    {
      for (byte i = 0; i < NUMBER_OF_VALVES; i++)
      {
        digitalWrite(relayPin[i], bitRead(value, i));
      }
    }
    //
    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(verboseDayOfWeek[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 fastClear()
    {
      lcd.setCursor(0, 0);
      lcd.print(F("                "));
      lcd.setCursor(0, 1);
      lcd.print(F("                "));
    }
    //
    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;
        }
      }
    }
    


  • @BulldogLowell
    HI
    Thanks for the post. On LCD there is no info about Time Synchronisation fail. It stops, as previously on info: Updating Valve : 0
    So I cant check if the RTC is working
    treb0r


  • Contest Winner

    @treb0r

    did you get your RTC connected and tested?



  • @BulldogLowell
    Yes, RTC is connected and tested with different sketches (just to check if RTC work correctly). Works ok.
    With your correctes projects, as above mentioned: On LCD there is no info neither about Time Synchronisation, nor about Time Synchronisation fail. It stops, as previously on info: Updating Valve : 0
    treb0r


  • Contest Winner

    Yes, since clock no longer needs to call server for time, synchronizing is not necessary.

    You should post serial output or show a video.

    Did you find out if Domoticz supports V_VAR1?



  • @BulldogLowell
    OK, I will post the video. If I will manage I will also post serial output
    treb0r


  • Hero Member

    @treb0r @BulldogLowel I had a chance to play a little bit with VAR1 this weekend. I verified that if you declare MyMessage var(CHILD_ID, V_VAR1); you can set it with gw.send(var.set("hello")); and request its value from the gateway using gw.request(CHILD_ID, V_VAR1);. you will get the answer in the incoming message handler under the V_VAR1 message

       if (message.type==V_VAR1) {
       	 Serial.println("got var1 answer");
       	 Serial.println(message.getString());
       }
    

    However I still didn't manage to find how to access or show these values on the domoticz. their site crashed so couldn't ask this in the forum


  • Hero Member

    @Moshe-Livne Domoticz (as of today) doesn't support V_VARx ...


  • Hero Member

    @epierre it does but in a strange way. The vars are not display vars. They are stored in the db and can be fetched and set only by the sensor. Tried it, it works....


  • Hero Member

    @Moshe-Livne this is not what @GizMoCuz said in a post... strange...


  • Hero Member

    @epierre can you please link to the post?


  • Hero Member


  • Hero Member

    @epierre He meant in the sense that it does not display or use it for anything. he said there "it is used to store/retrieve variables". The thread was about the option to show the vars as part of the sensor output. for storing and retrieving, it works.... verified.... I might get annoyed enough to add to the code that the lua script can also retrieve these vars and then it would be sweet.....


  • Hero Member

    ok good although it was not explicit... now I'll have to go back to him about water meter that heavily use V_VARs but is recognized.... as a power meter...



  • Hello
    And thx for a nice forum, I did build the irrigation controller and tried to connect it to Domoticz. Everything just seems fine, LCD works, push button works and I can turn on the irrigation from Domoticz and it shows in the LCD.

    But the problem is that it doesn't switch the relays on, it just says "no valve time" and then go watering cycle complete.

    Any suggestions on what the problem might be...... Domoticz?

    Regards


  • Contest Winner

    @moffen666

    I don't have Domoticz but I suspect that the callback isn't functioning.

    try populating the array with the desired times for each sequence. replace this:

    int allZoneTime [NUMBER_OF_VALVES + 1];
    int valveSoloTime [NUMBER_OF_VALVES + 1];
    

    with something like this:

    int allZoneTime [NUMBER_OF_VALVES + 1] = {0, 10, 10, 10, 5,<... how many valves you have with zero in the first position>} ;
    int valveSoloTime [NUMBER_OF_VALVES + 1] = {0, 5, 5, 5, 5,<... how many valves you have with zero in the first position>};
    

    This will load in the times that the program uses as your 'default' values. Then, you can check with Domoticz experts on getting the V_VAR variables working.



  • Thx Bulldog
    I will check asap and get back with the result.

    Regards



  • Hi
    I tried the code but it didn't compile, and I'm not good enough to be sure whats wrong.

    I did try change the code and I did get it to compile, but I don't know if I got it right. You can see the lame attempt below the colored line.

    upload-956d60c8-6d6d-44b7-abdb-015f701c65dc


  • Contest Winner

    @moffen666

    Clearly you understand that you are to put the times for each of the valve zones, led by a zero into the array, and not copy my verbatim instructions...

    How many valves do you have? You need that many (plus one) integer numbers separated by commas...

    Example 8 valves:

    ...= {0,5,5,5,5,5,5,5,5};

    You've commented out the wrong lines.



  • Thx for the quick answer

    I use 4 valves atm, I tried your suggestion but it seems it wont work for me.

    upload-edb305b1-3dc3-4afd-ae02-e2e779452d18

    Regards



  • The inserted values in the array works from start, but it looks like the irrigation controller immediately starts to request valve data from the controller for variable1 and 2. As we cant set variable1 and 2 in Domoticz I guess it returns 0 and overwrite the inserted values in the arrays...or is it anything else happening?

    Initialising...
    Turning All Valves Off...
    Unable to sync with the RTC
    Checking EEPROM for stored date:
    Retreiving last run time from EEPROM...
    send: 7-7-0-0 s=255,c=0,t=17,pt=0,l=3,sg=0,st=ok:1.5
    send: 7-7-0-0 s=255,c=3,t=6,pt=1,l=1,sg=0,st=ok:0
    read: 0-0-7 s=255,c=3,t=6,pt=0,l=1,sg=0:M
    sensor started, id=7, parent=0, distance=1
    send: 7-7-0-0 s=255,c=3,t=11,pt=0,l=11,sg=0,st=ok:MySprinkler
    send: 7-7-0-0 s=255,c=3,t=12,pt=0,l=6,sg=0,st=ok:2.0nsr
    send: 7-7-0-0 s=0,c=0,t=3,pt=0,l=0,sg=0,st=ok:
    send: 7-7-0-0 s=1,c=0,t=3,pt=0,l=0,sg=0,st=ok:
    send: 7-7-0-0 s=2,c=0,t=3,pt=0,l=0,sg=0,st=ok:
    send: 7-7-0-0 s=3,c=0,t=3,pt=0,l=0,sg=0,st=ok:
    send: 7-7-0-0 s=4,c=0,t=3,pt=0,l=0,sg=0,st=ok:
    Sensor Presentation Complete
    Ready...
    Calling for Valve 0 Data...
    send: 7-7-0-0 s=0,c=2,t=24,pt=0,l=0,sg=0,st=ok:
    read: 0-0-7 s=0,c=2,t=24,pt=0,l=0,sg=0:
    Recieved variable1 valve:0 = 0
    send: 7-7-0-0 s=0,c=2,t=25,pt=0,l=0,sg=0,st=ok:
    read: 0-0-7 s=0,c=2,t=25,pt=0,l=0,sg=0:
    Recieved variable2 valve:0 = 0
    send: 7-7-0-0 s=0,c=2,t=26,pt=0,l=0,sg=0,st=ok:
    read: 0-0-7 s=0,c=2,t=26,pt=0,l=0,sg=0:
    No Name Recieved for zone 0
    Calling for Valve 1 Data...
    send: 7-7-0-0 s=1,c=2,t=24,pt=0,l=0,sg=0,st=ok:
    read: 0-0-7 s=1,c=2,t=24,pt=0,l=0,sg=0:
    Recieved variable1 valve:1 = 0
    New Zone Times Recieved...
    Zone 1 individual time: 1 group time: 0
    Zone 2 individual time: 1 group time: 1
    Zone 3 individual time: 1 group time: 1
    Zone 4 individual time: 1 group time: 1
    send: 7-7-0-0 s=1,c=2,t=25,pt=0,l=0,sg=0,st=ok:
    read: 0-0-7 s=1,c=2,t=25,pt=0,l=0,sg=0:
    Recieved variable2 valve:1 = 0
    New Zone Times Recieved...
    Zone 1 individual time: 0 group time: 0
    Zone 2 individual time: 1 group time: 1
    Zone 3 individual time: 1 group time: 1
    Zone 4 individual time: 1 group time: 1
    send: 7-7-0-0 s=1,c=2,t=26,pt=0,l=0,sg=0,st=ok:
    read: 0-0-7 s=1,c=2,t=26,pt=0,l=0,sg=0:
    No Name Recieved for zone 1
    Calling for Valve 2 Data...
    send: 7-7-0-0 s=2,c=2,t=24,pt=0,l=0,sg=0,st=ok:
    read: 0-0-7 s=2,c=2,t=24,pt=0,l=0,sg=0:
    Recieved variable1 valve:2 = 0
    New Zone Times Recieved...
    Zone 1 individual time: 0 group time: 0
    Zone 2 individual time: 1 group time: 0
    Zone 3 individual time: 1 group time: 1
    Zone 4 individual time: 1 group time: 1
    send: 7-7-0-0 s=2,c=2,t=25,pt=0,l=0,sg=0,st=ok:
    read: 0-0-7 s=2,c=2,t=25,pt=0,l=0,sg=0:
    Recieved variable2 valve:2 = 0
    New Zone Times Recieved...
    Zone 1 individual time: 0 group time: 0
    Zone 2 individual time: 0 group time: 0
    Zone 3 individual time: 1 group time: 1
    Zone 4 individual time: 1 group time: 1
    send: 7-7-0-0 s=2,c=2,t=26,pt=0,l=0,sg=0,st=ok:
    read: 0-0-7 s=2,c=2,t=26,pt=0,l=0,sg=0:
    No Name Recieved for zone 2
    Calling for Valve 3 Data...
    send: 7-7-0-0 s=3,c=2,t=24,pt=0,l=0,sg=0,st=ok:
    read: 0-0-7 s=3,c=2,t=24,pt=0,l=0,sg=0:
    Recieved variable1 valve:3 = 0
    New Zone Times Recieved...
    Zone 1 individual time: 0 group time: 0
    Zone 2 individual time: 0 group time: 0
    Zone 3 individual time: 1 group time: 0
    Zone 4 individual time: 1 group time: 1
    send: 7-7-0-0 s=3,c=2,t=25,pt=0,l=0,sg=0,st=ok:
    read: 0-0-7 s=3,c=2,t=25,pt=0,l=0,sg=0:
    Recieved variable2 valve:3 = 0
    New Zone Times Recieved...
    Zone 1 individual time: 0 group time: 0
    Zone 2 individual time: 0 group time: 0
    Zone 3 individual time: 0 group time: 0
    Zone 4 individual time: 1 group time: 1
    send: 7-7-0-0 s=3,c=2,t=26,pt=0,l=0,sg=0,st=ok:
    read: 0-0-7 s=3,c=2,t=26,pt=0,l=0,sg=0:
    No Name Recieved for zone 3
    Calling for Valve 4 Data...
    send: 7-7-0-0 s=4,c=2,t=24,pt=0,l=0,sg=0,st=ok:
    read: 0-0-7 s=4,c=2,t=24,pt=0,l=0,sg=0:
    Recieved variable1 valve:4 = 0
    New Zone Times Recieved...
    Zone 1 individual time: 0 group time: 0
    Zone 2 individual time: 0 group time: 0
    Zone 3 individual time: 0 group time: 0
    Zone 4 individual time: 1 group time: 0
    send: 7-7-0-0 s=4,c=2,t=25,pt=0,l=0,sg=0,st=ok:
    read: 0-0-7 s=4,c=2,t=25,pt=0,l=0,sg=0:
    Recieved variable2 valve:4 = 0
    New Zone Times Recieved...
    Zone 1 individual time: 0 group time: 0
    Zone 2 individual time: 0 group time: 0
    Zone 3 individual time: 0 group time: 0
    Zone 4 individual time: 0 group time: 0
    send: 7-7-0-0 s=4,c=2,t=26,pt=0,l=0,sg=0,st=ok:
    read: 0-0-7 s=4,c=2,t=26,pt=0,l=0,sg=0:
    No Name Recieved for zone 4
    

  • Contest Winner

    @moffen666

    try commenting out this in setup():

    /*
    for (byte i = 0; i <= NUMBER_OF_VALVES; i++)
      {
        pinMode(relayPin[i], OUTPUT);
        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);
        }
      }*/
    

    and this in loop():

    //goGetValveTimes();
    

    That will disable those callbacks and you should be OK with a HardCoded time table for the valves and valve names.



  • Thx Bulldog for all the help, everything seems to be working as it should now.

    Keep up the good work 👍

    Updated code for 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 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 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};     // Insert values in min, 0 = all zone (always 0) this is a 4 chan relay
    int valveSoloTime [NUMBER_OF_VALVES + 1]= {0, 1, 1, 1, 1};   // Insert values in min, 0 = all zone (always 0) this is a 4 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;
    //
    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 = 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(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, V_VAR1);
        gw.request(valveIndex, V_VAR2);
        gw.request(valveIndex, V_VAR3);
        valveUpdateTime = millis();
        valveIndex++;
        if (valveIndex > NUMBER_OF_VALVES + 1)
        {
          valveIndex = 1;
        }
      }
    }```

  • Admin

    Hey Everyone,

    I just made a follow up video to this irrigation controller that shows my logic I'm using to save water. It's pretty specific to my environment but hopefully you can use some of the ideas to save water in your environment. I have attached the logic I used in my PLEG device.

    Pete

    PLEG Irrigation.pdf

    Automation to Adjust Irrigation Watering Time Based on Weather – 25:17
    — Pete B


Log in to reply
 

Suggested Topics

  • 8
  • 1
  • 90
  • 3
  • 2
  • 44

0
Online

11.4k
Users

11.1k
Topics

112.7k
Posts