Очень простой контролер аквариумного освещения

ilprohorowi4
Offline
Зарегистрирован: 22.02.2014

Здравствуйте, товарищи! Веду поиск безвозмездной помощи. Есть исходники, нужно чуток подредактировать. Вобщем, нужно сделать контроллер аквариумного освещения. 3 ШИМ канала, т.е. должны управлять диммируемыми драйверами. Принцип работы.

Канал 1. Старт освещения в 7:30, плавное нарастание мощности до предела к 8:30. С 18:30 до 19:30 плавное выключение до нуля.

Канал 2. Старт освещения в 8:10, плавное нарастание мощности до максимума в течение часа. В 17:50 - 18:50 плавное выключение до нуля. Т.е. иммитация рассветов и закатов.

Канал 3. Иммитация фаз луны. Алгоритм имеется. Работать должна после выключения 1 канала и до его включени.

Теперь исходник. Есть код для Ардуино мега 2560 с сенсорным экраном, но он дороговат, и там слишком много функций. Весь код прокомментирован, так что, думаю (человек предполагает, а Бог располагает) знающий человек может разобраться. Конечная прошивка нужна для Ардуино Леонардо (ATmega32U4, точнее для китайского клона, но пишут, что там полная совместимость).

Заранее большое спасибо за внимание. Буду ждать ответа, надежда умирает последней.

ilprohorowi4
Offline
Зарегистрирован: 22.02.2014
//************************************************************************************/
// Jarduino Aquarium Controller v.1.2(beta) - release date: May 2012
//   Written and Debugged by Jamie M. Jardin aka "TheDOdblG"
//   Copyright 2011, 2012 Jamie M. Jardin
//   email:  jjardi56@msn.com
// 
// Aquarium and Controller Build Details
//   <a data-cke-saved-href="http://ukreefs.com/index.php?topic=117.0" href="http://ukreefs.com/index.php?topic=117.0" rel="nofollow">http://ukreefs.com/index.php?topic=117.0</a>
//   <a data-cke-saved-href="http://www.reefcentral.co.uk/showthread.php/26598-44-Gallon-Pentagon-Corner-Tank-LED-Hood-DIY-Build-EXTRAS!-" href="http://www.reefcentral.co.uk/showthread.php/26598-44-Gallon-Pentagon-Corner-Tank-LED-Hood-DIY-Build-EXTRAS!-" rel="nofollow">http://www.reefcentral.co.uk/showthread.php/26598-44-Gallon-Pentagon-Corner-Tank-LED-Hood-DIY-Build-EXTRAS!-</a>(Sump-amp-Wave-Maker-etc)
//
// Jarduino Code Download Page
//   <a data-cke-saved-href="http://code.google.com/p/jarduino-aquarium-controller/" href="http://code.google.com/p/jarduino-aquarium-controller/" rel="nofollow">http://code.google.com/p/jarduino-aquarium-controller/</a>
//
// Jarduino Aquarium Controller v.1.2 Updates Demonstration Video
//   Coming soon to a YouTube near you!
//
// Jarduino Aquarium Controller v.1.1 Demonstration Video
//   <a data-cke-saved-href="http://www.youtube.com/watch?v=gN4XQHNijxw" href="http://www.youtube.com/watch?v=gN4XQHNijxw" rel="nofollow">http://www.youtube.com/watch?v=gN4XQHNijxw</a>
//
//************************************************************************************/
//
// Previous Versions 
//   Jarduino Aquarium Controller v.1.0 (December 2011)
//   Jarduino Aquarium Controller v.1.1 (April 2012)
//
// Updates to Current Version (Jarduino Aquarium Controller v.1.2)
//   • Added support for Arduino 1.0 IDE (Must use patched version)
//   • Replaced the ITDB02_Graph16.h Library with UTFT.h Library by Henning Karlsen
//   • Replaced Matt Joyce's DS1307 Library with Henning Karlsen's DS1307 Library
//       - modified formatting in Karlsen's DS1307 Library
//       - rewrote all RTC coding in sketch, based on Karlsen's "ITDB02_Analog_Clock"
//       - added "Day of the Week" to the "Date & Time Bar."
//       - fixed setting a date that does not exist possibility (ie. FEB 31, 2011)
//   • Added 24 Hour Time formatting to the "Test LED Array Output Settings" screen
//   • Modified "View/Change Moon LED Max Output"
//       - Added pictures and the ability to set/save the Minimum Illumination
//   • Replaced LED Output Testing "Widget" with "Slider Bars" 
//   • Upgraded "Change LED Output Values" page with "Slider Bars" 
//   • Included more Built-In Protections and Redundancies
//   • Added an additional page of user settings including:
//       - choice of showing the Day of the Week
//       - setting the Fan(s) startup temperature
//       - choosing to Dim the LEDs at user defined temperature & How much to Dim them
//       - added four user-defined options to the Screensaver
//   • Changed the look of some buttons as well as some other visual tweaks
//
// Coming soon to Jarduino v.1.3
//   • WiFi and possibly Android/iPhone App
//
// Other Possible Future Developments
//   • Improved User Interfaces (Main Screen Panels & Shortcuts)
//   • Replace the ITDB02_Touch.h Library with the latest release (when available)
//   • Random Weather (Clouds, Storms, etc. along with Increased Wave Action)
//   • Real Weather (Mirror the real weather conditions from user-selected locations)
//   • Modification of Wave Maker to include Tidal Forces with Lunar Cycle 
//   • Automatic Water Changer & Top Off 
//   • Inclusion of Other Sensors: 
//       1. pH 
//       2. Salinity 
//       3. Calcium 
//       4. Orp 
//   • Automatic Dosing 
//    
//************************************************************************************/
//
// Main code based on Stilo
//   <a data-cke-saved-href="http://code.google.com/p/stilo/" href="http://code.google.com/p/stilo/" rel="nofollow">http://code.google.com/p/stilo/</a>
//
// LED controlling algorithm is based on Krusduino by Hugh Dangerfield
//   <a data-cke-saved-href="http://code.google.com/p/dangerduino/" href="http://code.google.com/p/dangerduino/" rel="nofollow">http://code.google.com/p/dangerduino/</a>
//
// A number of functions and some button designs based on the work of Henning Karlsen
//   <a data-cke-saved-href="http://www.henningkarlsen.com/electronics/" href="http://www.henningkarlsen.com/electronics/" rel="nofollow">http://www.henningkarlsen.com/electronics/</a>
//
// Moon Phase algorithm is based in part on a Moon Phase function by NightAtTheOpera
//   <a data-cke-saved-href="http://www.nano-reef.com/forums/index.php?showtopic=217305&st=0&" href="http://www.nano-reef.com/forums/index.php?showtopic=217305&st=0&" rel="nofollow">http://www.nano-reef.com/forums/index.php?showtopic=217305&st=0&</a>
//
// Special Thanks:
//    Dave Rosser & Hugh Dangerfield - (aka Lewis & Clark?) - Reef Controller Pioneers
//      <a data-cke-saved-href="http://www.ultimatereef.net/forums/showthread.php?t=363432" href="http://www.ultimatereef.net/forums/showthread.php?t=363432" rel="nofollow">http://www.ultimatereef.net/forums/showthread.php?t=363432</a>
//    Mark Chester aka "Koyaanisqatsi" - Knows everything there's to know about LEDs
//      <a data-cke-saved-href="http://www.chestersgarage.com/" href="http://www.chestersgarage.com/" rel="nofollow">http://www.chestersgarage.com/</a>
//    Henning Karlsen
//      <a data-cke-saved-href="http://www.henningkarlsen.com/electronics/" href="http://www.henningkarlsen.com/electronics/" rel="nofollow">http://www.henningkarlsen.com/electronics/</a>
//    Kev Tench aka "tangtastic" - DIY Reef Wizard!
//      <a data-cke-saved-href="http://ukreefs.com/index.php?action=profile;u=1" href="http://ukreefs.com/index.php?action=profile;u=1" rel="nofollow">http://ukreefs.com/index.php?action=profile;u=1</a>
//    Ned Simpson aka "Surff" - Another DIY Reef Guy
//      <a data-cke-saved-href="http://www.ultimatereef.net/forums/showthread.php?t=400993" href="http://www.ultimatereef.net/forums/showthread.php?t=400993" rel="nofollow">http://www.ultimatereef.net/forums/showthread.php?t=400993</a>
//    Neil Williams aka "neildotwilliams" - Yet another DIY Reefer
//      <a data-cke-saved-href="http://www.ultimatereef.net/forums/member.php?u=37721" href="http://www.ultimatereef.net/forums/member.php?u=37721" rel="nofollow">http://www.ultimatereef.net/forums/member.php?u=37721</a>
//    Albert aka "selfonlypath" - Arduino genius
//      <a data-cke-saved-href="http://arduino.cc/forum/index.php?action=profile;u=12410" href="http://arduino.cc/forum/index.php?action=profile;u=12410" rel="nofollow">http://arduino.cc/forum/index.php?action=profile;u=12410</a>
//
// An Especially Big Thank You to all who Donated, helping to further development.
//
//************************************************************************************/
//
// Known Bugs/Issues:
//   • The level of automation may make you lazy
//   • If you spot an error or bug in this sketch, please let me know!
//   • 
//
//************************************************************************************/
//
// LEGAL DISCLAIMER:
//   Jarduino Aquarium Controller v.1.1 and v.1.2, Copyright 2011, 2012 Jamie M. Jardin.
//   I'm providing this program as free software with the sole intent on furthering 
//   DIY Aquarium Lighting, but WITHOUT ANY WARRANTY; without even the implied warranty 
//   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. You may modify and/or use 
//   it under the terms of the GNU General Public License as published by the Free 
//   Software Foundation version 3 of the License, or (at your option) any later 
//   version.  However if you intend on using the program (either in its entirety or any 
//   part of it) in any way, shape, or form for PROFIT, you MUST contact me and obtain 
//   my EXPRESS WRITTEN CONSENT (contact information is provided above).
//   VIOLATORS WILL BE PROSECUTED TO THE FULLEST EXTENT OF THE LAW.
//
//************************************************************************************/
//
// IF YOU WANT SOME HELP, PLEASE READ ME!
//   Feel free to make changes to suit your needs.  For you convenience, I’v listed the 
//   line numbers in the sketch most commonly changed.  Some of these values will require 
//   a change while other values can simply be modified according to user preference.  
//   If you make changes to lines other than those listed below, know that it may render 
//   the program inoperable or cause unpredictable behavior.  
//
//   144, 147/148, 191-197, 200-203, 206-209, 212, 216-218, 230 (0.2 or higher), 379-467
//
//************************************************************************************/
//LIBRARIES
#include <avr/pgmspace.h>
#include <ITDB02_Touch.h>
#include <Wire.h>
#include <EEPROM.h>
#include "writeAnything.h"
#include <DS1307.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <SdFat.h>
#include <SdFatUtil.h>

#include <UTFT.h>
//#include <ITDB02_Graph16.h>



//**********************Define Graph library type (for TFT flat cable) ****************************
//#define Graph16_lib

//**********************Define Shield TYPE ********************************************************
//#define Standard_shield      // Uncomment this line if you use the standard Shield for mega 2560, 
                               // standard Shield is support two modes, 6 channel only (UV and Yellow disconn.)
                               // mode 1 - 8bit PWM for all color
                               // mode 2 - 8bit PWM for Red, TV, Moon, and 11bit for RoyalBlue, Blue, White, Cyan 

//#define Aqua_shield_v2       // Uncomment this line if you use the Aqua Shield V2 by Oleg
                               // Aqua Shield V2 is support two modes, 8 channel
                               // mode 1 - 8bit PWM for all color
                               // mode 2 - 8bit PWM for UV, RoyalBlue, TV, and 11bit for  Blue, White, Cyan, Moon, Yellow, DeepRed 

#define Aqua_shield_v3         // Uncomment this line if you use the Aqua Shield V3...V3.5 by Oleg
                               // Aqua Shield V3...V3.2 is support two modes, 8 channel
                               // mode 1 - 8bit PWM for all color
                               // mode 2 - 11bit PWM for all color, exept Moon (1khz freq)
                               // Aqua Shield V3.5 by added TFT Britness dimming support	

//************************************************************************************************
//*********************** Change Touch Coordinate ************************************************
//#define Mirror_X
//#define Mirror_Y

//*********************** Define PWM Resolution **************************************************
//#define Timers_8bit       // 0-255 value for all version shield, and all colour 
//#define Timers_8_11bit      // 0-1985 value exept RoyalBlue(0-255), UV(0-255), TV(0-255) colors, for standart & Aqua_shield_v2
#define Timers_11bit      // 0-1985 value for standart Shield or Aqua_shield_v3, 11bit PWM for all colour 
//************************************************************************************************

//***********************LED Driver Settings******************************************************
boolean RECOM_RCD = true;            //Positive PWM output signal (true), for LDD, MW etc.
									 // Negative - false

//***********************PWM Frequency Setting ***************************************************
#ifdef Timers_8bit 
byte PWM_FRQ_Value = 3;	    	// PWM_FRQ_Value=2   8bit PWM Frequency = 3906 Hz for colours White, Yellow, Blue, Cyan, Moon, Red
				     		    // PWM_FRQ_Value=3   8bit PWM Frequency = 488 Hz 
		                        // PWM_FRQ_Value=4   8bit PWM Frequency = 122 Hz
								//                   8bit PWM Frequency = 976 Hz  for RoyalBlue, UV - fixed, DO NOT CHANGE

byte PWM_FRQ_ValueT2 = 4;		// PWM_FRQ_ValueT2=2  8bit PWM Frequency = 3906 Hz for colours True Violet (420nm)
					    		// PWM_FRQ_ValueT2=3  8bit PWM Frequency = 976 Hz  
		                        // PWM_FRQ_ValueT2=4  8bit PWM Frequency = 488 Hz  
		                        // PWM_FRQ_ValueT2=5  8bit PWM Frequency = 244 Hz  
		                        // PWM_FRQ_ValueT2=6  8bit PWM Frequency = 122 Hz
#endif

#ifdef Timers_8_11bit 
byte PWM_FRQ_Value = 3;	        // PWM_FRQ_Value=2    11bit PWM Frequency = 1khz for colours Cyan, White, Blue, DeepRed, Yellow, Moon 
								// PWM_FRQ_Value=3    11bit PWM Frequency = 125hz

byte PWM_FRQ_ValueT2 = 6;       // PWM_FRQ_ValueT2=2  8bit PWM Frequency = 3906 Hz for colours True Violet, UV, RoyalBlue  
					    		// PWM_FRQ_ValueT2=3  8bit PWM Frequency = 976 Hz  
		                        // PWM_FRQ_ValueT2=4  8bit PWM Frequency = 488 Hz  
		                        // PWM_FRQ_ValueT2=5  8bit PWM Frequency = 244 Hz  
		                        // PWM_FRQ_ValueT2=6  8bit PWM Frequency = 122 Hz
#endif

#ifdef Timers_11bit 
byte PWM_FRQ_Value = 3;	        // PWM_FRQ_Value=2    11bit PWM Frequency = 1khz for all colours exept Moon 
								// PWM_FRQ_Value=3    11bit PWM Frequency = 125hz
#endif


byte PWM_FRQ_Value_Fan = 5;     // PWM_FRQ_Value_Fan=5 PWM Frequency = 30 Hz for Fans
                                // PWM_FRQ_Value_Fan=4 PWM Frequency = 122 Hz 
//************************************************************************************************

//**********************Define LED PWM channel Colour ********************************************
const byte rgbCh0[] = {0, 255, 255};     // PWM 0 Cyan			|
const byte rgbCh1[] = {224, 102, 255};   // PWM 1 UV			|
const byte rgbCh2[] = {255, 255, 255};   // PWM 2 Cool White	|	
const byte rgbCh3[] = {43, 96, 222};     // PWM 3 Royal Blue	|	
const byte rgbCh4[] = {0, 0, 200};       // PWM 4 Blue			|
const byte rgbCh5[] = {255, 0, 0};       // PWM 5 Deep Red		|
const byte rgbCh6[] = {142, 53, 239};    // PWM 6 TV			|
const byte rgbCh7[] = {255, 255, 0};     // PWM 7 Yellow		|
const byte rgbCh8[] = {236, 214, 114};   // PWM 8 Moon			|
//************************************************************************************************


//**********************Define LED channel Name **************************************************
char* ChName[] PROGMEM = {                   //resolution define   8      8/11    11     mega2560 pin        
  "CY",               // ChName[0]  PWM 0 Cyan					| 8bit | 11bit | 11bit  
  "UV",               // ChName[1]  PWM 1 UV					| 8bit | 8bit  | 11bit
  "CW",               // ChName[2]  PWM 2 Cool White			| 8bit | 11bit | 11bit
  "RB",               // ChName[3]  PWM 3 Royal Blue			| 8bit | 8bit  | 11bit
  "Bl",               // ChName[4]  PWM 4 Blue					| 8bit | 11bit | 11bit
  "DR",               // ChName[5]  PWM 5 Deep Red				| 8bit | 11bit | 11bit
  "TV",               // ChName[6]  PWM 6 TV (420nm)			| 8bit | 8bit  | 11bit
  "Ye",               // ChName[7]  PWM 7 Yellow				| 8bit | 11bit | 11bit
  "Moon",             // ChName[8]  PWM 8 Moon					| 8bit | 11bit | 11bit
  "%" ,               // ChName[9]   %							|
  "="                 // ChName[10]  =							|
 };
//**********************Define LED channel Button Name ********************************************
char* ChButName[] PROGMEM = {
 "Cyan",              // ChButName[0]
 "UltraViolet",       // ChButName[1] 
 "White",             // ChButName[2]
 "Royal Blue",        // ChButName[3] 
 "Blue",              // ChButName[4]
 "DeepRed",           // ChButName[5]
 "TrueViolet",        // ChButName[6]
 "Yellow",            // ChButName[7]
 "Lunar",             // ChButName[8]
 "Curves Colors"      // ChButName[9]
 };
//************************************************************************************************

#ifdef Graph16_lib
ITDB02 myGLCD(38,39,40,41,ITDB32S);    //Uncomment this line for the SSD1289 & mega 2560 for ITDB02_Graph16
#else
UTFT myGLCD(ITDB32S, 38,39,40,41);    //Uncomment this line for the SSD1289 & mega 2560 for UTFT lib
#endif

#ifdef Standard_shield
ITDB02_Touch myTouch (6,5,4,3,2);   // for standart shield
#else
ITDB02_Touch myTouch (42,49,47,48,43);  // for Aqua_shield v3 and v2
#endif

//Initialize the DS1307
DS1307 rtc(20, 21);

Time t, t_temp;                      //Init Time-data structure
int rtcSetMin, rtcSetHr, rtcSetDy, 
    rtcSetMon, rtcSetYr;    


int clockCenterX=200;
int clockCenterY=120;

byte setCalendarFormat = 0;           //DD/MM/YYYY=0 || Month DD, YYYY=1 (change in prog)
byte displayDOW = 0;                  //Hide=0 || Show=1 (change in prog)
byte setTimeFormat = 0;               //24HR=0 || 12HR=1 (change in prog)
int AM_PM, yTime;                     //Setting clock stuff
int timeDispH, timeDispM, 
    xTimeH, xTimeM10, xTimeM1, 
    xTimeAMPM, xColon;
String time, day; 

byte setLockScreen = 0;              //Lock Screensaver is OFF=0 || Lock Screensaver is ON=1
byte setScreensaverOnOff = 0;        //OFF=0 || ON=1 Turns it ON/OFF (change in prog)
byte ClockType = 1;                  //ClockType = 0/1/2/3/ -> Blanc/An.Clock/Dig.Clock/Temperature
int SS_DOW_x;                        //Moves the DOW to correct position
byte setSSmintues;                   //Time in (minutes) before Screensaver comes on (change in program)
byte TempSSminutes;                  //Temporary SetSSminutes used in calcs and prints, etc.
byte setScreenSaverTimer;             //how long in (minutes) before Screensaver comes on (change in program)
byte screenSaverCounter = 0;          //counter for Screen Saver
byte returnTimer = 0;                 //counter for Screen Return, auto return after 2min timeout
byte BrigthnessCount = 4;            // brightness button counter (0-OFF, 4 - MAX)

//Declare which fonts to be utilized
extern uint8_t SmallFont[];
extern uint8_t BigFont[];

#ifdef Graph16_lib
extern uint8_t SevenSegNumFontPlus[];
#else
extern uint8_t SevenSegNumFont[];
#endif




//extern uint8_t RusFont1[];  // маленькая кириллица
//extern uint8_t RusFont3[];  // средняя кириллица

//extern uint8_t Ubuntu[];
//extern uint8_t OCR_A_Extended_M[];

//extern uint8_t SevenSegNumFontPlus[];
//extern uint8_t SixteenSegment[];
//extern uint8_t DotMatrix_M_Num[];
//extern uint8_t DotMatrix_XL_Num[];

#define LARGE true
#define SMALL false
//#define BlUE_BAC false
//#define GREEN_BAC true

const int BlUE_BAC = 0; 
const int GREEN_BAC = 1; 
const int GREY_BAC = 2; 




#ifdef Timers_8bit
int ResolutionLow = 255;
int ResolutionHigh= 255;
#endif

#ifdef Timers_8_11bit
int ResolutionLow = 255;
int ResolutionHigh= 1985;
#endif

#ifdef Timers_11bit
int ResolutionLow = 1985;
int ResolutionHigh= 1985; 
#endif

#ifdef Timers_8bit

#else
//*************************Define for 11bit timer ************************************************
#ifndef cbi_mix
#define cbi_mix(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi_mix
#define sbi_mix(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif
//************************************************************************************************
#endif

// ------------- FOR Standart Shield for MEGA2560 ------------------------------ 
#ifdef Standard_shield

const int ledPinRoyBlue = 11;        //  8/11bit timer, Timer1
const int ledPinUV = A1;             //  NC
const int ledPinWhite = 12;          //  8/11bit timer, Timer1
const int ledPinYellow  = A2;        //  NC
const int ledPinTV = 10;             //  8bit timer, Timer2
const int ledPinBlue = 7;            //  8/11bit timer, Timer4
const int ledPinCyan  = 8;           //  8/11bit timer, Timer4 
const int ledPinMoon = 13;           //  8bit timer, Timer0
const int ledPinRed = 9;             //  8bit timer, Timer2

const int Heatsink1_FansPWM = 44;    // Fan-PWM0 Heatsink1 Fan, Timer5 
const int Heatsink3_FansPWM = 45;    // Fan-PWM2 Heatsink3 Fan, Timer5
const int Heatsink2_FansPWM = 46;    // Fan-PWM1 Heatsink2 Fan, Timer5

const int tempAlarmPin = A3;          // Buzzer Alarm for Temperature error
const int tempHeatPin = 47;           // power switch0 Heater on/off (set thermostat on heater to highest desired level)
const int tempChillPin = 48;          // power switch1 Chiller on/off (set thermostat on chiller to lowest desired level)
const int PowerSwitch2 = A3;          // power switch2, temporary NU
const int PowerSwitch3 = A4;          // power switch2, temporary NU

const int SDchipSelect = 53;          //SD card attached to SPI bus as follows: MISO -pin 50, MOSI -pin 51, CLK- pin 52

const int Temp_SensorBus0 = A15;
// DS18B20 Temperature sensors plugged into pin 51 (Water, Hood, & Sump)
OneWire OneWireBus(Temp_SensorBus0);   //DS18B20 Temperature sensors pin

# endif

// ------------- FOR AQUA SHIELD V2 ------------------------------- 
#ifdef Aqua_shield_v2

const int ledPinCyan  = 2;           //PWM0/0-10V 8/11bit timer, Timer3 
const int ledPinUV = 4;              //PWM1/0-10V 8bit timer, Timer0
const int ledPinWhite = 12;          //PWM2/0-10V 8/11bit timer, Timer1
const int ledPinRoyBlue = 13;        //PWM3/0-10V 8bit timer, Timer0
const int ledPinBlue = 5;            //PWM4/0-10V 8/11bit timer, Timer3
const int ledPinRed = 6;             //PWM5/0-10V 8/11bit timer, Timer4
const int ledPinTV = 10;             //PWM6/0-10V 8bit timer, Timer2
const int ledPinYellow  = 11;        //PWM7/0-10V 8/11bit timer, Timer1
const int ledPinMoon = 3;            //PWM8 Moon, 8/11bit timer, Timer3

const int Heatsink1_FansPWM = 44;    //Fan-PWM0 Heatsink1 Fan, Timer5 
const int Heatsink2_FansPWM = 46;    //Fan-PWM1 Heatsink2 Fan, Timer5
const int Heatsink3_FansPWM = 45;    //Fan-PWM2 Heatsink3 Fan, Timer5

const int tempHeatPin = A9;          // power switch0 Heater on/off (set thermostat on heater to highest desired level)
const int tempChillPin = A11;        // power switch1 Chiller on/off (set thermostat on chiller to lowest desired level)
const int PowerSwitch2 = A13;        // power switch2
const int tempAlarmPin = 7;          // Buzzer Alarm for Temperature error
const int AnalogIN = A14; 

const int WirelessSPI_CS = A8;
const int WirelessW_CE = A10;
const int WirelessW_IRQ = A12;

const int SDchipSelect = 53;          //SD card attached to SPI bus as follows: MISO -pin 50, MOSI -pin 51, CLK- pin 52
const int Temp_SensorBus0 = A15;
OneWire OneWireBus(Temp_SensorBus0);   //DS18B20 Temperature sensors pin
const int BackLite = 13; 

// not used
//const int WaveMakerTop = A0;         //Hydor Koralia Evolution (Top Plug)
//const int WaveMakerBottom = A1;      //Hydor Koralia Evolution (Bottom Plug)
//const int autoFeeder = A2;           //Automatic Fish Feeder
#endif 

// ------------- FOR AQUA SHIELD V3 ------------------------------- 
#ifdef Aqua_shield_v3

const int ledPinCyan  = 2;           //PWM0/0-10V 11bit timer, Timer3 
const int ledPinUV = 3;              //PWM1/0-10V 11bit timer, Timer3
const int ledPinWhite = 12;          //PWM2/0-10V 11bit timer, Timer1
const int ledPinRoyBlue = 7;         //PWM3/0-10V 11bit timer, Timer4
const int ledPinBlue = 5;            //PWM4/0-10V 11bit timer, Timer3
const int ledPinRed = 6;             //PWM5/0-10V 11bit timer, Timer4
const int ledPinTV = 8;              //PWM6/0-10V 11bit timer, Timer4
const int ledPinYellow  = 11;        //PWM7/0-10V 11bit timer, Timer1
const int ledPinMoon = 4;            //PWM8 moon,  8bit timer, Timer0

const int Heatsink1_FansPWM = 44;    //Fan-PWM0 Heatsink1 Fan, Timer5 
const int Heatsink2_FansPWM = 9;     //Fan-PWM1 Heatsink2 Fan, Timer2
const int Heatsink3_FansPWM = 10;    //Fan-PWM2 Heatsink3 Fan, Timer2

const int tempHeatPin = A9;          // power switch0 Heater on/off (set thermostat on heater to highest desired level)
const int tempChillPin = 46;         // power switch1 Chiller on/off (set thermostat on chiller to lowest desired level)
const int PowerSwitch2 = 45;         // power switch2 
const int PowerSwitch3 = A14;        // power switch3 
const int tempAlarmPin = A11;        // Buzzer Alarm for Temperature error

const int WirelessSPI_CS = A8;
const int WirelessW_CE = A10;
const int WirelessW_IRQ = A12;

const int Temp_SensorBus0 = A15;
const int Temp_SensorBus1 = A13;

OneWire OneWireBus(Temp_SensorBus0);       //DS18B20 Temperature sensors pin - first sensor bus
//OneWire OneWireBus1(Temp_SensorBus1);    //DS18B20 Temperature sensors pin - second sensor bus
const int SDchipSelect = 53;               //SD card attached to SPI bus as follows: MISO -pin 50, MOSI -pin 51, CLK- pin 52
const int BackLite = 13;                   //PWMx  8bit timer, Timer0
#endif 

SdFat sd;
SdFile myFile;
#define error(s) sd.errorHalt_P(PSTR(s))

// Pass our oneWire reference to Dallas Temperature. 
DallasTemperature sensors(&OneWireBus);
DeviceAddress tempDeviceAddress;
DeviceAddress Heatsink1Thermometer;
DeviceAddress Heatsink2Thermometer;
DeviceAddress waterThermometer;

byte  resolution = 11;
unsigned long lastTempRequest = 0;
int  delayInMillis = 0;

float tempW = 0;                          //Water temperature values
float tempH1 = 0;                         //Heatsink temperature
float tempH2 = 0;                         //Heatsink2 heatsink temperature
float setTempToBeginHeatsink1FanC=0.0;    //Temperature to Turn on Heatsink1 Fans (in Degrees C)
float setTempToBeginHeatsink2FanC=0.0;    //Temperature to Turn on Heatsink2 Fan (in Degrees C)
float setTempToBeginHeatsink1FanF=0.0;    //Temperature to Turn on Heatsink1 Fans (in Degrees F)
float setTempToBeginHeatsink2FanF=0.0;    //Temperature to Turn on Heatsink2 Fan (in Degrees F)
byte  setTempToSoundAlarmC=0;             //Temperature to Heatsink Sound alarm (in Degrees C)
byte  setTempToSoundAlarmF=0;             //Temperature to Heatsink Sound alarm (in Degrees F)
byte  WaterTempErrorCount=0;              //Error temp read counter
byte  Heatsink1TempErrorCount=0;          //Error temp read counter
byte  Heatsink2TempErrorCount=0;          //Error temp read counter
float tempH1Store = 25;
float tempH2Store = 25;

float temp2beHFan;                        //Temporary Temperature Values
float temp2beSFan;                        //Temporary Temperature Values

int Heatsink1TempInterval = 0;            //Used for PWM Duty calculations
int Heatsink2TempInterval = 0;            //Used for PWM Duty calculations
byte  Heatsink1PWM = 0;                   //Used for PWM Duty calculations
byte  Heatsink2PWM = 0;                   //Used for PWM Duty calculations

float setTempC = 0.0;                //Desired Water Temperature (User input in program)
float setTempF = 0.0;
float offTempC = 0.0;                //Desired Water Temp. Offsets for Heater & Chiller (User input in program)
float offTempF = 0.0;
float alarmTempC = 0.0;              //Temperature the Alarm will sound (User input in program)
float alarmTempF = 0.0;
boolean tempCoolflag = 0;            //1 if cooling on
boolean tempHeatflag = 0;            //1 if heating on
boolean tempAlarmflagW = 0;          //1 if alarm on
boolean tempAlarmflagH1 = 0;         //1 if alarm on
boolean tempAlarmflagH2 = 0;         //1 if alarm on
boolean AlarmflagON = false ;
byte AlarmLevel = 0;
boolean SoftStartON= 0;

float temp2beS;                       //Temporary Temperature Values
float temp2beO;                       //Temporary Temperature Values
float temp2beA;                       //Temporary Temperature Values
byte setTempScale = 0;                //Celsius=0 || Fahrenheit=1 (change in prog)
String degC_F;                        //Used in the Conversion of Celsius to Fahrenheit 
float MaxTempW;                       // maximal day temperature
float MaxTempH1;
float MaxTempH2;

byte setDimLEDsOnOff = 0;             //If/When LEDs reach a certain temp they can dim down (feature off by default)
byte setLEDsDimTempC = 0;             //Default value is 0, set this value in program
byte setLEDsDimTempF = 0;             //Conversion of C-F
byte TempLEDsDimTemp;                 //Temporary LED Dimming Temp
byte setLEDsDimPercent = 0;           //Choose value to failsafe dim LEDs in program
byte TempLEDsDimPercent;              //Temporary LED Dimming Percent
float PercentDim = 0.0;               //Converts saved value in EEPROM to a percentage
float PercentSoftStart = 0.0;         //change from 0 to 1 with 0.1 increment, every 5sec after programm is started 

//int tempLED=setLEDsDimTempC+5;

float LC = 29.53059;                 //1 Lunar Cycle = 29.53059 days
String LP;                           //LP = Lunar Phase - variable used to print out Moon Phase
double AG;
byte tMaxI;                           //Maximum Illumination of Moon (User Defined/Set in Prog. -- Default = 0)
byte tMinI;                           //Minimum Illumination of Moon (User Defined/Set in Prog. -- Default = 0)
byte MinI = 10;
byte MaxI = 90;                       //Highest Value (0-255) at which Led is Still OFF, or the Value
                                     //you wish the New Moon to Shine (it will increase from here to MaxI)

           
//extern unsigned int WeatherPic[0xBD1];      // солнце, туча, гром
 
unsigned int *MoonPic;               //Pointer to the Lunar Phase Pics
extern unsigned int                  //Lunar Phase Pics
  New_Moon[0xD24],
  Waxing_Crescent[0xD24],
  First_Quarter[0xD24],
  Waxing_Gibbous[0xD24],
  Full_Moon[0xD24],
  Waning_Gibbous[0xD24],
  Last_Quarter[0xD24],
  Waning_Crescent[0xD24];

// text string for all windows header
prog_char Header_Text_string0[] PROGMEM =  "Do you want to save";   // "String 0" etc are strings to store - change to suit.
prog_char Header_Text_string1[] PROGMEM =  "      changes";
prog_char Header_Text_string2[] PROGMEM =  "    before exit?";
prog_char Header_Text_string3[] PROGMEM =  "TV  DR   CW  BL  RBL  UV  CY  YE  Moon";
prog_char Header_Text_string4[] PROGMEM =  "Change LED Output Values"; 
prog_char Header_Text_string5[] PROGMEM =  "Change Blue LED Output Values"; //NU
prog_char Header_Text_string6[] PROGMEM =  "Change Royal Blue LED Output Values"; //NU
prog_char Header_Text_string7[] PROGMEM =  "Change DeepRed LED Output Values"; //NU
prog_char Header_Text_string8[] PROGMEM =  "Change UltraViolet LED Output Values"; //NU
prog_char Header_Text_string9[] PROGMEM =  "Change TrueViolet LED Output Values";  //NU
prog_char Header_Text_string10[] PROGMEM = "Change Cyan LED Output Values"; //NU
prog_char Header_Text_string11[] PROGMEM = "Change Yellow LED Output Values"; //NU
prog_char Header_Text_string12[] PROGMEM = "Make a selection above. Choose";
prog_char Header_Text_string13[] PROGMEM = "any Two-Hour Increment";
prog_char Header_Text_string14[] PROGMEM = "then you can adjust values."; 
prog_char Header_Text_string15[] PROGMEM = "Choose Option";
prog_char Header_Text_string16[] PROGMEM = "Time and Date Settings";
prog_char Header_Text_string17[] PROGMEM = "H2O Temperature Control Settings";
prog_char Header_Text_string18[] PROGMEM = "LED Testing Options"; 
prog_char Header_Text_string19[] PROGMEM = "Rapid (x120) Test LED Array";
prog_char Header_Text_string20[] PROGMEM = "Individual LED Outputs: Color Choices";
prog_char Header_Text_string21[] PROGMEM = "View/Change Moon LED Min & Max Output";

prog_char Header_Text_string22[] PROGMEM = "View/Change Wavemaker Settings";
prog_char Header_Text_string23[] PROGMEM = "Alternating Flow Mode Settings";
prog_char Header_Text_string24[] PROGMEM = "Synchronous Flow Mode Settings";
prog_char Header_Text_string25[] PROGMEM = "Automatic Fish Feeder Page";  
prog_char Header_Text_string26[] PROGMEM =	"Set Feeding Time 1";
prog_char Header_Text_string27[] PROGMEM =	"Set Feeding Time 2";
prog_char Header_Text_string28[] PROGMEM =	"Set Feeding Time 3";
prog_char Header_Text_string29[] PROGMEM =	"Set Feeding Time 4";

prog_char Header_Text_string30[] PROGMEM = "View/Change General Settings: Page 1"; 
prog_char Header_Text_string31[] PROGMEM = "View/Change General Settings: Page 2"; 
prog_char Header_Text_string32[] PROGMEM = "View/Change Fans Startup Temperatures"; 
prog_char Header_Text_string33[] PROGMEM = "View/Change LEDs' Dimming Temperature";   
prog_char Header_Text_string34[] PROGMEM = "View/Change Screensaver Settings";
prog_char Header_Text_string35[] PROGMEM = "Jarduino AQUA Controller v1.40 Oleg mod";
prog_char Header_Text_string36[] PROGMEM = "View/Change General Settings: Page 3";
prog_char Header_Text_string37[] PROGMEM = "Config Clouds and Thunderstorm";
prog_char Header_Text_string38[] PROGMEM = "Clouds Setting";
prog_char Header_Text_string39[] PROGMEM = "Thunderstorm Setting";


char* Header_Text_table [] PROGMEM = 	{   
  Header_Text_string0,
  Header_Text_string1,
  Header_Text_string2,
  Header_Text_string3,
  Header_Text_string4,
  Header_Text_string5,
  Header_Text_string6,
  Header_Text_string7,
  Header_Text_string8,
  Header_Text_string9,
  Header_Text_string10,
  Header_Text_string11,
  Header_Text_string12,
  Header_Text_string13,
  Header_Text_string14,
  Header_Text_string15,
  Header_Text_string16,
  Header_Text_string17,
  Header_Text_string18,
  Header_Text_string19,
  Header_Text_string20,
  Header_Text_string21,
  Header_Text_string22,
  Header_Text_string23,
  Header_Text_string24,
  Header_Text_string25,
  Header_Text_string26,
  Header_Text_string27,
  Header_Text_string28,
  Header_Text_string29,
  Header_Text_string30,
  Header_Text_string31,
  Header_Text_string32,
  Header_Text_string33,
  Header_Text_string34,
  Header_Text_string35,
  Header_Text_string36,
  Header_Text_string37,
  Header_Text_string38,
  Header_Text_string39
   };

prog_char Text_string0[] PROGMEM = "Writing to file Backup.txt";
prog_char Text_string1[] PROGMEM = "Backup done.                 ";
prog_char Text_string2[] PROGMEM = "  N.C  ";
prog_char Text_string3[] PROGMEM = " Water ";
prog_char Text_string4[] PROGMEM = "H.Sink1";
prog_char Text_string5[] PROGMEM = "H.Sink2";
prog_char Text_string6[] PROGMEM = "Detect Dallas Sensors";
prog_char Text_string7[] PROGMEM = "Backup setting to SD Card";
prog_char Text_string8[] PROGMEM = "Reset setting to DEFAULT";
prog_char Text_string9[] PROGMEM = "Found: ";
prog_char Text_string10[] PROGMEM = "Dallas Sensors";
prog_char Text_string11[] PROGMEM = "Sensor N";
prog_char Text_string12[] PROGMEM = " connect to";
prog_char Text_string13[] PROGMEM = "Heatsink N1 FAN Startup temperature";
prog_char Text_string14[] PROGMEM = "Heatsink N2 FAN Startup temperature";
prog_char Text_string15[] PROGMEM = "20--50C";
prog_char Text_string16[] PROGMEM = "68--120F";
prog_char Text_string17[] PROGMEM = "Heatsink Sound Alarm temperature";
prog_char Text_string18[] PROGMEM = "40-99C";
prog_char Text_string19[] PROGMEM = "104-210F";
prog_char Text_string20[] PROGMEM = "Desired Temperature: ";
prog_char Text_string21[] PROGMEM = "Temperature Offset: 0.1-5";
prog_char Text_string22[] PROGMEM = "Alarm Offset: 0.1-9.9";
prog_char Text_string23[] PROGMEM = "50-104F";
prog_char Text_string24[] PROGMEM = "10-40C";

prog_char Text_string25[] PROGMEM = "Feeding Time 1 ";
prog_char Text_string26[] PROGMEM = "Feeding Time 2 ";
prog_char Text_string27[] PROGMEM = "Feeding Time 3 ";
prog_char Text_string28[] PROGMEM = "Feeding Time 4 ";

prog_char Text_string29[] PROGMEM = "ON";
prog_char Text_string30[] PROGMEM = "OFF";
prog_char Text_string31[] PROGMEM = "This time has not";
prog_char Text_string32[] PROGMEM = "been scheduled";
prog_char Text_string33[] PROGMEM = "Feed Fish Now!";
prog_char Text_string34[] PROGMEM = "Now Feeding";
prog_char Text_string35[] PROGMEM = "TrueViolet";
prog_char Text_string36[] PROGMEM = "DeepRed";
prog_char Text_string37[] PROGMEM = "White";
prog_char Text_string38[] PROGMEM = "Blue";
prog_char Text_string39[] PROGMEM = "Lunar";
prog_char Text_string40[] PROGMEM = "Royal Blue";
prog_char Text_string41[] PROGMEM = "UltraViolet";
prog_char Text_string42[] PROGMEM = "Cyan";
prog_char Text_string43[] PROGMEM = "Yellow";
prog_char Text_string44[] PROGMEM = "Curves Colors";
prog_char Text_string45[] PROGMEM = "Set Minimum";
prog_char Text_string46[] PROGMEM = "Illumination";
prog_char Text_string47[] PROGMEM = "(0...100%)";
prog_char Text_string48[] PROGMEM = "Set Maximum";
prog_char Text_string49[] PROGMEM = "New Moon";
prog_char Text_string50[] PROGMEM = "Full Moon";
prog_char Text_string51[] PROGMEM = "LED ARRAY";
prog_char Text_string52[] PROGMEM = "LUNAR PHASE";
prog_char Text_string53[] PROGMEM = "MONITORS & ALERTS";
prog_char Text_string54[] PROGMEM = "% of Full";
prog_char Text_string55[] PROGMEM = "Changed!" ;
prog_char Text_string56[] PROGMEM = "      OFF    " ;		
prog_char Text_string57[] PROGMEM = "Overheat only" ;
prog_char Text_string58[] PROGMEM = "      ON     " ;	

prog_char Text_string59[] PROGMEM = "  0%";
prog_char Text_string60[] PROGMEM = " 25%";
prog_char Text_string61[] PROGMEM = " 50%";		
prog_char Text_string62[] PROGMEM = " 75%";
prog_char Text_string63[] PROGMEM = "100%";	

prog_char Text_string64[] PROGMEM = "   Blank   ";
prog_char Text_string65[] PROGMEM = " Anl. Clock";
prog_char Text_string66[] PROGMEM = " Dig. Clock";		
prog_char Text_string67[] PROGMEM = "Temperature";
prog_char Text_string68[] PROGMEM = ": ";
prog_char Text_string69[] PROGMEM = " Temp:";


char* Text_table [] PROGMEM = 	{   
  Text_string0,
  Text_string1,
  Text_string2,
  Text_string3,
  Text_string4,
  Text_string5,
  Text_string6,
  Text_string7,
  Text_string8,
  Text_string9,
  Text_string10,
  Text_string11,
  Text_string12,
  Text_string13,
  Text_string14,
  Text_string15,
  Text_string16,
  Text_string17,
  Text_string18,
  Text_string19,
  Text_string20,
  Text_string21,
  Text_string22,
  Text_string23,
  Text_string24,
  Text_string25,
  Text_string26,
  Text_string27,
  Text_string28,
  Text_string29,
  Text_string30,
  Text_string31,
  Text_string32,
  Text_string33,
  Text_string34,
  Text_string35,
  Text_string36,
  Text_string37,
  Text_string38,
  Text_string39,
  Text_string40,
  Text_string41,
  Text_string42,
  Text_string43,
  Text_string44,
  Text_string45,
  Text_string46,
  Text_string47,
  Text_string48,
  Text_string49,
  Text_string50,
  Text_string51,
  Text_string52,
  Text_string53,
  Text_string54,
  Text_string55,
  Text_string56,
  Text_string57,
  Text_string58,
  Text_string59,
  Text_string60,
  Text_string61,
  Text_string62,
  Text_string63,
  Text_string64,
  Text_string65,
  Text_string66,
  Text_string67,
  Text_string68,
  Text_string69
    };

char* print_text[] PROGMEM = {
   "<< BACK",           // print_text[0]          
  "NEXT >>",            // print_text[1]  
  "SAVE",               // print_text[2]
  "CANCEL",             // print_text[3]
  "Dim LEDs Temp.",     // print_text[4] 
  "Screensaver",        // print_text[5]
  "Display MAX Temp.",  // print_text[6]
  "LED Soft Start",     // print_text[7]
  "Please press on the shield Reset Button",     // print_text[8]
  "or turn OFF ",       // print_text[9]
  "and then turn ON the controller",    // print_text[10]
  "Please WAIT, cleaning EEPROM memory", // print_text[11]
  "Alarm Buzzer Function",	// print_text[12]
  "Choose ScreenSaver type",// print_text[13]
  "Screen Lock ON/OFF",     // print_text[14]
  "Wait:",                  // print_text[15]
  "minutes",                // print_text[16]
  "Brightness of the TFT",  // print_text[17]
  "Clouds",                 // print_text[18]
  "Thunderstorm",           // print_text[19]
  "Test Weather",           // print_text[20]
  "Setting",                // print_text[21]
  "ON",						// print_text[22]
  "OFF",					// print_text[23]
  "Periodicity and duration of clouds are",  // print_text[24]
  "configured automatically, based on the",  // print_text[25]
  "random number generator",			     // print_text[26]
  "Clouds for day",							 // print_text[27]
  "(1...5 time)",							 // print_text[28]
  "Maximum duration of",					 // print_text[29]
  "cloud at a time",						 // print_text[30]
  "15...90 min",							 // print_text[31]
  "Quantity of cloudy",              		 // print_text[32]
  "days per week",		                     // print_text[33]
  "Storm generated randomly only the",       // print_text[34] 
  "presence of clouds",                      // print_text[35]
  "The maximum duration of",                 // print_text[36] 
  "a Thunderstorm",                          // print_text[37] 
  "Tunderstorm at night",                    // print_text[38]
  "Start",                                   // print_text[39] 
  "Stop"                                     // print_text[40]  
    };


char buffer[40];
int PrintStringIndex;

int dispScreen=0;                    // 0-Main Screen 
									 // 1-Menu 
									 // 2-Clock and data Setup screen
									 // 3-H2O Temp Control 
									 // 4-LED Testing Options 
									 // 5-Rapid (x120) Test LED Arrays
									 // 6-Test Individual LED Colors 
									 // 7-Change LED values 
									 // 8-SHOW LED OUTPUT VALUES CURVE SCREEN 
									 // 9-Change Selected Color Array Values
                                     // 10-Wavemaker 
									 // 11-Wavemaker Settings 
									 // 12-AUTOMATIC FISH FEEDER PAGE
									 // 13-SET AUTOMATIC FISH FEEDER TIMES 
									 // 14-GENERAL SETTINGS (PAGE 1)
									 // 15-GENERAL SETTINGS (PAGE 2)
									 // 16-CHANGE Heatsink1 FAN TEMP
									 // 17-DIM LEDs AT TEMP
								     // 18-SET SCREENSAVER WAIT TIME
                                     // 19-not used 
									 // 20-GENERAL SETTINGS (PAGE 3) 
									 // 21-Dallas Detect page 
									 // 22-Backup EEPROM to SD CARD
									 // 23-Preset Setting
									 // 24 -ScreenSaver  
                                     // 25-Weather Control
									 // 26-Cloud Control
									 // 27-Storm Control
									 // 28-Weather Test

//**************Weather ****************

byte TempCount = 0;
int timer; 
byte clouDonOff = 0;   //  для отображения включения облаков (0 -off, 1 on)
byte storMonOff = 0;   //  для отображения включения грозы (0 -off, 1 on)
//extern unsigned int oblaka[0x441];
//extern unsigned int groza2[0x441];
byte weezleONoff = 0; // 1 - включение погоды
float PercentDimLW = 0.0;
float PercentDimLW1 = 0.0;
int DimCloudMin = 10;         // изменяя эту величину мы делаем тучи темнее или светлее (0...100) %
int DimCloudMax = 100;        // изменяя эту величину мы делаем тучи темнее или светлее (0...100) %
int CloudTime;
int CloudStartTime;

int   dimmW = 10;
float DimCloud = 100;   // для плавного перехода в облака
float RampRatio = 1;
byte weeStart = 0;     // 0-обычный свет, 1-переход в облака, 2-выход из облаков 
float value = 0;    // изменение яркости при облачности
int valueH = 0;      
int valueH1 = 0;    
byte valHH=0;    
long previousMillisFive_One = 0;         
int Five_One = 5000;
byte stormGR;   // гроза 1-да, 0-нет
int time1=0;
byte weezON;

byte dayL=1;
byte dayLtmp;

byte timOBL=5; // облака 3 раза в день
byte timOBLtmp;
byte CloudDayQantity = 3;
byte CloudDuration = 45;
byte CloudWeekQantity = 3;
int timOBL1=0, timOBL2=0, timOBL3=0, timOBL4=0, timOBL5=0;  // время срабатывания облочности
int deltaOBL1, deltaOBL2, deltaOBL3, deltaOBL4, deltaOBL5; // продолжительность облачности
byte OBLoNoff=0;

byte deltaOBL=60;
byte deltaOBLtmp;
int timGroz1, timGroz2, timGroz3;  // время срабатывания грозы
int deltaGroz1, deltaGroz2, deltaGroz3; // продолжительность грозы

byte razOBL=3;
byte razOBLtmp=25;

byte kkT = 0;
byte kk1=0, kk2=0, kk3=0, kk4=0,kk5=0;
byte kf1=0, kf2=0, kf3=0, kf4=0, kf5=0;

int tew=0; // для теста
int timOBL1temp;
int deltaOBL1temp;
int timerGR1temp;
int deltaGR1temp;

byte GROZA=0;
int GROZAday=0;
byte GR1=0, GR2=0, GR3=0, GR4=0, GR5=0;
byte GR6=0;
int PercentDimLW1temp;
int timGROZ=2;
int timGROZtmp;
int timerGR1=0, timerGR2=0, timerGR3=0, timerGR4=0, timerGR5=0, timerGR6=0;
int deltaGR1, deltaGR2, deltaGR3, deltaGR4, deltaGR5, deltaGR6;
byte kfg1=1, kfg2=1, kfg3=1, kfg4=1, kfg5=1, kfg6=1;

byte GROZANight=0;
byte NightGR=0;

int Moln=0;

long GROZaMillis =0;
byte dayOBL[7] = {0, 0, 0, 0, 0, 0, 0} ; // для настройки облачности на неделю
byte OBLday;


int x, y;                            //touch coordinates

long previousMillisLED = 0;          //Used in the Test LED Array Function
long previousMillisWave = 0;         //Used in the WaveMaker Function wave_output()
long previousMillisFive = 0;         //Used in the Main Loop (Checks Time,Temp,LEDs,Screen)
long previousMillisOne = 0;          //Used in the Main Loop (LEDs level)
long previousMillisAlarm = 0;        //Used in the Alarm

boolean waveMakerOff = false;        //For Turning ON/OFF WaveMaker
boolean waveMakerTest = false;       //For Testing Wave Settings
long wPump1, wPump2;                 //Total Alternating Times
long intervalAlt = wPump1;           //Changing Interval for Alternating Mode
long wOnForT, wOffForT;              //Total Synchronous-Pulse Times
long intervalSynch = wOnForT;        //Changing Interval for Synch-Pulse Mode
int PumpTstate = LOW;                //Used to set the Top Powerhead ON or OFF
int PumpBstate = LOW;                //Used to set the Bottom Powerhead ON or OFF

int WAVE, Pump1m, Pump1s, Pump2m,    //EEPROM vars
    Pump2s, Synch, OnForTm, OnForTs, 
    OffForTm, OffForTs;
int MODE = WAVE;
int MIN1=0, SEC1=0, MIN2=0, SEC2=0,  //Used in the Wavemaker viewWaveTimes()
    minY1, minY2;    
int Min1=0, Sec1=0, Min2=0, Sec2=0;  //Used in the Wavemaker viewWaveTimesPage() & wave+/-
int min1X=91, sec1X=237,             //Used in the Wavemaker waveModePlusMinus()
    min2X=91, sec2X=237,
    tTime1=0, tTime2=0;
int WaveCorrector = 2;               //Fix for halving of wave seconds (Change to "1" if 
                                     //your wave seconds are doubled)
    
long previousMillisCt = 0;           //stores the last update for the Countdown Timer
long intervalCt = 1000;              //One Second Interval for Countdown Timer
int countDown  = 5*60 + 0;           //Countdown for 5 minutes and zero seconds
int MIN_O = 5;                       //Start the Time at 5 (for looks only)
int SEC_T = 0;
int SEC_O = 0;

byte LedChangTime = 0;                //LED change page, time and values
byte oldLCT ;

int min_cnt;                         // Used to determine the place in the color arrays
byte temp_sector;                    // used in led test arrays, min_cnt/15   

boolean LEDtestTick = false;         // for Rapid led test, speed up clock
boolean firstTouch  = false;         // for exit from screensaver #oleg
boolean SliderSwitch  = false;       // slider
int TopSldY ;						 // top slider
int BotSldY ;   					 // bot slider

byte ButtonShift;

boolean LedShannelFlag_on_off;        // flag led on/off channel status

byte LedShannelStatusByte =255;      // ON=1/OFF=0 channel, one bit - one channel   
byte GlobalStatus1Byte= 0x0;	     // bit 0 for Y/N button in reset default function
									 // bit 1 used in HOT led function
									 // bit 2 =1  for detect pressing button Yes/No	
									 // bit 3 =1 if led setting changed   
									 // GlobalStatus1Byte.4 = StartUPFan2 ;	
                                     // GlobalStatus1Byte.5 = StartUPFan2_Timeout; 
									 // GlobalStatus1Byte.6 = StartUPFan1 ;	
                                     // GlobalStatus1Byte.7)= StartUPFan1_Timeout; 

byte GlobalStatus2Byte=0x0;          // byte Led preset status
                                     // bit 0 - preset 1 (ON=1/OFF=0)
									 // bit 1 - preset 2
                                     // bit 2 - preset 3
                                     // bit 3 - preset 4

byte GlobalStatus3Byte=0x0;          // byte weather day on/off status
                                     // bit 0 - start/stop test
									 // bit 1 - tuesday;
                                     // bit 2 - wednesday;
                                     // bit 3 - thursday;
									 // bit 4 - friday;
									 // bit 5 - saturday;
									 // bit 6 - sunday;
									 // bit 7 - xxxx;


byte StartTime;
byte StopTime;
byte LightDay;
byte counterB1=0; 
byte counterB2=0; 
byte counterB3=0;
byte numberOfDevices=0;             // quantity of Dallas sensor connected to board
int  EndScale;
unsigned long previousMillis1sec;

int whiteLed, blueLed, rblueLed,			//previous LED output values
     redLed, uvLed, tvLed, cyLed, yeLed;
int bled_out, wled_out, rbled_out,			//current LED output values
     rled_out, uvled_out,
     moonled_out, tvled_out,
	 cyled_out, yeled_out;	
int bcol_out, wcol_out, rbcol_out,			//Current LED output values for Test Ind. Color LEDs
     rcol_out, uvcol_out, tvcol_out,
     mooncol_out, cycol_out, yelcol_out;
int tv_out, b_out, w_out, rb_out, r_out, uv_out, moon_out, cy_out, yel_out;     // led values for write to PWM


byte  AddressShift;                         // shift address preset in EEPROM

byte COLOR=0, WHITE=1, BLUE=2, ROYAL=3, //Used to Determine View/Change Color LED Values
    RED=4, ULTRA=5, TV=6, MOON=7,
    CYAN=8, YELLOW=9;

boolean colorLEDtest = false;        //if TRUE - led test, FALSE - regular mode
byte sbR, sbG, sbB; 
int	sbX1, sbX2;                      //Used in the Slider Bars
int tSlide=0;
boolean DrawStaticElement = false;             //Allows selection of changing LED values


byte feedTime;
byte FEEDTime1, FEEDTime2,
     FEEDTime3, FEEDTime4;

byte feedFish1H, feedFish1M,          //Times to feed the fish
     feedFish2H, feedFish2M,
     feedFish3H, feedFish3M,
     feedFish4H, feedFish4M;
    
byte MAX_Temp_on_off = 0;                 //OFF=0 || ON=1 (change in prog)    
byte fiveTillBackOn1, fiveTillBackOn2,
     fiveTillBackOn3, fiveTillBackOn4;
boolean FeedWaveCtrl_1 = false;
boolean FeedWaveCtrl_2 = false;
boolean FeedWaveCtrl_3 = false;
boolean FeedWaveCtrl_4 = false;

byte tvled[96] = {
  0, 0, 0, 0, 0, 0, 0, 0,                   //0 - 1
  0, 0, 0, 0, 0, 0, 0, 0,                   //2 - 3
  0, 0, 0, 0, 0, 0, 0, 0,                   //4 - 5
  0, 0, 0, 0, 0, 0, 0, 0,                   //6 - 7
  0, 0, 0, 0, 0, 0, 0, 0,                   //8 - 9
  0, 0, 0, 0, 2, 5, 8, 10,                  //10 - 11
  20, 40, 60, 70, 70, 70, 70, 70,           //12 - 13
  70, 70, 70, 70, 70, 70, 70, 70,           //14 - 15
  70, 70, 70, 70, 70, 70, 70, 70,           //16 - 17
  70, 70, 70, 70, 70, 70, 70, 70,           //18 - 19
  80, 80, 80, 80, 70, 60, 50, 40,           //20 - 21
  30, 20, 7, 2, 0, 0, 0, 0                  //22 - 23
};  
//ROYAL BLUE Dimming Values
byte rbled[96] = {
  0, 0, 0, 0, 0, 0, 0, 0,                   //0 - 1
  0, 0, 0, 0, 0, 0, 0, 0,                   //2 - 3
  0, 0, 0, 0, 0, 0, 0, 0,                   //4 - 5
  0, 0, 0, 0, 0, 0, 0, 0,                   //6 - 7
  0, 0, 0, 0, 0, 0, 0, 0,                   //8 - 9
  0, 0, 0, 0, 2, 5, 8, 10,                  //10 - 11
  20, 40, 60, 70, 70, 70, 70, 70,           //12 - 13
  70, 70, 70, 70, 70, 70, 70, 70,           //14 - 15
  70, 70, 70, 70, 70, 70, 70, 70,           //16 - 17
  70, 70, 70, 70, 70, 70, 70, 70,           //18 - 19
  70, 70, 70, 70, 60, 50, 40, 30,           //20 - 21
  20, 10, 5, 1, 0, 0, 0, 0                  //22 - 23
};  
//REGULAR BLUE Dimming Values
byte bled[96] = {
  0, 0, 0, 0, 0, 0, 0, 0,                   //0 - 1
  0, 0, 0, 0, 0, 0, 0, 0,                   //2 - 3
  0, 0, 0, 0, 0, 0, 0, 0,                   //4 - 5
  0, 0, 0, 0, 0, 0, 0, 0,                   //6 - 7
  0, 0, 0, 0, 0, 0, 0, 0,                   //8 - 9
  0, 0, 0, 0, 2, 5, 10, 20,                 //10 - 11
  25, 30, 40, 50, 60, 70, 70, 70,           //12 - 13
  70, 70, 70, 70, 70, 70, 70, 70,           //14 - 15
  70, 70, 70, 70, 70, 70, 70, 70,           //16 - 17
  70, 70, 70, 70, 70, 70, 70, 70,           //18 - 19
  70, 70, 70, 70, 50, 40, 30, 20,           //20 - 21
  10, 8, 5, 1, 0, 0, 0, 0                   //22 - 23
};  
//ULTRA VIOLET (UV) Dimming Values
byte uvled[96] = {
  0, 0, 0, 0, 0, 0, 0, 0,                   //0 - 1
  0, 0, 0, 0, 0, 0, 0, 0,                   //2 - 3
  0, 0, 0, 0, 0, 0, 0, 0,                   //4 - 5
  0, 0, 0, 0, 0, 0, 0, 0,                   //6 - 7
  0, 0, 0, 0, 0, 0, 0, 0,                   //8 - 9
  0, 0, 0, 0, 2, 10, 20, 30,                 //10 - 11
  40, 50, 60, 70, 80, 90, 90, 90,           //12 - 13
  90, 90, 90, 90, 90, 90, 90, 90,           //14 - 15
  90, 90, 90, 90, 90, 90, 90, 90,           //16 - 17
  90, 90, 90, 90, 90, 90, 90, 90,           //18 - 19
  80, 70, 60, 50, 40, 40, 30, 20,           //20 - 21
  10, 8, 5, 1, 0, 0, 0, 0                   //22 - 23
};
//Cyan Dimming Values
byte cyled[96] = {
  0, 0, 0, 0, 0, 0, 0, 0,                   //0 - 1
  0, 0, 0, 0, 0, 0, 0, 0,                   //2 - 3
  0, 0, 0, 0, 0, 0, 0, 0,                   //4 - 5
  0, 0, 0, 0, 0, 0, 0, 0,                   //6 - 7
  0, 0, 0, 0, 0, 0, 0, 0,                   //8 - 9
  0, 0, 0, 0, 2, 5, 10, 20,                 //10 - 11
  25, 30, 40, 50, 60, 70, 70, 70,           //12 - 13
  70, 70, 70, 70, 70, 70, 70, 70,           //14 - 15
  70, 70, 70, 70, 70, 70, 70, 70,           //16 - 17
  70, 70, 70, 70, 70, 70, 70, 70,           //18 - 19
  70, 70, 70, 70, 50, 30, 20, 20,           //20 - 21
  8, 5, 0, 0, 0, 0, 0, 0                    //22 - 23
};
//WHITE Dimming Values (White LED array in RAM)
  byte wled[96] = {
  0, 0, 0, 0, 0, 0, 0, 0,                   //0 - 1
  0, 0, 0, 0, 0, 0, 0, 0,                   //2 - 3
  0, 0, 0, 0, 0, 0, 0, 0,                   //4 - 5
  0, 0, 0, 0, 0, 0, 0, 0,                   //6 - 7
  0, 0, 0, 0, 0, 0, 0, 0,                   //8 - 9
  0, 0, 0, 0, 1, 10, 20, 30,                //10 - 11
  40, 50, 60, 70, 70, 70, 70, 70,           //12 - 13
  70, 70, 70, 70, 70, 70, 70, 70,           //14 - 15
  70, 70, 70, 70, 70, 70, 70, 70,           //16 - 17
  70, 70, 70, 70, 70, 70, 70, 70,           //18 - 19
  65, 60, 55, 50, 45, 40, 35, 30,           //20 - 21
  20, 10, 5, 1, 0, 0, 0, 0                  //22 - 23
};


//RED Dimming Values
byte rled[96] = {
  0, 0, 0, 0, 0, 0, 0, 0,                   //0 - 1
  0, 0, 0, 0, 0, 0, 0, 0,                   //2 - 3
  0, 0, 0, 0, 0, 0, 0, 0,                   //4 - 5
  0, 0, 0, 0, 0, 0, 0, 0,                   //6 - 7
  0, 0, 0, 0, 0, 0, 0, 0,                   //8 - 9
  0, 0, 0, 0, 1, 10, 20, 30,                //10 - 11
  40, 30, 20, 20, 20, 20, 20, 20,           //12 - 13
  20, 20, 20, 20, 20, 20, 20, 20,           //14 - 15
  20, 20, 20, 20, 20, 20, 20, 20,           //16 - 17
  20, 20, 20, 20, 20, 20, 20, 20,           //18 - 19
  20, 30, 40, 40, 40, 40, 35, 30,           //20 - 21
  20, 10, 5, 1, 0, 0, 0, 0                  //22 - 23
};  
// Yellow Dimming Values
byte yeled[96] = {
  0, 0, 0, 0, 0, 0, 0, 0,                   //0 - 1
  0, 0, 0, 0, 0, 0, 0, 0,                   //2 - 3
  0, 0, 0, 0, 0, 0, 0, 0,                   //4 - 5
  0, 0, 0, 0, 0, 0, 0, 0,                   //6 - 7
  0, 0, 0, 0, 0, 0, 0, 0,                   //8 - 9
  0, 0, 0, 0, 1, 10, 20, 30,                //10 - 11
  40, 50, 60, 70, 70, 70, 70, 70,           //12 - 13
  70, 70, 70, 70, 70, 70, 70, 70,           //14 - 15
  70, 70, 70, 70, 70, 70, 70, 70,           //16 - 17
  70, 70, 70, 70, 70, 70, 70, 70,           //18 - 19
  65, 60, 55, 50, 45, 40, 35, 30,           //20 - 21
  20, 10, 5, 1, 0, 0, 0, 0                  //22 - 23
};

byte tled[96];     //Temporary Array to Hold changed LED Values


/**************************** CHOOSE OPTION MENU BUTTONS *****************************/

const int temC[]= {10, 29, 155, 59};          //"H2O TEMP CONTROL" settings
const int WeatCtrl[]= {10, 69, 155, 99};      //"Weather CONTROL" settings
const int CloudCtrl[]=   {185, 19, 305, 39};  //"Cloud Setting" 
const int CloudCtrlON[]= {130, 19, 174, 39};  //"Cloud Setting  ON/OFF" 
const int StormCtrl[]=   {185, 49, 305, 69};  //"Storm Setting" 
const int StormCtrlON[]= {130, 49, 174, 69};  //"Storm Setting ON/OFF" 
const int StormCtrlONNight[]= {200, 124, 244, 144};  //"Storm night ON/OFF" 

const int ButMns[]= {0, 0, 22, 22};           // universal +/- button counter, defaul coordinate, 22x22 size

/*
 const int GrM[]= {200, 104-16, 220, 124-16};      
 const int GrP[]= {290, 104-16, 310, 124-16};    
const int OzM[]= {200, 132-8, 220, 152-8};     
const int OzP[]= {290, 132-8, 310, 152-8};     
 const int P0M[]= {200, 160+3, 220, 180+3};   
 const int P0P[]= {290, 160+3, 310, 180+3}; 
*/

//const int wave[]= {10, 109, 155, 139};      //"Wavemaker CONTROL" settings
//const int gSet[]= {10, 149, 155, 179};      //"GENERAL SETTINGS" page
const int gSet[]= {165, 149, 310, 179};       //"GENERAL SETTINGS" page
const int tesT[]= {165, 29, 310, 59};         //"LED TESTING OPTIONS" menu
const int ledChM[]= {165, 69, 310, 99};       //"CHANGE LED VALUES" menu
//const int aFeed[]= {165, 109, 310, 139};    //"AUTOMATIC FEEDER" menu
//const int about[]= {165, 149, 310, 179};    //"ABOUT" program information

const int prsM[]= {10, 200, 155, 220};        // Preset
/**************************** TIME AND DATE SCREEN BUTTONS ***************************/
const int houU[]= {110, 22, 135, 47};       //hour up
const int minU[]= {180, 22, 205, 47};       //min up
const int ampmU[]= {265, 22, 290, 47};      //AM/PM up
const int houD[]= {110, 73, 135, 98};       //hour down
const int minD[]= {180, 73, 205, 98};       //min down
const int ampmD[]= {265, 73, 290, 98};      //AM/PM down
const int dayU[]= {110, 112, 135, 137};     //day up
const int monU[]= {180, 112, 205, 137};     //month up
const int yeaU[]= {265, 112, 290, 137};     //year up
const int dayD[]= {110, 162, 135, 187};     //day down
const int monD[]= {180, 162, 205, 187};     //month down
const int yeaD[]= {265, 162, 290, 187};     //year down
/*************************** H2O TEMP CONTROL SCREEN BUTTONS *************************/
const int temM[]= {90, 49, 115, 74};        //temp. minus
const int temP[]= {205, 49, 230, 74};       //temp. plus
const int offM[]= {90, 99, 115, 124};       //offset minus
const int offP[]= {205, 99, 230, 124};      //offset plus
const int almM[]= {90, 149, 115, 174};      //alarm minus
const int almP[]= {205, 149, 230, 174};     //alarm plus
const int Beep[]= {30, 50};                 //Beep ON/OFF

/**************************** LED TESTING MENU BUTTONS *******************************/
const int tstLA[] =  {40, 59-25, 280, 99-25};      //"Test LED Array Output" settings
const int cntIL[] =  {40, 109-25, 280, 149-25};    //"Control Individual Leds" settings
const int PrButL[] = {40, 159-25, 280, 199-25};    //"Preset Leds" settings

/********************** TEST LED ARRAY OUTPUT SCREEN BUTTONS *************************/
const int stsT[]= {110, 105, 200, 175};     //start/stop
const int tenM[]= {20, 120, 90, 160};       //-10s
const int tenP[]= {220, 120, 290, 160};     //+10s
/******************** TEST INDIVIDUAL LED VALUES SCREEN BUTTONS **********************/
//See at the end of these buttons for the button functions
/****************** CHANGE INDIVIDUAL LED VALUES SCREEN BUTTONS **********************/
//These Buttons are made within the function
/************************* CHANGE LED VALUES MENU BUTTONS ****************************/
const int btCIL[]= {5, 188, 90, 220};       //back to Change Individual LEDs Screen
const int ledChV[]= {110, 200, 210, 220};   //LED Change Values
const int eeprom[]= {215, 200, 315, 220};   //Save to EEPROM (Right Button)
const int MINiM[]= {17, 147, 42, 172};      //MinI minus
const int MINiP[]= {116, 147, 141, 172};    //MinI plus
const int MAXiM[]= {179, 147, 204, 172};    //MaxI minus
const int MAXiP[]= {278, 147, 303, 172};    //MaxI plus
/********************* WAVEMAKER SCREEN & STETTINGS BUTTONS **************************/
//Many Wavemaker Buttons are made within the function(s)
const int pump1Mm[]= {21, 70, 46, 95};      //Pump 1 minute minus
const int pump1Mp[]= {120, 70, 145, 95};    //Pump 1 minute plus
const int pump1Sm[]= {175, 70, 200, 95};    //Pump 1 second minus
const int pump1Sp[]= {274, 70, 299, 95};    //Pump 1 second plus
const int pump2Mm[]= {21, 147, 46, 172};    //Pump 2 minute minus
const int pump2Mp[]= {120, 147, 145, 172};  //Pump 2 minute plus
const int pump2Sm[]= {175, 147, 200, 172};  //Pump 2 second minus
const int pump2Sp[]= {274, 147, 299, 172};  //Pump 2 second plus
/************************* AUTOMATIC FISH FEEDER BUTTONS *****************************/
//These Buttons are made within the function
/******************* SET AUTOMATIC FISH FEEDING TIMES BUTTONS ************************/
const int houP[]= {110, 38, 135, 63};       //hour up
const int minP[]= {180, 38, 205, 63};       //min up
const int ampmP[]= {265, 38, 290, 63};      //AM/PM up
const int houM[]= {110, 89, 135, 114};      //hour down
const int minM[]= {180, 89, 205, 114};      //min down
const int ampmM[]= {265, 89, 290, 114};     //AM/PM down
/***************************** MISCELLANEOUS BUTTONS *********************************/
const int backGS[]= {4, 200, 78, 220};      //BACK
const int nextGS[]= {83, 200, 157, 220};    //NEXT
const int prSAVEgs[]= {162, 200, 236, 220}; //SAVE
const int canCgs[]= {241, 200, 315, 220};   //CANCEL
//const int touchLock[]= {4, 200, 78, 220};   //Touch #oleg
const int touchLock[]= {4, 210, 64, 230};   //Touch #oleg
const int Again[]= {241, 200, 315, 220};    //Touch #oleg

const int HoodFanTm[]= {80, 40, 105, 64};   //Hood Fan Temp - // heatsink 1
const int HoodFanTp[]= {195, 40, 220, 64};  //Hood Fan Temp +
const int SumpFanTm[]= {80, 99, 105, 123};  //Sump Fan Temp -  //heatsink 2
const int SumpFanTp[]= {195, 99, 220, 123}; //Sump Fan Temp +
const int SoundAlarmTm[]= {80, 158, 105, 182};  //Sound Alarm Temp - 
const int SoundAlarmTp[]= {195, 158, 220, 182}; //Sound Alarm Temp + 

const int back[]= {5, 200, 105, 220};       //BACK
const int prSAVE[]= {110, 200, 210, 220};   //SAVE
const int canC[]= {215, 200, 315, 220};     //CANCEL

const int StopDay[]= {230, 0, 315, 14};     // NEXT TIME
const int StartDay[]= {5, 0, 85, 14};       // Prev TIME
const int Yes[]= {110, 125, 150, 145};      // Yes
const int No[]= {170, 125, 210, 145};       // No

const int LedPres1[]= {5, 0, 80, 14};        // Led Preset 1 button
const int LedPres2[]= {83, 0, 158, 14};      // Led Preset 2 button
const int LedPres3[]= {161, 0, 236, 14};     // Led Preset 3 button
const int LedPres4[]= {239, 0, 314, 14};     // Led Preset 4 button


void drawUpButtonSlide(int x, int y)
{
  myGLCD.setColor(64, 64, 128);
  myGLCD.fillRoundRect(x, y, x+30, y+22);
  myGLCD.setColor(255, 255, 255);
  myGLCD.drawRoundRect(x, y, x+30, y+22);
  myGLCD.setColor(128, 128, 255);
  for (int i=0; i<15; i++)
    myGLCD.drawLine(x+5+(i/1.5), y+18-i, x+26-(i/1.5), y+18-i);
}
void drawDownButtonSlide(int x, int y)
{
  myGLCD.setColor(64, 64, 128);
  myGLCD.fillRoundRect(x, y, x+30, y+22);
  myGLCD.setColor(255, 255, 255);
  myGLCD.drawRoundRect(x, y, x+30, y+22);
  myGLCD.setColor(128, 128, 255);
  for (int i=0; i<15; i++)
    myGLCD.drawLine(x+5+(i/1.5), y+4+i, x+26-(i/1.5), y+4+i);
}

void drawUpButton(int x, int y)
{
  myGLCD.setColor(0, 0, 255);
  myGLCD.fillRoundRect(x, y, x+25, y+25);
  myGLCD.setColor(255, 255, 255);
  myGLCD.drawRoundRect(x, y, x+25, y+25);
  for (int i=0; i<15; i++)
    myGLCD.drawLine(x+3+(i/1.5), y+19-i, x+22-(i/1.5), y+19-i);
}
void drawDownButton(int x, int y)
{
  myGLCD.setColor(0, 0, 255);
  myGLCD.fillRoundRect(x, y, x+25, y+25);
  myGLCD.setColor(255, 255, 255);
  myGLCD.drawRoundRect(x, y, x+25, y+25);
  for (int i=0; i<15; i++)
    myGLCD.drawLine(x+3+(i/1.5), y+6+i, x+22-(i/1.5), y+6+i);
}

/*
void printButton(char* text, int x1, int y1, int x2, int y2, boolean fontsize = false)
{
  int stl = strlen(text);
  int fx, fy;
  
  myGLCD.setColor(0, 0, 255);
  myGLCD.fillRoundRect (x1, y1, x2, y2);
  myGLCD.setColor(255, 255, 255);
  myGLCD.drawRoundRect (x1, y1, x2, y2);
 
  myGLCD.setBackColor(0, 0, 255);
  if (fontsize) {
    myGLCD.setFont(BigFont); 
    fx = x1+(((x2 - x1+1)-(stl*16))/2);
    fy = y1+(((y2 - y1+1)-16)/2);
    myGLCD.print(text, fx, fy);
    }
  else {
    myGLCD.setFont(SmallFont); 
    fx = x1+(((x2 - x1)-(stl*8))/2);
    fy = y1+(((y2 - y1-1)-8)/2);
    myGLCD.print(text, fx, fy);
    }
}
*/
/*
void printButton(char* text, int x1, int y1, int x2, int y2, boolean fontsize = false, boolean background = false)
{
  int stl = strlen(text);
  int fx, fy;
  
  if (background == true) {                                   // green background, black font
	  myGLCD.setColor(0, 255, 0);
      myGLCD.fillRoundRect (x1, y1, x2, y2);
	  myGLCD.setColor(255, 255, 255);
	  myGLCD.drawRoundRect (x1, y1, x2, y2);
      myGLCD.setBackColor(0, 255, 0);
	  myGLCD.setColor(0, 0, 0);
  }                       
  else {  myGLCD.setColor(0, 0, 255);						  // blue background, white font
		  myGLCD.fillRoundRect (x1, y1, x2, y2);
		  myGLCD.setColor(255, 255, 255);
          myGLCD.drawRoundRect (x1, y1, x2, y2);
          myGLCD.setBackColor(0, 0, 255);}
   
  if (fontsize) {
    myGLCD.setFont(BigFont); 
    fx = x1+(((x2 - x1+1)-(stl*16))/2);
    fy = y1+(((y2 - y1+1)-16)/2);
    myGLCD.print(text, fx, fy);
    }
  else {
    myGLCD.setFont(SmallFont); 
    fx = x1+(((x2 - x1)-(stl*8))/2);
    fy = y1+(((y2 - y1-1)-8)/2);
	myGLCD.print(text, fx, fy);
	   }
}
*/
void printButton(char* text, int x1, int y1, int x2, int y2, boolean fontsize = false, int background =0 )
{
  int stl = strlen(text);
  int fx, fy;
  
  if (background == 0) {
	      myGLCD.setColor(0, 0, 255);						  // blue background, white font
		  myGLCD.fillRoundRect (x1, y1, x2, y2);
		  myGLCD.setColor(255, 255, 255);
          myGLCD.drawRoundRect (x1, y1, x2, y2);
          myGLCD.setBackColor(0, 0, 255);}

    if (background == 1) {                                   // green background, black font
	  myGLCD.setColor(0, 255, 0);
      myGLCD.fillRoundRect (x1, y1, x2, y2);
	  myGLCD.setColor(255, 255, 255);
	  myGLCD.drawRoundRect (x1, y1, x2, y2);
      myGLCD.setBackColor(0, 255, 0);
	  myGLCD.setColor(0, 0, 0); }                       

  if (background == 2) {  
	      myGLCD.setColor(64, 64, 64);						  // grey background, white font
		  myGLCD.fillRoundRect (x1, y1, x2, y2);
		  myGLCD.setColor(255, 255, 255);
          myGLCD.drawRoundRect (x1, y1, x2, y2);
          myGLCD.setBackColor(64, 64, 64);}
   
  if (fontsize) {
    myGLCD.setFont(BigFont); 
    fx = x1+(((x2 - x1+1)-(stl*16))/2);
    fy = y1+(((y2 - y1+1)-16)/2);
    myGLCD.print(text, fx, fy);
    }
  else {
    myGLCD.setFont(SmallFont); 
    fx = x1+(((x2 - x1)-(stl*8))/2);
    fy = y1+(((y2 - y1-1)-8)/2);
	myGLCD.print(text, fx, fy);
	   }
}


void printButtonTouch(char* text, int x1, int y1, int x2, int y2, boolean fontsize = false, boolean background = false)
{
  int stl = strlen(text);
  int fx, fy;
  
  if (background == true) {                                   // green background, black font
	  myGLCD.setColor(0, 255, 0);
      myGLCD.fillRoundRect (x1, y1, x2, y2);
	  myGLCD.setColor(255, 255, 255);
	  myGLCD.drawRoundRect (x1, y1, x2, y2);
      myGLCD.setBackColor(0, 255, 0);
	  myGLCD.setColor(0, 0, 0);
  }                       
  else {  myGLCD.setColor(0, 0, 150);						  // blue background, white font
		  myGLCD.fillRoundRect (x1, y1, x2, y2);
		  myGLCD.setColor(150, 150, 150);
          myGLCD.drawRoundRect (x1, y1, x2, y2);
          myGLCD.setBackColor(0, 0, 150);}
   
  if (fontsize) {
    myGLCD.setFont(BigFont); 
    fx = x1+(((x2 - x1+1)-(stl*16))/2);
    fy = y1+(((y2 - y1+1)-16)/2);
    myGLCD.print(text, fx, fy);
    }
  else {
    myGLCD.setFont(SmallFont); 
    fx = x1+(((x2 - x1)-(stl*8))/2);
//    fy = y1+(((y2 - y1-1)-8)/2);
	fy = y1+(((y2 - y1-2)-8)/2);
	myGLCD.print(text, fx, fy);
	   }
}
/*
void printButtonVertical(char* text, int x1, int y1, boolean fontsize = false, boolean background = false)
{
  int stl = strlen(text);
  int fx, fy;
  
  if (background == true) {                                   // green background, black font
	  myGLCD.setColor(0, 255, 0);
      myGLCD.fillRoundRect (x1, y1, x1+20, y1+10+stl*8+10);
	  myGLCD.setColor(255, 255, 255);
      myGLCD.setBackColor(0, 255, 0);
	  myGLCD.setColor(0, 0, 0);
	  myGLCD.drawRoundRect (x1, y1, x1+20, y1+10+stl*8+10);
  }                       
  else {  myGLCD.setColor(0, 0, 255);						  // blue background, white font
          myGLCD.fillRoundRect (x1, y1, x1+20, y1+10+stl*8+10);
		  myGLCD.setColor(255, 255, 255);
		  myGLCD.setBackColor(0, 0, 255);
		  myGLCD.drawRoundRect (x1, y1, x1+20, y1+10+stl*8+10);
          }
   
  if (fontsize) {
    myGLCD.setFont(BigFont); 
    fx = x1+(x1+20-x1)/2-9;
    fy = y1+ 10+ stl*16;
    myGLCD.print(text, fx, fy, 270);
    }
  else {
    myGLCD.setFont(SmallFont); 
    fx = x1+(x1+20-x1)/2-6;
    fy = y1+ 10+ stl*8;
	myGLCD.print(text, fx, fy, 270);
	   }
}
*/

void waitForIt(int x1, int y1, int x2, int y2)   // Draw a red frame while a button is touched
{
  myGLCD.setColor(255, 0, 0);
  myGLCD.drawRoundRect (x1, y1, x2, y2);
  waitForTouchRelease();
  myGLCD.setColor(255, 255, 255);
  myGLCD.drawRoundRect (x1, y1, x2, y2);
}

void waitForIt_Wo_Touch(int x1, int y1, int x2, int y2)   // Draw a red frame while a button is touched
{
  myGLCD.setColor(255, 0, 0);
  myGLCD.drawRoundRect (x1, y1, x2, y2);
//waitForTouchRelease();
  delay(150);
  myGLCD.setColor(255, 255, 255);
  myGLCD.drawRoundRect (x1, y1, x2, y2);
}
/**************************** END OF PRIMARY BUTTONS **********************************/


/********************************* EEPROM FUNCTIONS ***********************************/


struct config_t
{
  int tempset;
  int tempFset;
  int tempoff;
  int tempFoff;
  int tempalarm;
  int tempFalarm;
  int tempSoundAlarmC;
  int tempSoundAlarmF;
} tempSettings;

struct config_m
{
  int MinI_t;
  int MaxI_t;
} MinMaxIsettings;

struct config_L
{
  int DimLEDsOnOff;
  int LEDsDimTempC;
  int LEDsDimTempF;  
  int LEDsDimPercent;
} LEDsFailsafeSettings;

struct config_w
{
  int waveMode;
  int altPump1m;
  int altPump1s;  
  int altPump2m;
  int altPump2s;
  int synchMode;
  int synchPumpOnM;
  int synchPumpOnS; 
  int synchPumpOffM;  
  int synchPumpOffS;
} WAVEsettings;

struct config_g
{
  int calendarFormat;
  int ShowHideDOW;
  int timeFormat;
  int tempScale;
  int Heatsink1FanTempC;
  int Heatsink1FanTempF;
  int Heatsink2FanTempC;
  int Heatsink2FanTempF;
  int SCREENsaverONOFF;
  int ScreensaverBrigthnessCount;
  int ScreensaverClockType;
  int ScreensaverTimer;
  int MAX_Temp_on_off;
  int SoftStartON;
  int AlarmLevel;
  int ScreenLock;
} GENERALsettings;

struct config_f
{
  int feedFish1h;
  int feedFish1m;
  int feedFish2h;
  int feedFish2m;
  int feedFish3h;
  int feedFish3m;
  int feedFish4h;
  int feedFish4m;
  int feedTime1;
  int feedTime2;
  int feedTime3;
  int feedTime4;  
} FEEDERsettings;

struct config_preset
{
  byte tvcol_out;
  byte rcol_out;
  byte wcol_out;
  byte bcol_out;
  byte rbcol_out;
  byte uvcol_out;
  byte cycol_out;
  byte yelcol_out;
} LedPresetSetting;

void EraseAllEEPROM_SaveDefault()  //check memory for my code format #oleg
{
 int k = EEPROM.read(0);
 if (k!=127) {
 myGLCD.setColor(0, 0, 0);
 setFont(SMALL, 255, 0, 0, 0, 0, 0);
 myGLCD.print(print_text[11], CENTER, 120); // "Please WAIT, cleaning memory"
 for (int i = 0; i < 4095; i++)
      {EEPROM.write(i, 0); 
 if (i ==0) {EEPROM.write(0,127);}
      if ((i==0)|| (i==512)|| (i==1024)||(i==1536)||(i==2048)||(i==2560)||(i==3072)||(i==3584)||(i==4094))
	  {myGLCD.printNumI(i, CENTER, 140); }
      }
   COLOR=0;
   SaveLEDToEEPROM();        // save default
   EEPROM.write(780, 0xFF);  // enable all led channel

//******* set some values to default ***********************
 setTempC= 26;
 setTempF =78.8;  
 offTempC=offTempF= 0.2;
 alarmTempC=alarmTempF= 4;
 setTempToSoundAlarmC=setTempToSoundAlarmF= 4;
 setTempToBeginHeatsink1FanC=setTempToBeginHeatsink1FanF =30;
 setTempToBeginHeatsink2FanC=setTempToBeginHeatsink2FanF =30;
 setTempToSoundAlarmC=60;
 setTempToSoundAlarmF=140;
 MinI = 20;  // minimum moon brightness
 MaxI = 80;  // maximum moon brightness
 
 SaveMoonLEDToEEPROM();
 SaveGenSetsToEEPROM();
 SaveTempToEEPROM();
   }
}




void SaveLEDToEEPROM()           // COLOR=0, WHITE=1, BLUE=2, ROYAL=3,     
								 //	RED=4,   ULTRA=5, TV=6,   MOON=7, 
								 // CYAN=8, YELLOW=9;
{
	EEPROM.write(0, 127);         //to determine if data available in EEPROM, write to first byte "127"
	  if ((COLOR==1) || (COLOR==0)) {
         for (int i=1; i<97; i++) 
		 { EEPROM.write(i+(96*0), wled[i-1]);} // xled[] address must be from 1 to 96
        }
       if ((COLOR==2) || (COLOR==0)) {
         for (int i=1; i<97; i++) 
		 { EEPROM.write(i+(96*1), bled[i-1]);} // xled[] address must be from 1 to 96
 		} 
	   if ((COLOR==3) || (COLOR==0)) {
         for (int i=1; i<97; i++)
		 {EEPROM.write(i+(96*2), rbled[i-1]);}
        }
       if ((COLOR==4) || (COLOR==0)) {
         for (int i=1; i<97; i++) 
		 {EEPROM.write(i+(96*3), rled[i-1]);}
        }  
       if ((COLOR==5) || (COLOR==0)) {
         for (int i=1; i<97; i++) 
		 {EEPROM.write(i+(96*4), uvled[i-1]);}
        }
       if ((COLOR==6) || (COLOR==0)) {
         for (int i=1; i<97; i++) 
		 {EEPROM.write(i+(96*5), tvled[i-1]);}
        }
	   if ((COLOR==8) || (COLOR==0)) {
         for (int i=1; i<97; i++) 
		 {EEPROM.write(i+(96*6), cyled[i-1]);}
        }
	   if ((COLOR==9) || (COLOR==0)) {
         for (int i=1; i<97; i++) 
		 {EEPROM.write(i+(96*7), yeled[i-1]);}
        }
//	   if (COLOR==0) {EEPROM.write(780, 0xFF);} // LedShannelStatusByte = 0xFF, all channel is ON  
//	   EEPROM.write(780, LedShannelStatusByte);
}


void SaveOnOffLedStatus(boolean LedShannelFlag_on_off= false)
{    if (LedShannelFlag_on_off == true)  
       {if (COLOR==1) {bitSet(LedShannelStatusByte,0); } 
        if (COLOR==2) {bitSet(LedShannelStatusByte,1); } 
        if (COLOR==3) {bitSet(LedShannelStatusByte,2); } 
        if (COLOR==4) {bitSet(LedShannelStatusByte,3); }
		if (COLOR==5) {bitSet(LedShannelStatusByte,4); } 
		if (COLOR==6) {bitSet(LedShannelStatusByte,5); } 
		if (COLOR==8) {bitSet(LedShannelStatusByte,6); } 
		if (COLOR==9) {bitSet(LedShannelStatusByte,7); } 
        } else
        {if (COLOR==1) {bitClear(LedShannelStatusByte,0);} 
         if (COLOR==2) {bitClear(LedShannelStatusByte,1); } 
         if (COLOR==3) {bitClear(LedShannelStatusByte,2); } 
		 if (COLOR==4) {bitClear(LedShannelStatusByte,3); }
		 if (COLOR==5) {bitClear(LedShannelStatusByte,4); } 
         if (COLOR==6) {bitClear(LedShannelStatusByte,5); } 
		 if (COLOR==8) {bitClear(LedShannelStatusByte,6); }
		 if (COLOR==9) {bitClear(LedShannelStatusByte,7); }
		} 
		EEPROM.write(780, LedShannelStatusByte);
}


void ReadOnOffLedStatus() // if reader bit =0 LedShannelFlag_on_off = false, else LedShannelFlag_on_off = true;
{ 		if (COLOR==1) {LedShannelFlag_on_off = bitRead(LedShannelStatusByte,0); } 
        if (COLOR==2) {LedShannelFlag_on_off = bitRead(LedShannelStatusByte,1); } 
        if (COLOR==3) {LedShannelFlag_on_off = bitRead(LedShannelStatusByte,2); } 
        if (COLOR==4) {LedShannelFlag_on_off = bitRead(LedShannelStatusByte,3); }
		if (COLOR==5) {LedShannelFlag_on_off = bitRead(LedShannelStatusByte,4); } 
		if (COLOR==6) {LedShannelFlag_on_off = bitRead(LedShannelStatusByte,5); } 
		if (COLOR==8) {LedShannelFlag_on_off = bitRead(LedShannelStatusByte,6); } 
		if (COLOR==9) {LedShannelFlag_on_off = bitRead(LedShannelStatusByte,7); }
}

void SaveMoonLEDToEEPROM() // shift all bytes on 200
{
  MinMaxIsettings.MinI_t = int(MinI);
  MinMaxIsettings.MaxI_t = int(MaxI);
  EEPROM_writeAnything(600+200, MinMaxIsettings);
}

void SaveLEDsFailsafeToEEPROM()
{
  LEDsFailsafeSettings.DimLEDsOnOff = int(setDimLEDsOnOff);
  LEDsFailsafeSettings.LEDsDimTempC = int(setLEDsDimTempC);
  LEDsFailsafeSettings.LEDsDimTempF = int(setLEDsDimTempF);  
  LEDsFailsafeSettings.LEDsDimPercent = int(setLEDsDimPercent);
  EEPROM_writeAnything(610+200, LEDsFailsafeSettings);  
}

void SaveWaveToEEPROM()
{
  WAVEsettings.waveMode = int(WAVE);
  WAVEsettings.altPump1m = int(Pump1m);
  WAVEsettings.altPump1s = int(Pump1s);  
  WAVEsettings.altPump2m = int(Pump2m);
  WAVEsettings.altPump2s = int(Pump2s);  
  WAVEsettings.synchMode = int(Synch);
  WAVEsettings.synchPumpOnM = int(OnForTm);
  WAVEsettings.synchPumpOnS = int(OnForTs);  
  WAVEsettings.synchPumpOffM = int(OffForTm);
  WAVEsettings.synchPumpOffS = int(OffForTs);  
  EEPROM_writeAnything(620+200, WAVEsettings);
}

void SaveTempToEEPROM()
{
  tempSettings.tempset = int(setTempC*10);
  tempSettings.tempFset = int(setTempF*10);  
  tempSettings.tempoff = int(offTempC*10);
  tempSettings.tempFoff = int(offTempF*10);  
  tempSettings.tempalarm = int(alarmTempC*10);
  tempSettings.tempFalarm = int(alarmTempF*10);
  tempSettings.tempSoundAlarmC =  int (setTempToSoundAlarmC);
  tempSettings.tempSoundAlarmF =  int (setTempToSoundAlarmF);
  EEPROM_writeAnything(640+200, tempSettings);
}

void SaveGenSetsToEEPROM()
{
  GENERALsettings.calendarFormat = int(setCalendarFormat);
  GENERALsettings.ShowHideDOW = int(displayDOW);
  GENERALsettings.timeFormat = int(setTimeFormat);
  GENERALsettings.tempScale = int(setTempScale);
  GENERALsettings.Heatsink1FanTempC = int(setTempToBeginHeatsink1FanC*10); 
  GENERALsettings.Heatsink1FanTempF = int(setTempToBeginHeatsink1FanF*10); 
  GENERALsettings.Heatsink2FanTempC = int(setTempToBeginHeatsink2FanC*10);  
  GENERALsettings.Heatsink2FanTempF = int(setTempToBeginHeatsink2FanF*10);  
  GENERALsettings.SCREENsaverONOFF = int(setScreensaverOnOff);
  GENERALsettings.ScreensaverBrigthnessCount = int(BrigthnessCount);      
  GENERALsettings.ScreensaverClockType = int(ClockType);    
  GENERALsettings.ScreensaverTimer = int(setSSmintues);    
  GENERALsettings.MAX_Temp_on_off = int(MAX_Temp_on_off);
  GENERALsettings.SoftStartON = int(SoftStartON);
  GENERALsettings.AlarmLevel = int(AlarmLevel);
  GENERALsettings.ScreenLock = int(setLockScreen);
  EEPROM_writeAnything(660+200, GENERALsettings);
}

void SaveFeedTimesToEEPROM()
{
  FEEDERsettings.feedFish1h = int(feedFish1H);
  FEEDERsettings.feedFish1m = int(feedFish1M);  
  FEEDERsettings.feedFish2h = int(feedFish2H);
  FEEDERsettings.feedFish2m = int(feedFish2M);  
  FEEDERsettings.feedFish3h = int(feedFish3H);
  FEEDERsettings.feedFish3m = int(feedFish3M);  
  FEEDERsettings.feedFish4h = int(feedFish4H);
  FEEDERsettings.feedFish4m = int(feedFish4M);
  FEEDERsettings.feedTime1 = int(FEEDTime1);  
  FEEDERsettings.feedTime2 = int(FEEDTime2);  
  FEEDERsettings.feedTime3 = int(FEEDTime3);  
  FEEDERsettings.feedTime4 = int(FEEDTime4);    
  EEPROM_writeAnything(680+200, FEEDERsettings);
}


void SaveDallasAddress ()
{
for (byte i = 0; i < 8; i++)
{ EEPROM.write(900+i, Heatsink1Thermometer [i]);  // sensor address
  EEPROM.write(900+i+9, Heatsink2Thermometer [i]);
  EEPROM.write(900+i+18, waterThermometer [i]);
 }
  EEPROM.write(900+8, counterB1);			 // config byte	
  EEPROM.write(900+17, counterB2);
  EEPROM.write(900+26, counterB3);
}

void SaveLEDPresetToEEPROM()
{
  LedPresetSetting.wcol_out = wcol_out;
  LedPresetSetting.bcol_out = bcol_out;
  LedPresetSetting.rbcol_out = rbcol_out;  
  LedPresetSetting.rcol_out =  rcol_out;
  LedPresetSetting.uvcol_out = uvcol_out;
  LedPresetSetting.tvcol_out = tvcol_out;
  LedPresetSetting.cycol_out = cycol_out;  
  LedPresetSetting.yelcol_out = yelcol_out;
  EEPROM_writeAnything(1000 + AddressShift, LedPresetSetting);  
}

void ReadLEDPresetFromEEPROM()
{
  EEPROM_readAnything(1000 + AddressShift, LedPresetSetting);
  wcol_out = LedPresetSetting.wcol_out;
  bcol_out = LedPresetSetting.bcol_out;
  rbcol_out = LedPresetSetting.rbcol_out;
  rcol_out = LedPresetSetting.rcol_out; 
  uvcol_out = LedPresetSetting.uvcol_out;
  tvcol_out = LedPresetSetting.tvcol_out;
  cycol_out= LedPresetSetting.cycol_out;
  yelcol_out = LedPresetSetting.yelcol_out;
}



void ReadLedFromEEPROM()
								 // COLOR=0 - read all colours 
								 // WHITE=1, BLUE=2, ROYAL=3, RED=4,
								 //	ULTRA=5, TV=6, MOON=7;
								 // CYAN=8,  YELLOW=9
{ 
  byte k = EEPROM.read(0);
  int Temp;
  if (k==127) {
	   if ((COLOR==1) || (COLOR==0)) { 
	      for (byte i=1; i<97; i++) 
		 { Temp = EEPROM.read(i+(96*0));
		  if (Temp >100) {Temp = 100;} 	 
			 wled[i-1] = Temp;} 
        }
       if ((COLOR==2) || (COLOR==0)) {
         for (byte i=1; i<97; i++) 
		  { Temp = EEPROM.read(i+(96*1));
		  if (Temp >100) {Temp = 100;} 	 
			 bled[i-1] = Temp;} 
 		} 
	   if ((COLOR==3) || (COLOR==0)) {
         for (byte i=1; i<97; i++) 
		 { Temp = EEPROM.read(i+(96*2));
		  if (Temp >100) {Temp = 100;} 	 
			 rbled[i-1] = Temp;} 
        }
       if ((COLOR==4) || (COLOR==0)) {
         for (byte i=1; i<97; i++) 
 		 { Temp = EEPROM.read(i+(96*3));
		  if (Temp >100) {Temp = 100;} 	 
			 rled[i-1] = Temp;}  
        }  
       if ((COLOR==5) || (COLOR==0)) {
         for (byte i=1; i<97; i++) 
 		 { Temp = EEPROM.read(i+(96*4));
		  if (Temp >100) {Temp = 100;} 	 
		     uvled[i-1] = Temp;} 
        }
       if ((COLOR==6) || (COLOR==0)) {
         for (byte i=1; i<97; i++) 
 		 { Temp = EEPROM.read(i+(96*5));
		  if (Temp >100) {Temp = 100;} 	 
		     tvled[i-1] = Temp;} 
        }
	   if ((COLOR==8) || (COLOR==0)) {
         for (byte i=1; i<97; i++) 
 		 { Temp = EEPROM.read(i+(96*6));
		  if (Temp >100) {Temp = 100;} 	 
			 cyled[i-1] = Temp;} 
	     }
       if ((COLOR==9) || (COLOR==0)) {
         for (byte i=1; i<97; i++) 
 		 { Temp = EEPROM.read(i+(96*7));
		  if (Temp >100) {Temp = 100;} 	 
			 yeled[i-1] = Temp;} 
		 }
      if ((COLOR==7) || (COLOR==0)) {
         EEPROM_readAnything(600+200, MinMaxIsettings);     // read moon values 200bytes shift for new colours
         MinI = MinMaxIsettings.MinI_t;
	    if ( MinI>100 ) {MinI= 10;}            // set default = 10   
         MaxI = MinMaxIsettings.MaxI_t;
		 if ( MaxI>100 ) {MaxI= 90;}           // set default = 90   
		  }
	  LedShannelStatusByte = EEPROM.read(780);
   }

  EEPROM_readAnything(610+200, LEDsFailsafeSettings);       
  setDimLEDsOnOff = LEDsFailsafeSettings.DimLEDsOnOff;      
  if (setDimLEDsOnOff >1) {setDimLEDsOnOff=1;}									   // set default = 1
  setLEDsDimTempC = LEDsFailsafeSettings.LEDsDimTempC;
  if ( setLEDsDimTempC>99 || setLEDsDimTempC<40 ) {setLEDsDimTempC=50;}            // set default = 50C   
  setLEDsDimTempF = LEDsFailsafeSettings.LEDsDimTempF;  
  if ( setLEDsDimTempF>210 || setLEDsDimTempF<104) {setLEDsDimTempF=122;}          // set default = 122F   
  setLEDsDimPercent = LEDsFailsafeSettings.LEDsDimPercent;
  if ( setLEDsDimPercent>80 || setLEDsDimPercent<10 ) {setLEDsDimPercent=50;}      // set default = 50%  
}


void ReadFromEEPROM()   // read from eeprom all data exclude LED SETTING
{
  int k = EEPROM.read(0);
  char tempString[3];

  EEPROM_readAnything(620+200, WAVEsettings);  
  WAVE = WAVEsettings.waveMode;
  if (WAVE <0 || WAVE >4) {WAVE=0;}  // set default = 0 all OFF
  Pump1m = WAVEsettings.altPump1m;
  Pump1s = WAVEsettings.altPump1s;
  Pump2m = WAVEsettings.altPump2m;
  Pump2s = WAVEsettings.altPump2s;
  Synch = WAVEsettings.synchMode;
  OnForTm = WAVEsettings.synchPumpOnM;
  OnForTs = WAVEsettings.synchPumpOnS;
  OffForTm = WAVEsettings.synchPumpOffM;
  OffForTs = WAVEsettings.synchPumpOffS;

 // all these default set if error reading from eeprom  
  EEPROM_readAnything(640+200, tempSettings);  
  setTempC = tempSettings.tempset;
  setTempC /=10;
  if (setTempC <10 || setTempC >40) {setTempC=26.0;} // set default = 26 C
  setTempF = tempSettings.tempFset;
  setTempF /=10;  
  if (setTempF <50 || setTempF >104) {setTempF=78.8;} // set default = 78.8 F
  offTempC = tempSettings.tempoff;
  offTempC /=10;
  if (offTempC <0 || offTempC >5) {offTempC=1.0;} // set default = 1 C
  offTempF = tempSettings.tempFoff;
  offTempF /=10;  
  if (offTempF <32 || offTempF >41) {offTempF=33.8;} // set default = 33.8 F
  alarmTempC = tempSettings.tempalarm;
  alarmTempC /= 10;
  if (alarmTempC == 255) {alarmTempC = 255;}
  else { if (alarmTempC <0 || alarmTempC >9.9) {alarmTempC=5.0;}} // set default = 5 C
  alarmTempF = tempSettings.tempFalarm;
  alarmTempF /= 10;
  if (alarmTempF == 255) {alarmTempF = 255;}
  else {if (alarmTempF <32 || alarmTempF >49.8) {alarmTempF=41.0;}} // set default = 41 F
  setTempToSoundAlarmC = tempSettings.tempSoundAlarmC;
     if (setTempToSoundAlarmC ==255) {setTempToSoundAlarmC = 255;}   // Sound is OFF
	 else {
		 if (setTempToSoundAlarmC <40 || setTempToSoundAlarmC >99) {setTempToSoundAlarmC=50;}} // set default = 50 C
  setTempToSoundAlarmF = tempSettings.tempSoundAlarmF;
        if (setTempToSoundAlarmF ==255) {setTempToSoundAlarmC = 255;}          // OFF alarm
	 else {
		 if (setTempToSoundAlarmF <104 || setTempToSoundAlarmF >210) {setTempToSoundAlarmF=122;}} // set default = 122 F
  
  
  EEPROM_readAnything(660+200, GENERALsettings);
  setCalendarFormat = GENERALsettings.calendarFormat;               //DD/MM/YYYY=0 || Month DD, YYYY=1 (change in prog)
  if (setCalendarFormat >1) {setCalendarFormat=0;}					// set default = DD/MM/YYYY
  displayDOW = GENERALsettings.ShowHideDOW;						    //Hide=0 || Show=1 (change in prog)	
  if (displayDOW >1) {displayDOW=1;}								// set default = 1
  setTimeFormat = GENERALsettings.timeFormat;					    //24HR=0 || 12HR=1 (change in prog)	
  if (setTimeFormat >1 ) {setTimeFormat=0;}							// set default = 0
  setTempScale = GENERALsettings.tempScale;
  if (setTempScale >1) {setTempScale=0;}							// Celsius=0 || Fahrenheit=1 -C, set default =0 if eeprom error 
  setTempToBeginHeatsink1FanC = GENERALsettings.Heatsink1FanTempC;
  setTempToBeginHeatsink1FanC /= 10;
  if (setTempToBeginHeatsink1FanC <20 || setTempToBeginHeatsink1FanC >50) {setTempToBeginHeatsink1FanC=29.0;} // set default = 29 C
  setTempToBeginHeatsink1FanF = GENERALsettings.Heatsink1FanTempF;
  setTempToBeginHeatsink1FanF /= 10;
  if (setTempToBeginHeatsink1FanF <68 || setTempToBeginHeatsink1FanF >122) {setTempToBeginHeatsink1FanF=84.2;} // set default = 84.2F

  setTempToBeginHeatsink2FanC = GENERALsettings.Heatsink2FanTempC;  
  setTempToBeginHeatsink2FanC /= 10;
  if (setTempToBeginHeatsink2FanC <20 || setTempToBeginHeatsink2FanC >50) {setTempToBeginHeatsink2FanC=29.0;} // set default = 29 C
  setTempToBeginHeatsink2FanF = GENERALsettings.Heatsink2FanTempF;  
  setTempToBeginHeatsink2FanF /= 10;
  if (setTempToBeginHeatsink2FanF <68 || setTempToBeginHeatsink2FanF >122) {setTempToBeginHeatsink2FanF=84.2;} // set default = 84.2F
  setScreensaverOnOff = GENERALsettings.SCREENsaverONOFF;				 //OFF=0 || ON=1 
  if (setScreensaverOnOff >1) {setScreensaverOnOff=1;} 
  BrigthnessCount = GENERALsettings.ScreensaverBrigthnessCount;         
  if (BrigthnessCount >4) {BrigthnessCount=4;}
  if (BrigthnessCount <0) {BrigthnessCount=4;}
  ClockType = GENERALsettings.ScreensaverClockType;   				//ClockType = 0/1/2/3/ -> Blank/An.Clock/Dig.Clock/Temperature
  if (ClockType >3) {ClockType=1;} 
  setSSmintues = GENERALsettings.ScreensaverTimer;					 // 	
  if (setSSmintues <1 || setSSmintues >99) {setSSmintues=20;}		 // 1....99 min
 MAX_Temp_on_off = GENERALsettings.MAX_Temp_on_off;				 //OFF=0 || ON=1
  if (MAX_Temp_on_off >1) {MAX_Temp_on_off=1;} 
  SoftStartON = GENERALsettings.SoftStartON;					     //OFF=0 || ON=1
  if (SoftStartON >1) {SoftStartON=1;}
  AlarmLevel = GENERALsettings.AlarmLevel;						     //All OFF=0, OverHeat=1, All ON=2
  if (AlarmLevel >2) {AlarmLevel=0;} 
  setLockScreen = GENERALsettings.ScreenLock;						 //OFF=0 || ON=1
  if (setLockScreen >1) {setLockScreen=1;}
  
       
  EEPROM_readAnything(680+200, FEEDERsettings);  
  feedFish1H = FEEDERsettings.feedFish1h;
  if (feedFish1H >24) {feedFish1H=20;}		    // 0....24 h
  feedFish1M = FEEDERsettings.feedFish1m;  
  if (feedFish1M >60) {feedFish1M=0;}		    // 0....60 min
  feedFish2H = FEEDERsettings.feedFish2h;
  if (feedFish2H >24) {feedFish2H=20;}		    // 0....24 h
  feedFish2M = FEEDERsettings.feedFish2m;  
  if (feedFish2M >60) {feedFish2M=0;}		    // 0....60 min
  feedFish3H = FEEDERsettings.feedFish3h;
  if (feedFish3H >24) {feedFish3H=20;}		    // 0....24 h
  feedFish3M = FEEDERsettings.feedFish3m;  
  if (feedFish3M >60) {feedFish3M=0;}		    // 0....60 min
  feedFish4H = FEEDERsettings.feedFish4h;
  if (feedFish4H >24) {feedFish4H=20;}		    // 0....24 h
  feedFish4M = FEEDERsettings.feedFish4m;
  if (feedFish4M >60) {feedFish4M=0;}		    // 0....60 min
  FEEDTime1 = FEEDERsettings.feedTime1;
  if (FEEDTime1 >1) {FEEDTime1=0;} 
  FEEDTime2 = FEEDERsettings.feedTime2;
  if (FEEDTime2 >1) {FEEDTime2=0;} 
  FEEDTime3 = FEEDERsettings.feedTime3;
  if (FEEDTime3 >1) {FEEDTime3=0;} 
  FEEDTime4 = FEEDERsettings.feedTime4;  
  if (FEEDTime4 >1) {FEEDTime4=0;} 
}

void ReadDallasAddress ()
{
for (byte i = 0; i < 8; i++)
{ Heatsink1Thermometer [i] = EEPROM.read(900+i);   // sensor address
  Heatsink2Thermometer [i] = EEPROM.read(900+i+9);
  waterThermometer [i] = EEPROM.read(900+i+18);
 }
  counterB1 = EEPROM.read(900+8);			// config byte
  counterB2 = EEPROM.read(900+17);
  counterB3 = EEPROM.read(900+26);
}

/***************************** END OF EEPROM FUNCTIONS ********************************/


/********************************** RTC FUNCTIONS *************************************/
void TimeDateBar(boolean refreshAll=false)
{
  int Hour12;
//  String ampm;
  t = rtc.getTime();
  
  //Date
  setFont(SMALL, 255, 255, 0, 64, 64, 64);
  if ((setCalendarFormat==0) && (displayDOW==1))
    { myGLCD.print("  ", 48, 227);
     myGLCD.print(rtc.getDateStr(FORMAT_LONG, FORMAT_LITTLEENDIAN, '/'), 56, 227);
      myGLCD.print("  ", 136, 227);
      t.dow=calcDOW(t.date, t.mon, t.year);          
      showDOWonBar(t.dow); 
    }
  if ((setCalendarFormat==1) && (displayDOW==1))  
    { myGLCD.print(rtc.getMonthStr(FORMAT_SHORT), 56, 227);    //3 letter Month
      myGLCD.print(" ", 80, 227);
      myGLCD.printNumI(t.date, 88, 227);
      if (t.date<10)
        { myGLCD.print(", ", 96, 227);
          myGLCD.printNumI(t.year, 112, 227);
          myGLCD.print("   ", 144, 227);}          
      else
        { myGLCD.print(", ", 104, 227);
          myGLCD.printNumI(t.year, 120, 227);
          myGLCD.print("   ", 152, 227);
        }
      t.dow=calcDOW(t.date, t.mon, t.year);          
      showDOWonBar(t.dow);        
    }
  if ((setCalendarFormat==0) && (displayDOW==0))
    { myGLCD.print("    ", 13, 227);
    myGLCD.print(rtc.getDateStr(FORMAT_LONG, FORMAT_LITTLEENDIAN, '/'), 45, 227);
      myGLCD.print("   ", 125, 227);}
  if ((setCalendarFormat==1) && (displayDOW==0))
    { myGLCD.print("    ", 5, 227);      
      myGLCD.print(rtc.getMonthStr(FORMAT_SHORT), 37, 227);    //3 letter Month
      myGLCD.print(" ", 61, 227);    
      myGLCD.printNumI(t.date, 69, 227);
      if (t.date<10)
        { myGLCD.print(", ", 77, 227);
          myGLCD.printNumI(t.year, 93, 227);
          myGLCD.print("   ", 125, 227);}          
      else
        { myGLCD.print(", ", 85, 227);
          myGLCD.printNumI(t.year, 101, 227);
          myGLCD.print("   ", 133, 227);
        }
    }

  //Time
  if (setTimeFormat==1) 
  {
// if(t.hour < 12){ ampm= " AM  "; }                        //Adding the AM/PM sufffix
//      else { ampm= " PM  "; }

  if(t.hour < 12){ myGLCD.print(" AM  ", 260, 227);}                        //Adding the AM/PM sufffix
      else {myGLCD.print(" PM  ", 260, 227);}

      if (t.hour==0) { Hour12 = 12; }                          //12 HR Format
        else {
          if (t.hour>12) { Hour12 = t.hour-12; }
            else { Hour12 = t.hour; }}

      if (Hour12<10)
        { myGLCD.print(" ", 220, 227);
          myGLCD.printNumI(Hour12, 228, 227);}
      else
        { myGLCD.printNumI(Hour12, 220, 227);}
      myGLCD.print(":", 236, 227);
      if (t.min<10)
        { myGLCD.printNumI(0, 244, 227);
          myGLCD.printNumI(t.min, 252, 227);}
      else
        { myGLCD.printNumI(t.min, 244, 227);}
//      myGLCD.print(ampm, 260, 227);
    }
  else
    { myGLCD.print(rtc.getTimeStr(FORMAT_SHORT), 220, 227);    //24 HR Format
      myGLCD.print("    ", 260, 227);}
}


byte calcDOW(byte d, byte m, int y)
{
  int dow;
  byte mArr[12] = {6,2,2,5,0,3,5,1,4,6,2,4};
  
  dow = (y % 100);
  dow = dow*1.25;
  dow += d;
  dow += mArr[m-1];
  if (((y % 4)==0) && (m<3))
    dow -= 1;
  while (dow>7)
    dow -= 7;
    
  return dow;
}

void showDOW_ScreenSaver(byte dow) // show day of week on screensaver
{
  char* str[] = {"MON","TUE","WED","THU","FRI","SAT","SUN"};
  
  setFont(SMALL, 200, 200, 200, 0, 0, 0);   // blue on black
  myGLCD.print(str[dow-1], SS_DOW_x, 157);
}

void showDOW(byte dow) // show day of week on menu setting time/date 
{
  char* str[] = {"MON","TUE","WED","THU","FRI","SAT","SUN"};
  setFont(SMALL, 255, 255, 255, 0, 0, 0);   // white on black
  myGLCD.print("         ", 17, 178);
  myGLCD.print(str[dow-1], 41, 178);
}


void showDOWonBar(byte dow) // show day of week on main windows bottom string 
{
  char* str[] = {"MON,","TUE,","WED,","THU,","FRI,","SAT,","SUN,"};
  myGLCD.print(str[dow-1], 16, 227);  // yellow on gray
}

byte validateDate(byte d, byte m, word y)
{
  byte mArr[12] = {31,0,31,30,31,30,31,31,30,31,30,31};
  byte od;
  
  if (m==2)
  { if ((y % 4)==0)
    { if (d==30)
        od=1;
      else if (d==0)
        od=29;
      else
        od=d;
    }
    else
    { if (d==29)
        od=1;
      else if (d==0)
        od=28;
      else
        od=d;
    }
  }
  else
  { if (d==0)
      od=mArr[m-1];
    else if (d==(mArr[m-1]+1))
      od=1;
    else
      od=d;
  }
  return od;
}


byte validateDateForMonth(byte d, byte m, word y)
{
  byte mArr[12] = {31,0,31,30,31,30,31,31,30,31,30,31};
  byte od;
  boolean dc=false;
  
  if (m==2)
  { if ((y % 4)==0)
    { if (d>29)
      { d=29;}
    }
    else
    { if (d>28)
      { d=28;}
    }
  }
  else
  { if (d>mArr[m-1])
    { d=mArr[m-1];}
  }
  return d;
}
/********************************* END OF RTC FUNCTIONS *******************************/

#ifdef Timers_11bit
/************************************* Calculate LED LEVELS 8/11 bit ******************/
void LED_levels_output()
{
  int sector, sstep, t1, t2 ;

  if (colorLEDtest==true) 
    {
     tvled_out = map(tvcol_out, 0, 100, 0, ResolutionHigh); // new value 0-100%, 
	 rbled_out = map(rbcol_out, 0, 100, 0, ResolutionHigh); 
     uvled_out = map(uvcol_out, 0, 100, 0, ResolutionHigh);
     rled_out = map(rcol_out, 0, 100, 0, ResolutionHigh); // ResolutionHigh = 2000
     wled_out = map(wcol_out, 0, 100, 0, ResolutionHigh); 
     bled_out = map(bcol_out, 0, 100, 0, ResolutionHigh);
     cyled_out = map(cycol_out, 0, 100, 0, ResolutionHigh);
     yeled_out = map(yelcol_out, 0, 100, 0, ResolutionHigh);	
     moonled_out = map(mooncol_out, 0, 100, 0, 255);
    } 
  else 
    {
     if (min_cnt>=1440) {min_cnt=1;}   // 24 hours of minutes 
     sector = min_cnt/15;              // divided by gives sector -- 15 minute
     sstep = min_cnt%15;               // remainder gives add on to sector value 
	 t1 =sector;
     if (t1==95) {t2=0;}
       else {t2 = t1+1;}

     if (sstep==0) 
       {
        tvled_out = map(tvled[t1],0, 100, 0, ResolutionHigh);  // new value 0-100%
		rbled_out = map(rbled[t1],0, 100, 0, ResolutionHigh);  // new value 0-100%
		uvled_out = map(uvled[t1],0, 100, 0, ResolutionHigh);  // new value 0-100%
		rled_out =  map(rled[t1],0, 100, 0, ResolutionHigh);  // new value 0-100% 
		wled_out =  map(wled[t1],0, 100, 0, ResolutionHigh);  // new value 0-100%
        bled_out =  map(bled[t1],0, 100, 0, ResolutionHigh);  // new value 0-100% 
		cyled_out = map(cyled[t1],0, 100, 0, ResolutionHigh);  // new value 0-100% 
        yeled_out = map(yeled[t1],0, 100, 0, ResolutionHigh);  // new value 0-100%
       } else 
          {
			  tvled_out  = check(tvled[t1]*20, tvled[t2]*20, sstep);
			  rbled_out  = check(rbled[t1]*20, rbled[t2]*20, sstep);
			  uvled_out  = check(uvled[t1]*20, uvled[t2]*20, sstep);
			  rled_out  = check(rled[t1]*20, rled[t2]*20, sstep);
			  wled_out  = check(wled[t1]*20, wled[t2]*20, sstep);
			  bled_out  = check(bled[t1]*20, bled[t2]*20, sstep);
			  cyled_out = check(cyled[t1]*20, cyled[t2]*20, sstep);	
              yeled_out = check(yeled[t1]*20, yeled[t2]*20, sstep);
		  }  

     float lunarCycle = moonPhase(t.year, t.mon, t.date);                 //get a value for the lunar cycle
	 moonled_out = map ((MinI *(1 - lunarCycle) + MaxI * lunarCycle + 0.5), 0, 100, 0, 255); //ResolutionLow = 255 for MOON
	}

   if (setDimLEDsOnOff==1) {HOT_LEDs();}  // 
   if (SoftStartON ==1) {Soft_Start_Led();}                      // increase led brigtness after start programm during 50sec
   
    wheaterDim ();

 if (clouDonOff ==1) {//wled_out = wled_out*PercentDimLW;
				tvled_out = PercentDimLW*tvled_out;
				bled_out =  PercentDimLW*bled_out;
				wled_out =  PercentDimLW*wled_out;
				rbled_out = PercentDimLW*rbled_out;
				rled_out =  PercentDimLW*rled_out;
				uvled_out = PercentDimLW*uvled_out;
				cyled_out = PercentDimLW*cyled_out;
				yeled_out = PercentDimLW*yeled_out;
  }


// check channel status ON/OFF
  if (bitRead(LedShannelStatusByte,0)== false) {wled_out=0;}     //  WHITE=1 (COLOR)  bit 0
  if (bitRead(LedShannelStatusByte,1)== false) {bled_out=0;}     //  BLUE=2  (COLOR)  bit 1
  if (bitRead(LedShannelStatusByte,2)== false) {rbled_out=0;}    //  ROYAL=3 (COLOR)  bit 2 
  if (bitRead(LedShannelStatusByte,3)== false) {rled_out=0;}     //  RED=4   (COLOR)  bit 3 
  if (bitRead(LedShannelStatusByte,4)== false) {uvled_out=0;}    //  ULTRA=5 (COLOR)  bit 4 
  if (bitRead(LedShannelStatusByte,5)== false) {tvled_out=0;}    //  TV=6    (COLOR)  bit 5 
  if (bitRead(LedShannelStatusByte,6)== false) {cyled_out=0;}    //  CYAN=8  (COLOR)  bit 6 
  if (bitRead(LedShannelStatusByte,7)== false) {yeled_out=0;}    //  YELLOW=9(COLOR)  bit 7
// end check	 	    


 if (RECOM_RCD) {
    rb_out = rbled_out;  // 11bit, 0-2000 value 
	uv_out = uvled_out;
	tv_out = tvled_out;
	r_out = rled_out;   
	w_out = wled_out;
    b_out = bled_out;
    cy_out = cyled_out;
    yel_out = yeled_out;
    moon_out = moonled_out;

  } else {
    rb_out = ResolutionHigh - rbled_out;
	uv_out = ResolutionHigh - uvled_out; 
	tv_out = ResolutionHigh - tvled_out;
 	r_out = ResolutionHigh - rled_out;
    w_out = ResolutionHigh - wled_out;
    b_out = ResolutionHigh - bled_out;
    cy_out = ResolutionHigh - cyled_out;
    yel_out = ResolutionHigh - yeled_out;
    moon_out = moonled_out;
  }

// if (clouDonOff ==1) {w_out = w_out*PercentDimLW;}


//----------- 11 bit PWM outputs ----------------------------------------

  if ( rb_out )   sbi_mix(TCCR4A, COM4B1);  else cbi_mix(TCCR4A, COM4B1); // T4B port 7
  if ( uv_out )   sbi_mix(TCCR3A, COM3C1);  else cbi_mix(TCCR3A, COM3C1); // T3C port 3
  if ( tv_out )   sbi_mix(TCCR4A, COM4C1);  else cbi_mix(TCCR4A, COM4C1); // T4C port 8
  if ( r_out )    sbi_mix(TCCR4A, COM4A1);  else cbi_mix(TCCR4A, COM4A1); // T4A port 6
  if ( w_out )    sbi_mix(TCCR1A, COM1B1);  else cbi_mix(TCCR1A, COM1B1); // T1B port 12
  if ( b_out )    sbi_mix(TCCR3A, COM3A1);  else cbi_mix(TCCR3A, COM3A1); // T3A port 5   
  if ( cy_out )   sbi_mix(TCCR3A, COM3B1);  else cbi_mix(TCCR3A, COM3B1); // T3B port 2      
  if ( yel_out )  sbi_mix(TCCR1A, COM1A1);  else cbi_mix(TCCR1A, COM1A1); // T1A port 11 

// ----------- reload Output Compare Register ---------------------------

  OCR4B = rb_out;       
  OCR3C = uv_out;		
  OCR4C = tv_out;       
  OCR4A = r_out;       
  OCR1B = w_out;		
  OCR3A = b_out;       
  OCR3B = cy_out;		
  OCR1A = yel_out;     

  analogWrite(ledPinMoon, moon_out); // 8 bit MOON PWM
//Serial.print ("w_out="); Serial.println (w_out);   //+

/*    
Serial.print ("rb_out="); Serial.println (rb_out);
Serial.print ("uv_out="); Serial.println (uv_out);
Serial.print ("tv_out="); Serial.println (tv_out);
Serial.print ("r_out="); Serial.println (r_out);
Serial.print ("w_out="); Serial.println (w_out);   //+
Serial.print ("b_out="); Serial.println (b_out);
Serial.print ("cy_out="); Serial.println (cy_out);
Serial.print ("yel_out="); Serial.println (yel_out); //+
Serial.print ("moon_out="); Serial.println (moon_out); //+
*/

}
#endif


#ifdef Timers_8_11bit
/************************************* Calculate LED LEVELS 8/11 bit ******************/
#ifdef Standard_shield
void LED_levels_output()
{
  int sector, sstep, t1, t2 ;

  if (colorLEDtest==true) 
    {
     tvled_out = map(tvcol_out, 0, 100, 0, ResolutionLow);    // new value 0-100%, ResolutionLow=255
	 rled_out = map(rcol_out, 0, 100, 0, ResolutionLow);      // 
	 moonled_out = map(mooncol_out, 0, 100, 0, ResolutionLow);

	 rbled_out = map(rbcol_out, 0, 100, 0, ResolutionHigh);   // new value 0-100%, ResolutionHigh=1990
     wled_out = map(wcol_out, 0, 100, 0, ResolutionHigh); 
	 bled_out = map(bcol_out, 0, 100, 0, ResolutionHigh);
     cyled_out = map(cycol_out, 0, 100, 0, ResolutionHigh);
    } 
  else 
    {
     if (min_cnt>=1440) {min_cnt=1;}   // 24 hours of minutes 
     sector = min_cnt/15;              // divided by gives sector -- 15 minute
     sstep = min_cnt%15;               // remainder gives add on to sector value 
	 t1 =sector;
     if (t1==95) {t2=0;}
       else {t2 = t1+1;}

     if (sstep==0) 
       {
        tvled_out = map(tvled[t1],0, 100, 0, ResolutionLow);  // new value 0-100%
		rled_out =  map(rled[t1],0, 100, 0, ResolutionLow);  // new value 0-100% 

		rbled_out = map(rbled[t1],0, 100, 0, ResolutionHigh);  // new value 0-100%
		wled_out =  map(wled[t1],0, 100, 0, ResolutionHigh);  // new value 0-100%
        bled_out =  map(bled[t1],0, 100, 0, ResolutionHigh);  // new value 0-100% 
		cyled_out = map(cyled[t1],0, 100, 0, ResolutionHigh);  // new value 0-100% 
       } else 
          {
			  tvled_out = check(map(tvled[t1],0, 100, 0, ResolutionLow), map(tvled[t2],0, 100, 0, ResolutionLow), sstep);
			  rled_out = check(map(rled[t1],0, 100, 0, ResolutionLow), map(rled[t2],0, 100, 0, ResolutionLow), sstep);
  			  
     		  rbled_out = check(rbled[t1]*20, rbled[t2]*20, sstep);
			  wled_out  = check(wled[t1]*20, wled[t2]*20, sstep);
			  bled_out  = check(bled[t1]*20, bled[t2]*20, sstep);
			  cyled_out = check(cyled[t1]*20, cyled[t2]*20, sstep);	
		  }  

     float lunarCycle = moonPhase(t.year, t.mon, t.date);                 //get a value for the lunar cycle
     moonled_out = map ((MinI *(1 - lunarCycle) + MaxI * lunarCycle + 0.5), 0, 100, 0, ResolutionLow);
	}

   if (setDimLEDsOnOff==1) {HOT_LEDs();}  // 
   if (SoftStartON ==1) {Soft_Start_Led();}                      // increase led brigtness after start programm during 50sec

// check channel status ON/OFF
  if (bitRead(LedShannelStatusByte,0)== false) {wled_out=0;}     //  WHITE=1 (COLOR)  bit 0
  if (bitRead(LedShannelStatusByte,1)== false) {bled_out=0;}     //  BLUE=2  (COLOR)  bit 1
  if (bitRead(LedShannelStatusByte,2)== false) {rbled_out=0;}    //  ROYAL=3 (COLOR)  bit 2 
  if (bitRead(LedShannelStatusByte,3)== false) {rled_out=0;}     //  RED=4   (COLOR)  bit 3 
  if (bitRead(LedShannelStatusByte,4)== false) {uvled_out=0;}    //  ULTRA=5 (COLOR)  bit 4 
  if (bitRead(LedShannelStatusByte,5)== false) {tvled_out=0;}    //  TV=6    (COLOR)  bit 5 
  if (bitRead(LedShannelStatusByte,6)== false) {cyled_out=0;}    //  CYAN=8  (COLOR)  bit 6 
  if (bitRead(LedShannelStatusByte,7)== false) {yeled_out=0;}    //  YELLOW=9(COLOR)  bit 7
// end check	 	    

 if (RECOM_RCD) {
    tv_out = tvled_out;
    r_out = rled_out;  // 8bit, 0-255 value 
    moon_out = moonled_out;

	rb_out = rbled_out;   // 11bit, 0-2000 value
	w_out = wled_out;
    b_out = bled_out;
    cy_out = cyled_out;

  } else {
    tv_out = ResolutionLow - tvled_out;
    r_out = ResolutionLow - rled_out;
	moon_out = moonled_out;
	
	rb_out = ResolutionHigh - rbled_out;
    w_out = ResolutionHigh - wled_out;
    b_out = ResolutionHigh - bled_out;
    cy_out = ResolutionHigh - cyled_out;
  }

 //----------- 8 bit PWM outputs --------------
  analogWrite(ledPinTV, tv_out); 
  analogWrite(ledPinRed, r_out);
  analogWrite(ledPinMoon, moon_out);

//----------- 11 bit PWM outputs ----------------------------------------
  if ( rb_out )   sbi_mix(TCCR1A, COM1A1);  else cbi_mix(TCCR1A, COM1A1);  // T1A port 11
  if ( w_out )    sbi_mix(TCCR1A, COM1B1);  else cbi_mix(TCCR1A, COM1B1);  // T1B port 12
  if ( b_out )    sbi_mix(TCCR4A, COM4B1);  else cbi_mix(TCCR4A, COM4B1);  // T4B port 7
  if ( cy_out )   sbi_mix(TCCR4A, COM4C1);  else cbi_mix(TCCR4A, COM4C1);  // T4C port 8
   
// ----------- reload Output Compare Register ---------------------------
  OCR1A = rb_out;     
  OCR1B = w_out;		
  OCR4B = b_out;       
  OCR4C = cy_out;       
}

#else
void LED_levels_output()
{
  int sector, sstep, t1, t2 ;

  if (colorLEDtest==true) 
    {
     tvled_out = map(tvcol_out, 0, 100, 0, ResolutionLow); // new value 0-100%, ResolutionLow=255  
	 rbled_out = map(rbcol_out, 0, 100, 0, ResolutionLow); 
     uvled_out = map(uvcol_out, 0, 100, 0, ResolutionLow);

     rled_out = map(rcol_out, 0, 100, 0, ResolutionHigh); // ResolutionHigh = 2000
     wled_out = map(wcol_out, 0, 100, 0, ResolutionHigh); 
     bled_out = map(bcol_out, 0, 100, 0, ResolutionHigh);
     cyled_out = map(cycol_out, 0, 100, 0, ResolutionHigh);
     yeled_out = map(yelcol_out, 0, 100, 0, ResolutionHigh);	
     moonled_out = map(mooncol_out, 0, 100, 0, ResolutionHigh);
    } 
  else 
    {
     if (min_cnt>=1440) {min_cnt=1;}   // 24 hours of minutes 
     sector = min_cnt/15;              // divided by gives sector -- 15 minute
     sstep = min_cnt%15;               // remainder gives add on to sector value 
	 t1 =sector;
     if (t1==95) {t2=0;}
       else {t2 = t1+1;}

     if (sstep==0) 
       {
        tvled_out = map(tvled[t1],0, 100, 0, ResolutionLow);  // new value 0-100%
		rbled_out = map(rbled[t1],0, 100, 0, ResolutionLow);  // new value 0-100%
		uvled_out = map(uvled[t1],0, 100, 0, ResolutionLow);  // new value 0-100%

		rled_out =  map(rled[t1],0, 100, 0, ResolutionHigh);  // new value 0-100% 
		wled_out =  map(wled[t1],0, 100, 0, ResolutionHigh);  // new value 0-100%
        bled_out =  map(bled[t1],0, 100, 0, ResolutionHigh);  // new value 0-100% 
		cyled_out = map(cyled[t1],0, 100, 0, ResolutionHigh);  // new value 0-100% 
        yeled_out = map(yeled[t1],0, 100, 0, ResolutionHigh);  // new value 0-100%
       } else 
          {
			  tvled_out = check(map(tvled[t1],0, 100, 0, ResolutionLow), map(tvled[t2],0, 100, 0, ResolutionLow), sstep);
			  rbled_out = check(map(rbled[t1],0, 100, 0, ResolutionLow), map(rbled[t2],0, 100, 0, ResolutionLow), sstep);
			  uvled_out = check(map(uvled[t1],0, 100, 0, ResolutionLow), map(uvled[t2],0, 100, 0, ResolutionLow), sstep);

			  rled_out  = check(rled[t1]*20, rled[t2]*20, sstep);
			  wled_out  = check(wled[t1]*20, wled[t2]*20, sstep);
			  bled_out  = check(bled[t1]*20, bled[t2]*20, sstep);
			  cyled_out = check(cyled[t1]*20, cyled[t2]*20, sstep);	
              yeled_out = check(yeled[t1]*20, yeled[t2]*20, sstep);
		  }  

     float lunarCycle = moonPhase(t.year, t.mon, t.date);                 //get a value for the lunar cycle
	 moonled_out = map ((MinI *(1 - lunarCycle) + MaxI * lunarCycle + 0.5), 0, 100, 0, ResolutionHigh);
	}

   if (setDimLEDsOnOff==1) {HOT_LEDs();}  // 
   if (SoftStartON ==1) {Soft_Start_Led();}                      // increase led brigtness after start programm during 50sec

// check channel status ON/OFF
  if (bitRead(LedShannelStatusByte,0)== false) {wled_out=0;}     //  WHITE=1 (COLOR)  bit 0
  if (bitRead(LedShannelStatusByte,1)== false) {bled_out=0;}     //  BLUE=2  (COLOR)  bit 1
  if (bitRead(LedShannelStatusByte,2)== false) {rbled_out=0;}    //  ROYAL=3 (COLOR)  bit 2 
  if (bitRead(LedShannelStatusByte,3)== false) {rled_out=0;}     //  RED=4   (COLOR)  bit 3 
  if (bitRead(LedShannelStatusByte,4)== false) {uvled_out=0;}    //  ULTRA=5 (COLOR)  bit 4 
  if (bitRead(LedShannelStatusByte,5)== false) {tvled_out=0;}    //  TV=6    (COLOR)  bit 5 
  if (bitRead(LedShannelStatusByte,6)== false) {cyled_out=0;}    //  CYAN=8  (COLOR)  bit 6 
  if (bitRead(LedShannelStatusByte,7)== false) {yeled_out=0;}    //  YELLOW=9(COLOR)  bit 7
// end check	 	    

 if (RECOM_RCD) {
    rb_out = rbled_out;  // 8bit, 0-255 value 
	uv_out = uvled_out;
	tv_out = tvled_out;

	r_out = rled_out;   // 11bit, 0-2000 value
	w_out = wled_out;
    b_out = bled_out;
    cy_out = cyled_out;
    yel_out = yeled_out;
    moon_out = moonled_out;

  } else {
    rb_out = ResolutionLow - rbled_out;
	uv_out = ResolutionLow - uvled_out; 
	tv_out = ResolutionLow - tvled_out;
    
	r_out = ResolutionHigh - rled_out;
    w_out = ResolutionHigh - wled_out;
    b_out = ResolutionHigh - bled_out;
    cy_out = ResolutionHigh - cyled_out;
    yel_out = ResolutionHigh - yeled_out;
    moon_out = moonled_out;
  }

 //----------- 8 bit PWM outputs --------------
  analogWrite(ledPinRoyBlue, rb_out); 
  analogWrite(ledPinUV, uv_out); 
  //  analogWrite(ledPinMoon, uv_out);   // for Pasha
  analogWrite(ledPinTV, tv_out); 
  
//----------- 11 bit PWM outputs ----------------------------------------
  if ( r_out )    sbi_mix(TCCR4A, COM4A1);  else cbi_mix(TCCR4A, COM4A1); 
  if ( w_out )    sbi_mix(TCCR1A, COM1B1);  else cbi_mix(TCCR1A, COM1B1);
  if ( b_out )    sbi_mix(TCCR3A, COM3A1);  else cbi_mix(TCCR3A, COM3A1);     
  if ( cy_out )   sbi_mix(TCCR3A, COM3B1);  else cbi_mix(TCCR3A, COM3B1);     
  if ( yel_out )  sbi_mix(TCCR1A, COM1A1);  else cbi_mix(TCCR1A, COM1A1);
  if ( moon_out ) sbi_mix(TCCR3A, COM3C1);  else cbi_mix(TCCR3A, COM3C1);     
// ----------- reload Output Compare Register ---------------------------

  OCR4A = r_out;       
  OCR1B = w_out;		
  OCR3A = b_out;       
  OCR3B = cy_out;		
  OCR1A = yel_out;     
  OCR3C = moon_out;     
}
#endif
#endif


#ifdef Timers_8bit
/************************************* LED LEVELS *************************************/
void LED_levels_output()
{
  int sector, sstep, t1, t2 ;
 
  if (colorLEDtest==true) 
    {
	 tvled_out = map(tvcol_out, 0, 100, 0, 255);  // new value 0-100%
     rled_out = map(rcol_out, 0, 100, 0, 255); 
     wled_out = map(wcol_out, 0, 100, 0, 255); 
     bled_out = map(bcol_out, 0, 100, 0, 255);
     rbled_out = map(rbcol_out, 0, 100, 0, 255); 
     uvled_out = map(uvcol_out, 0, 100, 0, 255);
	 cyled_out = map(cycol_out, 0, 100, 0, 255);
	 yeled_out = map(yelcol_out, 0, 100, 0, 255);	
     moonled_out = map(mooncol_out, 0, 100, 0, 255); 
    } 
  else 
    {
     if (min_cnt>=1440) {min_cnt=1;}   // 24 hours of minutes 
     sector = min_cnt/15;              // divided by gives sector -- 15 minute
     sstep = min_cnt%15;               // remainder gives add on to sector value 
	 t1 =sector;
     if (t1==95) {t2=0;}
       else {t2 = t1+1;}

     if (sstep==0) 
       {
        tvled_out =  map(tvled[t1],0, 100, 0, 255);  // new value 0-100%
        bled_out =  map(bled[t1],0, 100, 0, 255);  // new value 0-100%
		wled_out =  map(wled[t1],0, 100, 0, 255);  // new value 0-100%
        rbled_out = map(rbled[t1],0, 100, 0, 255);  // new value 0-100%
        rled_out =  map(rled[t1],0, 100, 0, 255);  // new value 0-100%
        uvled_out = map(uvled[t1],0, 100, 0, 255);  // new value 0-100%
		cyled_out =  map(cyled[t1],0, 100, 0, 255);  // new value 0-100%
        yeled_out = map(yeled[t1],0, 100, 0, 255);  // new value 0-100%
       } else 
          {
			tvled_out = check(&tvled[t1], &tvled[t2], sstep);
			tvled_out = map (tvled_out, 0, 100, 0, 255);

			bled_out = check(&bled[t1], &bled[t2], sstep);
			bled_out = map (bled_out, 0, 100, 0, 255);

            wled_out = check(&wled[t1], &wled[t2], sstep);
			wled_out = map (wled_out, 0, 100, 0, 255);

            rbled_out = check(&rbled[t1], &rbled[t2], sstep);
			rbled_out = map (rbled_out, 0, 100, 0, 255);

            rled_out = check(&rled[t1], &rled[t2], sstep);
			rled_out = map (rled_out, 0, 100, 0, 255);

            uvled_out = check(&uvled[t1], &uvled[t2], sstep);
			uvled_out = map (uvled_out, 0, 100, 0, 255);

			cyled_out = check(&cyled[t1], &cyled[t2], sstep);
			cyled_out = map (cyled_out, 0, 100, 0, 255);

            yeled_out = check(&yeled[t1], &yeled[t2], sstep);
			yeled_out = map (yeled_out, 0, 100, 0, 255);
		  }  

     float lunarCycle = moonPhase(t.year, t.mon, t.date); //get a value for the lunar cycle
//   moonled_out = MinI *(1 - lunarCycle) + MaxI * lunarCycle + 0.5; //MaximumIllumination * % of Full Moon (0-255)
	 moonled_out = map ((MinI *(1 - lunarCycle) + MaxI * lunarCycle + 0.5), 0, 100, 0, 255); 
	}

   if (setDimLEDsOnOff==1) {HOT_LEDs();}  // 
   if (SoftStartON ==1) {Soft_Start_Led();}                      // increase led brigtness after start programm during 50sec

  if (bitRead(LedShannelStatusByte,0)== false) {wled_out=0;}  
  if (bitRead(LedShannelStatusByte,1)== false) {bled_out=0;}
  if (bitRead(LedShannelStatusByte,2)== false) {rbled_out=0;}  
  if (bitRead(LedShannelStatusByte,3)== false) {rled_out=0;}  
  if (bitRead(LedShannelStatusByte,4)== false) {uvled_out=0;}  
  if (bitRead(LedShannelStatusByte,5)== false) {tvled_out=0;}  
  if (bitRead(LedShannelStatusByte,6)== false) {cyled_out=0;}  
  if (bitRead(LedShannelStatusByte,7)== false) {yeled_out=0;}  
// end check	 	    

 if (RECOM_RCD == true) {          // 0-255 PWM or 0-10V
    tv_out = tvled_out;
    b_out = bled_out;
    w_out = wled_out;
    rb_out = rbled_out;
    r_out = rled_out;
    uv_out = uvled_out;
    cy_out = cyled_out;
    yel_out = yeled_out;
    moon_out = moonled_out;
  } else {						  // 255-0 PWM or 10V-0v - inverse output	
    tv_out = 255 - tvled_out;
    b_out = 255 - bled_out;
	w_out = 255 - wled_out;
    rb_out = 255 - rbled_out;
    r_out = 255 - rled_out;
    uv_out = 255 - uvled_out; 
	cy_out = 255 - cyled_out;
    yel_out = 255 - yeled_out;
//  moon_out = 255 - moonled_out;
	moon_out = moonled_out;
  }
  analogWrite(ledPinTV, tv_out);
  analogWrite(ledPinRed, r_out);
  analogWrite(ledPinWhite, w_out);
  analogWrite(ledPinBlue, b_out);
  analogWrite(ledPinRoyBlue, rb_out);
  analogWrite(ledPinUV, uv_out); 
  analogWrite(ledPinCyan, cy_out); 
  analogWrite(ledPinYellow, yel_out); 
  analogWrite(ledPinMoon, moon_out);
//  analogWrite(ledPinMoon, uv_out);   // for Pasha

/*
Serial.print ("rb_out="); Serial.println (rb_out);
Serial.print ("uv_out="); Serial.println (uv_out);
Serial.print ("tv_out="); Serial.println (tv_out);
Serial.println ("        "); 
Serial.print ("r_out="); Serial.println (r_out);
Serial.print ("w_out="); Serial.println (w_out);   //+
Serial.print ("b_out="); Serial.println (b_out);
Serial.print ("cy_out="); Serial.println (cy_out);
Serial.print ("yel_out="); Serial.println (yel_out); //+
Serial.print ("moon_out="); Serial.println (moon_out); //+
Serial.println ("        "); 
*/
}
#endif

#ifdef Timers_8bit
int check( byte *pt1, byte *pt2, int lstep)
{
  int result;
  float fresult;
   
  if (*pt1==*pt2) {result = *pt1;}     // No change
    else if (*pt1<*pt2)                //Increasing brightness
    { fresult = ((float(*pt2-*pt1)/15.0) * float(lstep))+float(*pt1);
     result = int(fresult);
     }
    //Decreasing brightness
    else {fresult = -((float(*pt1-*pt2)/15.0) * float(lstep))+float(*pt1);
     result = int(fresult);                     
    } 
    return result;  
}
#else
int check( int pt1, int pt2, int lstep)
{
  int result;
  float fresult;
   
 if (pt1==pt2) {result = pt1;}                 // No change
    else if (pt1<pt2)                          //Increasing brightness
    { fresult = ((float(pt2-pt1)/900) * float(lstep*60+t.sec))+float(pt1);
     result = int(fresult);
     }
                                               //Decreasing brightness
    else {fresult = -((float(pt1-pt2)/900) * float(lstep*60+t.sec))+float(pt1);
     result = int(fresult);                     
    }
    return result;  
}
#endif
/********************************* END OF LED LEVELS **********************************/


/************************************ WAVE OUTPUT *************************************/
/*
void wave_output()
{
  unsigned long currentMillis = millis();

  if (WAVE==1)                         //Alternating Mode         
    {
     if (waveMakerTest==true)
       { 
        wPump1 = ((Min1*60)+Sec1*WaveCorrector);
        wPump1 = wPump1*1000;
        wPump2 = ((Min2*60)+Sec2*WaveCorrector);
        wPump2 = wPump2*1000;
       } 
     else
       { 
        wPump1 = ((Pump1m*60)+Pump1s*WaveCorrector);
        wPump1 = wPump1*1000;
        wPump2 = ((Pump2m*60)+Pump2s*WaveCorrector);
        wPump2 = wPump2*1000;
       }
       
     if (currentMillis - previousMillisWave > intervalAlt)
       {
        previousMillisWave = currentMillis;
        
        if (wPump1==wPump2) { wPump2 = wPump2+1;}
        
        if (intervalAlt==wPump1)      
          { intervalAlt=wPump2;
            PumpTstate = LOW; 
            PumpBstate = HIGH;}
        else 
          { intervalAlt=wPump1;
            PumpTstate = HIGH; 
            PumpBstate = LOW;}
       }
    }
  if ((WAVE==2) && (Synch==1))         //Synchronous - Constanly ON
    {
     PumpTstate = HIGH;
     PumpBstate = HIGH;
    } else    

  if ((WAVE==2) && (Synch==2))         //Synchronous - Pulsating
    {
     if (waveMakerTest==true)
       { 
        wOnForT = ((Min1*60)+Sec1*WaveCorrector);
        wOnForT = wOnForT*1000;
        wOffForT = ((Min2*60)+Sec2*WaveCorrector);
        wOffForT = wOffForT*1000;
       } 
     else
       {  
        wOnForT = (OnForTm*60)+OnForTs*WaveCorrector;
        wOnForT = wOnForT*1000;
        wOffForT = (OffForTm*60)+OffForTs*WaveCorrector;
        wOffForT = wOffForT*1000;
       }
       
     if (currentMillis - previousMillisWave > intervalSynch)
       {
        previousMillisWave = currentMillis;
        
        if (wOnForT==wOffForT) { wOffForT = wOffForT+1;}        
        
        if (intervalSynch==wOnForT) 
          { intervalSynch=wOffForT;
            PumpTstate = LOW; 
            PumpBstate = LOW;}
        else 
          { intervalSynch=wOnForT;
            PumpTstate = HIGH; 
            PumpBstate = HIGH;}
       }
    }
    digitalWrite(WaveMakerTop, PumpTstate);
    digitalWrite(WaveMakerBottom, PumpBstate);
}
*/




/********************************* END OF WAVE OUTPUT *********************************/

void DetectDallalsSensors(boolean refreshSensor=true)
{

	if (refreshSensor== true) 
	   {
	myGLCD.setColor(64, 64, 64);                   //Draw Dividers in Grey
	myGLCD.drawLine(0, 93, 319, 93);
	myGLCD.drawRect(0, 196, 319, 194);             //Bottom Horizontal Divider

    myGLCD.setColor(0, 0, 255);                   // draw buttor REFRESH rectangle
    myGLCD.fillRoundRect(200, 20, 300, 40);
	myGLCD.setColor(255, 255, 255);                    
    myGLCD.drawRoundRect(200, 20, 300, 40);
	setFont(SMALL, 255, 255, 255, 0, 0, 255);  
    myGLCD.print("Refresh", 226, 24);

	printButton("<< BACK", back[0], back[1], back[2], back[3], SMALL);
	printButton("SAVE", prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3], SMALL);
    printButton("CANCEL", canC[0], canC[1], canC[2], canC[3], SMALL);
	setFont(SMALL, 0, 255, 0, 0, 0, 0);
//	myGLCD.print("Found: ", 5, 24);
	strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[9]))); 
    myGLCD.print(buffer, 5, 24);
//	myGLCD.print("Dallas Sensors", 77, 24);
	strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[10]))); 
    myGLCD.print(buffer, 77, 24);
	   }
	
	if (refreshSensor== false) { 
	myGLCD.setColor(0, 0, 0);								 // clear button and text area after pressing refresh
	myGLCD.fillRoundRect(4, 95, 318, 190);
	myGLCD.fillRoundRect(4, 45, 318, 92);}

	sensors.begin();										// start sensors
	numberOfDevices = sensors.getDeviceCount();             // find devices

	setFont(SMALL, 0, 255, 0, 0, 0, 0);
	myGLCD.printNumI(numberOfDevices, 5+56, 24);            // print number 

	if (numberOfDevices == 0) {counterB1=0; counterB2=0; counterB3=0;}  // set all counter N.C, 
	  tempAlarmflagW = false;    // clear all error flag
	  tempAlarmflagH1 = false;
	  tempAlarmflagH2 = false;
	  AlarmflagON = false;
	  digitalWrite(tempAlarmPin, LOW);               // OFF Sound

	for (byte i = 0; i < 8; i++)                                        // clear previos sensor ID value
         { Heatsink1Thermometer[i]=0 ;
		   waterThermometer[i]=0 ;
		   Heatsink2Thermometer[i]=0 ; }

	for (byte k=0; k<numberOfDevices; k++)
	    {
	myGLCD.setColor(0, 0, 255);
    myGLCD.fillRoundRect(165, 83+20+30*k, 225, 83+40+30*k);
	myGLCD.setColor(255, 255, 255);                    
    myGLCD.drawRoundRect(165, 83+20+30*k, 225, 83+40+30*k);
	setFont(SMALL, 255, 255, 255, 0, 0, 255);
	if (k==0) {																			 // print button text
		       strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[2+counterB1]))); // counterBX = 0/1/2/3 -> NC/Water/H.Sink1/H.Sink2
			   myGLCD.print(buffer, 169, 83+24+30*k);}
	            
	if (k==1) {
        	   strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[2+counterB2]))); // counterBX = 0/1/2/3 -> NC/Water/H.Sink1/H.Sink2   
			   myGLCD.print(buffer, 169, 83+24+30*k); }
	            
	if (k==2) {
        		strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[2+counterB3]))); // counterBX = 0/1/2/3 -> NC/Water/H.Sink1/H.Sink2  
				myGLCD.print(buffer, 169, 83+24+30*k);}
	     }

	 setFont(SMALL, 0, 255, 0, 0, 0, 0);
	 for(byte k=0; k<numberOfDevices; k++)
     {   	

  	   if (sensors.getAddress(tempDeviceAddress, k))
	   {
	    float tempC = sensors.getTempC(tempDeviceAddress);

		// connect sensor 1...3 to output Water/Heatsink1/Heatsink2
	if (k==0)    {
		  for (byte i=0; i<8; i++) {
			  if (counterB1 == 1) {waterThermometer[i] = tempDeviceAddress[i];}
              if (counterB1 == 2) {Heatsink1Thermometer[i] = tempDeviceAddress[i];}
              if (counterB1 == 3) {Heatsink2Thermometer[i] = tempDeviceAddress[i];}
		                           }
			     }
	if (k==1) {
		  for (byte i=0; i<8; i++) {
			  if (counterB2 == 1) {waterThermometer[i] = tempDeviceAddress[i];}
              if (counterB2 == 2) {Heatsink1Thermometer[i] = tempDeviceAddress[i];}
              if (counterB2 == 3) {Heatsink2Thermometer[i] = tempDeviceAddress[i];}
		                           }
	          }
	if (k==2)   {
		  for (byte i=0; i<8; i++) {
			  if (counterB3 == 1) {waterThermometer[i] = tempDeviceAddress[i];}
              if (counterB3 == 2) {Heatsink1Thermometer[i] = tempDeviceAddress[i];}
              if (counterB3 == 3) {Heatsink2Thermometer[i] = tempDeviceAddress[i];}
		                           }
	             }

	    myGLCD.printNumF( tempC, 1, 230+40, k*30+83+24);     // print temperature from current sensor
		myGLCD.print("Temp=", 230, k*30+83+24);   
		myGLCD.print("C", 230+40+32+6, k*30+83+24);   
        myGLCD.drawCircle(230+40+32+2, k*30+83+26, 1); 

//		myGLCD.print("Sensor N", 5, k*15+48);
		strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[11]))); 
        myGLCD.print(buffer, 5, k*15+48);
		myGLCD.printNumI(k+1, 5+64, k*15+48);
//		myGLCD.print("Sensor N", 5, k*30+83+24); 
		myGLCD.print(buffer, 5, k*30+83+24);
		myGLCD.printNumI(k+1, 5+64, k*30+83+24);
		myGLCD.print(":", 5+64+8, k*15+48);
//		myGLCD.print(" connect to", 5+64+8, k*30+83+24);
		strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[12]))); 
        myGLCD.print(buffer, 5+64+8, k*30+83+24);

		for (byte i = 0; i < 8; i++)                        // print sensors unic ID
         {
    byte result;
	byte temp = tempDeviceAddress[i];
	result = temp/16;				// first char  convert HEX to ASCII for print
	if (result == 15) {myGLCD.print("F", i*24+88, k*15+48);}
	if (result == 14) {myGLCD.print("E", i*24+88, k*15+48);}
	if (result == 13) {myGLCD.print("D", i*24+88, k*15+48);}
	if (result == 12) {myGLCD.print("C", i*24+88, k*15+48);}
	if (result == 11) {myGLCD.print("B", i*24+88, k*15+48);}
	if (result == 10) {myGLCD.print("A", i*24+88, k*15+48);}
	if (result < 10 ) {myGLCD.printNumI(result, i*24+88, k*15+48);}

	result = temp - (temp/16)*16;   // second char  convert HEX to ASCII for print
	if (result == 15) {myGLCD.print("F", i*24+8+88, k*15+48);}
	if (result == 14) {myGLCD.print("E", i*24+8+88, k*15+48);}
	if (result == 13) {myGLCD.print("D", i*24+8+88, k*15+48);}
	if (result == 12) {myGLCD.print("C", i*24+8+88, k*15+48);}
	if (result == 11) {myGLCD.print("B", i*24+8+88, k*15+48);}
	if (result == 10) {myGLCD.print("A", i*24+8+88, k*15+48);}
	if (result < 10 ) {myGLCD.printNumI(result, i*24+8+88, k*15+48);}
	         if (i<7) {myGLCD.print(":", i*24+16+88, k*15+48);}
           }
	   }
	 }
  }


/*
void printTemperature(DeviceAddress deviceAddress)
{
  float tempC = sensors.getTempC(deviceAddress);
  Serial.print("Temp C: ");
  Serial.print(tempC);
  Serial.print(" Temp F: ");
  Serial.println(DallasTemperature::toFahrenheit(tempC)); // Converts tempC to Fahrenheit
}
*/

/*
void printAddress(DeviceAddress deviceAddress)
{
  for (byte i = 0; i < 8; i++)
  { Serial.print(deviceAddress[i], HEX);}
}
*/

void Backup()
{
	printButton("<< BACK", back[0], back[1], back[2], back[3], SMALL);
	printButton("CANCEL", canC[0], canC[1], canC[2], canC[3], SMALL);

	myGLCD.setColor(0, 0, 255);                    
    myGLCD.fillRoundRect(205, 40+34, 305, 60+34);
	myGLCD.fillRoundRect(15, 40+34, 115, 60+34);
	myGLCD.setColor(255, 255, 255);                    
    myGLCD.drawRoundRect(205, 40+34, 305, 60+34);
	myGLCD.drawRoundRect(15, 40+34, 115, 60+34);
	setFont(SMALL, 255, 255, 255, 0, 0, 255);  
    myGLCD.print("BACKUP", 226+5, 44+34);
	myGLCD.print("RESTORE",15+20, 44+34);

	myGLCD.setColor(64, 64, 64);                   //Draw Dividers in Grey
	myGLCD.drawLine(0, 60, 319, 60);

    setFont(SMALL, 0, 255, 0, 0, 0, 0);
	myGLCD.print("Initializing SD card...", 5, 24);

	// initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
  // breadboards.  use SPI_FULL_SPEED for better performance.
  if (!sd.init(SPI_HALF_SPEED, SDchipSelect)) {              
    sd.initErrorPrint();
	setFont(SMALL, 255, 0, 0, 0, 0, 0);
    myGLCD.print("initialization failed!", 5, 24+12+5);
  } else {myGLCD.print("initialization done.  ", 5, 24+12+5);}
  
/*
  if (!sd.begin(SDchipSelect, SPI_SIXTEENTH_SPEED)) {
    setFont(SMALL, 255, 0, 0, 0, 0, 0);
    myGLCD.print("initialization failed!", 5, 24+12+5);
    return;
  }
    myGLCD.print("initialization done.  ", 5, 24+12+5);
*/
}



/******************************** TEMPERATURE FUNCTIONS *******************************/
//----------------- CHECK TEMPERATURE -------------------
void checkTempC()
{ 
	if ((millis() - lastTempRequest) >= delayInMillis)    
  {
    digitalWrite(Temp_SensorBus0, LOW);
	tempW = (sensors.getTempC(waterThermometer));         //read water temperature
    tempH1 = (sensors.getTempC(Heatsink1Thermometer));    //read Heatsink1's heatsink temperature
    tempH2 = (sensors.getTempC(Heatsink2Thermometer));    //read Heatsink2's heatsink temperature

//  sensors.requestTemperatures();                        // immediately after fetching the temperature we request a new sample in the async modus
    delayInMillis = 750 / (1 << (12 - resolution));
    lastTempRequest = millis(); 

    digitalWrite(Temp_SensorBus0, HIGH);
    sensors.requestTemperatures();						 // call sensors.requestTemperatures() to issue a global 
        												 // temperature request to all devices on the bus
	 }
}


void WaterTempCheckFunction()
{
  String deg;  
	if (setTempScale==1) {deg ="F";}               //Print deg C or deg F
    else {deg = "C";}
  degC_F=deg;
  char bufferDeg[2];
  degC_F.toCharArray(bufferDeg,2);

//--------------- check Water temp and ON/OFF heater-chiller -----------------
	if (counterB1 ==1 || counterB2 ==1 || counterB3 ==1)          // check Water temperature if B1 or B2 or B3 = 1 (Water)
		{
    if (tempW == -127 || tempW == -196 || tempW <10 || tempW >40)                           //sensor disconnected
	    { 
			tempW = 0;   // temporary store error value
			if (WaterTempErrorCount >=12)
			{			
		   digitalWrite(tempHeatPin, LOW);						  // off heater and chiller
           digitalWrite(tempChillPin, LOW);          
		   if (AlarmLevel ==2) {tempAlarmflagW = true;}          //turn on sound alarm if possible
		   tempCoolflag=false;
           tempHeatflag=false;
			}
			if (WaterTempErrorCount <=12) {WaterTempErrorCount +=1;}
		} 
	else 
	{
		WaterTempErrorCount = 0;      //reset error counter
   if (tempW !=0)                     // No GPIO function on error   
       {
    if (alarmTempC>0)                                              //turn on alarm
     { if ((tempW>=(setTempC+offTempC+alarmTempC)) || (tempW<=(setTempC-offTempC-alarmTempC)))
	    { tempAlarmflagW = true;}}

	if (tempW<(setTempC+offTempC+alarmTempC) && tempW>(setTempC-offTempC-alarmTempC)) 
		{														   //turn off alarm after OverHeating/OverCooling
		tempAlarmflagW = false;
		     if (dispScreen==0)
			 { 
		myGLCD.setColor(0, 0, 0);                        
        myGLCD.fillRect(182, 203, 315, 221);                       // clear alarm notices
			 }
		AlarmflagON = false;
		digitalWrite(tempAlarmPin, LOW); }                         // OFF alarm
		
    if (tempW<(setTempC+offTempC) && tempW>(setTempC-offTempC))    //turn off chiller/heater, Water temp is NORMAL T< SET+offset
		{ tempCoolflag=false;
          tempHeatflag=false;
          digitalWrite(tempHeatPin, LOW);
		  digitalWrite(tempChillPin, LOW);
		       if (dispScreen==0)
          {  myGLCD.setColor(0, 0, 0);                        //clear cooler/heater notices
			 myGLCD.fillRect(200, 190, 280, 203);}
	    }
	
       if (tempW >=(setTempC+offTempC))           //turn on chiller
          {
        tempCoolflag=true;
		tempHeatflag=false;
		digitalWrite(tempHeatPin, LOW);          //turn off heater pin
        digitalWrite(tempChillPin, HIGH);        //turn on chiller pin
        
          }
     if (tempW<=(setTempC-offTempC))             //turn an heater
          {
        tempHeatflag=true;
		tempCoolflag=false;
		digitalWrite(tempChillPin, LOW);         //turn off chiller pin
        digitalWrite(tempHeatPin, HIGH);         //turn on heater pin
          }
        }
	  }

	} else {digitalWrite(tempHeatPin, LOW);          //turn off heater if sensor not present
	       digitalWrite(tempChillPin, LOW);          //turn off chiller
		   tempCoolflag=false;
		   tempHeatflag=false; }
	

// ------- display Water temp Messages -------------------

	     if (dispScreen==0)  // display value only in main window
  {	
  if (counterB1 ==1 || counterB2 ==1 || counterB3 ==1)
     {
//        if (tempW == -127 || tempW == -196 )                   //range in deg C no matter what
		 
		 if (WaterTempErrorCount >=12)
           { setFont(SMALL, 255, 0, 0, 0, 0, 0);
		     myGLCD.print("ERROR ", 260+8, 148);
			 tempCoolflag=false;
			 tempHeatflag=false;
             myGLCD.setColor(0, 0, 0);                        //clear cooler/heater notices
             myGLCD.fillRect(200, 190, 280, 203);
           }else 
		 { 
		 
			 if (tempW !=0)                                   // no display function if temp =0
			 {
		 if (setTempScale==1) { tempW = ((tempW*1.8) + 32.05);}         //C to F with rounding
		 
     if (tempCoolflag==true)                                   //Water temperature too HIGH
       { setFont(SMALL, 255, 255, 0, 0, 0, 0);
          myGLCD.print("Chiller ON", 200, 191);}
        else 
          if (tempHeatflag==true)                              //Water temperature too LOW
            { setFont(SMALL, 255, 255, 0 , 0, 0, 0);
              myGLCD.print("Heater ON ", 200, 191);}

	          setFont(SMALL, 0, 0, 0, 0, 0, 0);
		      myGLCD.print(" ",300 , 148);
			  setFont(SMALL, 0, 255, 0, 0, 0, 0);
	          myGLCD.printNumF( tempW, 1, 260+8, 148);         // print water temp
		      myGLCD.drawCircle(304, 148, 1);              
		      myGLCD.print(bufferDeg, 309, 148);

//------------------ Display MAX Temp ----------------------------		 
         if (MAX_Temp_on_off ==1)                    // Display ON 
		      {
		 if (tempW >= MaxTempW){ MaxTempW = tempW;}               // store max temp
				  setFont(SMALL, 0, 255, 0, 0, 0, 0);
				  myGLCD.printNumF(MaxTempW, 1, 105 ,191);
		      }
		     }
		   }
	     }

//-------- Clear Max Temp every morning --------------------
	 if (min_cnt/15 == StartTime) {
		 MaxTempW=0; MaxTempH1=0; MaxTempH2=0; }
  }
}

void FanTempCheckFunction()
{

  byte ShiftDrawY;
   String deg;  
  if (setTempScale==1) {deg ="F";}               //Print deg C or deg F
  else {deg = "C";}
  degC_F=deg;
  char bufferDeg[2];
  degC_F.toCharArray(bufferDeg,2);

//------------Fan Controller for Heatsink1 -----------------
if (counterB1 ==2 || counterB2 ==2 || counterB3 ==2)          // check Heatsink 1 temperature if B1 or B2 or B3 = 2
	{

//     Heatsink1TempInterval = (tempH1 - setTempToBeginHeatsink1FanC);    //Sets the interval to start from 0
	 
	 if ((tempH1Store-tempH1)>10 || (tempH1Store-tempH1)<-10) { 
		 if (Heatsink1TempErrorCount <=12) {Heatsink1TempErrorCount +=1;}
	 } else {Heatsink1TempErrorCount=0;
	         tempH1Store = tempH1;
	 	        }
	 if (Heatsink1TempErrorCount == 0) {
	    Heatsink1TempInterval = (tempH1 - setTempToBeginHeatsink1FanC);    //Sets the interval to start from 0
	                                  }
	 if (Heatsink1TempErrorCount !=0) {tempH1=0;}

//		if (Heatsink1TempInterval >=20 )  
		if (Heatsink1TempInterval >=20 || Heatsink1TempErrorCount >=12 )  // Set maximal value PWM =255 if current temp >= setTempToBeginHeatsink2FanC+20C
		{Heatsink1TempInterval =20; }                                     // or error counter >12 


		if (Heatsink1TempInterval <= -1) { Heatsink1PWM =0; 
		     analogWrite(Heatsink1_FansPWM, Heatsink1PWM); 
			 bitClear(GlobalStatus1Byte,6);								// GlobalStatus1Byte.6 = StartUPFan1 ;
		     bitClear(GlobalStatus1Byte,7);}							// GlobalStatus1Byte.6 = StartUPFan1_Timeout; 
                           
   if (Heatsink1TempInterval >=1)
              {
            Heatsink1PWM = map (Heatsink1TempInterval, -1 , 20, 100, 255); //  maximum PWM = setTempToBeginHeatsink2FanC+20C, minimum speed 40% of max
			if (bitRead(GlobalStatus1Byte,7) == false) {				   // set flag startup process
            analogWrite(Heatsink1_FansPWM, 255);  
            unsigned long cMillis = millis();
            previousMillisAlarm = cMillis;                                 // reset 1 sec timer for fan startup process 
			bitSet(GlobalStatus1Byte,6);}
              
			else { analogWrite(Heatsink1_FansPWM, Heatsink1PWM);
			}
			  }

//---------------------- Sound alarm Section ------------------------------
/*
   if (setTempScale ==0 ) {
	   if (tempH1 >= setTempToSoundAlarmC) 
	        {tempAlarmflagH1 = true; analogWrite(Heatsink1_FansPWM, 255);}                 // Alarm on overheat led, set maximum fan speed
	   else 
	        {tempAlarmflagH1 = false; digitalWrite(tempAlarmPin, LOW);}   	               // OFF alarm

	   if ((tempH1 == -127) && (AlarmLevel ==2))										   //All OFF=0, OverHeat=1, All ON=2	
	   { tempAlarmflagH1 = true; analogWrite(Heatsink1_FansPWM, 255);}					   // alarm on disconnect or error read sensor	
*/
       if (setTempScale ==0 ) {
	   	   if (tempH1 >= setTempToSoundAlarmC ) 
	        {tempAlarmflagH1 = true; analogWrite(Heatsink1_FansPWM, 255);}                 // Alarm on overheat led, set maximum fan speed
	   else 
	        {tempAlarmflagH1 = false; digitalWrite(tempAlarmPin, LOW);}   	               // OFF alarm

	   if ((tempH1 == 0) && (AlarmLevel ==2) && Heatsink1TempErrorCount >12)			   //All OFF=0, OverHeat=1, All ON=2	
	   { tempAlarmflagH1 = true; analogWrite(Heatsink1_FansPWM, 255);}					   // alarm on disconnect or error read sensor	
                          }

/*
   if (setTempScale ==1 ) {
	   if (tempH1 >= setTempToSoundAlarmF) 
	        {tempAlarmflagH1 = true; analogWrite(Heatsink1_FansPWM, 255);}                 // set maximum fan speed
	   else 
	        {tempAlarmflagH1 = false; digitalWrite(tempAlarmPin, LOW);}   	// OFF alarm
	   if ((tempH1 == -196) && (AlarmLevel ==2)) 
	        {tempAlarmflagH1 = true; analogWrite(Heatsink1_FansPWM, 255);}
	                       }	
*/

   if (setTempScale ==1 ) {
	   if (tempH1 >= setTempToSoundAlarmF) 
	        {tempAlarmflagH1 = true; analogWrite(Heatsink1_FansPWM, 255);}                 // set maximum fan speed
	   else 
	        {tempAlarmflagH1 = false; digitalWrite(tempAlarmPin, LOW);}   	// OFF alarm
	   if ((tempH1 == -196) && (AlarmLevel ==2) && Heatsink1TempErrorCount >12) 
	        {tempAlarmflagH1 = true; analogWrite(Heatsink1_FansPWM, 255);}
                          }
/*   
   if (setTempScale ==0 ) {
	   if (tempH1 >= setTempToSoundAlarmC || tempH1 == -127) {tempAlarmflagH1 = true;
	                      analogWrite(Heatsink1_FansPWM, 255);}                 // set maximum fan speed}
	   else {tempAlarmflagH1 = false; digitalWrite(tempAlarmPin, LOW);}}		// OFF alarm
   if (setTempScale ==1 ) {
       if (tempH1 >= setTempToSoundAlarmF || tempH1 == -196) {tempAlarmflagH1 = true; 
		                  analogWrite(Heatsink1_FansPWM, 255);}	    			// set maximum fan speed 
	   else {tempAlarmflagH1 = false; digitalWrite(tempAlarmPin, LOW);}}		// OFF alarm
*/
    }

//-------- Display Heatsink1 temperature ----------------------

     if (dispScreen==0)   // display value only in main window
  {	
  if (counterB1 ==2 || counterB2 ==2 || counterB3 ==2)
     { 
	 if (((counterB1 + counterB2 + counterB3) == 2) || ((counterB1 + counterB2 + counterB3) == 5)) {ShiftDrawY= 0;}
	 if (((counterB1 + counterB2 + counterB3) == 3) || ((counterB1 + counterB2 + counterB3) == 6)) {ShiftDrawY= +13;}

		 if (setTempScale==1)  { tempH1 = ((tempH1*1.8) + 32.05);}      // display in F

//		if (tempH1 == -127 || tempH1 == -196)
        if (Heatsink1TempErrorCount >12)
			{ setFont(SMALL, 255, 0, 0, 0, 0, 0);
	          myGLCD.print("ERROR ", 260+8, 148+ShiftDrawY);			// sensor disconnected
           }else
           {

        if (tempH1 !=0) {     
       	   setFont(SMALL, 0, 0, 0, 0, 0, 0);
		   myGLCD.print(" ",300 , 148+ShiftDrawY);
		   setFont(SMALL, 0, 255, 0, 0, 0, 0);
		   myGLCD.printNumF( tempH1, 1, 260+8, 148+ShiftDrawY);          //Heatsink1 temperature (No Flags)
		   myGLCD.drawCircle(304, 148+ShiftDrawY+2, 1);              
		   myGLCD.print(bufferDeg, 309, 148+ShiftDrawY);
		                
//-------------- Display Day MAX TEMP ------------------
		if (MAX_Temp_on_off ==1)                    // Display ON 
		 {
         if (tempH1 >= MaxTempH1){ MaxTempH1 = tempH1;}                              // store max temp
			 myGLCD.printNumF(MaxTempH1, 1, 105 ,202);
		 }
		                }
	   }
     }
  }
//--------------Fan Controller for Heatsink2 ---------------------------------------------------------

if (counterB1 ==3 || counterB2 ==3 || counterB3 ==3) 						// check Heatsink 2 temperature if B1 or B2 or B3 = 3
       {

		   if ((tempH2Store-tempH2)>10 || (tempH2Store-tempH2)<-10) { 
		 if (Heatsink2TempErrorCount <=12) {Heatsink2TempErrorCount +=1;}
	 } else {Heatsink2TempErrorCount=0;
	         tempH2Store = tempH2;
	 	        }
	 if (Heatsink2TempErrorCount == 0) {
	    Heatsink2TempInterval = (tempH2 - setTempToBeginHeatsink2FanC);    //Sets the interval to start from 0
	                                  }
	 if (Heatsink2TempErrorCount !=0) {tempH2=0;}

		if (Heatsink2TempInterval >=20 || Heatsink2TempErrorCount >=12 )  // Set maximal value PWM =255 if current temp >= setTempToBeginHeatsink2FanC+20C
		{Heatsink2TempInterval =20; }                                

/*
       Heatsink2TempInterval = (tempH2 - setTempToBeginHeatsink2FanC);      //Sets the interval to start from 0

		if (Heatsink2TempInterval >=20 ) 
		{Heatsink2TempInterval =20; }										// Set maximal value PWM =255 if current temp >= setTempToBeginHeatsink2FanC+20C
*/
		if (Heatsink2TempInterval <= -1) { Heatsink2PWM =0; 
		     analogWrite(Heatsink2_FansPWM, Heatsink2PWM); 
		     bitClear(GlobalStatus1Byte,4);                // GlobalStatus1Byte.4 = StartUPFan2 ;
			 bitClear(GlobalStatus1Byte,5); }              // GlobalStatus1Byte.5 = StartUPFan2_Timeout; 
                              
   if (Heatsink2TempInterval >=1)
              {
            Heatsink2PWM = map (Heatsink2TempInterval, -1 , 20, 100, 255);    //  maximum PWM = setTempToBeginHeatsink2FanC+20C
			if (bitRead(GlobalStatus1Byte,5) == false) {					  // set flag startup process
            analogWrite(Heatsink2_FansPWM, 255);  

            unsigned long cMillis = millis();
            previousMillisAlarm = cMillis;							          // reset 1 sec timer for fan startup process 
			bitSet(GlobalStatus1Byte,4);}

			else { analogWrite(Heatsink2_FansPWM, Heatsink2PWM); }
              }

//---------------------- Sound alarm Section ------------------------------
/*
   if (setTempScale ==0 ) {
	   if (tempH2 >= setTempToSoundAlarmC) {tempAlarmflagH2 = true; analogWrite(Heatsink2_FansPWM, 255);}                 // set maximum fan speed
	   else {tempAlarmflagH2 = false; digitalWrite(tempAlarmPin, LOW);}   	// OFF alarm
	   if ((tempH2 == -127) && (AlarmLevel ==2)) {tempAlarmflagH2 = true; analogWrite(Heatsink2_FansPWM, 255);}
	                       }	

   if (setTempScale ==1 ) {
	   if (tempH2 >= setTempToSoundAlarmF) {tempAlarmflagH2 = true; analogWrite(Heatsink2_FansPWM, 255);}                 // set maximum fan speed
	   else {tempAlarmflagH2 = false; digitalWrite(tempAlarmPin, LOW);}   	// OFF alarm
	   if ((tempH1 == -196) && (AlarmLevel ==2)) {tempAlarmflagH2 = true; analogWrite(Heatsink2_FansPWM, 255);}
	                       }	
*/
       if (setTempScale ==0 ) {
	   if (tempH2 >= setTempToSoundAlarmC ) 
	        {tempAlarmflagH2 = true; analogWrite(Heatsink2_FansPWM, 255);}                 // Alarm on overheat led, set maximum fan speed
	   else 
	        {tempAlarmflagH2 = false; digitalWrite(tempAlarmPin, LOW);}   	               // OFF alarm

	   if ((tempH2 == 0) && (AlarmLevel ==2) && Heatsink2TempErrorCount >12)			   //All OFF=0, OverHeat=1, All ON=2	
	   { tempAlarmflagH2 = true; analogWrite(Heatsink2_FansPWM, 255);}					   // alarm on disconnect or error read sensor	
                          }

       if (setTempScale ==1 ) {
	   if (tempH2 >= setTempToSoundAlarmF) 
	        {tempAlarmflagH2 = true; analogWrite(Heatsink2_FansPWM, 255);}                 // set maximum fan speed
	   else 
	        {tempAlarmflagH2 = false; digitalWrite(tempAlarmPin, LOW);}   	// OFF alarm
	   if ((tempH1 == -196) && (AlarmLevel ==2) && Heatsink2TempErrorCount >12) 
	        {tempAlarmflagH2 = true; analogWrite(Heatsink2_FansPWM, 255);}
	   }
   /*
   if (setTempScale ==0 ) {
	   if (tempH2 >= setTempToSoundAlarmC || tempH2 == -127) {tempAlarmflagH2 = true;
	                      analogWrite(Heatsink2_FansPWM, 255);}                 // set maximum fan speed}
	   else {tempAlarmflagH2 = false; digitalWrite(tempAlarmPin, LOW);}}		// OFF alarm
   if (setTempScale ==1 ) {
       if (tempH2 >= setTempToSoundAlarmF || tempH2 == -196) {tempAlarmflagH2 = true; 
		   analogWrite(Heatsink2_FansPWM, 255);}								// set maximum fan speed 
	   else {tempAlarmflagH2 = false; digitalWrite(tempAlarmPin, LOW);}}		// OFF alarm
*/
     }

//-------- Display Heatsink2 temperature -----------
     if (dispScreen==0)  // display value only in main window
  {	
  if (counterB1 ==3 || counterB2 ==3 || counterB3 ==3)
    {  
		if ((counterB1 + counterB2 + counterB3) == 3) {ShiftDrawY= 0;}
	    if (((counterB1 + counterB2 + counterB3) == 4) || ((counterB1 + counterB2 + counterB3) == 5)) {ShiftDrawY= +13;}
		if ((counterB1 + counterB2 + counterB3) == 6) {ShiftDrawY= +26;}

		if (setTempScale==1) { tempH2 = ((tempH2*1.8) + 32.05); }       // display in F

		if (Heatsink2TempErrorCount >12)
//		if (tempH2 == -127 || tempH2 == -196)
			{ setFont(SMALL, 255, 0, 0, 0, 0, 0);
	          myGLCD.print("ERROR ", 260+8, 148+ShiftDrawY);             // sensor disconnected
           }else
            {
	 if (tempH2 !=0) { 
           setFont(SMALL, 0, 0, 0, 0, 0, 0);
		   myGLCD.print(" ",300 , 148+ShiftDrawY);
  		   setFont(SMALL, 0, 255, 0, 0, 0, 0);
           myGLCD.printNumF( tempH2, 1, 260+8, 148+ShiftDrawY);		     //Heatsink2 temperature (No Flags)
		   myGLCD.drawCircle(304, 148+ShiftDrawY+2, 1);              
		   myGLCD.print(bufferDeg, 309, 148+ShiftDrawY);
//-------------- Display Day MAX TEMP ------------------ 
	   if (MAX_Temp_on_off ==1)                    // Display ON 
		 {	    
       if (tempH2 >= MaxTempH2){ MaxTempH2 = tempH2;}                           // store max temp
			myGLCD.printNumF(MaxTempH2, 1, 105 ,214);
	     }
	                }
	    }
	 }
   }
}


void Alarm()
{
          unsigned long cMillis = millis();
          if (cMillis - previousMillisAlarm > 700)
       {  previousMillisAlarm = cMillis;
//----------- FAN start UP -----------------------------------------
  		if (bitRead(GlobalStatus1Byte,6) == true) // startup for FAN1
		      { bitClear(GlobalStatus1Byte,6);
		        bitSet(GlobalStatus1Byte,7); }  

		if (bitRead(GlobalStatus1Byte,4) == true) // startup for FAN2
		      { bitClear(GlobalStatus1Byte,4);
		        bitSet(GlobalStatus1Byte,5); }  

//------------- Sound Alarm & Display alarm -------------------------------------
        if ((counterB1 + counterB2 + counterB3 !=0))  // no sound alarm if dallas sensor not installed, ie counterB1=counterB2=counterB3=0
             {
          if (tempAlarmflagW == true || tempAlarmflagH1 == true || tempAlarmflagH2 == true)
        	   { 
		    if (AlarmflagON == false) //true) 
			{  if (AlarmLevel >=1) {digitalWrite(tempAlarmPin, HIGH);}  // ON alarm
			  if (dispScreen == 0){
			  setFont(LARGE, 255, 0, 0, 0, 0, 0); 
			  myGLCD.print("ALARM", 185+16, 204);}
			  AlarmflagON = true;} //false; }
			else {// if (AlarmflagON == false)
//			{
			  if (AlarmLevel >=1) {digitalWrite(tempAlarmPin, LOW);}    // OFF alarm
			  if (dispScreen == 0){
			  setFont(LARGE, 255, 0, 0, 0, 0, 0); 
			  myGLCD.print("     ", 185+16, 204);}
			           AlarmflagON = false; //true;
//			}
                 }
	          }
		  else {if (AlarmflagON == true) {
			  setFont(LARGE, 255, 0, 0, 0, 0, 0); 
			  myGLCD.print("     ", 185+16, 204);
			  AlarmflagON = false; //true;
		                                 }
		       }
	      }
/*
//------------- Display ALARM -----------------------------------------
		if (counterB1 + counterB2 + counterB3 !=0)
		{
           if (tempAlarmflagW == true || tempAlarmflagH1 == true || tempAlarmflagH2 == true)
		    { setFont(LARGE, 255, 0, 0, 0, 0, 0);
       		  myGLCD.print("ALARM!!", 185, 204);}
		}  
*/
     }
}


/*************************** END OF TEMPERATURE FUNCTIONS *****************************/

//************ Soft Led Start function **************************************
void Soft_Start_Led()  // increase led brigtness after start programm during 50sec
{
  if (PercentSoftStart < 1) 
    {

#ifdef Timers_8bit 
	 PercentSoftStart +=0.1;
#else 
     PercentSoftStart +=0.02;
#endif

     tvled_out = PercentSoftStart*tvled_out;
     bled_out = PercentSoftStart*bled_out;
     wled_out = PercentSoftStart*wled_out;
     rbled_out = PercentSoftStart*rbled_out;
     rled_out = PercentSoftStart*rled_out;
     uvled_out = PercentSoftStart*uvled_out;
	 cyled_out = PercentSoftStart*cyled_out;
     yeled_out = PercentSoftStart*yeled_out;
    }   
}

/**************************** DIM LEDs WHEN HOT FUNCTION ******************************/
void HOT_LEDs()
{
  if (tempH1>=setLEDsDimTempC+1 || tempH2>=setLEDsDimTempC+1) // || tempW>=setLEDsDimTempC+1)          
    { bitSet(GlobalStatus1Byte,1); }

 if (tempH1<=setLEDsDimTempC-1 && tempH2<=setLEDsDimTempC-1) // && tempW<=setLEDsDimTempC-1)
     {bitClear(GlobalStatus1Byte,1);}

	if (bitRead(GlobalStatus1Byte,1) == true) {
	 PercentDim = setLEDsDimPercent*0.01;
     tvled_out = PercentDim*tvled_out;
     bled_out = PercentDim*bled_out;
     wled_out = PercentDim*wled_out;
     rbled_out = PercentDim*rbled_out;
     rled_out = PercentDim*rled_out;
     uvled_out = PercentDim*uvled_out;
	 cyled_out = PercentDim*cyled_out;
     yeled_out = PercentDim*yeled_out;
	}

}
/*************************END OF DIM LEDs WHEN HOT FUNCTION ***************************/


/******************************* LUNAR PHASE FUNCTION *********************************/
float moonPhase(int moonYear, int moonMonth, int moonDay)
{ 
  float phase;
  double IP; 
  long YY, MM, K1, K2, K3, JulianDay; 
  YY = moonYear - floor((12 - moonMonth) / 10); 
  MM = moonMonth + 9;
  if (MM >= 12)
    { MM = MM - 12; }
  K1 = floor(365.25 * (YY + 4712));
  K2 = floor(30.6 * MM + 0.5);
  K3 = floor(floor((YY / 100) + 49) * 0.75) - 38;
  JulianDay = K1 + K2 + moonDay + 59;
  if (JulianDay > 2299160)
    { JulianDay = JulianDay - K3; }
  IP = MyNormalize((JulianDay - 2451550.1) / LC);
  AG = IP*LC;
  phase = 0; 
  
  //Determine the Moon Illumination %
  if ((AG >= 0) && (AG <= LC/2))             //FROM New Moon 0% TO Full Moon 100%
    { phase = (2*AG)/LC; }
  if ((AG > LC/2) && (AG <= LC))             //FROM Full Moon 100% TO New Moon 0%
    { phase = 2*(LC-AG)/LC; }

  //Determine the Lunar Phase
  if ((AG >= 0) && (AG <= 1.85))             //New Moon; ~0-12.5% illuminated
    { LP = "    New Moon   "; 
      MoonPic = New_Moon; }
  if ((AG > 1.85) && (AG <= 5.54))           //New Crescent; ~12.5-37.5% illuminated
    { LP = "Waxing Crescent";
      MoonPic = Waxing_Crescent; }
  if ((AG > 5.54) && (AG <= 9.23))           //First Quarter; ~37.5-62.5% illuminated
    { LP = " First Quarter ";
      MoonPic = First_Quarter; }
  if ((AG > 9.23) && (AG <= 12.92))          //Waxing Gibbous; ~62.5-87.5% illuminated
    { LP = "Waxing Gibbous ";
      MoonPic = Waxing_Gibbous; }
  if ((AG > 12.92) && (AG <= 16.61))         //Full Moon; ~87.5-100-87.5% illuminated
    { LP = "   Full Moon   ";
      MoonPic = Full_Moon; }    
  if ((AG > 16.61) && (AG <= 20.30))         //Waning Gibbous; ~87.5-62.5% illuminated
    { LP = "Waning Gibbous ";
      MoonPic = Waning_Gibbous; }
  if ((AG > 20.30) && (AG <= 23.99))         //Last Quarter; ~62.5-37.5% illuminated
    { LP = " Last Quarter  ";
      MoonPic = Last_Quarter; }
  if ((AG > 23.99) && (AG <= 27.68))         //Old Crescent; ~37.5-12.5% illuminated
    { LP = "Waning Crescent";
      MoonPic = Waning_Crescent; }
  if ((AG >= 27.68) && (AG <= LC))           //New Moon; ~12.5-0% illuminated
    { LP = "    New Moon   ";
      MoonPic = New_Moon; }
        
  return phase; 
}

double MyNormalize(double v) 
{ 
  v = v - floor(v);
  if (v < 0)
    v = v + 1;
  return v;
} 
/**************************** END OF LUNAR PHASE FUNCTION *****************************/


/********************************* MISC. FUNCTIONS ************************************/
void clearScreen()
{
  myGLCD.setColor(0, 0, 0);
  myGLCD.fillRect(1, 14, 318, 226);
}


void printHeader()
{
  setFont(SMALL, 255, 255, 0, 255, 255, 0);
  myGLCD.fillRect (0, 0, 318, 14);
  myGLCD.setColor(0, 0, 0);
  strcpy_P(buffer, (char*)pgm_read_word_near(&(Header_Text_table[PrintStringIndex]))); 
  myGLCD.print(buffer, CENTER, 1 );
}

/*
void printHeader(char* headline)
{
  setFont(SMALL, 255, 255, 0, 255, 255, 0);
  myGLCD.fillRect (0, 0, 318, 14);
  myGLCD.setColor(0, 0, 0);
  myGLCD.print(headline, CENTER, 1);   
}
*/

void setFont(boolean font, byte cr, byte cg, byte cb, byte br, byte bg, byte bb)
{
  myGLCD.setBackColor(br, bg, bb);               //font background black
  myGLCD.setColor(cr, cg, cb);                   //font color white
  if (font==LARGE)
    myGLCD.setFont(BigFont);                     //font size LARGE
  else if (font==SMALL)
    myGLCD.setFont(SmallFont);
}


void waitForTouchRelease()
{
  while (myTouch.dataAvailable()==true)          //Wait for release
    myTouch.read();
}

int LedToPercent (int Led_out, int resolution) //returns LED output in % with rounding to the nearest whole number
{
  int result;
  float Temp_in = Led_out;
  float Temp = 100*Temp_in/resolution;
  result  = map(Led_out, 0, resolution, 0, 100); 
  if ((Temp - result) >= 0.5) {result +=1;};      // rounding to the nearest whole number
  
  return result; 
}


void SmallLedBarGraph(int Led_out, int resolution, byte shift_X, byte cR, byte cG, byte cB)
{
	int bar = map(Led_out, 0, resolution, 131, 31);       // Top end bar - Y=31, Bot end bar Y=131
	if (bar <31 ){bar=31;}
	if (bar >131){bar=131;}
    myGLCD.setColor(0, 0, 0);
    myGLCD.fillRect(31+shift_X, bar, 31+10+shift_X, 31);  //hide end of last bar (Top end bar)
	myGLCD.setColor(cR, cG, cB);               
    myGLCD.drawRect(31+shift_X, 131, 31+10+shift_X, 130); // %bar place holder
    myGLCD.fillRect(31+shift_X, 130, 31+10+shift_X, bar); // percentage bar
}

// led bar graph in main window
void drawBarGraph()
{
  myGLCD.setColor(255, 255, 255);                //static LED Chart
  setFont(SMALL, 255, 255, 255, 0, 0, 0);     
   
  myGLCD.drawRect(26, 132, 143, 133);            //x-line
  myGLCD.drawRect(26, 132, 27, 31);              //y-line
  myGLCD.setColor(128, 128, 128);				 
   for (int i=0; i<10; i++)                      //tick-marks  
   { myGLCD.drawLine(28, (i*10)+32, 30, (i*10)+32);
    for (int k=0; k<12; k++)
     myGLCD.drawPixel(29+(k*10), 32+(i*10));}

  myGLCD.print("100", 2, 27); 
  myGLCD.print("90", 10, 37);
  myGLCD.print("80", 10, 47); 
  myGLCD.print("70", 10, 57);
  myGLCD.print("60", 10, 67);
  myGLCD.print("50", 10, 77);
  myGLCD.print("40", 10, 87); 
  myGLCD.print("30", 10, 97);
  myGLCD.print("20", 10, 107);
  myGLCD.print("10", 10, 117);
  myGLCD.print("0", 18,  127);
}

int SliderBarsForChange(int TopSldY, int BopSldY, int y, int sbR, int sbG, int sbB, int sbX1, int sbX2)
{													// Slider bar vertical size: TopSldY/BotSldY
 											        // Y - value, sbR/sbG/sbB - colour
  int TempY;										// sbX1/sbX2 - horisontal size
  if (y<=TopSldY) {y=TopSldY;}
  if (y>=BotSldY) {y=BotSldY;} 

  if (SliderSwitch == true) {						  // for slider update after pressing up/down button 
 	  if (tSlide<=0) {tSlide=0;}				      // and for first time open slider windows
      if (tSlide>=100) {tSlide=100;} 
	  y = map(tSlide, 0, 100, BotSldY, TopSldY);	  // mapping 0-100 counter to slider size and draw
	  TempY = tSlide;								  // for display value in %	
      }    

  myGLCD.setColor(0, 0, 0);  
  myGLCD.fillRect(sbX1+1, y, sbX2-1, TopSldY);       //hide the bar (for white bar rectangle)
//myGLCD.fillRect(sbX1+1, y, sbX2-1, TopSldY+1);     //hide the bar (for color bar rectangle)
  myGLCD.setColor(sbR, sbG, sbB);                    //Slider Bar Color
  myGLCD.fillRect(sbX1+1, y, sbX2-1, BotSldY);       //draw the bar where you touch

  if (SliderSwitch == false) {						 // for TOUCH function, convert touch coordinate to 0-100% 	
         TempY = map(y, BotSldY, TopSldY, 0, 100);   // mapping slider size to 0-100% 
         if (TempY>=100) {TempY=100;}				 // slider change from 0% to 100%
         if (TempY<=0) {TempY=0;}
         }

   if (LedShannelFlag_on_off == false) 
     {setFont(LARGE, 200, 200, 200, 0, 0, 0);
	  myGLCD.print("O", sbX1-8+((sbX2- sbX1))/2, TopSldY-34 + (BotSldY -TopSldY)/2); 
	  myGLCD.print("F", sbX1-8+((sbX2- sbX1))/2, TopSldY-10 + (BotSldY -TopSldY)/2);
      myGLCD.print("F", sbX1-8+((sbX2- sbX1))/2, TopSldY+14 + (BotSldY -TopSldY)/2);
     }

//     setFont(SMALL, sbR, sbG, sbB, 0, 0, 0);     // set printed text colour
       setFont(SMALL, 255, 255, 255, 0, 0, 0);     // set printed text colour 
	if (TempY<10) 
      {myGLCD.print("  ", sbX1+0, BotSldY+2); 
	     myGLCD.printNumI(TempY, sbX1+16, BotSldY+2); myGLCD.print("%", sbX1+24, BotSldY+2);}
    if ((TempY>=10) && (TempY<100)) 
      {myGLCD.print("  ", sbX1+0, BotSldY+2); 
	     myGLCD.printNumI(TempY, sbX1+8, BotSldY+2); myGLCD.print("%", sbX1+24, BotSldY+2);}
	if (TempY>=100) 
        {myGLCD.printNumI(TempY, sbX1+0, BotSldY+2); myGLCD.print("%", sbX1+24, BotSldY+2);}

	tSlide = TempY;								   // temporary store previos value 
	return TempY;
}

void DrawAnalogClock(boolean refreshAll=false)
{
 if (refreshAll == true){
  TempSSminutes = 0;
  myGLCD.setColor(0, 0, 200);
  myGLCD.setBackColor(0, 0, 0);
  myGLCD.drawRoundRect (90, 10, 310, 230);              // draw clock frame
  myGLCD.drawRoundRect (91, 11, 309, 229);
  myGLCD.drawRoundRect (92, 12, 308, 228);
  myGLCD.drawRoundRect (93, 13, 307, 227);

  drawDOWDATE(); // draw DOW and frame

  myGLCD.setFont(BigFont);
  myGLCD.setColor(200, 200, 200);
  myGLCD.print("3", clockCenterX+87, clockCenterY-8);
  myGLCD.print("9", clockCenterX-100, clockCenterY-8);
  myGLCD.print("6", clockCenterX-8, clockCenterY+87);
  myGLCD.print("12", clockCenterX-16, clockCenterY-85-16);
  
  for (int i=0; i<12; i++)
  { if ((i % 3)!=0) drawMark(i); }  
                     }

  t.dow=calcDOW(t.date, t.mon, t.year);
  if (t.min == 0) { drawDOWDATE(); }    // update DOW every new hour
  if (t.min != TempSSminutes) {         // update DOW every 1min
		 drawMin(t.min);				// drawing the clock hands
		 drawHour(t.hour, t.min);		// drawing the clock hands 
		 TempSSminutes = t.min;

  myGLCD.setColor(255, 255, 0);
  myGLCD.drawCircle(clockCenterX, clockCenterY, 6);
  myGLCD.fillCircle(clockCenterX, clockCenterY, 6);
  myGLCD.setColor(0, 255, 0);
  myGLCD.drawCircle(clockCenterX, clockCenterY, 4);
  myGLCD.fillCircle(clockCenterX, clockCenterY, 4);

  }
  
}

void drawMark(int h)
{
  float x1, y1, x2, y2;
  
  h=h*30;
  h=h+270;
  
  x1=110*cos(h*0.0175);
  y1=110*sin(h*0.0175);
  x2=100*cos(h*0.0175);
  y2=100*sin(h*0.0175);
  myGLCD.setFont(SmallFont);
  myGLCD.setColor(200, 200, 200);
  myGLCD.print("*", (x1+x2)/2 +clockCenterX, (y1+y2)/2 +clockCenterY);

}

void drawDOWDATE()
{ 
  myGLCD.setColor(0, 0, 200);
  myGLCD.setBackColor(0, 0, 0);
  myGLCD.drawRect(176, 152, 228, 172);     // draw dow/date frame
  myGLCD.drawRect(177, 153, 227, 171);     
  myGLCD.drawLine (205, 152, 205, 172);
  myGLCD.drawLine (206, 152, 206, 172);

  myGLCD.setColor(200, 200, 200);
  myGLCD.setFont(SmallFont);
  SS_DOW_x=180;
  showDOW_ScreenSaver(t.dow);
  
  if (t.date <10) { myGLCD.print(" ", 210, 157);
	  myGLCD.printNumI(t.date, 218, 157);}
  else { myGLCD.printNumI(t.date, 210, 157);}
}

void drawHandClock (float x1, float x2, float x3, float x4, float y1, float y2, float y3, float y4, boolean cycle= false )
{
if (cycle == true){
for (int i=-1 ; i<=1; i++) {
	myGLCD.drawLine(x1+clockCenterX+i, y1+clockCenterY+i, x3+clockCenterX+i, y3+clockCenterY+i);
	myGLCD.drawLine(x3+clockCenterX+i, y3+clockCenterY+i, x2+clockCenterX+i, y2+clockCenterY+i);
	myGLCD.drawLine(x2+clockCenterX+i, y2+clockCenterY+i, x4+clockCenterX+i, y4+clockCenterY+i);
	myGLCD.drawLine(x4+clockCenterX+i, y4+clockCenterY+i, x1+clockCenterX+i, y1+clockCenterY+i);}}

else {myGLCD.drawLine(x1+clockCenterX, y1+clockCenterY, x3+clockCenterX, y3+clockCenterY);
	  myGLCD.drawLine(x3+clockCenterX, y3+clockCenterY, x2+clockCenterX, y2+clockCenterY);
	  myGLCD.drawLine(x2+clockCenterX, y2+clockCenterY, x4+clockCenterX, y4+clockCenterY);
	  myGLCD.drawLine(x4+clockCenterX, y4+clockCenterY, x1+clockCenterX, y1+clockCenterY);}
}

void drawMin(int m)
{
  float x1, y1, x2, y2, x3, y3, x4, y4;
  int pm = m-1;

 if (pm==-1)
    pm=59;
  pm=pm*6;
  pm=pm+270;
  
  x1=80*cos(pm*0.0175);
  y1=80*sin(pm*0.0175);
  x2=5*cos(pm*0.0175);
  y2=5*sin(pm*0.0175);
  x3=30*cos((pm+4)*0.0175);
  y3=30*sin((pm+4)*0.0175);
  x4=30*cos((pm-4)*0.0175);
  y4=30*sin((pm-4)*0.0175);

  myGLCD.setColor(0, 0, 0);     // clear previos hands clock
  drawHandClock (x1, x2, x3, x4, y1, y2, y3, y4, true); 
 
    if ((t.min >20 && t.min <40))   // redraw dow/date frame
	{drawDOWDATE();}  // redraw dow/date frame

  m=m*6;
  m=m+270;
  
  x1=80*cos(m*0.0175);
  y1=80*sin(m*0.0175);
  x2=5*cos(m*0.0175);
  y2=5*sin(m*0.0175);
  x3=30*cos((m+4)*0.0175);
  y3=30*sin((m+4)*0.0175);
  x4=30*cos((m-4)*0.0175);
  y4=30*sin((m-4)*0.0175);

  myGLCD.setColor(0, 255, 0);   // draw current hands clock
  drawHandClock (x1, x2, x3, x4, y1, y2, y3, y4, false);

}

void drawHour(int h, int m)
{
  float x1, y1, x2, y2, x3, y3, x4, y4;
  int ph = h;
  
  if (m==0)
  {
    ph=((ph-1)*30)+((m+59)/2);
  }
  else
  {
    ph=(ph*30)+((m-1)/2);
  }
  ph=ph+270;
  
  x1=60*cos(ph*0.0175);
  y1=60*sin(ph*0.0175);
  x2=5*cos(ph*0.0175);
  y2=5*sin(ph*0.0175);
  x3=20*cos((ph+5)*0.0175);
  y3=20*sin((ph+5)*0.0175);
  x4=20*cos((ph-5)*0.0175);
  y4=20*sin((ph-5)*0.0175);
  
  myGLCD.setColor(0, 0, 0);     // clear previos hands clock
  drawHandClock (x1, x2, x3, x4, y1, y2, y3, y4, true); 

  if ((t.hour >16 && t.hour <20))  // redraw dow/date frame
	{drawDOWDATE();}  // redraw dow/date frame
  
  h=(h*30)+(m/2);
  h=h+270;
  
  x1=60*cos(h*0.0175);
  y1=60*sin(h*0.0175);
  x2=5*cos(h*0.0175);
  y2=5*sin(h*0.0175);
  x3=20*cos((h+5)*0.0175);
  y3=20*sin((h+5)*0.0175);
  x4=20*cos((h-5)*0.0175);
  y4=20*sin((h-5)*0.0175);

  myGLCD.setColor(255, 255, 0);  // draw current hands clock
  drawHandClock (x1, x2, x3, x4, y1, y2, y3, y4, false); 
  
}

void DrawTemperatureScreen(boolean refreshAll=false)
{
	String deg;  
	if (setTempScale==1) {deg ="F";}               //Print deg C or deg F
    else {deg = "C";}
    degC_F=deg;
    char bufferDeg[2];
    degC_F.toCharArray(bufferDeg,2);
	int ShiftDrawY =0;
    myGLCD.setFont(BigFont); 
	myGLCD.setColor(0, 0, 255);
	myGLCD.setBackColor(0, 0, 0);

	if (refreshAll== true ) {
          if (counterB1 ==1 || counterB2 ==1 || counterB3 ==1)
	      {
			if (tempW !=0) {
			strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[3]))); // "Water"
			myGLCD.print(buffer, 48 , 100);
			strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[68]))); // ": "
			myGLCD.print(buffer, 144 , 100);
			myGLCD.printNumF( tempW, 1, 176, 100);         // print water temp
			myGLCD.drawCircle(240, 100, 1);              
			myGLCD.print(bufferDeg, 245, 100);
			               } 
	      }

	  if (counterB1 ==2 || counterB2 ==2 || counterB3 ==2)
	     { 
	    if (((counterB1 + counterB2 + counterB3) == 2) || ((counterB1 + counterB2 + counterB3) == 5)) {ShiftDrawY= 0;}
	    if (((counterB1 + counterB2 + counterB3) == 3) || ((counterB1 + counterB2 + counterB3) == 6)) {ShiftDrawY= 20;}
		    if (tempH1 !=0) {
			strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[4]))); // "H1"
			myGLCD.print(buffer, 32 , 100+ShiftDrawY);
			strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[68]))); // ": "
			myGLCD.print(buffer, 144, 100+ShiftDrawY);
			myGLCD.printNumF( tempH1, 1, 176, 100+ShiftDrawY);         // print H1 temp
			myGLCD.drawCircle(240, 100+ShiftDrawY, 1);              
			myGLCD.print(bufferDeg, 245, 100+ShiftDrawY);
			                }
		 }


	  if (counterB1 ==3 || counterB2 ==3 || counterB3 ==3)
	     {   
		if ((counterB1 + counterB2 + counterB3) == 3) {ShiftDrawY= 0;}
	    if (((counterB1 + counterB2 + counterB3) == 4) || ((counterB1 + counterB2 + counterB3) == 5)) {ShiftDrawY= 20;}
		if ((counterB1 + counterB2 + counterB3) == 6) {ShiftDrawY= 40;}
		    if (tempH2 !=0) {
			strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[5]))); // "H2"
			myGLCD.print(buffer, 32 , 100+ShiftDrawY);
			strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[68]))); // ": "
			myGLCD.print(buffer, 144, 100+ShiftDrawY);
			myGLCD.printNumF( tempH2, 1, 176, 100+ShiftDrawY);         // print H2 temp
			myGLCD.drawCircle(240, 100+ShiftDrawY, 1);              
			myGLCD.print(bufferDeg, 245, 100+ShiftDrawY);
			                }
	    }
	}
}

void DrawDigitalClock(boolean refreshAll=false)
{
	if (refreshAll== true && setTimeFormat==0) {
	myGLCD.setColor(0, 0, 200);
	myGLCD.setBackColor(0, 0, 0);
	myGLCD.drawRoundRect (77, 67, 243, 158);              // draw clock frame for 24HR format
	myGLCD.drawRoundRect (76, 68, 244, 159);              // draw clock frame
	myGLCD.drawRoundRect (75, 69, 245, 160);              // draw clock frame
	myGLCD.fillCircle(141, 88, 4);						  // draw : symbol
	myGLCD.fillCircle(141, 112, 4);					      // draw : symbol beetween hour and min
	}

  if (setTimeFormat==0)                                   //display 24HR Format
    { 
	myGLCD.setColor(0, 0, 255);
    myGLCD.setBackColor(0, 0, 0);  

	
#ifdef Graph16_lib
myGLCD.setFont(SevenSegNumFontPlus);
#else
myGLCD.setFont(SevenSegNumFont);
#endif

//  myGLCD.setFont(SevenSegNumFont);
//	myGLCD.setFont(DotMatrix_XL_Num);
    myGLCD.print(rtc.getTimeStr(FORMAT_SHORT), CENTER, 75);  // print time
    myGLCD.setFont(BigFont);
    myGLCD.print(rtc.getDateStr(FORMAT_LONG), 80, 137);
    }

if (refreshAll== true && setTimeFormat==1) {
	myGLCD.setColor(0, 0, 200);
	myGLCD.setBackColor(0, 0, 0);
	myGLCD.drawRoundRect (77, 67, 263, 158);              // draw clock frame for 12HR format
	myGLCD.drawRoundRect (76, 68, 264, 159);              // draw clock frame
	myGLCD.drawRoundRect (75, 69, 265, 160);              // draw clock frame
	}

  if (setTimeFormat==1)                                 //display 12HR Format
    {
     myGLCD.setColor(0, 0, 255);
     myGLCD.setBackColor(0, 0, 0);  
//   myGLCD.setFont(SevenSegNumFont);

#ifdef Graph16_lib
myGLCD.setFont(SevenSegNumFontPlus);
#else
myGLCD.setFont(SevenSegNumFont);
#endif

     if (t.hour==0)                                     //Display HOUR
       { myGLCD.print("12", 61, 75);}

     if ((t.hour>=1) && (t.hour<=9))
       { myGLCD.setColor(0, 0, 0);
         myGLCD.fillRect(61, 95, 92, 145);
         myGLCD.setColor(0, 0, 255);
         myGLCD.printNumI(t.hour, 93, 75);}

     if ((t.hour>=10) && (t.hour<=12))
       { myGLCD.printNumI(t.hour, 61, 75);}

     if ((t.hour>=13) && (t.hour<=21))
       { myGLCD.setColor(0, 0, 0);
         myGLCD.fillRect(61, 95, 92, 145);
         myGLCD.setColor(0, 0, 255);
         myGLCD.printNumI(t.hour-12, 93, 75);}
     if (t.hour>=22)
       myGLCD.printNumI(t.hour-12, 61, 75);

		myGLCD.fillCircle(141, 88, 4);				// draw : symbol
		myGLCD.fillCircle(141, 112, 4);             // draw : symbol beetween hour and min

		myGLCD.printNumI(t.min, 157, 75, 2, '0');    //Display MINUTES

	 setFont(LARGE, 0, 0, 255, 0, 0, 0);
     if ((t.hour>=0) && (t.hour<=11))                   //Display AM/PM
       { myGLCD.print("AM", 225, 79);}
     else
       { myGLCD.print("PM", 225, 79);} 

	 myGLCD.setFont(BigFont);
     myGLCD.print(rtc.getDateStr(FORMAT_LONG), 80, 137);
    }

     
}
void screenSaverBrightness()
{ if (BrigthnessCount <= 0) {analogWrite(BackLite, 0); }
  if (BrigthnessCount == 1) {analogWrite(BackLite, 63); }
  if (BrigthnessCount == 2) {analogWrite(BackLite, 127); }
  if (BrigthnessCount == 3) {analogWrite(BackLite, 191); }
  if (BrigthnessCount >= 4) {analogWrite(BackLite, 255); }
}

void screenSaver()                               // Make the Screen Go ScreenSaver after so long 
{        myGLCD.setColor(0, 0, 150);
         setScreenSaverTimer = setSSmintues * 12;       // 5sec*12=1 min, convert minutes to 5sec stepping

  
		if ((setScreensaverOnOff==1) && (tempAlarmflagW==false))
		   { if (screenSaverCounter <= setScreenSaverTimer) {screenSaverCounter++;}         // increment screen saver time
		                                               //screenSaverCounter +=6; } // test only 

        if (screenSaverCounter==setScreenSaverTimer)
		  {	dispScreen=24; 
            myGLCD.clrScr();
            screenSaverBrightness();
			if (ClockType==1)  {DrawAnalogClock(true);}       //display TIME in screensaver
			if (ClockType==2)  {DrawDigitalClock(true);}      //display TIME in screensaver
			if (ClockType==3)  {DrawTemperatureScreen(true);} //display Temperature in screensaver
         													  // "Blank" screensaver
            if (setLockScreen ==1)
			{ButtonShift = random (0, 200);
			printButtonTouch("Touch", touchLock[0], touchLock[1]-ButtonShift, touchLock[2], touchLock[3]-ButtonShift, SMALL);}
		  }

		if (screenSaverCounter > setScreenSaverTimer)             
		 {
 			if (ClockType==1)  {DrawAnalogClock(false);}        //display TIME in screensaver
			if (ClockType==2)  {DrawDigitalClock(false);}       //display TIME in screensaver
			if (ClockType==3)  {DrawTemperatureScreen(true);}   //display Temperature in screensaver
         													    // "Blank" screensaver

			 if (setLockScreen ==1)
			  {
                 firstTouch  = false;						    // clear touch flag and button "Again" after timeout 5sec, if no pressed AGAIN
                 myGLCD.setColor(0, 0, 0);
//               myGLCD.fillRect(Again[0], Again[1], Again[2]+2, Again[3]+2);       // clear button "Again"
				 myGLCD.fillRect(touchLock[0], 240-(touchLock[1]-ButtonShift-3), touchLock[2], 240-(touchLock[3]-ButtonShift+3));

				 myGLCD.fillRect(touchLock[0], touchLock[1]-ButtonShift-3, touchLock[2], touchLock[3]-ButtonShift+3); // clear button TOUCH
				 ButtonShift = random (0, 200);
				 printButtonTouch("Touch", touchLock[0], touchLock[1]-ButtonShift, touchLock[2], touchLock[3]-ButtonShift, SMALL);
			 	 screenSaverBrightness();
			  }
		  }	  
     }
 }

void ScreensaverSelect()
{
	printButton("    ", 206, 20, 310, 40, SMALL);
	setFont(SMALL, 255, 255, 255, 0, 0, 255);
    strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[64+ClockType]))); // ClockType = 0/1/2/3/ -> Blanc/An.Clock/Dig.Clock/Temperature
    myGLCD.print(buffer, 214, 24);

    printButton("    ", 206, 82, 260, 102, SMALL); // print button "background brightness"
	setFont(SMALL, 255, 255, 255, 0, 0, 255);
	strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[59+BrigthnessCount]))); // counter = 0/1/2/3/4 -> 0%-25%-50%-75%-100%
	myGLCD.print(buffer, 217, 86);
}


void genSetSelect_1()
{
	 
 if (setCalendarFormat==0)                      //Calendar Format Buttons
     { myGLCD.setColor(0, 0, 255);
       myGLCD.fillRoundRect(185, 49, 305, 69);    
       setFont(SMALL, 255, 255, 255, 0, 0, 255);     
       myGLCD.print(" DD/MM/YYYY ", 199, 53);
     }
 else {myGLCD.setColor(0, 0, 255);
       myGLCD.fillRoundRect(185, 49, 305, 69);    
       setFont(SMALL, 255, 255, 255, 0, 0, 255);     
	   myGLCD.print("MTH DD, YYYY", 199, 53);   
      }

   if (displayDOW==1)                             //Show/Hide the Day of the Week 
    { myGLCD.setColor(0, 0, 255);
      myGLCD.fillRoundRect(185, 79, 229, 99);
      setFont(SMALL, 255, 255, 255, 0, 0, 255);  
      myGLCD.print(" ON ", 193, 83);    
    }
    else 
      { myGLCD.setColor(0, 0, 255);
        myGLCD.fillRoundRect(185, 79, 229, 99);
        setFont(SMALL, 255, 255, 255, 0, 0, 255);
        myGLCD.print("OFF", 199, 83);    
      }  

    if (setTimeFormat==0)                          //Time Format Buttons
      { myGLCD.setColor(0, 0, 255);
        myGLCD.fillRoundRect(185, 109, 229, 129);      
        setFont(SMALL, 255, 255, 255, 0, 0, 255);
        myGLCD.print("24HR", 191, 113);   
    }
    else 
      { myGLCD.setColor(0, 0, 255);
        myGLCD.fillRoundRect(185, 109, 229, 129);      
        setFont(SMALL, 255, 255, 255, 0, 0, 255);
        myGLCD.print("12HR", 191, 113);   
      }

 if (setTempScale==0)                           //Temperature Scale Buttons
    { myGLCD.setColor(0, 0, 255);
      myGLCD.fillRoundRect(185, 139, 229, 159);
      setFont(SMALL, 255, 255, 255, 0, 0, 255);  
      myGLCD.print("C", 205, 142);   
      myGLCD.drawCircle(200, 144, 1);              
    }
    else 
      {myGLCD.setColor(0, 0, 255);
      myGLCD.fillRoundRect(185, 139, 229, 159);
      setFont(SMALL, 255, 255, 255, 0, 0, 255);  
      myGLCD.print("F", 205, 142);   
      myGLCD.drawCircle(200, 144, 1);              
      }  

  myGLCD.setColor(0, 0, 255);                    //Change Time/Date Button
  myGLCD.fillRoundRect(185, 19, 305, 39);
  setFont(SMALL, 255, 255, 255, 0, 0, 255);  
  myGLCD.print(" Time/Date", 199, 23);

  myGLCD.setColor(0, 0, 255);                    //Change Fan Startup Temps Button
  myGLCD.fillRoundRect(185, 169, 305, 189);
  setFont(SMALL, 255, 255, 255, 0, 0, 255);  
  myGLCD.print("Change Temp", 199, 173);
  
  myGLCD.setColor(255, 255, 255);
  myGLCD.drawRoundRect(185, 19, 305, 39);		// time and date
  myGLCD.drawRoundRect(185, 49, 305, 69);		// calendar
  myGLCD.drawRoundRect(185, 79, 229, 99);       // day of week 
  myGLCD.drawRoundRect(185, 109, 229, 129);     // 12/24
  myGLCD.drawRoundRect(185, 139, 229, 159);     // C/F
  myGLCD.drawRoundRect(185, 169, 305, 189);     // fan

}    


void genSetSelect_2()
{

	 if (setDimLEDsOnOff==1)                             
    {   myGLCD.setColor(0, 0, 255);
        myGLCD.fillRoundRect(130, 19, 174, 39);
	    myGLCD.fillRoundRect(185, 19, 305, 39);
        setFont(SMALL, 255, 255, 255, 0, 0, 255);  
        myGLCD.print(" ON ", 138, 23);
	    myGLCD.print("Change Temp", 203, 23);
    }
    else 
      { myGLCD.setColor(0, 0, 255);
        myGLCD.fillRoundRect(130, 19, 174, 39);
    	setFont(SMALL, 255, 255, 255, 0, 0, 255);
        myGLCD.print("OFF", 144, 23);

		myGLCD.setColor(64, 64, 64);
		myGLCD.fillRoundRect(185, 19, 305, 39);
		setFont(SMALL, 255, 255, 255, 64, 64, 64);
		myGLCD.print("Change Temp", 203, 23);
      }  

if (setScreensaverOnOff==1)                         //Screensaver Buttons
    {   myGLCD.setColor(0, 0, 255);
	    myGLCD.fillRoundRect(130, 49, 174, 69);
	    myGLCD.fillRoundRect(185, 49, 305, 69);
	    setFont(SMALL, 255, 255, 255, 0, 0, 255); 
        myGLCD.print(" ON ", 138, 53);    
//	    myGLCD.print("Setting", 217, 53);
		myGLCD.print(print_text[21], 217, 53);
    }
    else 
      { myGLCD.setColor(0, 0, 255);
        myGLCD.fillRoundRect(130, 49, 174, 69);
    	setFont(SMALL, 255, 255, 255, 0, 0, 255);
        myGLCD.print("OFF", 144, 53);

		myGLCD.setColor(64, 64, 64);
		myGLCD.fillRoundRect(185, 49, 305, 69);
		setFont(SMALL, 255, 255, 255, 64, 64, 64);
//		myGLCD.print("Setting", 217, 53);
		myGLCD.print(print_text[21], 217, 53);
      }  

if (MAX_Temp_on_off ==1)                            // Display MAX TEMP is ON
    {  myGLCD.setColor(0, 0, 255);
       myGLCD.fillRoundRect(185, 79, 229, 99);
       setFont(SMALL, 255, 255, 255, 0, 0, 255);  
       myGLCD.print(" ON ", 193, 83);    
    }
    else 
      { myGLCD.setColor(0, 0, 255);
        myGLCD.fillRoundRect(185, 79, 229, 99);
        setFont(SMALL, 255, 255, 255, 0, 0, 255);
        myGLCD.print("OFF", 199, 83);    
      }  

if (SoftStartON ==1)                            // Display MAX TEMP is ON
    {  myGLCD.setColor(0, 0, 255);
       myGLCD.fillRoundRect(185, 109, 229, 129);
       setFont(SMALL, 255, 255, 255, 0, 0, 255);  
       myGLCD.print(" ON ", 193, 113);    
    }
    else 
      { myGLCD.setColor(0, 0, 255);
        myGLCD.fillRoundRect(185, 109, 229, 129);
        setFont(SMALL, 255, 255, 255, 0, 0, 255);
        myGLCD.print("OFF", 199, 113);    
      }  
//----------------ALARM LEVEL -------------------------------
	   myGLCD.setColor(0, 0, 255);
       myGLCD.fillRoundRect(185, 139, 305, 159);
	   myGLCD.drawRoundRect(185, 139, 305, 159);
       setFont(SMALL, 255, 255, 255, 0, 0, 255);  
	   strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[56+AlarmLevel]))); // 
	   myGLCD.print(buffer, 193, 143);


  myGLCD.setColor(255, 255, 255);
  myGLCD.drawRoundRect(130, 19, 174, 39);       // dim led on/off
  myGLCD.drawRoundRect(185, 19, 305, 39);       // dim led 
  myGLCD.drawRoundRect(130, 49, 174, 69);       // screen saver on/off
  myGLCD.drawRoundRect(185, 49, 305, 69);       // screen saver 
  myGLCD.drawRoundRect(185, 79, 229, 99);       // Max Temp
  myGLCD.drawRoundRect(185, 109, 229, 129);     // Soft Start
  myGLCD.drawRoundRect(185, 139, 305, 159);     // Buzzer ON/OFF
}  

/*
void feedingTimeOnOff()
{
  if ((feedTime==1) && (FEEDTime1==1))
    { myGLCD.setColor(0, 255, 0);
      myGLCD.fillRoundRect(70, 150, 250, 170); 
      setFont(SMALL, 0, 0, 0, 0, 255, 0);
//    myGLCD.print("Feeding Time 1 ON", 94, 154);}
  	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[25]))); 
      myGLCD.print(buffer, 94, 154);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[29]))); 
	  myGLCD.print(buffer, 94+120, 154);}

  if ((feedTime==1) && (FEEDTime1==0))
    { myGLCD.setColor(255, 0, 0);
      myGLCD.fillRoundRect(70, 150, 250, 170); 
      setFont(SMALL, 255, 255, 255, 255, 0, 0);
//    myGLCD.print("Feeding Time 1 OFF", 90, 154);}
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[25]))); 
      myGLCD.print(buffer, 90, 154);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[30]))); 
	  myGLCD.print(buffer, 90+120, 154);}

  if ((feedTime==2) && (FEEDTime2==1))
    { myGLCD.setColor(0, 255, 0);
      myGLCD.fillRoundRect(70, 150, 250, 170); 
      setFont(SMALL, 0, 0, 0, 0, 255, 0);
//    myGLCD.print("Feeding Time 2 ON", 94, 154);}
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[26]))); 
      myGLCD.print(buffer, 94, 154);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[29]))); 
	  myGLCD.print(buffer, 94+120, 154);}

  if ((feedTime==2) && (FEEDTime2==0))
    { myGLCD.setColor(255, 0, 0);
      myGLCD.fillRoundRect(70, 150, 250, 170); 
      setFont(SMALL, 255, 255, 255, 255, 0, 0);
//    myGLCD.print("Feeding Time 2 OFF", 90, 154);}
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[26]))); 
      myGLCD.print(buffer, 90, 154);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[30]))); 
	  myGLCD.print(buffer, 90+120, 154);}

  if ((feedTime==3) && (FEEDTime3==1))
    { myGLCD.setColor(0, 255, 0);
      myGLCD.fillRoundRect(70, 150, 250, 170); 
      setFont(SMALL, 0, 0, 0, 0, 255, 0);
//    myGLCD.print("Feeding Time 3 ON", 94, 154);}
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[27]))); 
      myGLCD.print(buffer, 94, 154);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[29]))); 
	  myGLCD.print(buffer, 94+120, 154);}

  if ((feedTime==3) && (FEEDTime3==0))
    { myGLCD.setColor(255, 0, 0);
      myGLCD.fillRoundRect(70, 150, 250, 170); 
      setFont(SMALL, 255, 255, 255, 255, 0, 0);
//    myGLCD.print("Feeding Time 3 OFF", 90, 154);}
   	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[27]))); 
      myGLCD.print(buffer, 90, 154);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[30]))); 
	  myGLCD.print(buffer, 90+120, 154);}

  if ((feedTime==4) && (FEEDTime4==1))
    { myGLCD.setColor(0, 255, 0);
      myGLCD.fillRoundRect(70, 150, 250, 170); 
      setFont(SMALL, 0, 0, 0, 0, 255, 0);
//      myGLCD.print("Feeding Time 4 ON", 94, 154);}
   	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[28]))); 
      myGLCD.print(buffer, 94, 154);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[29]))); 
	  myGLCD.print(buffer, 94+120, 154);}

  if ((feedTime==4) && (FEEDTime4==0))
    { myGLCD.setColor(255, 0, 0);
      myGLCD.fillRoundRect(70, 150, 250, 170); 
      setFont(SMALL, 255, 255, 255, 255, 0, 0);
//      myGLCD.print("Feeding Time 4 OFF", 90, 154);}
   	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[28]))); 
      myGLCD.print(buffer, 90, 154);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[30]))); 
	  myGLCD.print(buffer, 90+120, 154);}

  myGLCD.setColor(255, 255, 255);
  myGLCD.drawRoundRect(70, 150, 250, 170);   
}
*/

/******************************* END OF MISC. FUNCTIONS *******************************/


/*********************** MAIN SCREEN ********** dispScreen = 0 ************************/
void mainScreen(boolean refreshAll=false)
{
  int ledLevel, bar;
  String oldval, deg;  
  char buffer_Led_Out[8];  

  TimeDateBar(true);
  
  oldval = day;                                  //refresh day if different
  day = String(t.date);
  if ((oldval!=day) || refreshAll)
    {
     myGLCD.setColor(64, 64, 64);                //Draw Borders & Dividers in Grey
     myGLCD.drawRect(0, 0, 319, 239);            //Outside Border
     myGLCD.drawRect(158, 14, 160, 226);         //Vertical Divider
     myGLCD.drawRect(160, 125, 319, 127);        //Horizontal Divider
	 myGLCD.drawRect(0, 188, 158, 190);          //Horizontal Divider 
     myGLCD.fillRect(0, 0, 319, 14);             //Top Bar
     myGLCD.setColor(0, 0, 0);
     myGLCD.drawLine(159, 126, 161, 126);        //Horizontal Divider Separator     
     setFont(SMALL, 255, 255, 0, 64, 64, 64);
//   myGLCD.print("Jarduino AQUA Controller V1.2 Oleg mod", CENTER, 1);
	 PrintStringIndex=35; 
     printHeader ();
     setFont(SMALL, 255, 255, 255, 0, 0, 0);
//     myGLCD.print("LED ARRAY", 52, 15);
//     myGLCD.print("LUNAR PHASE", 196, 20); 
//     myGLCD.print("MONITORS & ALERTS", 174, 133);
	 strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[51]))); 
     myGLCD.print(buffer, 52, 15);
	 strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[52]))); 
     myGLCD.print(buffer, 196, 20);
	 strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[53]))); 
     myGLCD.print(buffer, 174, 133);
     
     float lunarCycle = moonPhase(t.year, t.mon, t.date); //get a value for the lunar cycle
     myGLCD.drawBitmap(211, 35, 58, 58, MoonPic, 1);      //Moon Phase Picture (middle 240,64)
     setFont(SMALL, 176, 176, 176, 0, 0, 0);            
     char bufferLP[16];
     LP.toCharArray(bufferLP, 16);
     myGLCD.print(bufferLP, 180, 96);            //Print Moon Phase Description to LCD
     if ((lunarCycle*100) < 1)                   //Print % of Full to LCD
       { myGLCD.print(" 0.0", 188, 108); }
       else { myGLCD.printNumF(lunarCycle*100, 1, 188, 108);}
//     myGLCD.print("% of Full", 220, 108);
	   strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[54]))); 
       myGLCD.print(buffer, 220, 108);
    }


  if ((tvLed!=tvled_out) || refreshAll)         //refresh TV led display
   {
    tvLed = tvled_out;
	ledLevel = LedToPercent(tvled_out, ResolutionLow);
//	oldval = "TV: " + String(ledLevel) + "% ";
	oldval = ChName[10] + String(ledLevel) + ChName[9];
	oldval.toCharArray(buffer_Led_Out, 6);
	SmallLedBarGraph(tvled_out, ResolutionLow, 0, rgbCh6[0], rgbCh6[1], rgbCh6[2]); // led_out, resoluton, Xshift, bar color
	setFont(SMALL, 0, 255, 0, 0, 0, 0);
	myGLCD.print(ChName[6], 10, 137);
	myGLCD.print(buffer_Led_Out, 10+16, 137);
	
   }    
#ifdef Standard_shield
     if ((redLed!=rled_out) || refreshAll)          //refresh red led display
   {
    redLed = rled_out;
    ledLevel = LedToPercent(rled_out, ResolutionLow);
	oldval = ChName[10] + String(ledLevel) + ChName[9];
	oldval.toCharArray(buffer_Led_Out, 6);
    SmallLedBarGraph(rled_out, ResolutionLow, 14, rgbCh5[0], rgbCh5[1], rgbCh5[2]); // led_out, resoluton, Xshift, bar color
	setFont(SMALL, 0, 255, 0, 0, 0, 0);
	myGLCD.print(ChName[5], 10, 149);
    myGLCD.print(buffer_Led_Out, 10+16, 149);
   }
#else
  if ((redLed!=rled_out) || refreshAll)          //refresh red led display
   {
    redLed = rled_out;
    ledLevel = LedToPercent(rled_out, ResolutionHigh);
//	oldval = "DR: " + String(ledLevel) + "% ";
	oldval = ChName[10] + String(ledLevel) + ChName[9];
	oldval.toCharArray(buffer_Led_Out, 6);
	SmallLedBarGraph(rled_out, ResolutionHigh, 14, rgbCh5[0], rgbCh5[1], rgbCh5[2]); // led_out, resoluton, Xshift, bar color
    setFont(SMALL, 0, 255, 0, 0, 0, 0);      
	myGLCD.print(ChName[5], 10, 149);
    myGLCD.print(buffer_Led_Out, 10+16, 149);
   }    
#endif

  if ((whiteLed!=wled_out) || refreshAll)        //refresh white led display
   {
    whiteLed = wled_out;
    ledLevel = LedToPercent(wled_out, ResolutionHigh);
//	oldval = "CW: " + String(ledLevel) + "% ";
	oldval = ChName[10] + String(ledLevel) + ChName[9];
	oldval.toCharArray(buffer_Led_Out, 6);
	SmallLedBarGraph(wled_out, ResolutionHigh, 28, rgbCh2[0], rgbCh2[1], rgbCh2[2]); // led_out, resoluton, Xshift, bar color
    setFont(SMALL, 0, 255, 0, 0, 0, 0);
	myGLCD.print(ChName[2], 10, 161);
    myGLCD.print(buffer_Led_Out, 10+16, 161);
    }
     
  if ((blueLed!=bled_out) || refreshAll)         //refresh blue led displays
   {
    blueLed = bled_out;
    ledLevel = LedToPercent(bled_out, ResolutionHigh);
//  oldval = "Bl: " + String(ledLevel) + "% ";
	oldval = ChName[10] + String(ledLevel) + ChName[9];
	oldval.toCharArray(buffer_Led_Out, 6);
	SmallLedBarGraph(bled_out, ResolutionHigh, 42, rgbCh4[0], rgbCh4[1], rgbCh4[2]); // led_out, resoluton, Xshift, bar color
    setFont(SMALL, 0, 255, 0, 0, 0, 0);
	myGLCD.print(ChName[4], 10, 173);
    myGLCD.print(buffer_Led_Out, 10+16, 173);
   }

#ifdef Standard_shield
      if ((rblueLed!=rbled_out) || refreshAll)       //refresh royal blue led display
   {
    rblueLed = rbled_out;
#ifdef Timers_8bit
    ledLevel = LedToPercent(rbled_out, ResolutionLow);
	oldval = ChName[10] + String(ledLevel) + ChName[9];
	oldval.toCharArray(buffer_Led_Out, 6);
    SmallLedBarGraph(rbled_out, ResolutionLow, 56, rgbCh3[0], rgbCh3[1], rgbCh3[2]); // led_out, resoluton, Xshift, bar color
#endif
#ifdef Timers_8_11bit
    ledLevel = LedToPercent(rbled_out, ResolutionHigh);
	oldval = ChName[10] + String(ledLevel) + ChName[9];
	oldval.toCharArray(buffer_Led_Out, 6);
	SmallLedBarGraph(rbled_out, ResolutionHigh, 56, rgbCh3[0], rgbCh3[1], rgbCh3[2]); // led_out, resoluton, Xshift, bar color
#endif
	setFont(SMALL, 0, 255, 0, 0, 0, 0);
	myGLCD.print(ChName[3], 85, 137);
    myGLCD.print(buffer_Led_Out, 85+16, 137);
   }
#else
  if ((rblueLed!=rbled_out) || refreshAll)       //refresh royal blue led display
   {
    rblueLed = rbled_out;
    ledLevel = LedToPercent(rbled_out, ResolutionLow);
//  oldval = "RB: " + String(ledLevel) + "% "; 
	oldval = ChName[10] + String(ledLevel) + ChName[9];
	oldval.toCharArray(buffer_Led_Out, 8);
	SmallLedBarGraph(rbled_out, ResolutionLow, 56, rgbCh3[0], rgbCh3[1], rgbCh3[2]); // led_out, resoluton, Xshift, bar color
	setFont(SMALL, 0, 255, 0, 0, 0, 0);
	myGLCD.print(ChName[3], 85, 137);
    myGLCD.print(buffer_Led_Out, 85+16, 137);

   }
#endif

  if ((uvLed!=uvled_out) || refreshAll)          //refresh UV led display
   {
    uvLed = uvled_out;
    ledLevel = LedToPercent(uvled_out, ResolutionLow);
//  oldval = "UV: " + String(ledLevel) + "% ";
	oldval = ChName[10] + String(ledLevel) + ChName[9];
	oldval.toCharArray(buffer_Led_Out, 6);
	SmallLedBarGraph(uvled_out, ResolutionLow, 70, rgbCh1[0], rgbCh1[1], rgbCh1[2]); // led_out, resoluton, Xshift, bar color
    setFont(SMALL, 0, 255, 0, 0, 0, 0);
	myGLCD.print(ChName[1], 85, 149);
    myGLCD.print(buffer_Led_Out, 85+16, 149);
   }

  if ((cyLed!=cyled_out) || refreshAll)          //refresh Cyan led display
   {
    cyLed = cyled_out;
    ledLevel = LedToPercent(cyled_out, ResolutionHigh);
//  oldval = "CY: " + String(ledLevel) + "% "; 
	oldval = ChName[10] + String(ledLevel) + ChName[9];
	oldval.toCharArray(buffer_Led_Out, 6);
	SmallLedBarGraph(cyled_out, ResolutionHigh, 84, rgbCh0[0], rgbCh0[1], rgbCh0[2]); // led_out, resoluton, Xshift, bar color
	setFont(SMALL, 0, 255, 0, 0, 0, 0);
	myGLCD.print(ChName[0], 85, 161);
    myGLCD.print(buffer_Led_Out, 85+16, 161);
   }

  if ((yeLed!=yeled_out) || refreshAll)          // Yellow led
   {
    yeLed = yeled_out;
    ledLevel = LedToPercent(yeled_out, ResolutionHigh);
//  oldval = "YE: " + String(ledLevel) + "% ";
	oldval = ChName[10] + String(ledLevel) + ChName[9];
	oldval.toCharArray(buffer_Led_Out, 6);
	SmallLedBarGraph(yeled_out, ResolutionHigh, 98, rgbCh7[0], rgbCh7[1], rgbCh7[2]); // led_out, resoluton, Xshift, bar color
    setFont(SMALL, 0, 255, 0, 0, 0, 0);
	myGLCD.print(ChName[7], 85, 173);
    myGLCD.print(buffer_Led_Out, 85+16, 173);
   }


  if ((tvLed=tvled_out) || (redLed=rled_out) ||(whiteLed=wled_out) || (blueLed=bled_out) ||
	  (rblueLed=rbled_out) || (uvLed=uvled_out) || (cyLed=cyled_out) || (yeLed=yeled_out) || refreshAll)          

	  {drawBarGraph();}								 //refresh all static led bar 


// ------------- display temperature ------------------
  if (setTempScale==1) {deg ="F";}               //Print deg C or deg F
    else {deg = "C";}
  degC_F=deg;
  char bufferDeg[2];
  degC_F.toCharArray(bufferDeg,2);
      
  int ShiftDrawY =0;

  
  if (refreshAll ) 
   {

    if (counterB1 ==1 || counterB2 ==1 || counterB3 ==1)
	    {   setFont(SMALL, 0, 255, 0, 0, 0 , 0);
//			myGLCD.print("Water Temp:", 169+8, 148);
	        strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[3]))); // "Water"
			myGLCD.print(buffer, 169, 148);
			strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[69]))); // " Temp:"
			myGLCD.print(buffer, 217, 148);
			if (MAX_Temp_on_off ==1)
			{myGLCD.print("Max Temp W:", 5, 191);}
	    }

	  if (counterB1 ==2 || counterB2 ==2 || counterB3 ==2)
	     { 
	    if (((counterB1 + counterB2 + counterB3) == 2) || ((counterB1 + counterB2 + counterB3) == 5)) {ShiftDrawY= 0;}
	    if (((counterB1 + counterB2 + counterB3) == 3) || ((counterB1 + counterB2 + counterB3) == 6)) {ShiftDrawY= +13;}
			setFont(SMALL, 0, 255, 0, 0, 0 , 0);
//			myGLCD.print("H.Sink1 Temp:", 161 , 148+ShiftDrawY);
			strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[4]))); // "H.Sink1"
			myGLCD.print(buffer, 161 , 148+ShiftDrawY);
			strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[69]))); // " Temp:"
			myGLCD.print(buffer, 217 , 148+ShiftDrawY);
			if (MAX_Temp_on_off ==1)
			{myGLCD.print("Max Temp H1:", 5, 202);}
         }
	  if (counterB1 ==3 || counterB2 ==3 || counterB3 ==3)
	     {   
		if ((counterB1 + counterB2 + counterB3) == 3) {ShiftDrawY= 0;}
	    if (((counterB1 + counterB2 + counterB3) == 4) || ((counterB1 + counterB2 + counterB3) == 5)) {ShiftDrawY= +13;}
		if ((counterB1 + counterB2 + counterB3) == 6) {ShiftDrawY= +26;}
	         setFont(SMALL, 0, 255, 0, 0, 0 , 0); 
//           myGLCD.print("H.Sink2 Temp:", 161, 148+ShiftDrawY);
			 strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[5]))); // "H.Sink2"
			 myGLCD.print(buffer, 161 , 148+ShiftDrawY);
			 strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[69]))); // " Temp:"
			 myGLCD.print(buffer, 217 , 148+ShiftDrawY);
			 if (MAX_Temp_on_off ==1)
			 {myGLCD.print("Max Temp H2:", 5, 214);}
         }
	  calculateStartTime();
    }
		WaterTempCheckFunction();   // ON/OFF chiller, heater and display TEMP value and messages 
		FanTempCheckFunction();     // ON/OFF heatsink fans
}


//*********************** EXIT from ScreenSaver ********************
void Exit_From_ScreenSaver()
{
				myTouch.read();

#ifdef Mirror_X
  x=320-myTouch.getX();
#else
  x=myTouch.getX();
#endif

#ifdef Mirror_Y
  y=240-myTouch.getY();
#else
  y=myTouch.getY();
#endif
   if (setLockScreen ==1)
   {
		if ((x>=touchLock[0]) && (x<=touchLock[2]) && (y>=(touchLock[1]-ButtonShift)) && (y<=(touchLock[3]-ButtonShift)) && (firstTouch == false))
			{
			waitForIt(touchLock[0], touchLock[1]-ButtonShift, touchLock[2], touchLock[3]-ButtonShift); // wait for press "TOUCH" button
			unsigned long currentMillis = millis();
			previousMillisFive = currentMillis;                   //start new 5sec interval
			myGLCD.setColor(0, 0, 0);
			myGLCD.fillRect(touchLock[0], touchLock[1]-ButtonShift-3, touchLock[2], touchLock[3]-ButtonShift+3); // clear button TOUCH
			firstTouch  = true;   
//			printButtonTouch("Again", Again[0], Again[1], Again[2], Again[3], SMALL, GREEN_BAC);
			printButtonTouch("Again", touchLock[0], 240-(touchLock[3]-ButtonShift), touchLock[2], 240-(touchLock[1]-ButtonShift), SMALL, GREEN_BAC); //mirror button
			} 
    }

//        if ((x>=Again[0]) && (x<=Again[2]) && (y>=Again[1]) && (y<=Again[3]) && (firstTouch == true))
//              {
//			waitForIt(Again[0], Again[1], Again[2], Again[3]);       // wait for press "AGAIN" button

      if (setLockScreen ==1)
	   { 
        if ((x>=touchLock[0]) && (x<=touchLock[2]) && (y>=240-(touchLock[3]-ButtonShift)) && (y<=240-(touchLock[1]-ButtonShift)) && (firstTouch == true))
              {
			waitForIt(touchLock[0], 240-(touchLock[3]-ButtonShift), touchLock[2], 240-(touchLock[1]-ButtonShift));       // wait for press "AGAIN" button
		    firstTouch  = false; 
			screenSaverCounter=0;
			dispScreen=0;
			clearScreen();
			myGLCD.setColor(64, 64, 64);
			myGLCD.fillRect(0, 226, 319, 239);                     //Bottom Bar    
			mainScreen(true);
		     }
       }
   else {	clearScreen();
			analogWrite(BackLite, 255);					// set normal brightness
	        screenSaverCounter=0;
			dispScreen=0;
			myGLCD.setColor(64, 64, 64);
			myGLCD.fillRect(0, 226, 319, 239);                     //Bottom Bar    
			mainScreen(true);
        }
}

/******************************** END OF MAIN SCREEN **********************************/
void screenReturn()                                    //Auto Return to MainScreen() after 2min timeout, exept screensaver
{
	if (dispScreen!=24)            // no exit to main from screensaver
  {
    if (dispScreen!=0)
     {
      if (myTouch.dataAvailable())
      { processMyTouch(); returnTimer=0; }
       else { returnTimer++; }

	    if (returnTimer>=24) // return after timeout 120sec -> 120/5 = 24 i.e 5sec steps  
      { returnTimer=0;
        dispScreen=0;
		if ((GlobalStatus2Byte & 0x0F) ==0 ) {colorLEDtest = false;} // clear led test flag if all presert is OFF

        clearScreen();
		myGLCD.setColor(64, 64, 64);
		myGLCD.fillRect(0, 226, 319, 239);    
        mainScreen(true);
       }
     }
  }
}


/*********************** MENU SCREEN ********** dispScreen = 1 ************************/
void menuScreen()
{
 // printHeader("Choose Option");
  PrintStringIndex=15; 
  printHeader ();
  
  myGLCD.setColor(64, 64, 64);
  myGLCD.drawRect(0, 196, 319, 194);
  printButton("CANCEL", canC[0], canC[1], canC[2], canC[3], SMALL);  
  
//  printButton("Time and Date", tanD[0], tanD[1], tanD[2], tanD[3]);
  printButton("H2O Temp Control", temC[0], temC[1], temC[2], temC[3]);
  printButton("Weather Control",WeatCtrl[0],WeatCtrl[1],WeatCtrl[2],WeatCtrl[3]); 
//  printButton("WaveMaker", wave[0], wave[1], wave[2], wave[3]);
  printButton("General Settings", gSet[0], gSet[1], gSet[2], gSet[3]);    
  printButton("LED Testing", tesT[0], tesT[1], tesT[2], tesT[3]);
  printButton("Change LED Values", ledChM[0], ledChM[1], ledChM[2], ledChM[3]);
//  printButton("Automatic Feeder", aFeed[0], aFeed[1], aFeed[2], aFeed[3]);
//  printButton("About", about[0], about[1], about[2], about[3]);

// draw correct button in main menu windows
    if ((GlobalStatus2Byte & 0x0F) == 0) {printButton("Preset OFF",  prsM[0],prsM[1],prsM[2],prsM[3], SMALL);
	    if ((min_cnt/15 >= StartTime-1) && (min_cnt/15 <= StopTime))
			{digitalWrite(PowerSwitch2, LOW);}  //ON driver before StartTime - 15min
		else {digitalWrite(PowerSwitch2, HIGH);}} //OFF driver before StartTime}
	                                     
    if ((GlobalStatus2Byte & 0x0F) == 1) {printButton("Preset 1 ON", prsM[0],prsM[1],prsM[2],prsM[3], SMALL, GREEN_BAC); digitalWrite(PowerSwitch2, LOW);}
    if ((GlobalStatus2Byte & 0x0F) == 2) {printButton("Preset 2 ON", prsM[0],prsM[1],prsM[2],prsM[3], SMALL, GREEN_BAC); digitalWrite(PowerSwitch2, LOW);}
	if ((GlobalStatus2Byte & 0x0F) == 4) {printButton("Preset 3 ON", prsM[0],prsM[1],prsM[2],prsM[3], SMALL, GREEN_BAC); digitalWrite(PowerSwitch2, LOW);}
	if ((GlobalStatus2Byte & 0x0F) == 8) {printButton("Preset 4 ON", prsM[0],prsM[1],prsM[2],prsM[3], SMALL, GREEN_BAC); digitalWrite(PowerSwitch2, LOW);}
 
}
/********************************* END OF MENU SCREEN *********************************/


/************** TIME and DATE SCREEN ********** dispScreen = 2 ************************/
void clockScreen(boolean refreshAll=true) 
{
  if (refreshAll)
  {
    rtcSetMin=t.min; rtcSetHr=t.hour; 
    rtcSetDy=t.date; rtcSetMon=t.mon; rtcSetYr=t.year;
    
 //   printHeader("Time and Date Settings");
	PrintStringIndex=16; 
    printHeader ();

    myGLCD.setColor(64, 64, 64);                   //Draw Dividers in Grey
    myGLCD.drawRect(0, 196, 319, 194);             //Bottom Horizontal Divider
    myGLCD.drawLine(0, 104, 319, 104);             //Middle Horizontal Divider
    printButton("<< BACK", back[0], back[1], back[2], back[3], SMALL);
    printButton("SAVE", prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3], SMALL);
    printButton("CANCEL", canC[0], canC[1], canC[2], canC[3], SMALL);

    drawUpButton(houU[0], houU[1]);                //hour up
    drawUpButton(minU[0], minU[1]);                //min up
    drawDownButton(houD[0], houD[1]);              //hour down
    drawDownButton(minD[0], minD[1]);              //min down
    if (setTimeFormat==1)
      { drawUpButton(ampmU[0], ampmU[1]);          //AM/PM up   
        drawDownButton(ampmD[0], ampmD[1]);}       //AM/PM down  
    
    drawUpButton(dayU[0], dayU[1]);                //day up
    drawUpButton(monU[0], monU[1]);                //month up
    drawUpButton(yeaU[0], yeaU[1]);                //year up
    drawDownButton(dayD[0], dayD[1]);              //day down
    drawDownButton(monD[0], monD[1]);              //month down
    drawDownButton(yeaD[0], yeaD[1]);              //year down
	xTimeH=107; yTime=52; xColon=xTimeH+42;
	xTimeM10=xTimeH+70; xTimeM1=xTimeH+86; xTimeAMPM=xTimeH+155;
	timeChange(); 
  }
     
  timeDispH=rtcSetHr; timeDispM=rtcSetMin; 
  xTimeH=107; yTime=52; xColon=xTimeH+42;
  xTimeM10=xTimeH+70; xTimeM1=xTimeH+86; xTimeAMPM=xTimeH+155;
//  timeChange();
  timeCorrectFormat();

	if (refreshAll)
		{
  setFont(LARGE, 0, 0, 255, 0, 0, 0);    
  myGLCD.print("Date", 20, 142);
  setFont(LARGE, 255, 255, 255, 0, 0, 0);      
  myGLCD.print("/", 149, 142);    
  myGLCD.print("/", 219, 142);
	if (setCalendarFormat==0)                             //DD/MM/YYYY Format
    {
     setFont(SMALL, 0, 0, 255, 0, 0, 0); 
     myGLCD.print("(DD/MM/YYYY)", 5, 160); 
     } 
  if (setCalendarFormat==1)                             //MM/DD/YYYY Format
      {
     setFont(SMALL, 0, 0, 255, 0, 0, 0); 
     myGLCD.print("(MM/DD/YYYY)", 5, 160); 
      }
}
  if (setCalendarFormat==0)                             //DD/MM/YYYY Format
    {
//     setFont(SMALL, 0, 0, 255, 0, 0, 0); 
//     myGLCD.print("(DD/MM/YYYY)", 5, 160); 
     setFont(LARGE, 255, 255, 255, 0, 0, 0);          
     if ((rtcSetDy>=0) && (rtcSetDy<=9))                //Set DAY
       { myGLCD.print("0", 107, 142);
         myGLCD.printNumI(rtcSetDy, 123, 142);}
     else { myGLCD.printNumI(rtcSetDy, 107, 142);} 
     if ((rtcSetMon>=0) && (rtcSetMon<=9))              //Set MONTH
       { myGLCD.print("0", 177, 142);
         myGLCD.printNumI(rtcSetMon, 193, 142);}
     else { myGLCD.printNumI(rtcSetMon, 177, 142);} 
    } else
  if (setCalendarFormat==1)                             //MM/DD/YYYY Format
    {
//     setFont(SMALL, 0, 0, 255, 0, 0, 0); 
//     myGLCD.print("(MM/DD/YYYY)", 5, 160); 
     setFont(LARGE, 255, 255, 255, 0, 0, 0);          
     if ((rtcSetMon>=0) && (rtcSetMon<=9))              //Set MONTH
       { myGLCD.print("0", 107, 142);
         myGLCD.printNumI(rtcSetMon, 123, 142);}
     else { myGLCD.printNumI(rtcSetMon, 107, 142);} 
     if ((rtcSetDy>=0) && (rtcSetDy<=9))                //Set DAY
       { myGLCD.print("0", 177, 142);
         myGLCD.printNumI(rtcSetDy, 193, 142);}
     else { myGLCD.printNumI(rtcSetDy, 177, 142);} 
    }  
  myGLCD.printNumI(rtcSetYr, 247, 142);                 //Set YEAR
}

void timeChange()
{
  setFont(LARGE, 0, 0, 255, 0, 0, 0); 
  myGLCD.print("Time", 20, yTime);

  if (setTimeFormat==0)                                 //24HR Format
    { setFont(SMALL, 0, 0, 255, 0, 0, 0); 
      myGLCD.print("(24HR)", 29, yTime+18);}

  if (setTimeFormat==1)                                 //12HR Format
    { setFont(SMALL, 0, 0, 255, 0, 0, 0);  
      myGLCD.print("(12HR)", 29, yTime+18);}

//  timeCorrectFormat();
}

void timeCorrectFormat()
{
  setFont(LARGE, 255, 255, 255, 0, 0, 0);   
  myGLCD.print(":",  xColon, yTime);  
  if (setTimeFormat==0)                                 //24HR Format
    {
     setFont(LARGE, 255, 255, 255, 0, 0, 0);  
     if ((timeDispH>=0) && (timeDispH<=9))              //Set HOUR
       { myGLCD.print("0", xTimeH, yTime);
         myGLCD.printNumI(timeDispH, xTimeH+16, yTime);}
     else { myGLCD.printNumI(timeDispH, xTimeH, yTime);} 
    }    
  if (setTimeFormat==1)                                 //12HR Format
    {
     setFont(LARGE, 255, 255, 255, 0, 0, 0);  
     if (timeDispH==0)                                  //Set HOUR
       { myGLCD.print("12", xTimeH, yTime);}
     if ((timeDispH>=1) && (timeDispH<=9))
       { myGLCD.print("0", xTimeH, yTime);
         myGLCD.printNumI(timeDispH, xTimeH+16, yTime);}
     if ((timeDispH>=10) && (timeDispH<=12))
       { myGLCD.printNumI(timeDispH, xTimeH, yTime);}
     if ((timeDispH>=13) && (timeDispH<=21))
       { myGLCD.print("0", xTimeH, yTime);
         myGLCD.printNumI(timeDispH-12, xTimeH+16, yTime);}
     if (timeDispH>=22)
       { myGLCD.printNumI(timeDispH-12, xTimeH, yTime);}
      
     if (AM_PM==1)
       { myGLCD.print("AM", xTimeAMPM, yTime); }
     if (AM_PM==2)
       { myGLCD.print("PM", xTimeAMPM, yTime); }
    }
  if ((timeDispM>=0) && (timeDispM<=9))                 //Set MINUTES
    { myGLCD.print("0", xTimeM10, yTime);
      myGLCD.printNumI(timeDispM, xTimeM1, yTime);}
  else { myGLCD.printNumI(timeDispM, xTimeM10, yTime);} 
}    
/**************************** END OF TIME and DATE SCREEN *****************************/


/*********** H2O TEMP CONTROL SCREEN ********** dispScreen = 3 ************************/
void tempScreen(boolean refreshAll=false)
{
//  String deg;
  if (refreshAll)
    {
     if ((setTempC==0) && (setTempScale==0)) {
       setTempC = 26.1;  }                         //change to 26.1 deg C
     if (((setTempF==0) || (setTempF==setTempC)) && (setTempScale==1)) {
       setTempF = 79.0;  }                         //change to 79.0 deg F
       
     if (setTempScale==1) {
       temp2beS = setTempF;
       temp2beO = offTempF;
       temp2beA = alarmTempF; }
     else {
     temp2beS = setTempC;
     temp2beO = offTempC;
     temp2beA = alarmTempC; }
     
//   printHeader("H2O Temperature Control Settings");
	 PrintStringIndex=17; 
     printHeader ();
     
     myGLCD.setColor(64, 64, 64);                    //Draw Dividers in Grey
     myGLCD.drawRect(0, 196, 319, 194);              //Bottom Horizontal Divider
     printButton("<< BACK", back[0], back[1], back[2], back[3], SMALL);
     printButton("SAVE", prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3], SMALL);
     printButton("CANCEL", canC[0], canC[1], canC[2], canC[3], SMALL);

     setFont(SMALL, 255, 255, 255, 0, 0, 0);
//   myGLCD.print("Desired Temperature: ", 52, 34);
//	 myGLCD.print("Temperature Offset: 0.1-5", 60, 84);
//	 myGLCD.print("Alarm Offset: 0.1-9.9", 76, 134);
	 strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[20]))); 
     myGLCD.print(buffer, 52, 34);
	 strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[21]))); 
     myGLCD.print(buffer, 60, 84);
	 strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[22]))); 
     myGLCD.print(buffer, 76, 134);

	 if (setTempScale==1) { 
//		 myGLCD.print("50-104F",218, 34);
	 	 strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[23]))); 
         myGLCD.print(buffer, 218, 34);
	      }
	 else { 
//		 myGLCD.print("10-40C",218,34);
		 strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[24]))); 
         myGLCD.print(buffer, 218, 34);
	      }
     
     printButton("-", temM[0], temM[1], temM[2], temM[3], true);      //temp minus
     printButton("+", temP[0], temP[1], temP[2], temP[3], true);      //temp plus
     printButton("-", offM[0], offM[1], offM[2], offM[3], true);      //offset minus
     printButton("+", offP[0], offP[1], offP[2], offP[3], true);      //offset plus
     printButton("-", almM[0], almM[1], almM[2], almM[3], true);      //alarm minus
     printButton("+", almP[0], almP[1], almP[2], almP[3], true);      //alarm plus
//     printButtonVertical("   BEEP OFF  ", Beep[0], Beep[1], SMALL);
  
  }

  setFont(LARGE, 255, 255, 255, 0, 0, 0);
  if (setTempScale==1 && temp2beS <100 ) {myGLCD.print(" ",189,54);}
  myGLCD.printNumF(temp2beS, 1, 125, 54);
  myGLCD.printNumF(temp2beO, 1, 139, 104);
  myGLCD.printNumF(temp2beA, 1, 139, 154);

}
/************************** END of H20 TEMP CONTROL SCREEN ****************************/


/********** LED TESTING OPTIONS SCREEN ******** dispScreen = 4 ************************/
void ledTestOptionsScreen()
{
//  printHeader("LED Testing Options"); 
  PrintStringIndex=18; 
  printHeader (); 

  myGLCD.setColor(64, 64, 64);                       //Draw Dividers in Grey
  myGLCD.drawRect(0, 196, 319, 194);                 //Bottom Horizontal Divider   
  printButton("<< BACK", back[0], back[1], back[2], back[3], SMALL);
  printButton("CANCEL", canC[0], canC[1], canC[2], canC[3], SMALL);
  
  printButton("Rapid (x120) Test LED Array", tstLA[0], tstLA[1], tstLA[2], tstLA[3]);
  printButton("Control Individual Leds", cntIL[0], cntIL[1], cntIL[2], cntIL[3]);
  printButton("Preset Setting", PrButL[0], PrButL[1], PrButL[2], PrButL[3]);
}
/*************************** END OF LED TEST OPTIONS SCREEN ***************************/


 void AllColourGraph()   // used in "rapid test" and "All color graph "
{

   	myGLCD.setColor(0, 0, 0);
    myGLCD.fillRect(0, 0, 319, 15);                              // clear only header
	myGLCD.setColor(64, 64, 64);                                 //Draw Dividers in Grey
	myGLCD.drawRect(0, 196, 319, 194);                           //Bottom Horizontal Divider
	printButton("<< BACK", back[0], back[1], back[2], back[3], SMALL);
	printButton("CANCEL", canC[0], canC[1], canC[2], canC[3], SMALL);
	if (dispScreen ==5)											// rapid test window
	{printButton("START", ledChV[0], ledChV[1], ledChV[2], ledChV[3], SMALL);} // button start/stop test oly in rapid test window

	calculateStartTime();  // calculate SUNRISE time 
	calculateStopTime();   // calculate SUNSET time 

/*
	byte i;
	for (i=95; i>0; i--)       // find "StopTime"
     {  
	if (tvled[i]!=0 && bitRead(LedShannelStatusByte,5)== true) {goto ext_SStlbl;}	
	if (bled[i]!=0 && bitRead(LedShannelStatusByte,1)== true)  {goto ext_SStlbl;}	
	if (wled[i]!=0 && bitRead(LedShannelStatusByte,0)== true)  {goto ext_SStlbl;}	
	if (rbled[i]!=0 && bitRead(LedShannelStatusByte,2)== true) {goto ext_SStlbl;}
	if (rled[i]!=0 && bitRead(LedShannelStatusByte,3)== true)  {goto ext_SStlbl;}	
	if (uvled[i]!=0 && bitRead(LedShannelStatusByte,4)== true) {goto ext_SStlbl;}
	if (cyled[i]!=0 && bitRead(LedShannelStatusByte,6)== true) {goto ext_SStlbl;}	
	if (yeled[i]!=0 && bitRead(LedShannelStatusByte,7)== true) {goto ext_SStlbl;}
	 }
ext_SStlbl:
      StopTime=i+1;
*/

	  if (LedShannelStatusByte==0) {StartTime=0; StopTime=95;}      // draw graph if all led is OFF 

	  drawLedStaticChartP1 ();

// repeat 9 time
  for (byte i=1; i<=9; i++)	
  {   COLOR = i; 
  if (i==1) {
    for (byte i=0; i<96; i++)
	  tled[i] = wled[i]; sbR= rgbCh2[0]; sbG= rgbCh2[1]; sbB= rgbCh2[2];}
  if (i==2) {
    for (byte i=0; i<96; i++)
      tled[i] = bled[i]; sbR= rgbCh4[0]; sbG= rgbCh4[1]; sbB= rgbCh4[2];}
  if (i==3) {
    for (byte i=0; i<96; i++)
      tled[i] = rbled[i]; sbR= rgbCh3[0]; sbG= rgbCh3[1]; sbB= rgbCh3[2];}
  if (i==4) {
    for (byte i=0; i<96; i++)
      tled[i] = rled[i]; sbR= rgbCh5[0]; sbG= rgbCh5[1]; sbB= rgbCh5[2];}  
  if (i==5) {
    for (byte i=0; i<96; i++)
    tled[i] = uvled[i]; sbR= rgbCh1[0]; sbG= rgbCh1[1]; sbB= rgbCh1[2];}
  if (i==6) {
    for (byte i=0; i<96; i++)
    tled[i] = tvled[i]; sbR= rgbCh6[0]; sbG= rgbCh6[1]; sbB= rgbCh6[2];}
  if (i==8) {
    for (byte i=0; i<96; i++)
    tled[i] = cyled[i];	sbR= rgbCh0[0]; sbG= rgbCh0[1]; sbB= rgbCh0[2];}
  if (i==9) {
    for (byte i=0; i<96; i++)
    tled[i] = yeled[i];	sbR= rgbCh7[0]; sbG= rgbCh7[1]; sbB= rgbCh7[2];}

  if (i!=7) { ReadOnOffLedStatus();
          if (LedShannelFlag_on_off == true)
		        { draw_one_led_graph();  }
		          else { EndScale=290;}   // for draw tick scale if all led is OFF
	        }
      }
            drawLedStaticChartP2 ();
}

void draw_one_led_graph()
{           byte stepScale = (294 - 26)/(StopTime-StartTime);			// 26 and 294 - left / right 
	        myGLCD.setColor(sbR, sbG, sbB);
            for (byte i=StartTime; i<StopTime; i++)						// draw led value graph (curve)
	       {  int tempLineS;											//start segment of line
		      int tempLineE;											//stop segment of line
		      int XStep = map((i-StartTime), 0, (StopTime-StartTime), 26, 294);

	     tempLineS=tled[i];
		 if (tempLineS > 100) {tempLineS =100;}
		 tempLineE=tled[i+1];
   		 if (tempLineE > 100) {tempLineE =100;}
		 tempLineS= map (tempLineS, 0, 100, BotSldY, TopSldY);      // mapping 0-100 value to chart size
		 tempLineE= map (tempLineE, 0, 100, BotSldY, TopSldY);

		 myGLCD.drawLine(XStep, tempLineS, XStep+stepScale, tempLineE );
		 myGLCD.drawLine(XStep, tempLineS+1, XStep+stepScale, tempLineE+1 );
		 EndScale = XStep+stepScale;
		  }
}
void drawLedStaticChartP1 ()   // draw TOP ON/OFF time and X/Y border
{

   TopSldY=20; BotSldY=170;						    // graph vertical size
	  LightDay= (StopTime-StartTime)/4*10;			// light day in HOUR * 10
	  int Temp = 10*(StopTime-StartTime)/4;			// rounding to the nearest whole number if "light day" similar 3.4 or 3.75 etc...
	  if ((Temp - LightDay)>=5) {LightDay= (StopTime-StartTime)/4+1;}
	  else {LightDay= (StopTime-StartTime)/4;}    

	  myGLCD.setColor(255, 255, 255);								//static LED Chart
	  setFont(SMALL, 255, 255, 255, 0, 0, 0);     
	  myGLCD.drawRect(26, BotSldY, 27, TopSldY);					//print y-line
	     for (byte i=1; i<11; i++)                           
		     { myGLCD.drawLine(28, (i*(BotSldY-TopSldY)/10+5), 30, (i*(BotSldY-TopSldY)/10+5));} // Y tick-marks 

    	  myGLCD.drawRect(26, BotSldY, 318, BotSldY+1);					//print x-line

	     for (byte i=0; i<=10; i++)									    // print 0-100 vertical scale
	         {if (i==0)  {myGLCD.printNumI(0, 18, ((BotSldY-TopSldY)/10*(11-i)));}
                 if (i==10) {myGLCD.printNumI(100, 2, (BotSldY-TopSldY)/10*(11-i));}
		     else   {myGLCD.printNumI(i*10, 10, (BotSldY-TopSldY)/10*(11-i));}
		     }

        myGLCD.setColor(255, 255, 255);       
        myGLCD.drawRect(1, 1, 106, 14);									// print white border for ON TIME 
		myGLCD.drawRect(205, 1, 318, 14);								// print white border for OFF TIME
        setFont(SMALL, 0, 0, 0, 0, 255, 0);    
		myGLCD.print("ON TIME-",2, 2); myGLCD.print(" ", 66, 2);            // print ON TIME (on TOP) 
		     if ((StartTime/4)<=9) {myGLCD.printNumI((StartTime/4), 66+8, 2);}
		        else {myGLCD.printNumI((StartTime/4), 66, 2);} 
		myGLCD.print(":", 82, 2); myGLCD.printNumI((StartTime*15)%60, 90, 2, 2, '00');
/*
		 setFont(SMALL, 255, 255, 255, 0, 0, 0); 
	 	 myGLCD.printNumI(StartTime/4, 8, BotSldY+8, 2, '00');             // print start time on scale
		 myGLCD.print(":", 24, BotSldY+8);
		 myGLCD.printNumI((StartTime*15)%60, 32, BotSldY+8, 2, '00');
*/
		 setFont(SMALL, 0, 0, 0, 0, 255, 0);
		 myGLCD.print("OFF TIME-",206, 2); myGLCD.print(" ", 278, 2);        // print OFF TIME (on TOP) 
       		 if ((StopTime/4)<=9) {myGLCD.printNumI((StopTime/4), 278+8, 2);}
		        else {myGLCD.printNumI((StopTime/4), 278, 2); }
		 myGLCD.print(":", 294, 2); myGLCD.printNumI((StopTime*15)%60, 302, 2, 2, '00');
}

void drawLedStaticChartP2 ()    // draw BOT ON/OFF time and X/Y scale and tick mark
{
/*       
	byte Temp = StartTime/4+2;
	byte DeltaI;
	if ((StartTime*15)%60 == 0)  {DeltaI=4;}
	if ((StartTime*15)%60 == 15) {DeltaI=4;}
	if ((StartTime*15)%60 == 30) {DeltaI=3;}
	if ((StartTime*15)%60 == 45) {DeltaI=2;}
*/	

	         myGLCD.setColor(255, 255, 255);
	         myGLCD.drawRect(26, BotSldY, 318, BotSldY+1);					        //print x-line
	  	     if (LightDay<=7)														// print X-tick and dot background	
		       {for (byte i=0; i<(StopTime-StartTime)+2; i++)	 					// i-horisontal count, X tick-marks with 15min resolution
			      {int XStep = map(i, 0, (StopTime-StartTime), 26, EndScale);
			          myGLCD.setColor(255, 255, 255);
                      myGLCD.drawLine(XStep, BotSldY+3, XStep, BotSldY-3);

			            for (byte k=1; k<=10; k++)                                   // k - vertical count
						   { myGLCD.setColor(180, 180, 180);
					    	 myGLCD.drawPixel(XStep, k*(BotSldY-TopSldY)/10+5);}}}

		     if (LightDay>7 && LightDay<=12)
		       {for (byte i=0; i<(StopTime-StartTime)/2+2; i++)						 //X tick-marks with 30min resolution
			        { int XStep = map(i, 0, (StopTime-StartTime)/2, 26, EndScale);
			           myGLCD.setColor(255, 255, 255);
			           myGLCD.drawLine(XStep, BotSldY+3, XStep, BotSldY-3);           // X mark on horisontal scale
/*
   				  if ( i>= DeltaI && i<((StopTime-StartTime)/2-2)) { 
					  if (i%2 ==0 ){
                  setFont(SMALL, 255, 255, 255, 0, 0, 0); 
                    myGLCD.printNumI(Temp, XStep-6, BotSldY+8, 2, '00');
					Temp +=1;
					Serial.print("i="); Serial.println(i);
//					Serial.print("DeltaI="); Serial.println(DeltaI);
					  } }
*/   
			             for (byte k=1; k<=10; k++)                                   // k - vertical count
						   { myGLCD.setColor(180, 180, 180);
						     myGLCD.drawPixel(XStep, k*(BotSldY-TopSldY)/10+5);}}}       

		     if (LightDay>12 && LightDay<=24)
		       {for (byte i=0; i<(StopTime-StartTime)/4+4; i++)						 //X tick-marks with 1hour resolution
			        {int XStep = map(i, 0, (StopTime-StartTime)/4, 26, EndScale);
                        myGLCD.setColor(255, 255, 255); 
	                    myGLCD.drawLine(XStep, BotSldY+3, XStep, BotSldY-3);
			             for (byte k=1; k<=10; k++)                                   // k - vertical count
						   { myGLCD.setColor(180, 180, 180);
						     myGLCD.drawPixel(XStep, k*(BotSldY-TopSldY)/10+5);}}}  


                 setFont(SMALL, 255, 255, 255, 0, 0, 0); 
	 			 myGLCD.printNumI(StartTime/4, 8, BotSldY+8, 2, '00');              // print start time on scale
				 myGLCD.print(":", 24, BotSldY+8);
				 myGLCD.printNumI((StartTime*15)%60, 32, BotSldY+8, 2, '00');  
	
        	     setFont(SMALL, 255, 255, 255, 0, 0, 0);
	  	         myGLCD.printNumI(StopTime/4, EndScale-16, BotSldY+8);              // print stop time on scale
		         myGLCD.print(":", EndScale, BotSldY+5);
		         myGLCD.printNumI((StopTime*15)%60, EndScale+8, BotSldY+8, 2, '00');

}

void drawTestLedArrayScale()
{
              int i=0;               // start scale is constant
		      min_cnt = StartTime*15;

		  while (LEDtestTick== true &&  i<= ((StopTime-StartTime)*15)/2) // LEDtestTick== true - start test
		  {
        	   unsigned long currentMillis = millis();
			    if (myTouch.dataAvailable()) 
                     { processMyTouch();}

         if (currentMillis - previousMillisLED > 1000)    //change time every 1s
               {previousMillisLED = currentMillis; 

			  int XStep = map(i, 0, ((StopTime-StartTime)*15)/2, 26, EndScale);
		        myGLCD.setColor(255, 255, 255);       
                myGLCD.drawRect(136, 1, 177, 14);
		        setFont(SMALL, 0, 0, 0, 0, 255, 0);    
                        myGLCD.print(" ", 137, 2);            
		           if (((min_cnt/15)/4)<=9) {myGLCD.printNumI((min_cnt/15)/4, 145, 2);}
		               else {myGLCD.printNumI((min_cnt/15)/4, 137, 2);} 
		                 myGLCD.print(":", 153, 2); myGLCD.printNumI(min_cnt%60, 161, 2, 2, '00');
        	          myGLCD.setColor(0, 255, 0);
					  myGLCD.drawLine(XStep, BotSldY+8, XStep, BotSldY+3 );
		              LED_levels_output();
					  min_cnt+=2 ;   // two minutes increment
					  i +=1;
             }
         }
      printButton("START", ledChV[0], ledChV[1], ledChV[2], ledChV[3], SMALL); // buton start/stop test
	  LEDtestTick = false;         // end test, enable button BACK/Cancel 
}

void calculateStartTime()
{
	byte i;
	 for (i=0; i<=95; i++)       // find "StartTime"
     {  
	if (tvled[i]!=0 && bitRead(LedShannelStatusByte,5)== true) {goto ext_Stlbl;}	
	if (bled[i]!=0 && bitRead(LedShannelStatusByte,1)== true)  {goto ext_Stlbl;}	
	if (wled[i]!=0 && bitRead(LedShannelStatusByte,0)== true)  {goto ext_Stlbl;}	
	if (rbled[i]!=0 && bitRead(LedShannelStatusByte,2)== true) {goto ext_Stlbl;}
	if (rled[i]!=0 && bitRead(LedShannelStatusByte,3)== true)  {goto ext_Stlbl;}	
	if (uvled[i]!=0 && bitRead(LedShannelStatusByte,4)== true) {goto ext_Stlbl;}
	if (cyled[i]!=0 && bitRead(LedShannelStatusByte,6)== true) {goto ext_Stlbl;}	
	if (yeled[i]!=0 && bitRead(LedShannelStatusByte,7)== true) {goto ext_Stlbl;}
	 }
ext_Stlbl:
    StartTime=i-1;
	if (StartTime == 255) {StartTime=0;}
}

void calculateStopTime()
{
	byte i;
	for (i=95; i>0; i--)       // find "StopTime"
     {  
	if (tvled[i]!=0 && bitRead(LedShannelStatusByte,5)== true) {goto ext_SStlbl;}	
	if (bled[i]!=0 && bitRead(LedShannelStatusByte,1)== true)  {goto ext_SStlbl;}	
	if (wled[i]!=0 && bitRead(LedShannelStatusByte,0)== true)  {goto ext_SStlbl;}	
	if (rbled[i]!=0 && bitRead(LedShannelStatusByte,2)== true) {goto ext_SStlbl;}
	if (rled[i]!=0 && bitRead(LedShannelStatusByte,3)== true)  {goto ext_SStlbl;}	
	if (uvled[i]!=0 && bitRead(LedShannelStatusByte,4)== true) {goto ext_SStlbl;}
	if (cyled[i]!=0 && bitRead(LedShannelStatusByte,6)== true) {goto ext_SStlbl;}	
	if (yeled[i]!=0 && bitRead(LedShannelStatusByte,7)== true) {goto ext_SStlbl;}
	 }
ext_SStlbl:
      StopTime=i+1;
}


/********* TEST INDIVIDUAL LED(S) SCREEN ****** dispScreen = 6 ************************/
void testIndLedScreen(boolean refreshTest=false)
{

	TopSldY=53; BotSldY=TopSldY+100;
 if (refreshTest==true)
     {
   myGLCD.setColor(0, 0, 0);
   myGLCD.fillRect(0, 0, 319, 15); // clear only header
   setFont(SMALL, 255, 255, 255, 0, 0, 0);
// myGLCD.print("TV  DR   CW  BL  RBL  UV  CY  YE  Moon", 15, 15);
//   PrintStringIndex=3;  // print string from Flash
//   strcpy_P(buffer, (char*)pgm_read_word_near(&(Header_Text_table[PrintStringIndex]))); // print string number 3 from flash
//   myGLCD.print(buffer, 15, 15 );

   myGLCD.print(ChName[6], 15, 15 );      // TV
   myGLCD.print(ChName[5], 15+35, 15 );   // DR
   myGLCD.print(ChName[2], 15+70, 15 );   // CW
   myGLCD.print(ChName[4], 15+105, 15 );  // BL
   myGLCD.print(ChName[3], 15+140, 15 );  // RBL
   myGLCD.print(ChName[1], 15+175, 15 );  // UV
   myGLCD.print(ChName[0], 15+210, 15 );  // CY 
   myGLCD.print(ChName[7], 15+245, 15 );  // Ye
   myGLCD.print(ChName[8], 15+270, 15 );  // Moon
   

   for (byte b=0; b<9; b++)                             //UP Buttons
   { drawUpButtonSlide((b*35)+4, TopSldY-26); } 
   for (byte b=0; b<9; b++)                             //DOWN Buttons
   { drawDownButtonSlide((b*35)+4, TopSldY+115);}

        temp_sector= min_cnt/15;  // read current time sector only first time

  		myGLCD.setColor(64, 64, 64);                       //Draw Dividers in Grey
		myGLCD.drawRect(0, 196, 319, 194);                 //Bottom Horizontal Divider
		printButton("<< BACK", back[0], back[1], back[2], back[3], SMALL);
		printButton("PREV SECT", ledChV[0], ledChV[1], ledChV[2], ledChV[3], SMALL);
		printButton("NEXT SECT", canC[0], canC[1], canC[2], canC[3], SMALL);
  		printButton("SunSet", StopDay[0], StopDay[1], StopDay[2], StopDay[3], SMALL);  // top buttons
		printButton("SunRise", StartDay[0], StartDay[1], StartDay[2], StartDay[3], SMALL);  // top buttons
     }

       if (refreshTest==true)
	      {
		 myGLCD.setColor(255, 255, 255);         //Draw white rectangle
         myGLCD.drawRect(88, 0, 227, 14);
	     myGLCD.setColor(0, 255, 0);             //fill sector background in green 
         myGLCD.fillRect(89, 1, 226, 14);
//---------- display current TIME sector = min_cnt/15, convert to hour min_cnt/15)/4, to min. (min_cnt/15)*15)%60 
        setFont(SMALL, 0, 0, 0, 0, 255, 0);       // print SECTOR TIME on TOP
    	myGLCD.print("TIME SECTOR   :  ",91, 2);
	   }
	           setFont(SMALL, 0, 0, 0, 0, 255, 0);
           if ((temp_sector/4)<=9) {
			   myGLCD.print(" ",91+96, 2);
			   myGLCD.printNumI(temp_sector/4, 91+104, 2);}  // Start sector is min_cnt/15 
	           else {myGLCD.printNumI(temp_sector/4, 91+96, 2);}               
	                 myGLCD.printNumI((temp_sector*15)%60, 91+120, 2, 2, '00');		  // min 00/15/30/45 in hour


		tv_out = tvled[temp_sector];     // read setting from buffer
		b_out = bled[temp_sector];
		w_out = wled[temp_sector];
		rb_out = rbled[temp_sector];
		r_out = rled[temp_sector];
		uv_out = uvled[temp_sector];
		cy_out = cyled[temp_sector];
		yel_out = yeled[temp_sector];

      for (byte i=0; i<9; i++)                          // draw white bar outline rectangle
		{ sbX1=(i*35)+4; sbX2=(i*35)+34;
	      setFont(SMALL, 255, 255, 255, 0, 0, 0); 
		  myGLCD.drawRect(sbX1, TopSldY-1, sbX2, BotSldY);}
		
   for (byte i=0; i<9; i++)                                  //print Slider Bar current values
     { 
	   sbX1=(i*35)+4; sbX2=(i*35)+34;
       SliderSwitch  = true;
		
	    if (i==0) 
	 {  LedShannelFlag_on_off =true;  
	 if (bitRead(LedShannelStatusByte,5) == false) {tv_out=0; LedShannelFlag_on_off =false; }
	 sbR= rgbCh6[0]; sbG= rgbCh6[1]; sbB= rgbCh6[2];  tSlide= tv_out;              // TV colour	
     setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
     tvcol_out = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}

  	     if (i==1) 
    {  LedShannelFlag_on_off = true;
    if (bitRead(LedShannelStatusByte,3) == false) {r_out=0; LedShannelFlag_on_off =false; }  
	sbR= rgbCh5[0]; sbG= rgbCh5[1]; sbB= rgbCh5[2]; tSlide= r_out;					   // DR colour	
    setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
	rcol_out = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}    

	     if (i==2) 
	{   LedShannelFlag_on_off = true;
    if (bitRead(LedShannelStatusByte,0) == false) {w_out=0; LedShannelFlag_on_off =false; }  
	sbR= rgbCh2[0]; sbG= rgbCh2[1]; sbB= rgbCh2[2]; tSlide= w_out;				   // CW colour	
    setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
	wcol_out = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}    

	     if (i==3) 
	{   LedShannelFlag_on_off = true;
    if (bitRead(LedShannelStatusByte,1) == false) {b_out=0; LedShannelFlag_on_off =false; }   
	sbR= rgbCh4[0]; sbG= rgbCh4[1]; sbB= rgbCh4[2]; tSlide= b_out;					   // BL colour
    setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
	bcol_out = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);} 

 	     if (i==4) 
	{  LedShannelFlag_on_off = true;
    if (bitRead(LedShannelStatusByte,2) == false) {rb_out=0; LedShannelFlag_on_off =false; }  
	sbR= rgbCh3[0]; sbG= rgbCh3[1]; sbB= rgbCh3[2]; tSlide = rb_out;				   // RBL colour
    setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
	rbcol_out = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}    

	     if (i==5) 
	{  LedShannelFlag_on_off = true;
    if (bitRead(LedShannelStatusByte,4) == false) {uv_out=0; LedShannelFlag_on_off =false; }  
	sbR= rgbCh1[0]; sbG= rgbCh1[1]; sbB= rgbCh1[2]; tSlide= uv_out;				   // UV colour
    setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
	uvcol_out = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}

	     if (i==6) 
	{  LedShannelFlag_on_off = true;
    if (bitRead(LedShannelStatusByte,6) == false) {cy_out=0; LedShannelFlag_on_off =false; }  
	sbR= rgbCh0[0]; sbG= rgbCh0[1]; sbB= rgbCh0[2]; tSlide= cy_out ;	 // CY colour
    setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
	cycol_out = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}    

	     if (i==7)  
	{  LedShannelFlag_on_off = true;
    if (bitRead(LedShannelStatusByte,7) == false) {yel_out=0; LedShannelFlag_on_off =false; }  
	sbR= rgbCh7[0]; sbG= rgbCh7[1]; sbB= rgbCh7[2];	tSlide= yel_out;				   // Yellow colour
    setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
	yelcol_out = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}

	     if (i==8) 
	{ sbR= rgbCh8[0]; sbG= rgbCh8[1]; sbB= rgbCh8[2]; tSlide= map (moon_out, 0, 255, 0, 100);		       // MOON colour
    setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
	mooncol_out = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}
  }
     LedShannelFlag_on_off = true;
}


void PresetLedScreen(boolean refreshPresetscreen = false)
{
   if (refreshPresetscreen == true)
   {
   myGLCD.setColor(0, 0, 0);
   myGLCD.fillRect(0, 0, 319, 15);						// clear only header
   setFont(SMALL, 255, 255, 255, 0, 0, 0);
// myGLCD.print("TV  DR   CW  BL  RBL  UV  CY  YE  Moon", 15, 15);
   PrintStringIndex=3;  // print string from Flash
   strcpy_P(buffer, (char*)pgm_read_word_near(&(Header_Text_table[PrintStringIndex]))); // print string number 3 from flash
   myGLCD.print(buffer, 15+18, 15 );
   myGLCD.print("  ", 300, 15); // clean last text (Moon)
   calculateStopTime() ;
   TopSldY=53; BotSldY=TopSldY+100;

   for (byte b=0; b<8; b++)                                     //UP Buttons
   { drawUpButtonSlide((b*35)+4+18, TopSldY-26);} 
   for (byte b=0; b<8; b++)                                     //DOWN Buttons
   { drawDownButtonSlide((b*35)+4+18, TopSldY+115);}

        temp_sector= min_cnt/15;  // read current time sector only first time

	     for (byte i=0; i<8; i++)                          // draw white bar outline rectangle
		{ sbX1=(i*35)+4+18; sbX2=(i*35)+34+18;
	      setFont(SMALL, 255, 255, 255, 0, 0, 0); 
		  myGLCD.drawRect(sbX1, TopSldY-1, sbX2, BotSldY);}
   }

       SliderSwitch  = true;

   if ((GlobalStatus2Byte & 0x0F) ==0 ) {   // no preset 
		      tvcol_out =0;         // TV colour	
		      rcol_out =0;		    // DR colour	
			  wcol_out =0;		    // CW colour	
		      bcol_out =0;			// BL colour
		      rbcol_out =0;	    	// RBL colour
		      uvcol_out =0;         // UV colour
		      cycol_out =0;         // CY colour
		      yelcol_out =0;	    // Yellow colour
			  colorLEDtest = false;
	   	   } 

   for (byte i=0; i<8; i++)                                  //print Slider Bar current values
     { 
	   sbX1=(i*35)+4+18; sbX2=(i*35)+34+18;
	    if (i==0) 
	 {  LedShannelFlag_on_off =true;  
	 if (bitRead(LedShannelStatusByte,5) == false) {tvcol_out=0; LedShannelFlag_on_off =false; }
	 sbR= rgbCh6[0]; sbG= rgbCh6[1]; sbB= rgbCh6[2];  tSlide= tvcol_out;              // TV colour	
     setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
     tvcol_out = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}

  	     if (i==1) 
    {  LedShannelFlag_on_off = true;
    if (bitRead(LedShannelStatusByte,3) == false) {rcol_out=0; LedShannelFlag_on_off =false; }  
	sbR= rgbCh5[0]; sbG= rgbCh5[1]; sbB= rgbCh5[2]; tSlide= rcol_out;					   // DR colour	
    setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
	rcol_out = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}    

	     if (i==2) 
	{   LedShannelFlag_on_off = true;
    if (bitRead(LedShannelStatusByte,0) == false) {wcol_out=0; LedShannelFlag_on_off =false; }  
	sbR= rgbCh2[0]; sbG= rgbCh2[1]; sbB= rgbCh2[2]; tSlide= wcol_out;				   // CW colour	
    setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
	wcol_out = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}    

	     if (i==3) 
	{   LedShannelFlag_on_off = true;
    if (bitRead(LedShannelStatusByte,1) == false) {bcol_out=0; LedShannelFlag_on_off =false; }   
	sbR= rgbCh4[0]; sbG= rgbCh4[1]; sbB= rgbCh4[2]; tSlide= bcol_out;					   // BL colour
    setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
	bcol_out = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);} 

 	     if (i==4) 
	{  LedShannelFlag_on_off = true;
    if (bitRead(LedShannelStatusByte,2) == false) {rbcol_out=0; LedShannelFlag_on_off =false; }  
	sbR= rgbCh3[0]; sbG= rgbCh3[1]; sbB= rgbCh3[2]; tSlide = rbcol_out;				   // RBL colour
    setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
	rbcol_out = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}    

	     if (i==5) 
	{  LedShannelFlag_on_off = true;
    if (bitRead(LedShannelStatusByte,4) == false) {uvcol_out=0; LedShannelFlag_on_off =false; }  
	sbR= rgbCh1[0]; sbG= rgbCh1[1]; sbB= rgbCh1[2]; tSlide= uvcol_out;				   // UV colour
    setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
	uvcol_out = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}

	     if (i==6) 
	{  LedShannelFlag_on_off = true;
    if (bitRead(LedShannelStatusByte,6) == false) {cycol_out=0; LedShannelFlag_on_off =false; }  
	sbR= rgbCh0[0]; sbG= rgbCh0[1]; sbB= rgbCh0[2]; tSlide= cycol_out ;	 // CY colour
    setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
	cycol_out = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}    

	     if (i==7)  
	{  LedShannelFlag_on_off = true;
    if (bitRead(LedShannelStatusByte,7) == false) {yelcol_out=0; LedShannelFlag_on_off =false; }  
	sbR= rgbCh7[0]; sbG= rgbCh7[1]; sbB= rgbCh7[2];	tSlide= yelcol_out;				   // Yellow colour
    setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
	yelcol_out = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}
    }
        LedShannelFlag_on_off = true;
        LED_levels_output();			    // send calculated value to PWM
         
        if (refreshPresetscreen == true)
		{
        myGLCD.setColor(64, 64, 64);                       //Draw Dividers in Grey
		myGLCD.drawRect(0, 196, 319, 194);                 //Bottom Horizontal Divider
		printButton("<< BACK", back[0], back[1], back[2], back[3], SMALL);
		printButton("SAVE", prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3], SMALL);
		printButton("CANCEL", canC[0], canC[1], canC[2], canC[3], SMALL);  

	if (bitRead(GlobalStatus2Byte,0)== 1){printButton("Preset 1", LedPres1[0], LedPres1[1], LedPres1[2], LedPres1[3], SMALL, GREEN_BAC);} // ON preset
	                                else {printButton("Preset 1", LedPres1[0], LedPres1[1], LedPres1[2], LedPres1[3], SMALL);} // OFF preset
    if (bitRead(GlobalStatus2Byte,1)== 1){printButton("Preset 2", LedPres2[0], LedPres2[1], LedPres2[2], LedPres2[3], SMALL, GREEN_BAC);} // ON preset
	                                else {printButton("Preset 2", LedPres2[0], LedPres2[1], LedPres2[2], LedPres2[3], SMALL);} // OFF preset
    if (bitRead(GlobalStatus2Byte,2)== 1){printButton("Preset 3", LedPres3[0], LedPres3[1], LedPres3[2], LedPres3[3], SMALL, GREEN_BAC);} // ON preset
	                                else {printButton("Preset 3", LedPres3[0], LedPres3[1], LedPres3[2], LedPres3[3], SMALL);} // OFF preset
    if (bitRead(GlobalStatus2Byte,3)== 1){printButton("Preset 4", LedPres4[0], LedPres4[1], LedPres4[2], LedPres4[3], SMALL, GREEN_BAC);} // ON preset
	                                else {printButton("Preset 4", LedPres4[0], LedPres4[1], LedPres4[2], LedPres4[3], SMALL);} // OFF preset

		}
}


void SaveAndExit ()
{
   myGLCD.setColor(255, 255, 255);                       
   myGLCD.drawRoundRect(1, 53, 318, 153);                 
   myGLCD.setColor(100, 100, 100);
   myGLCD.fillRoundRect(2, 54, 317, 152); 
   setFont(LARGE, 255, 255, 255, 100, 100, 100);
//   myGLCD.print("Do you want to save", 7, 63);
//   myGLCD.print("changes", 104, 83);
//   myGLCD.print("before exit?", 64, 103);
   for (int PrintStringIndex = 0; PrintStringIndex <3; PrintStringIndex++)
  { strcpy_P(buffer, (char*)pgm_read_word_near(&(Header_Text_table[PrintStringIndex])));  
	myGLCD.print(buffer, 7, 63+PrintStringIndex*20); }
   printButton("YES", Yes[0], Yes[1], Yes[2], Yes[3], SMALL);  
   printButton("NO", No[0], No[1], No[2], No[3], SMALL); 

//		DisplayTimeSector(temp_sector);
		tv_out = tvled[temp_sector];  // read setting from buffer
		b_out = bled[temp_sector];
		w_out = wled[temp_sector];
		rb_out = rbled[temp_sector];
		r_out = rled[temp_sector];
		uv_out = uvled[temp_sector];
		cy_out = cyled[temp_sector];
		yel_out = yeled[temp_sector];

// check if channel on or off
  if (bitRead(LedShannelStatusByte,0) == false) {w_out=0;}  
  if (bitRead(LedShannelStatusByte,1) == false) {b_out=0;}  
  if (bitRead(LedShannelStatusByte,2) == false) {rb_out=0;}  
  if (bitRead(LedShannelStatusByte,3) == false) {r_out=0;}  
  if (bitRead(LedShannelStatusByte,4) == false) {uv_out=0;}  
  if (bitRead(LedShannelStatusByte,5) == false) {tv_out=0;}  
  if (bitRead(LedShannelStatusByte,6) == false) {cy_out=0;}  
  if (bitRead(LedShannelStatusByte,7) == false) {yel_out=0;}  

}

/******** SHOW LED COLOR CHOICES SCREEN ******* dispScreen = 7 ************************/
void ledColorViewScreen() // print led & moon colour buttons
{
//ReadLedFromEEPROM();  //#oleg new read with convert 0-255 to 0%-100%
//  printHeader("Individual LED Outputs: Color Choices");
  PrintStringIndex=20; 
  printHeader ();

  myGLCD.setColor(64, 64, 64);                      //Draw Dividers in Grey
  myGLCD.drawRect(0, 196, 319, 194);                //Bottom Horizontal Divider
  printButton("<< BACK", back[0], back[1], back[2], back[3], SMALL);
  printButton("CANCEL", canC[0], canC[1], canC[2], canC[3], SMALL); 
 // first column
  myGLCD.setColor(rgbCh6[0], rgbCh6[1], rgbCh6[2]);
  myGLCD.fillRoundRect(10, 20, 150, 45);       //button size 25x140, vertical clearens 10pix  
  setFont(SMALL, 0, 0, 0, rgbCh6[0], rgbCh6[1], rgbCh6[2]);   
 //myGLCD.print("TrueViolet", 40, 26);   
  myGLCD.print(ChButName[6], 40, 26); 

  myGLCD.setColor(rgbCh5[0], rgbCh5[1], rgbCh5[2]);
  myGLCD.fillRoundRect(10, 55, 150, 80);
  setFont(SMALL, 0, 0, 0, rgbCh5[0], rgbCh5[1], rgbCh5[2]);
//myGLCD.print("DeepRed", 47, 61); 
  myGLCD.print(ChButName[5], 47, 61); 

  myGLCD.setColor(rgbCh2[0], rgbCh2[1], rgbCh2[2]);
  myGLCD.fillRoundRect(10, 90, 150, 115);
  setFont(SMALL, 0, 0, 0, rgbCh2[0], rgbCh2[1], rgbCh2[2]);   
//myGLCD.print("White", 60, 96);
  myGLCD.print(ChButName[2], 60, 96); 

  myGLCD.setColor(rgbCh4[0], rgbCh4[1], rgbCh4[2]);  
  myGLCD.fillRoundRect(10, 125, 150, 150);
  setFont(SMALL, 0, 0, 0, rgbCh4[0], rgbCh4[1], rgbCh4[2]);   
//myGLCD.print("Blue", 60, 131);
  myGLCD.print(ChButName[4], 60, 131); 
   
  myGLCD.setColor( rgbCh8[0], rgbCh8[1], rgbCh8[2]);              
  myGLCD.fillRoundRect(10, 160, 150, 185);
  setFont(SMALL, 0, 0, 0, rgbCh8[0], rgbCh8[1], rgbCh8[2]); // (R,G,B- font colour, R,G,B- fon colour )
//myGLCD.print("Lunar", 60, 166);
  myGLCD.print(ChButName[8], 60, 166); 

  // second column   
  myGLCD.setColor( rgbCh3[0], rgbCh3[1], rgbCh3[2]);
  myGLCD.fillRoundRect(170, 20, 310, 45);
  setFont(SMALL, 0, 0, 0, rgbCh3[0], rgbCh3[1], rgbCh3[2]);   
//myGLCD.print("Royal Blue", 196, 26);
  myGLCD.print(ChButName[3], 196, 26); 
   
  myGLCD.setColor(rgbCh1[0], rgbCh1[1], rgbCh1[2]);
  myGLCD.fillRoundRect(170, 55, 310, 80);
  setFont(SMALL, 0, 0, 0, rgbCh1[0], rgbCh1[1], rgbCh1[2]);   
//myGLCD.print("UltraViolet", 196, 61);
  myGLCD.print(ChButName[1], 196, 61); 

  myGLCD.setColor(rgbCh0[0], rgbCh0[1], rgbCh0[2]);
  myGLCD.fillRoundRect(170, 90, 310, 115);
  setFont(SMALL, 0, 0, 0, rgbCh0[0], rgbCh0[1], rgbCh0[2]);   
//myGLCD.print("Cyan", 220, 96);
  myGLCD.print(ChButName[0], 220, 96); 
   
  myGLCD.setColor(rgbCh7[0], rgbCh7[1], rgbCh7[2]);
  myGLCD.fillRoundRect(170, 125, 310, 150);
  setFont(SMALL, 0, 0, 0, rgbCh7[0], rgbCh7[1], rgbCh7[2]);   
//myGLCD.print("Yellow", 215, 131);
  myGLCD.print(ChButName[7], 215, 131); 

  myGLCD.setColor(200, 200, 200);
  myGLCD.fillRoundRect(170, 160, 310, 185);
  setFont(SMALL, 0, 0, 0, 200, 200, 200);   
//myGLCD.print("Curves Colors", 191, 166);
  myGLCD.print(ChButName[9], 191, 166); 

  myGLCD.setColor(255, 255, 255);    // draw button white border
  for (int x=0; x<2; x++)
  { for (int y=0; y<5; y++)
      { myGLCD.drawRoundRect((x*160)+10, (y*35)+20, (x*160)+150, (y*35)+45); }
  }
  //myGLCD.drawRoundRect(10, 160, 150, 185); // lunar button
}
/************************** END OF LED COLOR CHOICES SCREEN ***************************/


/****** SHOW LED VALUES FOR CHOICE SCREEN ********** dispScreen = 8 *******************/
void ledValuesScreen() //print TOP NAME bar & horisontal buttons, with timetable 12x8
{   
	myGLCD.setColor(0, 0, 0);
    myGLCD.fillRect(0, 0, 319, 15); // clear only header

  if (COLOR==1) {
    for (byte i=0; i<96; i++)
	{tled[i] = wled[i]; sbR= rgbCh2[0]; sbG= rgbCh2[1]; sbB= rgbCh2[2]; }}
  if (COLOR==2) {
    for (byte i=0; i<96; i++)
	{tled[i]=bled[i];  sbR= rgbCh4[0]; sbG= rgbCh4[1]; sbB= rgbCh4[2];}}
  if (COLOR==3) {
    for (byte i=0; i<96; i++)
	{tled[i] = rbled[i]; sbR= rgbCh3[0]; sbG= rgbCh3[1]; sbB= rgbCh3[2];}}
  if (COLOR==4) {
    for (byte i=0; i<96; i++)
	{tled[i] = rled[i]; sbR= rgbCh5[0]; sbG= rgbCh5[1]; sbB= rgbCh5[2];}}  
  if (COLOR==5) {
    for (byte i=0; i<96; i++)
	{tled[i] = uvled[i]; sbR= rgbCh1[0]; sbG= rgbCh1[1]; sbB= rgbCh1[2];}}
  if (COLOR==6) {
    for (byte i=0; i<96; i++)
	{tled[i] = tvled[i]; sbR= rgbCh6[0]; sbG= rgbCh6[1]; sbB= rgbCh6[2];}}
  if (COLOR==8) {
    for (byte i; i<96; i++)
	{tled[i] = cyled[i]; sbR= rgbCh0[0]; sbG= rgbCh0[1]; sbB= rgbCh0[2];}}
    if (COLOR==9) {
    for (byte i=0; i<96; i++)
	{tled[i] = yeled[i]; sbR= rgbCh7[0]; sbG= rgbCh7[1]; sbB= rgbCh7[2];}}

	ReadOnOffLedStatus();			
	myGLCD.setColor(255, 255, 255);                                 //draw white border
	myGLCD.drawRoundRect(110, 0, 201, 17);
   	myGLCD.setColor(0, 0, 255);										//print on/off button
	myGLCD.fillRoundRect(111, 1, 200, 16);
   	setFont(SMALL, 255, 255, 255, 0, 0, 255 );   
	    if (LedShannelFlag_on_off == true) { myGLCD.print("LED ON", 129, 3);}
	        else { myGLCD.print("LED OFF", 129, 3);}

    for (byte i=0; i<=95; i++)			  // find START graph Time
	{ byte TEMP=tled[i]; 
	   if (TEMP>0) { StartTime=i-1;
	   if (StartTime == 255) {StartTime=0;} 
	   break; }}

	for (byte i=95; i>0; i-- )			  // find STOP graph Time
	{ byte TEMP=tled[i];
	if (TEMP>0) {StopTime=i+1; break; }}

//			byte stepScale = (294 - 26)/(StopTime-StartTime);		// 26 and 318 - left / right
			drawLedStaticChartP1 ();		                        // calculate draw TOP ON/OFF time and X/Y border
       		draw_one_led_graph(); 
			drawLedStaticChartP2 ();		             // draw BOT ON/OFF time and X/Y scale and tick mark (15min/30min/1hour)

		myGLCD.setColor(64, 64, 64);       
		myGLCD.drawRect(0, 196, 319, 194); 
		printButton("<< BACK", back[0], back[1], back[2], back[3], SMALL);
		printButton("CHANGE", ledChV[0], ledChV[1], ledChV[2], ledChV[3], SMALL);
		printButton("SAVE", eeprom[0], eeprom[1], eeprom[2], eeprom[3]);
  }


/*************************** END OF SHOW LED VALUES SCREEN ****************************/

void MoonPictureScreen()  // print moon picture& table
{    
    tMinI=MinI;
    tMaxI=MaxI;
//  printHeader("View/Change Moon LED Min & Max Output");
	PrintStringIndex=21; 
    printHeader ();
    setFont(SMALL, 255, 255, 255, 0, 0, 0);
//  myGLCD.print("Set Minimum", 36, 20);
	strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[45]))); 
    myGLCD.print(buffer, 36, 20); 
//  myGLCD.print("Illumination", 32, 32); 
	strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[46]))); 
    myGLCD.print(buffer, 32, 32); 
    myGLCD.drawBitmap(52, 47, 58, 58, New_Moon, 1);      //New Moon Picture
//  myGLCD.print("(0...100%)", 40, 132);
    strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[47]))); 
    myGLCD.print(buffer, 40, 132); 
    myGLCD.print("-1", 22, 177);        
    myGLCD.print("+1", 121, 177);  
//  myGLCD.print("Set Maximum", 196, 20); 
    strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[48]))); 
    myGLCD.print(buffer, 196, 20); 
//  myGLCD.print("Illumination", 192, 32); 
    strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[46]))); 
    myGLCD.print(buffer, 192, 32); 
    myGLCD.drawBitmap(211, 47, 58, 58, Full_Moon, 1);    //Full Moon Picture
//  myGLCD.print("(0...100%)", 202, 132);
	strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[47]))); 
    myGLCD.print(buffer, 202, 132); 
    myGLCD.print("-1", 184, 177);        
    myGLCD.print("+1", 283, 177);      
    setFont(SMALL, 176, 176, 176, 0, 0, 0);            
//  myGLCD.print("New Moon", 48, 108);
    strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[49]))); 
    myGLCD.print(buffer, 48, 108); 
//  myGLCD.print("Full Moon", 204, 108); 
    strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[50]))); 
    myGLCD.print(buffer, 204, 108); 

    setFont(LARGE, 255, 255, 255, 0, 0, 0);
    myGLCD.print("   ", 55, 152);
    if (tMinI<=9)
      { myGLCD.printNumI(tMinI, 71, 152);}
    if ((tMinI>=10)&&(tMinI<=99))
      { myGLCD.printNumI(tMinI, 63, 152);}
    if (tMinI>=100)
      { myGLCD.printNumI(tMinI, 55, 152);}
      
    myGLCD.print("   ", 217, 152);
    if (tMaxI<=9)
      { myGLCD.printNumI(tMaxI, 233, 152);}
    if ((tMaxI>=10)&&(tMaxI<=99))
      { myGLCD.printNumI(tMaxI, 225, 152);}
    if (tMaxI>=100)
      { myGLCD.printNumI(tMaxI, 217, 152);}
   
    printButton("-", MINiM[0], MINiM[1], MINiM[2], MINiM[3], true);  //Minimum Illum. minus
    printButton("+", MINiP[0], MINiP[1], MINiP[2], MINiP[3], true);  //Minimum Illum. plus
    printButton("-", MAXiM[0], MAXiM[1], MAXiM[2], MAXiM[3], true);  //Max Illum. minus
    printButton("+", MAXiP[0], MAXiP[1], MAXiP[2], MAXiP[3], true);  //Max Illum. plus

    myGLCD.setColor(64, 64, 64);
    myGLCD.drawRect(158, 14, 160, 194);
    myGLCD.drawRect(0, 196, 319, 194);
    myGLCD.setColor(0, 0, 0);
    myGLCD.drawLine(159, 193, 159, 195);
	printButton("<< BACK", back[0], back[1], back[2], back[3], SMALL);
    printButton("SAVE", prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3], SMALL);
    printButton("CANCEL", canC[0], canC[1], canC[2], canC[3], SMALL);    
}

void MoonChangeScreen()  // + or - led brigtness value ---------
{
    if ((x>=MINiM[0]) && (x<=MINiM[2]) && (y>=MINiM[1]) && (y<=MINiM[3]))   //press button "MinI minus"
      {
//       waitForIt(MINiM[0], MINiM[1], MINiM[2], MINiM[3]);  // wait for press button
       tMinI -= 1;
       if (tMinI == 255) {tMinI = 100; }
       MinI = tMinI;         
       setFont(LARGE, 255, 255, 255, 0, 0, 0);
       myGLCD.print("   ", 55, 152);
       if (tMinI<=9)
         { myGLCD.printNumI(tMinI, 71, 152);}
       if ((tMinI>=10)&&(tMinI<=99))
         { myGLCD.printNumI(tMinI, 63, 152);}
       if (tMinI>=100)
        { myGLCD.printNumI(tMinI, 55, 152);}
          delay(200);
     } else      
	
    if ((x>=MINiP[0]) && (x<=MINiP[2]) && (y>=MINiP[1]) && (y<=MINiP[3]))   //press button "MinI plus"
      {
//     waitForIt(MINiP[0], MINiP[1], MINiP[2], MINiP[3]);
       tMinI += 1;
         if (tMinI >100) {tMinI = 0; }
       MinI = tMinI;         
       setFont(LARGE, 255, 255, 255, 0, 0, 0);
       myGLCD.print("   ", 55, 152);
       if (tMinI<=9)
         { myGLCD.printNumI(tMinI, 71, 152);}
       if ((tMinI>=10)&&(tMinI<=99))
         { myGLCD.printNumI(tMinI, 63, 152);}
       if (tMinI>=100)
         { myGLCD.printNumI(tMinI, 55, 152);}
       delay(200);
      } else

    if ((x>=MAXiM[0]) && (x<=MAXiM[2]) && (y>=MAXiM[1]) && (y<=MAXiM[3]))   //press buton "MaxI minus"
      {
//       waitForIt(MAXiM[0], MAXiM[1], MAXiM[2], MAXiM[3]);
       tMaxI -= 1;
       if (tMaxI == 255) { tMaxI = 100; }
       MaxI = tMaxI;         
       setFont(LARGE, 255, 255, 255, 0, 0, 0);
       myGLCD.print("   ", 217, 152);
       if (tMaxI<=9)
         { myGLCD.printNumI(tMaxI, 233, 152);}
       if ((tMaxI>=10)&&(tMaxI<=99))
         { myGLCD.printNumI(tMaxI, 225, 152);}
       if (tMaxI>=100)
         { myGLCD.printNumI(tMaxI, 217, 152);}
       delay(200);
      } else      
    if ((x>=MAXiP[0]) && (x<=MAXiP[2]) && (y>=MAXiP[1]) && (y<=MAXiP[3]))   //press button "MaxI plus"
      {
//       waitForIt(MAXiP[0], MAXiP[1], MAXiP[2], MAXiP[3]);
       tMaxI += 1;
         if (tMaxI >100) {tMaxI = 0; }
       MaxI = tMaxI;         
       setFont(LARGE, 255, 255, 255, 0, 0, 0);
       myGLCD.print("   ", 217, 152);
       if (tMaxI<=9)
         { myGLCD.printNumI(tMaxI, 233, 152);}
       if ((tMaxI>=10)&&(tMaxI<=99))
         { myGLCD.printNumI(tMaxI, 225, 152);}
       if (tMaxI>=100)
         { myGLCD.printNumI(tMaxI, 217, 152);}
        delay(200);
      }
}

/********** CHANGE LED VALUES SCREEN ********** dispScreen = 9 ************************/
void ledChangeScreen() //print TOP timetable & Vertical buttons, w/o slider
{
  if (COLOR==1)
    {   PrintStringIndex=4;
        printHeader ();
		//printHeader("Change White LED Output Values"); 
      sbR= rgbCh2[0]; sbG= rgbCh2[1]; sbB= rgbCh2[2]; }
  if (COLOR==2)
    { PrintStringIndex=4; //5; 
      printHeader ();
//		printHeader("Change Blue LED Output Values"); 
      sbR= rgbCh4[0]; sbG= rgbCh4[1]; sbB= rgbCh4[2]; }  
  if (COLOR==3)
    { PrintStringIndex=4; //6;
      printHeader (); 
//		printHeader("Change Royal Blue LED Output Values"); 
      sbR= rgbCh3[0]; sbG= rgbCh3[1]; sbB= rgbCh3[2]; }
  if (COLOR==4)
    {  PrintStringIndex=4; //7;
       printHeader ();
//		printHeader("Change Red LED Output Values"); 
      sbR= rgbCh5[0]; sbG= rgbCh5[1]; sbB= rgbCh5[2]; }      
  if (COLOR==5)
    { PrintStringIndex=4; //8; 
      printHeader ();
//		printHeader("Change UltraViolet LED Output Values"); 
      sbR= rgbCh1[0]; sbG= rgbCh1[1]; sbB= rgbCh1[2]; }  
  if (COLOR==6)
    {   PrintStringIndex=4;// 9; 
        printHeader ();
//	printHeader("Change TrueViolet LED Output Values");  
       sbR= rgbCh6[0]; sbG= rgbCh6[1]; sbB= rgbCh6[2]; }
  if (COLOR==8)
    {   PrintStringIndex=4; //10; 
        printHeader ();
//		printHeader("Change Cyan LED Output Values");
  sbR=rgbCh0[0]; sbG=rgbCh0[1]; sbB= rgbCh0[2];}
  if (COLOR==9)
    {  PrintStringIndex=4; //11; 
       printHeader ();
//		printHeader("Change Yellow LED Output Values");  
       sbR= rgbCh7[0]; sbG= rgbCh7[1]; sbB= rgbCh7[2]; }    

  setFont(SMALL, 0, 255, 255, 0,0,0);                  //Top time selector bar
  for (int i=0; i<12; i++) {
    myGLCD.setColor(0, 255, 255);
    if (i<5) {
      myGLCD.printNumI((i*2), (i*26)+15, 17);
      myGLCD.printNumI(((i*2)+1), (i*26)+15, 28);}
    else {
      myGLCD.printNumI((i*2), (i*26)+11, 17);
      myGLCD.printNumI(((i*2)+1), (i*26)+11, 28);}
    myGLCD.setColor(100, 100, 100);
    myGLCD.drawRect((i*26)+4, 16 , (i*26)+30, 41);
    }      


  myGLCD.setColor(0, 0, 0);					// clear bottom time|date bar
  myGLCD.fillRect(1, 226, 318, 240);

  myGLCD.drawRect(4, 43, 30, 223);                     //left menu bar
  myGLCD.setColor(0, 0, 255);
  myGLCD.fillRoundRect(8, 66, 26, 140);                //OK Button (long)
  myGLCD.fillRoundRect(8, 145, 26, 219);  
  myGLCD.setColor(255, 255, 255);
  myGLCD.drawRoundRect(8, 66, 26, 140);                //OK Button (long)
  myGLCD.drawRoundRect(8, 145, 26, 219);               //CANCEL Button  
  
  setFont(SMALL, 255, 255, 255, 0, 0, 255); 
  myGLCD.print("O", 14, 91);   
  myGLCD.print("K", 14, 101);

  myGLCD.print("C", 14, 152);    
  myGLCD.print("A", 14, 162);
  myGLCD.print("N", 14, 172);
  myGLCD.print("C", 14, 182);  
  myGLCD.print("E", 14, 192);
  myGLCD.print("L", 14, 202);  
  
  setFont(SMALL, 255, 0, 0, 0, 0, 0);     
//  myGLCD.print("Make a selection above. Choose", 57, 110);
//  myGLCD.print("any Two-Hour Increment", 89, 122);
//  myGLCD.print("then you can adjust values.", 73, 134);       
   strcpy_P(buffer, (char*)pgm_read_word_near(&(Header_Text_table[12]))); 
   myGLCD.print(buffer, 57, 110 );
   strcpy_P(buffer, (char*)pgm_read_word_near(&(Header_Text_table[13]))); 
   myGLCD.print(buffer, 89, 122 );
   strcpy_P(buffer, (char*)pgm_read_word_near(&(Header_Text_table[14]))); 
   myGLCD.print(buffer, 73, 134 );
}
/*************************** END OF CHANGE LED VALUES SCREEN **************************/  

/*************************** Preset Function ******************************************/
void PresetSwitch ()
{
	calculateStopTime() ;
	switch ((GlobalStatus2Byte & 0x0F)) {
	case 0:
					printButton("Preset 1 ON", prsM[0],prsM[1],prsM[2],prsM[3], SMALL, GREEN_BAC); 
				    GlobalStatus2Byte = (GlobalStatus2Byte & 0xF0 | 0x1);
					AddressShift = 0;
					ReadLEDPresetFromEEPROM();
				    colorLEDtest = true;
					digitalWrite(PowerSwitch2, LOW);      // ON led driver 
    break;

	case 1:
				    printButton("Preset 2 ON", prsM[0],prsM[1],prsM[2],prsM[3], SMALL, GREEN_BAC); 
				    GlobalStatus2Byte = (GlobalStatus2Byte & 0xF0 | 0x2);  
					AddressShift = 9;
					ReadLEDPresetFromEEPROM();
				    colorLEDtest = true;
					digitalWrite(PowerSwitch2, LOW);      // ON led driver 
    break;

	case 2:
					printButton("Preset 3 ON", prsM[0],prsM[1],prsM[2],prsM[3], SMALL, GREEN_BAC); 
				    GlobalStatus2Byte = (GlobalStatus2Byte & 0xF0 | 0x4);
					AddressShift = 18;
					ReadLEDPresetFromEEPROM();
				    colorLEDtest = true;
					digitalWrite(PowerSwitch2, LOW);      // ON led driver 
    break;

	case 4:
					printButton("Preset 4 ON", prsM[0],prsM[1],prsM[2],prsM[3], SMALL, GREEN_BAC); 
				    GlobalStatus2Byte = (GlobalStatus2Byte & 0xF0 | 0x8);
					AddressShift = 27;
					ReadLEDPresetFromEEPROM();
				    colorLEDtest = true;
					digitalWrite(PowerSwitch2, LOW);      // ON led driver 
    break;

	case 8:
					printButton("Preset OFF", prsM[0],prsM[1],prsM[2],prsM[3], SMALL); 
					GlobalStatus2Byte = (GlobalStatus2Byte & 0xF0); 
					colorLEDtest = false;
                    if ((min_cnt/15 >= StartTime-1) && (min_cnt/15 <= StopTime))
			             {digitalWrite(PowerSwitch2, LOW);}  //ON driver before StartTime - 15min
			              else {digitalWrite(PowerSwitch2, HIGH);} //OFF driver before StartTime
    break;
	                                 }
}

/************ WAVEMAKER SCREEN **************** dispScreen = 10 ***********************/
/*
void WaveMakerButtons()
{
  myGLCD.setColor(255, 0, 0);
  myGLCD.fillRoundRect(5, 20, 155, 40);        //Alternating Mode Button
  myGLCD.fillRoundRect(165, 20, 315, 40);      //Synchronous Mode Button
  myGLCD.fillRoundRect(5, 46, 155, 66);        //Feeding Mode Button
  myGLCD.fillRoundRect(165, 46, 315, 66);      //Turn Pumps ON/OFF Button
  setFont(SMALL, 255, 255, 255, 255, 0, 0);
  myGLCD.print("Alternating Mode", 16, 24); 
  myGLCD.print("Synchronous Mode", 176, 24);
  myGLCD.print("Feeding Mode", 32, 50);
  myGLCD.print("Turn Pumps OFF", 184, 50);
}

void WaveMakerScreen()
{ 
//  printHeader("View/Change Wavemaker Settings");
  PrintStringIndex=22; 
  printHeader ();
   
  myGLCD.setColor(64, 64, 64);                 //Draw Dividers in Grey
  myGLCD.drawRect(0, 70, 319, 72);             //Top Horizontal Divider
  myGLCD.drawRect(0, 196, 319, 194);           //Bottom Horizontal Divider
  printButton("<< BACK", back[0], back[1], back[2], back[3], SMALL);
  printButton("CANCEL", canC[0], canC[1], canC[2], canC[3], SMALL); 
   
  setFont(LARGE, 255, 255, 255, 0, 0, 0);
  myGLCD.print("Current Status:", CENTER, 80);
} 

void viewWaveTimes()
{
  setFont(SMALL, 0, 255, 0, 0, 0, 0);     
  int dynamicXm=135;
  if ((MIN1<=99) && (MIN1>=10)) {dynamicXm+=8;}
  if (MIN1<=9) {dynamicXm+=16;}
  myGLCD.printNumI(MIN1, dynamicXm, minY1);
  int dynamicXs=231;
  if (SEC1<=9) {dynamicXs+=8;}
  myGLCD.printNumI(SEC1, dynamicXs, minY1);     
  dynamicXm=135;
  if ((MIN2<=99) && (MIN2>=10)) {dynamicXm+=8;}
  if (MIN2<=9) {dynamicXm+=16;}
  myGLCD.printNumI(MIN2, dynamicXm, minY2);
  dynamicXs=231;
  if (SEC2<=9) {dynamicXs+=8;}
  myGLCD.printNumI(SEC2, dynamicXs, minY2);     
}

void WaveMakerStatusScreen()
{
  myGLCD.setColor(0, 0, 0);                    //Clear Status Area
  myGLCD.fillRect( 1, 96, 318, 193);
  
  WaveMakerButtons();
  
  if (WAVE==0)
    {
     setFont(LARGE, 255, 0, 0, 0, 0, 0);
     myGLCD.print("No Mode Saved!", CENTER, 100);
     setFont(SMALL, 255, 0, 0, 0, 0, 0);     
     myGLCD.print("Make a selection above. Choose", CENTER, 130);
     myGLCD.print("either Alternating or Synchronous", CENTER, 142);
     myGLCD.print("then save your settings.", CENTER, 154);          
    } else
      
  if (WAVE==1)
    {
     myGLCD.setColor(0, 255, 0);
     myGLCD.fillRoundRect(5, 20, 155, 40);  
     setFont(SMALL, 0, 0, 0, 0, 255, 0);
     myGLCD.print("Alternating Mode", 16, 24); 
     myGLCD.setColor(255, 255, 255);
     myGLCD.drawRoundRect(5, 20, 155, 40);
     
     setFont(LARGE, 0, 255, 0, 0, 0, 0);
     myGLCD.print("Alternating Flow", CENTER, 100);
     
     myGLCD.print("Pump1->", 15, 140);
     myGLCD.print("min", 167, 140); 
     myGLCD.print("sec", 255, 140); 
     myGLCD.print("Pump2->", 15, 160);    
     myGLCD.print("min", 167, 160); 
     myGLCD.print("sec", 255, 160);     

     MIN1=Pump1m, SEC1=Pump1s, MIN2=Pump2m, SEC2=Pump2s;
     minY1=144, minY2=164;
     viewWaveTimes();
    } else
    
    
  if (WAVE==2)
    {
     myGLCD.setColor(0, 255, 0);
     myGLCD.fillRoundRect(165, 20, 315, 40);  
     setFont(SMALL, 0, 0, 0, 0, 255, 0);
     myGLCD.print("Synchronous Mode", 176, 24);
     myGLCD.setColor(255, 255, 255);
     myGLCD.drawRoundRect(165, 20, 315, 40);
     
     setFont(LARGE, 0, 255, 0, 0, 0, 0);
     myGLCD.print("Synchronous Flow", CENTER, 100);
     
     if (Synch==1) 
       { 
        myGLCD.print("Constantly ON", CENTER, 116);
        setFont(SMALL, 255, 0, 0, 0, 0, 0);
        myGLCD.print("Both powerheads are ON constantly.", CENTER, 144);
        myGLCD.print("To change to Pulsating Mode, push", CENTER, 156);  
        myGLCD.print("the Synchronous Mode button above", CENTER, 168);         
       }     
     if (Synch==2) 
       { 
        myGLCD.print("Pulsating Mode", CENTER, 116);

        myGLCD.print("ON for", 15, 146);
        myGLCD.print("min", 167, 146); 
        myGLCD.print("sec", 255, 146); 
        myGLCD.print("OFF for", 15, 166);    
        myGLCD.print("min", 167, 166); 
        myGLCD.print("sec", 255, 166);     

        MIN1=OnForTm, SEC1=OnForTs, MIN2=OffForTm, SEC2=OffForTs;
        minY1=150, minY2=170;
        viewWaveTimes();
       }
    } else
    
    
  if (WAVE==3)
    {
     myGLCD.setColor(0, 255, 0);
     myGLCD.fillRoundRect(165, 46, 315, 66);  
     setFont(SMALL, 0, 0, 0, 0, 255, 0);
     myGLCD.print("Turn Pumps ON", 188, 50);      
     myGLCD.setColor(255, 255, 255);
     myGLCD.drawRoundRect(165, 46, 315, 66);
     
     setFont(LARGE, 0, 255, 0, 0, 0, 0);
     myGLCD.print("Powerheads are OFF", CENTER, 100);
     setFont(SMALL, 0, 255, 0, 0, 0, 0);
     myGLCD.print("To turn the powerheads back ON", CENTER, 125);
     if (MODE==1) { myGLCD.print("and resume in Alternating Mode,", CENTER, 137);} else
     if (MODE==2) { myGLCD.print("and resume in Synchronous Mode,", CENTER, 137);}
     myGLCD.print("push the Turn Pumps ON button above", CENTER, 149);     
     
     waveMakerOff=true;
     digitalWrite(WaveMakerTop, LOW);
     digitalWrite(WaveMakerBottom, LOW);    
    }  
    
  myGLCD.setColor(255, 255, 255);
  for (int x=0; x<2; x++)
    { for (int y=0; y<2; y++)
        { myGLCD.drawRoundRect((x*160)+5, (y*26)+20, (x*160)+155, (y*26)+40); }
    }  
        
  if (WAVE==4)
    {
     myGLCD.setColor(0, 255, 0);
     myGLCD.fillRoundRect(5, 46, 155, 66);  
     setFont(SMALL, 0, 0, 0, 0, 255, 0);
     myGLCD.print("Feeding Mode", 32, 50);
     myGLCD.setColor(255, 255, 255);
     for (int x=0; x<2; x++)
       { for (int y=0; y<2; y++)
           { myGLCD.drawRoundRect((x*160)+5, (y*26)+20, (x*160)+155, (y*26)+40); }
       }  
     
     setFont(LARGE, 0, 255, 0, 0, 0, 0);
     myGLCD.print("Feeding", CENTER, 100);
     setFont(SMALL, 0, 255, 0, 0, 0, 0);
     myGLCD.print("Powerheads will remain OFF", CENTER, 125);
     myGLCD.print("for 5 minutes", CENTER, 137);
     if (MODE==1) { myGLCD.print("Alternating Mode will resume in:", CENTER, 155);} else
     if (MODE==2) { myGLCD.print("Synchronous Mode will resume in:", CENTER, 155);}
     
     waveMakerOff=true;   
     digitalWrite(WaveMakerTop, LOW);
     digitalWrite(WaveMakerBottom, LOW);    
    }
    while (WAVE==4)
      {
       unsigned long currentMillis = millis();
     
       if (myTouch.dataAvailable())  
         { processMyTouch();}
    
       if(currentMillis - previousMillisCt >= intervalCt) 
         {
          previousMillisCt = currentMillis;   
          if(countDown>=0)
            {
             if (countDown<=30) 
               { myGLCD.setColor(0, 0, 0);
                 myGLCD.fillRect(128, 173, 192, 189);}
             MIN_O= (countDown / 60) % 10;
             SEC_T= (countDown % 60) / 10;
             SEC_O= (countDown % 60) % 10;
             setFont(LARGE, 255, 0, 0, 0, 0, 0);       
             myGLCD.printNumI(MIN_O, 128, 173);
             myGLCD.print(":", 144, 173);
             myGLCD.printNumI(SEC_T, 160, 173);
             myGLCD.printNumI(SEC_O, 176, 173);
             if(countDown==0)
               {
                WAVE=MODE;
                WaveMakerStatusScreen(); 
               }
             countDown--;
             checkTempC();
             TimeDateBar();             
            }
          waveMakerOff=false;            
         }   
      }
}
*/
/******************************* END OF WAVEMAKER SCREEN ******************************/  


/******** WAVEMAKER SETTINGS SCREEN ************** dispScreen = 11 ********************/
/*
void WaveMakerSettingsScreen()
{ 
  myGLCD.setColor(64, 64, 64);                 //Draw Dividers in Grey
  myGLCD.drawRect(0, 196, 319, 194);           //Bottom Horizontal Divider
  
  myGLCD.setColor(0, 0, 255);
  myGLCD.fillRoundRect(5, 200, 105, 220);      //BACK Button
  myGLCD.fillRoundRect(110, 200, 210, 220);    //TEST Button
  myGLCD.fillRoundRect(215, 200, 315, 220);    //SAVE Button

  setFont(SMALL, 255, 255, 255, 0, 0, 255);
  myGLCD.print("<< BACK", 27, 204);
  myGLCD.print("TEST", 144, 204);  
  myGLCD.print("SAVE", 241, 204);
  
  myGLCD.setColor(255, 255, 255);
  for (int x=0; x<3; x++)
    { myGLCD.drawRoundRect((x*105)+5, 200, (x*105)+105, 220); }    


  setFont(LARGE, 255, 255, 255, 0, 0, 0);
  if (WAVE==1) 
    {
//	  printHeader("Alternating Flow Mode Settings");
	  PrintStringIndex=23; 
      printHeader ();
      myGLCD.setColor(64, 64, 64);                 //Draw Dividers in Grey
      myGLCD.drawRect(0, 38, 319, 40);             //Top Horizontal Divider    
      myGLCD.drawRect(0, 115, 319, 117);           //Middle Horizontal Divider          
      setFont(SMALL, 255, 0, 0, 0, 0, 0);
      myGLCD.print("Set how long each powerhead will be ON", CENTER, 20); 
      setFont(SMALL, 0, 255, 0, 0, 0, 0);
      myGLCD.print("POWERHEAD 1", CENTER, 50);
      myGLCD.print("POWERHEAD 2", CENTER, 127);
      setFont(SMALL, 255, 255, 255, 0, 0, 0);
      myGLCD.print("Minutes", 57, 100);
      myGLCD.print("Seconds", 211, 100);
      myGLCD.print("Minutes", 57, 177);
      myGLCD.print("Seconds", 211, 177);
      
      Min1=Pump1m, Sec1=Pump1s, Min2=Pump2m, Sec2=Pump2s;     
      viewWaveTimesPage();
    }
    
  if (WAVE==2) 
    {
//     printHeader("Synchronous Flow Mode Settings");
     PrintStringIndex=24; 
     printHeader ();
     myGLCD.setColor(64, 64, 64);                 //Draw Dividers in Grey
     myGLCD.drawRect(0, 44, 319, 46);             //Top Horizontal Divider     
    }  
}

void synchronousSynch()
{
  myGLCD.setColor(0, 0, 0);                       //Clear Status Area
  myGLCD.fillRect( 1, 47, 318, 193);  
  myGLCD.setColor(255, 0, 0);
  myGLCD.fillRoundRect(5, 20, 155, 40);           //Constantly ON Mode Button
  myGLCD.fillRoundRect(165, 20, 315, 40);         //Pulsating Mode Mode Button
  setFont(SMALL, 255, 255, 255, 255, 0, 0);
  myGLCD.print("Constantly ON", 28, 24); 
  myGLCD.print("Pulsating Mode", 184, 24);  
  for (int x=0; x<2; x++)
    { myGLCD.drawRoundRect((x*160)+5, 20, (x*160)+155, 40); } 
       
  if (Synch==0)
    {  
     setFont(LARGE, 255, 0, 0, 0, 0, 0);
     myGLCD.print("NO Synchronous Mode", CENTER, 80);
     myGLCD.print("has been selected!", CENTER, 100);       
     setFont(SMALL, 255, 0, 0, 0, 0, 0);     
     myGLCD.print("Choose either Constantly ON or", CENTER, 130);
     myGLCD.print("Pulsating Mode. Afterwards, you", CENTER, 142);       
     myGLCD.print("can alter the settings.", CENTER, 154);                
    } else

  if (Synch==1)
    {  
     myGLCD.setColor(0, 255, 0);
     myGLCD.fillRoundRect(5, 20, 155, 40);  
     setFont(SMALL, 0, 0, 0, 0, 255, 0);
     myGLCD.print("Constantly ON", 28, 24); 
     myGLCD.setColor(255, 255, 255);
     myGLCD.drawRoundRect(5, 20, 155, 40);
 
     setFont(LARGE, 0, 255, 0, 0, 0, 0);
     myGLCD.print("Constantly ON Mode", CENTER, 80);
     myGLCD.print("has been selected!", CENTER, 100);       
     setFont(SMALL, 255, 0, 0, 0, 0, 0);     
     myGLCD.print("Both powerheads will remain", CENTER, 130);
     myGLCD.print("ON constantly. To change to", CENTER, 142);       
     myGLCD.print("Pulsating Mode select it above.", CENTER, 154);             
    } else

  if (Synch==2)
    {  
     myGLCD.setColor(0, 255, 0);
     myGLCD.fillRoundRect(165, 20, 315, 40);  
     setFont(SMALL, 0, 0, 0, 0, 255, 0);
     myGLCD.print("Pulsating Mode", 184, 24);
     myGLCD.setColor(255, 255, 255);
     myGLCD.drawRoundRect(165, 20, 315, 40);
   
     myGLCD.setColor(64, 64, 64);                 //Draw Dividers in Grey
     myGLCD.drawRect(0, 120, 319, 122);           //Middle Horizontal Divider          
     setFont(SMALL, 0, 255, 0, 0, 0, 0);
     myGLCD.print("POWERHEADS WIll RUN FOR", CENTER, 50);
     myGLCD.print("POWERHEADS WILL STOP FOR", CENTER, 127);
     setFont(SMALL, 255, 255, 255, 0, 0, 0);
     myGLCD.print("Minutes", 57, 100);
     myGLCD.print("Seconds", 211, 100);
     myGLCD.print("Minutes", 57, 177);
     myGLCD.print("Seconds", 211, 177);
     
     Min1=OnForTm, Sec1=OnForTs, Min2=OffForTm, Sec2=OffForTs;     
     viewWaveTimesPage();     
    }
}

void viewWaveTimesPage()
{
  setFont(LARGE, 255, 255, 255, 0, 0, 0);
  if (Min1==0) { myGLCD.print("000", 59, 75); }
  if ((Min1>=1) && (Min1<=9)) 
    { myGLCD.print("00", 59, 75); 
      myGLCD.printNumI(Min1, 91, 75);}
  if ((Min1>=10) && (Min1<=99)) 
    { myGLCD.print("0", 59, 75); 
      myGLCD.printNumI(Min1, 75, 75);}
  if (Min1>=100) { myGLCD.printNumI(Min1, 59, 75);}

  if (Sec1==0) { myGLCD.print("00", 221, 75); }
  if ((Sec1>=1) && (Sec1<=9)) 
    { myGLCD.print("0", 221, 75); 
      myGLCD.printNumI(Sec1, 237, 75);}
  if (Sec1>=10) { myGLCD.printNumI(Sec1, 221, 75);}

  if (Min2==0) { myGLCD.print("000", 59, 152); }
  if ((Min2>=1) && (Min2<=9)) 
    { myGLCD.print("00", 59, 152); 
      myGLCD.printNumI(Min2, 91, 152);}
  if ((Min2>=10) && (Min2<=99)) 
    { myGLCD.print("0", 59, 152); 
      myGLCD.printNumI(Min2, 75, 152);}
  if (Min2>=100) { myGLCD.printNumI(Min2, 59, 152);}
      
  if (Sec2==0) { myGLCD.print("00", 221, 152); }
  if ((Sec2>=1) && (Sec2<=9)) 
    { myGLCD.print("0", 221, 152); 
      myGLCD.printNumI(Sec2, 237, 152);}
  if (Sec2>=10) { myGLCD.printNumI(Sec2, 221, 152);}
  
  printButton("-", pump1Mm[0], pump1Mm[1], pump1Mm[2], pump1Mm[3], LARGE);
  printButton("+", pump1Mp[0], pump1Mp[1], pump1Mp[2], pump1Mp[3], LARGE);      
  printButton("-", pump1Sm[0], pump1Sm[1], pump1Sm[2], pump1Sm[3], LARGE);
  printButton("+", pump1Sp[0], pump1Sp[1], pump1Sp[2], pump1Sp[3], LARGE);      
  printButton("-", pump2Mm[0], pump2Mm[1], pump2Mm[2], pump2Mm[3], LARGE);
  printButton("+", pump2Mp[0], pump2Mp[1], pump2Mp[2], pump2Mp[3], LARGE);      
  printButton("-", pump2Sm[0], pump2Sm[1], pump2Sm[2], pump2Sm[3], LARGE);
  printButton("+", pump2Sp[0], pump2Sp[1], pump2Sp[2], pump2Sp[3], LARGE);  
}

void waveModePlusMinus()
{
  setFont(LARGE, 255, 255, 255, 0, 0, 0);  
  if ((y>=70) && (y<=95))                        //First Row   
    {
     if ((x>=21) && (x<=46))                     //Pump 1 Minute Minus
       {
        waitForIt(21, 70, 46, 95);
        Min1 -= 1;
        if ((min1X>=10) && (Min1<=99)) {min1X=75; myGLCD.print("0", 59, 75);}
        if ((Min1<=9) && (Min1>0)) {min1X=91; myGLCD.print("00", 59, 75);}
        if (Min1<=0) {Min1=0; myGLCD.print("0", 91, 75);}
        setFont(LARGE, 255, 255, 255, 0, 0, 0);
        myGLCD.printNumI(Min1, min1X, 75);
       }
     if ((x>=120) && (x<=145))                   //Pump 1 Minute Plus
       {
        waitForIt(120, 70, 145, 95);
        Min1 += 1;
        if ((Min1>=0) && (Min1<=9)) {min1X=91;}
        if (Min1>9) {min1X=75;}
        if (Min1>99) {min1X=59;}
        if (Min1>=999) {Min1=999;}             
        setFont(LARGE, 255, 255, 255, 0, 0, 0);
        myGLCD.printNumI(Min1, min1X, 75);
       }
     if ((x>=175) && (x<=200))                   //Pump 1 Second Minus
       {
        waitForIt(175, 70, 200, 95);
        Sec1 -= 1;
        if ((sec1X>=10) && (Sec1<=59)) {sec1X=221;}
        if ((Sec1<=9) && (Sec1>0)) {sec1X=237; myGLCD.print("0", 221, 75);}
        if (Sec1<=0) {Sec1=0; myGLCD.print("0", 237, 75);}
        setFont(LARGE, 255, 255, 255, 0, 0, 0);
        myGLCD.printNumI(Sec1, sec1X, 75);
       }
     if ((x>=274) && (x<=299))                   //Pump 1 Second Plus
       {
        waitForIt(274, 70, 299, 95);
        Sec1 += 1;
        if ((Sec1>=0) && (Sec1<=9)) {sec1X=237;}
        if (Sec1>9) {sec1X=221;}
        if (Sec1>=59) {Sec1=59;}             
        setFont(LARGE, 255, 255, 255, 0, 0, 0);
        myGLCD.printNumI(Sec1, sec1X, 75);
       }
    }
      
  if ((y>=147) && (y<=172))                         //Second Row
    {
     if ((x>=21) && (x<=46))                        //Pump 2 Minute Minus
       {
        waitForIt(21, 147, 46, 172);
        Min2 -= 1;
        if ((min2X>=10) && (Min2<=99)) {min2X=75; myGLCD.print("0", 59, 152);}
        if ((Min2<=9) && (Min2>0)) {min2X=91; myGLCD.print("00", 59, 152);}
        if (Min2<=0) {Min2=0; myGLCD.print("0", 91, 152);}
        setFont(LARGE, 255, 255, 255, 0, 0, 0);
        myGLCD.printNumI(Min2, min2X, 152);
       }
     if ((x>=120) && (x<=145))                      //Pump 2 Minute Plus
       {
        waitForIt(120, 147, 145, 172);
        Min2 += 1;
        if ((Min2>=0) && (Min2<=9)) {min2X=91;}
        if (Min2>9) {min2X=75;}
        if (Min2>99) {min2X=59;}
        if (Min2>=999) {Min2=999;}             
        setFont(LARGE, 255, 255, 255, 0, 0, 0);
        myGLCD.printNumI(Min2, min2X, 152);
       }
     if ((x>=175) && (x<=200))                      //Pump 2 Second Minus
       {
        waitForIt(175, 147, 200, 172);
        Sec2 -= 1;
        if ((sec2X>=10) && (Sec2<=59)) {sec2X=221;}
        if ((Sec2<=9) && (Sec2>0)) {sec2X=237; myGLCD.print("0", 221, 152);}
        if (Sec2<=0) {Sec2=0; myGLCD.print("0", 237, 152);}
        setFont(LARGE, 255, 255, 255, 0, 0, 0);
        myGLCD.printNumI(Sec2, sec2X, 152);
       } 
     if ((x>=274) && (x<=299))                      //Pump 2 Second Plus
       {
        waitForIt(274, 147, 299, 172);
        Sec2 += 1;
        if ((Sec2>=0) && (Sec2<=9)) {sec2X=237;}
        if (Sec2>9) {sec2X=221;}
        if (Sec2>=59) {Sec2=59;}             
        setFont(LARGE, 255, 255, 255, 0, 0, 0);
        myGLCD.printNumI(Sec2, sec2X, 152);
       }  
    }
}
*/
/************************** END OF WAVEMAKER SETTINGS SCREEN **************************/  


/******** AUTOMATIC FEEDER SCREEN ************* dispScreen = 12 ***********************/
/*
void autoFeederScreen()
{
//  printHeader("Automatic Fish Feeder Page");  
    PrintStringIndex=25; 
    printHeader ();
  
  myGLCD.setColor(64, 64, 64);
  myGLCD.drawRect(0, 196, 319, 194);
  printButton("<< BACK", back[0], back[1], back[2], back[3], SMALL);
  printButton("CANCEL", canC[0], canC[1], canC[2], canC[3], SMALL);     
  myGLCD.setColor(64, 64, 64);
  myGLCD.drawRect(159, 194, 161, 121);
  myGLCD.drawRoundRect(78, 87, 242, 121);    
  myGLCD.drawRoundRect(80, 89, 240, 119);  
  myGLCD.drawRect(0, 103, 78, 105);
  myGLCD.drawRect(242, 103, 319, 105); 
  myGLCD.drawLine(159, 87, 159, 14);  
  myGLCD.drawLine(161, 87, 161, 14);  
  myGLCD.setColor(0, 0, 0);
  myGLCD.drawLine(160, 195, 160, 193);
  myGLCD.drawLine(160, 122, 160, 120);
  myGLCD.drawLine(77, 104, 79, 104);
  myGLCD.drawLine(241, 104, 243, 104);  
  myGLCD.drawLine(160, 88, 160, 86);

  myGLCD.setColor(153, 0, 102);
  myGLCD.fillRoundRect(85, 94, 235, 114);           //Feed Fish Now Button
  myGLCD.setColor(255, 255, 255);
  myGLCD.drawRoundRect(85, 94, 235, 114); 
  setFont(SMALL, 255, 255, 255, 153, 0, 102);
//myGLCD.print("Feed Fish Now!", 106, 98);
  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[33]))); 
  myGLCD.print(buffer, 106, 98);

  if (FEEDTime1==0)                                 //Feeding Time 1 Button 
    { myGLCD.setColor(255, 0, 0);
      myGLCD.fillRoundRect(5, 20, 155, 40);
      setFont(SMALL, 255, 255, 255, 255, 0, 0);
//    myGLCD.print("Feeding Time 1", 24, 24);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[25]))); 
      myGLCD.print(buffer, 24, 24);
      setFont(SMALL, 255, 0, 0, 0, 0, 0);     
//    myGLCD.print("This time has not", 12, 52);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[31]))); 
      myGLCD.print(buffer, 12, 52);
//    myGLCD.print("been scheduled", 24, 65);}      
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[32]))); 
	  myGLCD.print(buffer, 24, 65);}
  else
    { myGLCD.setColor(0, 255, 0);
      myGLCD.fillRoundRect(5, 20, 155, 40);
      setFont(SMALL, 0, 0, 0, 0, 255, 0);
//    myGLCD.print("Feeding Time 1", 24, 24); 
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[25]))); 
      myGLCD.print(buffer, 24, 24);
      timeDispH=feedFish1H; timeDispM=feedFish1M; 
      if (setTimeFormat==0) { xTimeH=40;}
      if (setTimeFormat==1) { xTimeH=16;}
//      ReadFromEEPROM();
      if ((timeDispH>=0) && (timeDispH<=11)) { AM_PM=1;}
      else { AM_PM=2;}          
      yTime=56; xColon=xTimeH+32;
      xTimeM10=xTimeH+48; xTimeM1=xTimeH+64; xTimeAMPM=xTimeH+96;
      timeCorrectFormat();}
  if (FEEDTime2==0)                                 //Feeding Time 2 Button
    { myGLCD.setColor(255, 0, 0);
      myGLCD.fillRoundRect(165, 20, 315, 40);
      setFont(SMALL, 255, 255, 255, 255, 0, 0);
//    myGLCD.print("Feeding Time 2", 184, 24);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[26]))); 
      myGLCD.print(buffer, 184, 24);
      setFont(SMALL, 255, 0, 0, 0, 0, 0);     
//    myGLCD.print("This time has not", 172, 52);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[31]))); 
      myGLCD.print(buffer, 172, 52);
//    myGLCD.print("been scheduled", 184, 65);}
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[32]))); 
	  myGLCD.print(buffer, 184, 65);}

  else
    { myGLCD.setColor(0, 255, 0);
      myGLCD.fillRoundRect(165, 20, 315, 40);
      setFont(SMALL, 0, 0, 0, 0, 255, 0);
//    myGLCD.print("Feeding Time 2", 184, 24);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[26]))); 
      myGLCD.print(buffer, 184, 24);

      timeDispH=feedFish2H; timeDispM=feedFish2M; 
      if (setTimeFormat==0) { xTimeH=200;}
      if (setTimeFormat==1) { xTimeH=176;}      
//      ReadFromEEPROM();
      if ((timeDispH>=0) && (timeDispH<=11)) { AM_PM=1;}
      else { AM_PM=2;}          
      yTime=56; xColon=xTimeH+32;
      xTimeM10=xTimeH+48; xTimeM1=xTimeH+64; xTimeAMPM=xTimeH+96;      
      timeCorrectFormat();}          
  if (FEEDTime3==0)                                 //Feeding Time 3 Button
    { myGLCD.setColor(255, 0, 0);
      myGLCD.fillRoundRect(5, 168, 155, 188);
      setFont(SMALL, 255, 255, 255, 255, 0, 0);
//      myGLCD.print("Feeding Time 3", 24, 172);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[27]))); 
      myGLCD.print(buffer, 24, 172);
      setFont(SMALL, 255, 0, 0, 0, 0, 0);     
//      myGLCD.print("This time has not", 12, 133);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[31]))); 
      myGLCD.print(buffer, 12, 133);
//      myGLCD.print("been scheduled", 24, 146);}       
  	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[32]))); 
	  myGLCD.print(buffer, 24, 146);}
  else
    { myGLCD.setColor(0, 255, 0);
      myGLCD.fillRoundRect(5, 168, 155, 188);
      setFont(SMALL, 0, 0, 0, 0, 255, 0);
//    myGLCD.print("Feeding Time 3", 24, 172);
  	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[27]))); 
      myGLCD.print(buffer, 24, 172);

      timeDispH=feedFish3H; timeDispM=feedFish3M; 
      if (setTimeFormat==0) { xTimeH=40;}
      if (setTimeFormat==1) { xTimeH=16;}
 //     ReadFromEEPROM();
      if ((timeDispH>=0) && (timeDispH<=11)) { AM_PM=1;}
      else { AM_PM=2;}          
      yTime=137; xColon=xTimeH+32;
      xTimeM10=xTimeH+48; xTimeM1=xTimeH+64; xTimeAMPM=xTimeH+96;      
      timeCorrectFormat();}          
  if (FEEDTime4==0)                                 //Feeding Time 4 Button
    { myGLCD.setColor(255, 0, 0);
      myGLCD.fillRoundRect(165, 168, 315, 188);
      setFont(SMALL, 255, 255, 255, 255, 0, 0);
//      myGLCD.print("Feeding Time 4", 184, 172);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[28]))); 
      myGLCD.print(buffer, 184, 172);
      setFont(SMALL, 255, 0, 0, 0, 0, 0);     
//    myGLCD.print("This time has not", 172, 133);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[31]))); 
      myGLCD.print(buffer, 172, 133);
//      myGLCD.print("been scheduled", 184, 146);}
  	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[32]))); 
	  myGLCD.print(buffer, 184, 146);}
  else
    { myGLCD.setColor(0, 255, 0);
      myGLCD.fillRoundRect(165, 168, 315, 188);
      setFont(SMALL, 0, 0, 0, 0, 255, 0);
//    myGLCD.print("Feeding Time 4", 184, 172);
	  strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[28]))); 
      myGLCD.print(buffer, 184, 172);
      timeDispH=feedFish4H; timeDispM=feedFish4M;
      if (setTimeFormat==0) { xTimeH=200;}
      if (setTimeFormat==1) { xTimeH=176;}      
 //     ReadFromEEPROM();
      if ((timeDispH>=0) && (timeDispH<=11)) { AM_PM=1;}
      else { AM_PM=2;}          
      yTime=137; xColon=xTimeH+32;
      xTimeM10=xTimeH+48; xTimeM1=xTimeH+64; xTimeAMPM=xTimeH+96;      
      timeCorrectFormat();}      

  myGLCD.setColor(255, 255, 255);
  for (int x=0; x<2; x++)
    { for (int y=0; y<2; y++)
        { myGLCD.drawRoundRect((x*160)+5, (y*148)+20, (x*160)+155, (y*148)+40); }
    }    
}


void feedingTimeOutput()
{
  if ((FEEDTime1==1) && (feedFish1H==t.hour) && (feedFish1M==t.min) 
     && (t.sec>=0 || t.sec<5))
    { if (setAutoStop==1)
        { waveMakerOff=true;
          digitalWrite(WaveMakerTop, LOW);
          digitalWrite(WaveMakerBottom, LOW);
          fiveTillBackOn1=0;
          FeedWaveCtrl_1=true;}
      digitalWrite(autoFeeder, HIGH);
      delay(6000);
      t=rtc.getTime();
      digitalWrite(autoFeeder, LOW); 
    }
 if (FeedWaveCtrl_1==true)
    { fiveTillBackOn1++;
      if (fiveTillBackOn1>60)                       //60 is 5 minutes (60/12=5) 
        { waveMakerOff=false; FeedWaveCtrl_1=false;}
    }

  if ((FEEDTime2==1) && (feedFish2H==t.hour) && (feedFish2M==t.min)
     && (t.sec>=0 || t.sec<5))  
    { if (setAutoStop==1)
        { waveMakerOff=true;
          digitalWrite(WaveMakerTop, LOW);
          digitalWrite(WaveMakerBottom, LOW);
          fiveTillBackOn2=0;
          FeedWaveCtrl_2=true;}
      digitalWrite(autoFeeder, HIGH);
      delay(6000);
      t=rtc.getTime();
      digitalWrite(autoFeeder, LOW); 
    }
 if (FeedWaveCtrl_2==true)
    { fiveTillBackOn2++;
      if (fiveTillBackOn2>60) 
        { waveMakerOff=false; FeedWaveCtrl_2=false;}
    }
    
  if ((FEEDTime3==1) && (feedFish3H==t.hour) && (feedFish3M==t.min)
     && (t.sec>=0 || t.sec<5))
    { if (setAutoStop==1)
        { waveMakerOff=true;
          digitalWrite(WaveMakerTop, LOW);
          digitalWrite(WaveMakerBottom, LOW);
          fiveTillBackOn3=0;
          FeedWaveCtrl_3=true;}
      digitalWrite(autoFeeder, HIGH);
      delay(6000);
      t=rtc.getTime();
      digitalWrite(autoFeeder, LOW); 
    }
 if (FeedWaveCtrl_3==true)
    { fiveTillBackOn3++;
      if (fiveTillBackOn3>60) 
        { waveMakerOff=false; FeedWaveCtrl_3=false;}
    }    

  if ((FEEDTime4==1) && (feedFish4H==t.hour) && (feedFish4M==t.min)
     && (t.sec>=0 || t.sec<5))
    { if (setAutoStop==1)
        { waveMakerOff=true;
          digitalWrite(WaveMakerTop, LOW);
          digitalWrite(WaveMakerBottom, LOW);
          fiveTillBackOn4=0;
          FeedWaveCtrl_4=true;}
      digitalWrite(autoFeeder, HIGH);
      delay(6000);
      t=rtc.getTime();
      digitalWrite(autoFeeder, LOW); 
    }
 if (FeedWaveCtrl_4==true)
    { fiveTillBackOn4++;
      if (fiveTillBackOn4>60) 
        { waveMakerOff=false; FeedWaveCtrl_4=false;}
    }    
}
*/
/*********************** END OF AUTOMATIC FEEDER SETTINGS SCREEN **********************/  


/***** SET AUTOMATIC FEEDER TIMES SCREEN ********** dispScreen = 13 *******************/
/*
void setFeederTimesScreen(boolean refreshAll=true) 
{
  if (feedTime==1)
    { //printHeader("Set Feeding Time 1"); }
      PrintStringIndex=26; 
	  printHeader ();}
  if (feedTime==2)
    { //printHeader("Set Feeding Time 2");}
      PrintStringIndex=27; 
	  printHeader ();}
  if (feedTime==3)
    { //printHeader("Set Feeding Time 3");}
      PrintStringIndex=28; 
	  printHeader ();}
  if (feedTime==4)
    { //printHeader("Set Feeding Time 4");}
      PrintStringIndex=29; 
	  printHeader ();}

  if (refreshAll)
  { 
   rtcSetMin=t.min; rtcSetHr=t.hour; 
  
   myGLCD.setColor(64, 64, 64);
   myGLCD.drawRect(0, 196, 319, 194);
   printButton("<< BACK", back[0], back[1], back[2], back[3], SMALL);
   printButton("SAVE", prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3], SMALL);
   printButton("CANCEL", canC[0], canC[1], canC[2], canC[3], SMALL);   

   feedingTimeOnOff();

   drawUpButton(houP[0], houP[1]);                //hour up
   drawUpButton(minP[0], minP[1]);                //min up
   drawDownButton(houM[0], houM[1]);              //hour down
   drawDownButton(minM[0], minM[1]);              //min down
   if (setTimeFormat==1)
     { drawUpButton(ampmP[0], ampmP[1]);          //AM/PM up   
       drawDownButton(ampmM[0], ampmM[1]);}       //AM/PM down  
  }    
  
  timeDispH=rtcSetHr; timeDispM=rtcSetMin;
  xTimeH=107; yTime=68;  xColon=xTimeH+42;
  xTimeM10=xTimeH+70; xTimeM1=xTimeH+86; xTimeAMPM=xTimeH+155;
  timeChange();
}
*/
/********************** END OF SET AUTOMATIC FEEDER TIMES SCREEN **********************/


/******* GENERAL SETTINGS PG1 SCREEN ************ dispScreen = 14 *********************/
void generalSettingsScreen_1()
{
//  printHeader("View/Change General Settings: Page 1");  
  PrintStringIndex=30; 
  printHeader ();

  myGLCD.setColor(64, 64, 64);
  myGLCD.drawRect(0, 196, 319, 194);
  for (byte y=0; y<5; y++)
     { myGLCD.drawLine(0, (y*30)+44, 319, (y*30)+44); }

  printButton("<< BACK", backGS[0], backGS[1], backGS[2], backGS[3], SMALL);
  printButton("NEXT >>", nextGS[0], nextGS[1], nextGS[2], nextGS[3], SMALL);
  printButton("SAVE", prSAVEgs[0], prSAVEgs[1], prSAVEgs[2], prSAVEgs[3], SMALL);
  printButton("CANCEL", canCgs[0], canCgs[1], canCgs[2], canCgs[3], SMALL); 
    
  setFont(SMALL, 0, 255, 0, 0, 0, 0);
  myGLCD.print("Set Time and Date", 25, 23);  
  myGLCD.print("Calendar Format", 25, 53);  
  myGLCD.print("Show Day of Week", 25, 83);    
  myGLCD.print("Time Format", 25, 113);  
  myGLCD.print("Temperature Scale", 25, 143);    
  myGLCD.print("Fan Startup Temps", 25, 173);    

  genSetSelect_1();
}
/************************ END OF GENERAL SETTINGS PAGE 1 SCREEN ***********************/ 


/******* GENERAL SETTINGS PG2 SCREEN ************ dispScreen = 15 *********************/
void generalSettingsScreen_2()
{
//  printHeader("View/Change General Settings: Page 2");  
	PrintStringIndex=31; 
    printHeader ();

    myGLCD.setColor(64, 64, 64);
    myGLCD.drawRect(0, 196, 319, 194);
    for (byte y=0; y<5; y++)
        { myGLCD.drawLine(0, (y*30)+44, 319, (y*30)+44); }

//  printButton("<< BACK", backGS[0], backGS[1], backGS[2], backGS[3], SMALL);
//  printButton("NEXT >>", nextGS[0], nextGS[1], nextGS[2], nextGS[3], SMALL);
//  printButton("SAVE", prSAVEgs[0], prSAVEgs[1], prSAVEgs[2], prSAVEgs[3], SMALL);
//  printButton("CANCEL", canCgs[0], canCgs[1], canCgs[2], canCgs[3], SMALL); 
 
	printButton(print_text[0], backGS[0], backGS[1], backGS[2], backGS[3], SMALL);
	printButton(print_text[1], nextGS[0], nextGS[1], nextGS[2], nextGS[3], SMALL);
	printButton(print_text[2], prSAVEgs[0], prSAVEgs[1], prSAVEgs[2], prSAVEgs[3], SMALL);
	printButton(print_text[3], canCgs[0], canCgs[1], canCgs[2], canCgs[3], SMALL);
  
	setFont(SMALL, 0, 255, 0, 0, 0, 0);
    myGLCD.print(print_text[4], 15, 23);  
    myGLCD.print(print_text[5], 15, 53);    
    myGLCD.print(print_text[6], 15, 83);    
    myGLCD.print(print_text[7], 15, 113);
	myGLCD.print(print_text[12], 15, 143);

  genSetSelect_2();
}
/************************ END OF GENERAL SETTINGS PAGE 2 SCREEN ***********************/ 

/******* GENERAL SETTINGS PG3 SCREEN ************ dispScreen = 20 *********************/
void generalSettingsScreen_3()
{
//  printHeader("View/Change General Settings: Page 3");  
	PrintStringIndex=36; 
    printHeader ();

	setFont(SMALL, 0, 255, 0, 0, 0, 0);
//  myGLCD.print("Detect Dallas Sensors", 25, 24);
	strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[6]))); 
    myGLCD.print(buffer, 24, 23); 
//	myGLCD.print("Backup setting to SD Card", 5, 58);
	strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[7]))); 
    myGLCD.print(buffer, 5, 53); 
//	myGLCD.print("Reset setting to DEFAULT", 5, 92);
	strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[8]))); 
    myGLCD.print(buffer, 5, 83); 

	myGLCD.setColor(64, 64, 64);
    myGLCD.drawRect(0, 196, 319, 194);
    for (byte y=0; y<3; y++)
        { myGLCD.drawLine(0, (y*30)+44, 319, (y*30)+44); }


	myGLCD.setColor(0, 0, 255);                    
    myGLCD.fillRoundRect(205, 19, 305, 39);       // detect
	myGLCD.fillRoundRect(205, 49, 305, 69);       // backup
	myGLCD.fillRoundRect(205, 79, 305, 99);       // reset

	myGLCD.setColor(255, 255, 255);                    
    myGLCD.drawRoundRect(205, 19, 305, 39);       // detect
	myGLCD.drawRoundRect(205, 49, 305, 69);       // backup
	myGLCD.drawRoundRect(205, 79, 305, 99);      // reset

	setFont(SMALL, 255, 255, 255, 0, 0, 255);  
    myGLCD.print("DETECT", 231, 23);
	myGLCD.print("BACKUP", 231, 53);
	myGLCD.print("RESET", 235, 83);

	bitClear(GlobalStatus1Byte,0);               // reset bit for Y/N button

	printButton("<< BACK", backGS[0], backGS[1], backGS[2], backGS[3], SMALL);
	printButton("CANCEL", canCgs[0], canCgs[1], canCgs[2], canCgs[3], SMALL); 
}

/******** CHANGE FAN TEMPS SCREEN ************* dispScreen = 16 ***********************/
void ChangeFanTempsScreen(boolean refreshAll=false)
{
  String deg;
  if (refreshAll)
    {
     if ((setTempToBeginHeatsink1FanC==0) && (setTempScale==0)) 
       { setTempToBeginHeatsink1FanC = 29.0;}                         //change to 29 deg C
     if ((setTempToBeginHeatsink2FanC==0) && (setTempScale==0)) 
       { setTempToBeginHeatsink2FanC = 29.0;}                         //change to 29 deg C
     if (((setTempToBeginHeatsink1FanF==0) || (setTempToBeginHeatsink1FanF==setTempToBeginHeatsink1FanC)) 
        && (setTempScale==1)) 
       { setTempToBeginHeatsink1FanF = 84.2;}                         //change to 84 deg F
     if (((setTempToBeginHeatsink2FanF==0) || (setTempToBeginHeatsink2FanF==setTempToBeginHeatsink2FanC)) 
        && (setTempScale==1)) 
       { setTempToBeginHeatsink2FanF = 84.2;}                         //change to 84 deg F    

     if (setTempScale==1)
       { temp2beHFan=setTempToBeginHeatsink1FanF;
         temp2beSFan=setTempToBeginHeatsink2FanF; }
     else
       { temp2beHFan=setTempToBeginHeatsink1FanC;
         temp2beSFan=setTempToBeginHeatsink2FanC;} 
         
//   printHeader("View/Change Fans Startup Temperatures");    
     PrintStringIndex=32; 
     printHeader (); 
     myGLCD.setColor(64, 64, 64);
	 myGLCD.drawRect(0, 73, 319, 75);   
	 myGLCD.drawRect(0, 73+60, 319, 75+60);   

     setFont(SMALL, 0, 255, 0, 0, 0, 0);
//   myGLCD.print("Heatsink N1 FAN", CENTER, 20);  
	 strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[13]))); 
     myGLCD.print(buffer, CENTER, 20);
//   myGLCD.print("Heatsink N2 FAN", CENTER, 111);
     strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[14]))); 
     myGLCD.print(buffer, CENTER, 81);
     strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[17]))); // sound alarm temp
     myGLCD.print(buffer, CENTER, 140);

     if (setTempScale==1)
       {   strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[16]))); 
           myGLCD.print(buffer, 231, 46);
		   myGLCD.print(buffer, 231, 105);
//         myGLCD.print("(68.0--120.0)", CENTER, 177);
		   strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[19]))); 
		   myGLCD.print(buffer, 231, 164);
	    }
     else 
       {   strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[15]))); 
           myGLCD.print(buffer, 235, 46);
		   myGLCD.print(buffer, 235, 105);
//         myGLCD.print("(20.0--50.0)", CENTER, 177);
		   strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[18]))); 
		   myGLCD.print(buffer, 235, 164);
	   }

     printButton("-", HoodFanTm[0], HoodFanTm[1], HoodFanTm[2], HoodFanTm[3], LARGE);
     printButton("+", HoodFanTp[0], HoodFanTp[1], HoodFanTp[2], HoodFanTp[3], LARGE);      
     printButton("-", SumpFanTm[0], SumpFanTm[1], SumpFanTm[2], SumpFanTm[3], LARGE);
     printButton("+", SumpFanTp[0], SumpFanTp[1], SumpFanTp[2], SumpFanTp[3], LARGE);
	 printButton("-", SoundAlarmTm[0], SoundAlarmTm[1], SoundAlarmTm[2], SoundAlarmTm[3], LARGE);
     printButton("+", SoundAlarmTp[0], SoundAlarmTp[1], SoundAlarmTp[2], SoundAlarmTp[3], LARGE);
	  
     myGLCD.setColor(64, 64, 64);
     myGLCD.drawRect(0, 196, 319, 194);  
     printButton("<< BACK", back[0], back[1], back[2], back[3], SMALL);
     printButton("SAVE", prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3], SMALL);
     printButton("CANCEL", canC[0], canC[1], canC[2], canC[3], SMALL);
    }
    
   setFont(LARGE, 255, 255, 255, 0, 0, 0);
   myGLCD.printNumF(temp2beHFan, 1, 112, 45); 
   if (setTempScale==1 && temp2beHFan <100 ) {myGLCD.print(" ",176, 45);}  // Fan 1
   myGLCD.printNumF(temp2beSFan, 1, 112, 103);
   if (setTempScale==1 && temp2beSFan <100 ) {myGLCD.print(" ",176, 103);} // Fan 2 
   if (setTempScale==0) {myGLCD.printNumF(setTempToSoundAlarmC, 1, 112, 162);}  // display sound alarm temp
   if (setTempScale==1) { myGLCD.printNumF(setTempToSoundAlarmF, 1, 112, 162);}
//	     }
}
/*************************** END OF CHANGE FAN TEMPS SCREEN ***************************/ 


/******** DIM LEDs AT TEMP SCREEN ************* dispScreen = 17 ***********************/
void DimLEDsAtTempScreen()
{
//  printHeader("View/Change LEDs' Dimming Temperature");    
  PrintStringIndex=33; 
  printHeader ();
  
  setFont(SMALL, 0, 255, 0, 0, 0, 0);
  myGLCD.print("If temp reaches:", 39, 59);
  if (setTempScale==1) {myGLCD.print("F", 278, 59);}                //Print deg C or deg F
      else {myGLCD.print("C", 278, 59);}
/*      
  String deg;
  if (setTempScale==1) {deg ="F";}                //Print deg C or deg F
    else {deg = "C";}
  degC_F=deg;
  char bufferDeg[3];
  degC_F.toCharArray(bufferDeg,3);  
*/
  myGLCD.drawCircle(273, 61, 1);              
//  myGLCD.print(bufferDeg, 278, 59);  

  myGLCD.print("Dim the LEDs to:", 39, 140);  
  myGLCD.print("%.", 273, 140);  
  
  myGLCD.setColor(64, 64, 64);  
  myGLCD.drawRoundRect(175, 31, 265, 96);
  drawUpButton(235, 36);  
  drawDownButton(235, 66);
  myGLCD.setColor(64, 64, 64);    
  myGLCD.drawRoundRect(175, 112, 265, 177);
  drawUpButton(235, 117);  
  drawDownButton(235, 147);

  if (setTempScale==1)  
    { TempLEDsDimTemp=setLEDsDimTempF;}
  else {TempLEDsDimTemp=setLEDsDimTempC;}
		TempLEDsDimPercent=setLEDsDimPercent;  
		setFont(LARGE, 0, 255, 0, 0, 0, 0);
 		myGLCD.printNumI(TempLEDsDimTemp, 181, 55);

		myGLCD.printNumI(TempLEDsDimPercent, 181, 136);
  
  myGLCD.setColor(64, 64, 64);
  myGLCD.drawRect(0, 196, 319, 194);  
  printButton("<< BACK", back[0], back[1], back[2], back[3], SMALL);
  printButton("SAVE", prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3], SMALL);
  printButton("CANCEL", canC[0], canC[1], canC[2], canC[3], SMALL);  
}
/*************************** END OF DIM LEDs AT TEMP SCREEN ***************************/ 


/***** SET SCREENSAVER WAIT TIME SCREEN ********** dispScreen = 18 ********************/
void ScreensaverSettingsScreen()
{
//  printHeader("View/Change Screensaver Settings"); 
  PrintStringIndex=34; 
  printHeader ();

  myGLCD.setColor(64, 64, 64);
  myGLCD.drawLine(0, 45, 319, 45);   
  myGLCD.drawLine(0, 76, 319, 76);   
  myGLCD.drawLine(0, 107, 319, 107);   
  myGLCD.drawRoundRect(115, 102+10, 205, 167+10);
  myGLCD.drawRect(0, 196, 319, 194);  

  setFont(SMALL, 0, 255, 0, 0, 0, 0);

  myGLCD.print(print_text[13], 10, 24);
  myGLCD.print(print_text[14], 10, 55);
  myGLCD.print(print_text[17], 10, 86);
  myGLCD.print(print_text[15], 67, 130+10);
  myGLCD.print(print_text[16], 213, 130+10);
//  myGLCD.print("Choose ScreenSaver type", 10, 24);
//  myGLCD.print("Screen Lock ON/OFF", 10, 55);    
//  myGLCD.print("Wait:", 67, 130);  
//  myGLCD.print("minutes", 213, 130);
  drawUpButton(175, 107+10);  
  drawDownButton(175, 137+10);
  
  if (setLockScreen==1)                             // ON/OFF Screensaver lock function
    {printButton(" ON ", 206, 51, 260, 71, SMALL); }
    else 
		{ printButton(" OFF", 206, 51, 260, 71, SMALL); }  
    
  setFont(LARGE, 0, 255, 0, 0, 0, 0);
  TempSSminutes=setSSmintues;
  if (TempSSminutes>=10)	
    { myGLCD.printNumI(TempSSminutes, 129, 126+10);}			// prins screen saver time
  else { myGLCD.printNumI(TempSSminutes, 137, 126+10);}
  
  printButton("<< BACK", back[0], back[1], back[2], back[3], SMALL);
  printButton("SAVE", prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3], SMALL);
  printButton("CANCEL", canC[0], canC[1], canC[2], canC[3], SMALL); 
 
  ScreensaverSelect();
}
/********************** END OF SET SCREENSAVER WAIT TIME SCREEN ***********************/ 

int PlusMinusCount ( boolean refreshAll, int XShift, int YShift, int Min, int Max, int Step, int PlsMnsCount=0 ) // increase/decrease all values counter
{
/*
int XShift - X fist left "-" button coordinate
int YShift   Y fist left "-" button coordinate
byte ButDist - distence between "-" and "+" buttons
int Min - minimum value of counter
int Max - maximum counter
int Step - step
int PlsMnsCount - input/output value
*/
   byte ButDist = 90; // distanse beetween  +/- buttons
   if (refreshAll == true){
   myGLCD.setColor(255, 255, 255);
   myGLCD.drawRoundRect (ButMns[0]+XShift-2, ButMns[1]+YShift-2, ButMns[2]+XShift+ButDist+2, ButMns[3]+YShift+2); 

   printButton("-", (ButMns[0]+XShift), (ButMns[1]+YShift), (ButMns[2]+XShift), (ButMns[3]+YShift), SMALL);
   printButton("+", (ButMns[0]+XShift+ButDist), (ButMns[1]+YShift), (ButMns[2]+XShift+ButDist), (ButMns[3]+YShift), SMALL);
   }

      if (x>=(ButMns[0]+XShift) && x<=(ButMns[2]+XShift) && y>=(ButMns[1]+YShift) && y<=(ButMns[3]+YShift))  //press "-"
   { waitForIt_Wo_Touch(ButMns[0]+XShift, ButMns[1]+YShift, ButMns[2]+XShift, ButMns[3]+YShift);
	  PlsMnsCount -= Step; 
	  if (PlsMnsCount > Max) {PlsMnsCount = Min;}
	  if (PlsMnsCount < Min) {PlsMnsCount = Max;}
	  }

      if (x>=(ButMns[0]+XShift+ButDist) && x<=(ButMns[2]+XShift+ButDist) && y>=(ButMns[1]+YShift) && y<=(ButMns[3]+YShift))  //press "+"
   { waitForIt_Wo_Touch(ButMns[0]+XShift+ButDist, ButMns[1]+YShift, ButMns[2]+XShift+ButDist, ButMns[3]+YShift);
	  PlsMnsCount += Step; 
	  if (PlsMnsCount > Max) {PlsMnsCount = Min;}
	  if (PlsMnsCount < Min) {PlsMnsCount = Max;}
	  }

      setFont(LARGE, 255, 255, 255, 0, 0, 0);
	  myGLCD.print("   ", (((ButMns[2]+XShift)+(ButMns[0]+XShift+ButDist))/2-24),ButMns[1]+YShift+3);
	  if (PlsMnsCount >=0 && PlsMnsCount <10 ) {myGLCD.printNumI(PlsMnsCount,(((ButMns[2]+XShift)+(ButMns[0]+XShift+ButDist))/2-8),ButMns[1]+YShift+3);}
      if (PlsMnsCount >=10 && PlsMnsCount <100) {myGLCD.printNumI(PlsMnsCount, (((ButMns[2]+XShift)+(ButMns[0]+XShift+ButDist))/2-16),ButMns[1]+YShift+3);} 
      if (PlsMnsCount >=100) {myGLCD.printNumI(PlsMnsCount, (((ButMns[2]+XShift)+(ButMns[0]+XShift+ButDist))/2-24),ButMns[1]+YShift+3);}
	  return PlsMnsCount;

   }

//************************ Weather Function start *********************
void wthScreen (boolean refreshAll=false) {			// control weather main csreen

if (refreshAll){
   PrintStringIndex=37; // config clouds.... header 
   printHeader ();

   myGLCD.setColor(64, 64, 64);
    myGLCD.drawRect(0, 196, 319, 194);
    for (byte y=0; y<3; y++)
        { myGLCD.drawLine(0, (y*30)+44, 319, (y*30)+44); }

	printButton(print_text[0], backGS[0], backGS[1], backGS[2], backGS[3], SMALL); // "Back"
	printButton(print_text[3], canCgs[0], canCgs[1], canCgs[2], canCgs[3], SMALL); // "Cancel"
  
	setFont(SMALL, 0, 255, 0, 0, 0, 0);
    myGLCD.print(print_text[18], 15, 23);  // Clouds
    myGLCD.print(print_text[19], 15, 53);  // ThuderStorm  
    myGLCD.print(print_text[20], 15, 83);  // Test Weather  

}

if (clouDonOff == 0) 
		   { printButton(print_text[23], CloudCtrlON[0], CloudCtrlON[1], CloudCtrlON[2], CloudCtrlON[3], SMALL);     //"OFF"  
			 printButton(print_text[21], CloudCtrl[0], CloudCtrl[1], CloudCtrl[2], CloudCtrl[3], SMALL, GREY_BAC);   //"Setting"
			 printButton(print_text[23], StormCtrlON[0], StormCtrlON[1], StormCtrlON[2], StormCtrlON[3], SMALL, GREY_BAC);  //"OFF"  
			 printButton(print_text[21], StormCtrl[0], StormCtrl[1], StormCtrl[2], StormCtrl[3], SMALL, GREY_BAC);   //"Setting"
 		   }
		 else {
		     printButton(print_text[22], CloudCtrlON[0], CloudCtrlON[1], CloudCtrlON[2], CloudCtrlON[3], SMALL);  //"ON" 
		     printButton(print_text[21], CloudCtrl[0], CloudCtrl[1], CloudCtrl[2], CloudCtrl[3], SMALL);          //"Setting" (BLUE_BAC)
		      }

if  (storMonOff==0 & clouDonOff == 1)
			   {
             printButton(print_text[23], StormCtrlON[0], StormCtrlON[1], StormCtrlON[2], StormCtrlON[3], SMALL);    //"OFF"  
			 printButton(print_text[21], StormCtrl[0], StormCtrl[1], StormCtrl[2], StormCtrl[3], SMALL, GREY_BAC);  //"Setting"
		   }
if  (storMonOff==1 & clouDonOff == 1)		  
		 {
		     printButton(print_text[22], StormCtrlON[0], StormCtrlON[1], StormCtrlON[2], StormCtrlON[3], SMALL);  //"ON" 
		     printButton(print_text[21], StormCtrl[0], StormCtrl[1], StormCtrl[2], StormCtrl[3], SMALL);          //"Setting" (BLUE_BAC)
		      }
       

if (bitRead(GlobalStatus3Byte,0) == 1){
	printButton(print_text[39], StormCtrl[0], StormCtrl[1]+30, StormCtrl[2], StormCtrl[3]+30, SMALL, GREEN_BAC);}  //"Start" (BLUE_BAC)
else { printButton(print_text[40], StormCtrl[0], StormCtrl[1]+30, StormCtrl[2], StormCtrl[3]+30, SMALL);}   //"Stop" (BLUE_BAC)

}

//******************** Cloud setting **************************** dispScreen = 26 */
void clouDScreen(boolean refreshAll=false) {
	if (refreshAll){
	PrintStringIndex=38; 
    printHeader ();
  
    myGLCD.setColor(64, 64, 64);                    //Draw Dividers in Grey
	myGLCD.drawRect(0, 80, 319, 74);
	myGLCD.drawRect(0, 114, 319, 114); 
	myGLCD.drawRect(0, 154, 319, 154);
	myGLCD.drawRect(0, 194, 319, 194);
    myGLCD.drawRect(0, 196, 319, 196);

	setFont(SMALL, 0, 255, 0, 0, 0, 0);
	myGLCD.print(print_text[24], 8, 20);
	myGLCD.print(print_text[25], 8, 32);
	myGLCD.print(print_text[26], 8, 44);

	myGLCD.print(print_text[27], 8, 83); //cloud/day
	myGLCD.print(print_text[28], 8, 98);
	
	myGLCD.print(print_text[29], 8, 116); //duration
	myGLCD.print(print_text[30], 8, 128);
	myGLCD.print(print_text[31], 8, 141);

	myGLCD.print(print_text[32], 8, 160); // quantity day in week
	myGLCD.print(print_text[33], 8, 173);

// ----------------------- display values --------------------- 
	PlusMinusCount (true, 200, 88, 1, 5, 1, CloudDayQantity);    // quant Cloud/day
	PlusMinusCount (true, 200, 124, 15, 90, 1, CloudDuration);   //duration one cloud period
	PlusMinusCount (true, 200, 163, 1, 7, 1, CloudWeekQantity);  // week cloudy day

	
    printButton(print_text[0], backGS[0], backGS[1], backGS[2], backGS[3], SMALL); // "Back"
    printButton(print_text[3], canCgs[0], canCgs[1], canCgs[2], canCgs[3], SMALL); // "Cancel"
    printButton(print_text[2], prSAVEgs[0], prSAVEgs[1], prSAVEgs[2], prSAVEgs[3], SMALL); // Save
	}
}

//******************** Storm setting **************************** dispScreen = 27 */
void storMScreen(boolean refreshAll=false) {
	if (refreshAll){
	PrintStringIndex=39; 
	printHeader ();

    myGLCD.setColor(64, 64, 64);                    //Draw Dividers in Grey
	myGLCD.drawRect(0, 80, 319, 74);
	myGLCD.drawRect(0, 114, 319, 114); 
	myGLCD.drawRect(0, 154, 319, 154);
	myGLCD.drawRect(0, 194, 319, 194);
	myGLCD.drawRect(0, 196, 319, 196);
 
	setFont(SMALL, 0, 255, 0, 0, 0, 0);
	myGLCD.print(print_text[34], 8, 20);
	myGLCD.print(print_text[35], 8, 32);
	
	myGLCD.print(print_text[36], 8, 74+9); //maximum duration
	myGLCD.print(print_text[37], 8, 74+7+12+5);
	
	myGLCD.print(print_text[38], 8, 128); //storm at night
	
	// ----------------------- display values --------------------- 

	PlusMinusCount (true, 200, 88, 1, 10, 1, timGROZtmp);      // storm duration 
	

   if (NightGR==1)                                                                                                             // Storm on/off
   { printButton(print_text[22], StormCtrlONNight[0], StormCtrlONNight[1], StormCtrlONNight[2], StormCtrlONNight[3], SMALL); } //"ON"

     else  { printButton(print_text[23], StormCtrlONNight[0], StormCtrlONNight[1], StormCtrlONNight[2], StormCtrlONNight[3], SMALL); }  //"OFF" 
     
    printButton(print_text[0], backGS[0], backGS[1], backGS[2], backGS[3], SMALL); // "Back"
    printButton(print_text[3], canCgs[0], canCgs[1], canCgs[2], canCgs[3], SMALL); // "Cancel"
    printButton(print_text[2], prSAVEgs[0], prSAVEgs[1], prSAVEgs[2], prSAVEgs[3], SMALL); // Save
	}
}   

void wheaterDim ()
{
	if ((clouDonOff ==1) && (weeStart==1))  {  // start process, decrease brigthness to DimCloudMin (default 10%)
        DecreaseBrightness ();
	if (DimCloud < DimCloudMin) { bitSet(GlobalStatus3Byte,1); weeStart= 0 ; DimCloudMax = random (50,100); 
//Serial.print("max1="); Serial.println(DimCloudMax);
	                            } // end start, next mode - random  
	                                        }

	if ((clouDonOff ==1) && (weeStart==0))  {  // random mode, increase/ decrease beetween DimCloudMax/DimCloudMin
		if (bitRead(GlobalStatus3Byte,1) == 1) { IncreaseBrightness ();
		if (DimCloud >= DimCloudMax) { bitClear(GlobalStatus3Byte,1); DimCloudMin = random (12,50); 
//Serial.print("min="); Serial.println(DimCloudMin);
		                             }
		}	else {DecreaseBrightness ();
		if (DimCloud < DimCloudMin) { bitSet(GlobalStatus3Byte,1); DimCloudMax = random (50,100); 
//Serial.print("max="); Serial.println(DimCloudMax);
		                            }
       }
	}
	if ((clouDonOff ==1) && (weeStart==2))  {  // end process encrease to DimCloudMax =100
      IncreaseBrightness ();
	  if (DimCloud >= 100) { clouDonOff=0 ;
	  if (dispScreen== 25) {
		  printButton(print_text[40], StormCtrl[0], StormCtrl[1]+30, StormCtrl[2], StormCtrl[3]+30, SMALL);}  //"Stop" (BLUE_BAC)
	  }
    }
	if (clouDonOff ==1) {PercentDimLW = DimCloud*0.01;}
}

void DecreaseBrightness ()
{ //      3min from 100% to 10%
/* 
	    if ((w_out >=1500) && (w_out <=2200) ) {DimCloud = DimCloud -1.25 ; }  // 2-0.5
		if ((w_out >=1000) && (w_out <1500) )  {DimCloud = DimCloud -0.75 ; }
		if ((w_out >=500) &&  (w_out <1000) )  {DimCloud = DimCloud -0.5 ; }
		if ((w_out >=250) &&  (w_out <500) )   {DimCloud = DimCloud -0.25 ; }
		if (w_out <250 )                       {DimCloud = DimCloud -0.13 ; }

		if ((w_out >=1750) && (w_out <2100) )  {RampRatio = 1;}  
		if ((w_out >=1500) && (w_out <1750) )  {RampRatio = 1;} 
		if ((w_out >=1250) && (w_out <1500) )  {RampRatio = 1.2;}
		if ((w_out >=1000) && (w_out <1250) )  {RampRatio = 1.5;}
		if ((w_out >=750) &&  (w_out <1000) )  {RampRatio = 2;}
		if ((w_out >=500) &&  (w_out <750) )   {RampRatio = 2.2;}
		if ((w_out >=250) &&  (w_out <500)  )  {RampRatio = 2.5;}
		if (w_out <250 )                       {RampRatio = 2.7;}
*/
//      2min 40sec 100% to 10%															   // delta100%->10% |70% ->10% |45% ->10% |25%->10%
	    if ((wled_out >=1750) && (wled_out <2100) )  {DimCloud = DimCloud -1.60*RampRatio ; }  // d=32				
		if ((wled_out >=1500) && (wled_out <1750) )  {DimCloud = DimCloud -1.30*RampRatio ; }  // d=26
		if ((wled_out >=1250) && (wled_out <1500) )  {DimCloud = DimCloud -1.00*RampRatio ; }  // d=20			  d=17
		if ((wled_out >=1000) && (wled_out <1250) )  {DimCloud = DimCloud -0.75*RampRatio ; }  // d=15			  d=12
		if ((wled_out >=750) &&  (wled_out <1000) )  {DimCloud = DimCloud -0.50*RampRatio ; }  // d=10			  d=8		 d=9	    
		if ((wled_out >=500) &&  (wled_out <750) )   {DimCloud = DimCloud -0.35*RampRatio ; }  // d=8			      d=8		 d=9	    
		if ((wled_out >=250) &&  (wled_out <500) )   {DimCloud = DimCloud -0.25*RampRatio ; }  // d=5			      d=5		 d=4       d=2   
		if (wled_out <250 )                       {DimCloud = DimCloud -0.18*RampRatio ; }  // d=2			      d=3		 d=3	   d=2

}

void IncreaseBrightness ()
{
	    if ((wled_out >=1750) && (wled_out <2100) )  {DimCloud = DimCloud +1.60*RampRatio ; }  
		if ((wled_out >=1500) && (wled_out <1750) )  {DimCloud = DimCloud +1.30*RampRatio ; } 
		if ((wled_out >=1250) && (wled_out <1500) )  {DimCloud = DimCloud +1.00*RampRatio ; }
		if ((wled_out >=1000) && (wled_out <1250) )  {DimCloud = DimCloud +0.75*RampRatio ; }
		if ((wled_out >=750) &&  (wled_out <1000) )  {DimCloud = DimCloud +0.5*RampRatio  ; }
		if ((wled_out >=500) &&  (wled_out <750) )   {DimCloud = DimCloud +0.35*RampRatio ; }  
		if ((wled_out >=250) &&  (wled_out <500) )   {DimCloud = DimCloud +0.25*RampRatio ; }
		if (wled_out <250 )                       {DimCloud = DimCloud +0.18*RampRatio ; }
}

void RampRatioCalc()
{		if ((wled_out >=1750) && (wled_out <2100) )  {RampRatio = 1;}  
		if ((wled_out >=1500) && (wled_out <1750) )  {RampRatio = 1;} 
		if ((wled_out >=1250) && (wled_out <1500) )  {RampRatio = 1.2;}
		if ((wled_out >=1000) && (wled_out <1250) )  {RampRatio = 1.5;}
		if ((wled_out >=750) &&  (wled_out <1000) )  {RampRatio = 2;}
		if ((wled_out >=500) &&  (wled_out <750)  )  {RampRatio = 2.2;}
		if ((wled_out >=250) &&  (wled_out <500)  )  {RampRatio = 2.5;}
		if (wled_out <250 )                       {RampRatio = 2.7;}
}

void timeStartOBL () {   // опрос таймеров на погоду
if (weezON==0) {kk1=0; kk2=0; kk3=0; kk4=0; kk5=0;}

if (timOBL1 !=0) {
  if ((min_cnt >=timOBL1) && (min_cnt < timOBL1+deltaOBL1)) {kf1=0;  if (kk1==0) {if (weezON==1) {DimCloud=dimmW;} else {DimCloud=100;} valHH=1; valueH1=8; weeStart=1; weezON=1;  kk1=1;}}
  if ((min_cnt >= timOBL1+deltaOBL1)&&(kf1==0)) { weeStart=2;  DimCloud=dimmW; kf1=1;
          if (tew==1) { timOBL1 = timOBL1temp; deltaOBL1 = deltaOBL1temp; 
                        timerGR1 = timerGR1temp; deltaGR1 = deltaGR1temp; tew=0;    } } }

//Serial.print ("timOBL1="); Serial.println (timOBL1);

/*
if (timOBL2 !=0) {
  if ((timer >=timOBL2) && (timer < timOBL2+deltaOBL2)) {kf2=0;  if (kk2==0) { if (weezON==1) {DimCloud=dimmW;} else {DimCloud=100;} valHH=1; valueH1=8; weeStart=1; weezON=1;  kk2=1;}}
  if ((timer >= timOBL2+deltaOBL2)&&(kf2==0)) { weeStart=2;  DimCloud=dimmW; kf2=1;} }

if (timOBL3 !=0) {
  if ((timer >=timOBL3) && (timer < timOBL3+deltaOBL3)) {kf3=0;  if (kk3==0) { if (weezON==1) {DimCloud=dimmW;} else {DimCloud=100;} valHH=1; valueH1=8; weeStart=1; weezON=1;  kk3=1;}}
  if ((timer >= timOBL3+deltaOBL3)&&(kf3==0)) { weeStart=2;  DimCloud=dimmW; kf3=1;} }
  
if (timOBL4 !=0) {
  if ((timer >=timOBL4) && (timer < timOBL4+deltaOBL4)) {kf4=0;  if (kk4==0) { if (weezON==1) {DimCloud=dimmW;} else {DimCloud=100;} valHH=1; valueH1=8; weeStart=1; weezON=1;  kk4=1;}}
  if ((timer >= timOBL4+deltaOBL4)&&(kf4==0)) { weeStart=2;  DimCloud=dimmW; kf4=1;} }

if (timOBL5 !=0) {
  if ((timer >=timOBL5) && (timer < timOBL5+deltaOBL5)) {kf5=0;  if (kk5==0) { if (weezON==1) {DimCloud=dimmW;} else {DimCloud=100;} valHH=1; valueH1=8; weeStart=1; weezON=1;  kk5=1;}}
  if ((timer >= timOBL5+deltaOBL5)&&(kf5==0)) { weeStart=2;  DimCloud=dimmW; kf5=1;} }  
*/
// Гроза (молнии)
if (timerGR1 !=0) {
    if ((timer >= timerGR1) && (timer < timerGR1+deltaGR1)) { if (kfg1==1) { GROZA=1;  }  kfg1=0; }
    if ((timer >= timerGR1+deltaGR1)&&(kfg1==0)) {GROZA=0; valHH=1; valueH1=8;  kfg1=1; }  }
if (timerGR2 !=0) {
    if ((timer >= timerGR2) && (timer < timerGR2+deltaGR2)) { if (kfg2==1) { GROZA=1;  }  kfg2=0; }
    if ((timer >= timerGR2+deltaGR2)&&(kfg2==0)) {GROZA=0; valHH=1; valueH1=8; kfg2=1; }  }
if (timerGR3 !=0) {
    if ((timer >= timerGR3) && (timer < timerGR3+deltaGR3)) { if (kfg3==1) { GROZA=1; }  kfg3=0; }
    if ((timer >= timerGR3+deltaGR3)&&(kfg3==0)) {GROZA=0; valHH=1; valueH1=8; kfg3=1; }  }
if (timerGR4 !=0) {
    if ((timer >= timerGR4) && (timer < timerGR4+deltaGR4)) { if (kfg4==1) { GROZA=1; }  kfg4=0; }
    if ((timer >= timerGR4+deltaGR4)&&(kfg4==0)) {GROZA=0; valHH=1; valueH1=8; kfg4=1; }  }
if (timerGR5 !=0) {
    if ((timer >= timerGR5) && (timer < timerGR5+deltaGR5)) { if (kfg5==1) { GROZA=1; }  kfg5=0; }
    if ((timer >= timerGR5+deltaGR5)&&(kfg5==0)) {GROZA=0; valHH=1; valueH1=8; kfg5=1; }  }    
if (timerGR6 !=0) {
    if ((timer >= timerGR6) && (timer < timerGR6+deltaGR6)) { if (kfg6==1) { GROZA=1; }  kfg6=0; }
    if ((timer >= timerGR6+deltaGR6)&&(kfg6==0)) {GROZA=0; valHH=1; valueH1=8; kfg6=1; }  } 
}

void CalcCoud()
{
int cloudDayFromTo;
int TempX;
//byte TempY;

          calculateStartTime();      // calculate SUNRISE Time  
	      calculateStopTime();       // calculate SUNSET Time  
          cloudDayFromTo = (StopTime*15 - StartTime*15) - 60; // -60min, end cloud 60min before sunset
		  TempX = cloudDayFromTo/CloudDayQantity;

 Serial.println(StartTime*15);
 Serial.println(StopTime*15);
 Serial.println(TempX);

		  for (int i=0; i<CloudDayQantity; i++)
		 {   int TempY;
//		  TempY= ((StartTime*15)+ TempX*i);
		 TempY= random(((StartTime*15)+ TempX*i), (((StartTime*15)+ TempX*i)+ TempX)); 

Serial.println(TempY);
		  }

//CloudDayQantity
//CloudDuration
//CloudWeekQantity


}
void planPOG () {    //  планирование погоды 

    OBLday = dayOBL[dayL];

  timOBL1=0; timOBL2=0; timOBL3=0; timOBL4=0; timOBL5=0;  //  планирование погоды на день
  int tOBL_1=0;
  int tOBL_2=0;
  int tOBL_3=0;
  int tOBL_4=0;
  OBLday = 7;
  dimmW = random(30,60); 
  
  if ((timOBL == 1)&&(OBLday !=0))  { tOBL_1 = random(1,6);}
  if ((timOBL == 2)&&(OBLday !=0))  { tOBL_1 = random(1,6); tOBL_2 = random(1,6); }
  if ((timOBL == 3)&&(OBLday !=0))  { tOBL_1 = random(1,6); tOBL_2 = random(1,6); tOBL_3 = random(1,6); }
  if ((timOBL == 4)&&(OBLday !=0))  { tOBL_1 = random(1,6); tOBL_2 = random(1,6); tOBL_3 = random(1,6); tOBL_4 = random(1,6);}

// cloud for one day
// timOBL cloud counter 1..5
// timOBL1....timOBL5 cloud start time
// deltaOBL cloud duration

  if ((tOBL_1 == 1)||(tOBL_2 == 1)||(tOBL_3 == 1)||(tOBL_4 == 1)) {timOBL1 = random(600,720); deltaOBL1 = random(5,deltaOBL);  } 
  if ((tOBL_1 == 2)||(tOBL_2 == 2)||(tOBL_3 == 2)||(tOBL_4 == 2)) {timOBL2 = random(720,840);  deltaOBL2 = random(5,deltaOBL);  }
  if ((tOBL_1 == 3)||(tOBL_2 == 3)||(tOBL_3 == 3)||(tOBL_4 == 3)) {timOBL3 = random(840,960); deltaOBL3 = random(5,deltaOBL);  } 
  if ((tOBL_1 == 4)||(tOBL_2 == 4)||(tOBL_3 == 4)||(tOBL_4 == 4)) {timOBL4 = random(960,1080); deltaOBL4 = random(5,deltaOBL);  }
  if ((tOBL_1 == 5)||(tOBL_2 == 5)||(tOBL_3 == 5)||(tOBL_4 == 5)) {timOBL5 = random(1080,1200); deltaOBL5 = random(5,deltaOBL);  }

  if (timOBL == 5) {
   timOBL1 = random(600,720); deltaOBL1 = random(5,deltaOBL);    // 10-12 hour
    timOBL2 = random(720,840); deltaOBL2 = random(5,deltaOBL);    // 12-14
    timOBL3 = random(840,960); deltaOBL3 = random(5,deltaOBL);    // 14-16
    timOBL4 = random(960,1080); deltaOBL4 = random(5,deltaOBL);   // 16-18
    timOBL5 = random(1080,1200); deltaOBL5 = random(5,deltaOBL);  // 18-20
  }

Serial.print ("timOBL="); Serial.println (timOBL);
Serial.print ("timOBL1="); Serial.println (timOBL1);
Serial.print ("timOBL2="); Serial.println (timOBL2);
Serial.print ("timOBL3="); Serial.println (timOBL3);
Serial.print ("timOBL4="); Serial.println (timOBL4);
Serial.print ("timOBL5="); Serial.println (timOBL5);
Serial.print ("tOBL_1="); Serial.println (tOBL_1);



// Панирование грозы
GR1=0; GR2=0; GR3=0; GR4=0; GR5=0; GR6=0;
timerGR1=0; timerGR2=0; timerGR3=0; timerGR4=0; timerGR5=0; timerGR6=0;

if (stormGR==1) {
    if (random(0,2)==1) {GROZAday=1;} else {GROZAday=0;} // решается, будет гроза сегодня или нет
    
    if ((timOBL1 != 0)&&(GROZAday==1)) { if (random(0,3) !=1) {GR1=1; timerGR1=timOBL1+deltaOBL1/2;      // решается, будет гроза или нет (в облачночть 1)
        deltaGR1=random(1,timGROZ); }} 
    if ((timOBL2 != 0)&&(GROZAday==1)) { if (random(0,3) !=1) {GR2=1; timerGR2=timOBL2+deltaOBL2/2;
        deltaGR2=random(1,timGROZ);  }}
    if ((timOBL3 != 0)&&(GROZAday==1)) { if (random(0,3) !=1) {GR3=1; timerGR3=timOBL3+deltaOBL3/2;
        deltaGR3=random(1,timGROZ);  }}
    if ((timOBL4 != 0)&&(GROZAday==1)) { if (random(0,3) !=1) {GR4=1; timerGR4=timOBL4+deltaOBL4/2;
        deltaGR4=random(1,timGROZ);  }}
    if ((timOBL5 != 0)&&(GROZAday==1)) { if (random(0,3) !=1) {GR5=1; timerGR5=timOBL5+deltaOBL5/2;
        deltaGR5=random(1,timGROZ);  }}
        
    if (GROZANight==1) { if (random(0,2)==1) { GR6=1; 
              timerGR6=random(2, 600); deltaGR6=random(1,timGROZ);}}// Гроза ночью
}}  

void planPOG_ned() {    //  планирование облаков на неделю

for (int i=1; i<8; i++) {dayOBL[i]=0;} // обнулеение массива дней облаков (недели) и планирование погоды (облаков) на неделю
  byte po1=0, po2=0, po3=0, po4=0;
  if (razOBL==1) { po1=random(1,8); dayOBL[po1]=1; } 
  if (razOBL==2) { po1=random(1,4); po2=random(4,8); dayOBL[po1]=1; dayOBL[po2]=1; }

  if (razOBL==3) { po1=random(1,4); po2=random(4,8); po3=random(1,8); dayOBL[po1]=1; dayOBL[po2]=1; dayOBL[po3]=1; }
  if (razOBL==4) { po1=random(1,4); po2=random(4,8); po3=random(1,8); po4=random(1,8); dayOBL[po1]=1; dayOBL[po2]=1; dayOBL[po3]=1; dayOBL[po4]=1; }

  if ((razOBL==5)||(razOBL==6)||(razOBL==7)) { for (int i=1; i<=7; i++) {dayOBL[i]=1; } 
      if (razOBL==5) {po1=random(1,4);  po2=random(4,8); dayOBL[po1] =0; dayOBL[po2] =0; }  
      if (razOBL==6) {po1=random(1,8); dayOBL[po1] =0; }  }
}



/************************************ TOUCH SCREEN ************************************/
void processMyTouch()
{
  myTouch.read();
//  x=myTouch.getX();
//  y=myTouch.getY();

#ifdef Mirror_X
  x=320-myTouch.getX();
#else
  x=myTouch.getX();
#endif

#ifdef Mirror_Y
  y=240-myTouch.getY();
#else
  y=myTouch.getY();
#endif

  
  returnTimer=0;
  screenSaverCounter=0;  

  if ((x>=canC[0]) && (x<=canC[2]) && (y>=canC[1]) && (y<=canC[3])  //press cancel 
     && (dispScreen!=0) && (dispScreen!=5) && (dispScreen!=6) && (dispScreen!=8) 
     && (dispScreen!=9) && (dispScreen!=11) && (dispScreen!=14) && (dispScreen!=15)
	 && (dispScreen!=20) && (dispScreen!=26) && (dispScreen!=27))
    {
     waitForIt(canC[0], canC[1], canC[2], canC[3]);
//     waveMakerOff = false;     
     dispScreen=0;
     clearScreen();
     mainScreen(true);
    }  else
  if ((x>=back[0]) && (x<=back[2]) && (y>=back[1]) && (y<=back[3]) 					//press back    
     && (dispScreen!=0) && (dispScreen!=1) && (dispScreen!=2) && (dispScreen!=5) && (dispScreen!=6)
     && (dispScreen!=8) && (dispScreen!=9) && (dispScreen!=11) && (dispScreen!=13)
     && (dispScreen!=14) && (dispScreen!=15) && (dispScreen!=16) && (dispScreen!=17)
     && (dispScreen!=18) && (dispScreen!=20) && (dispScreen!=21) && (dispScreen!=22) && (dispScreen!=23) && (dispScreen!=26) && (dispScreen!=27))
	 {
     waitForIt(back[0], back[1], back[2], back[3]);
//     waveMakerOff = false;
     dispScreen=1;
     clearScreen();
     menuScreen();
        } else

  {
  switch (dispScreen) {
  case 0:     //--------------- MAIN SCREEN (Press Any Key) ---------------
    dispScreen=1;
    clearScreen();
    menuScreen();
  break;
      
  case 1:     //--------------------- MENU SCREEN -------------------------

      if ((x>=temC[0]) && (x<=temC[2]))                      //first column
	  {
/*
    if ((x>=tanD[0]) && (x<=tanD[2]))                      //first column
      {

       if ((y>=tanD[1]) && (y<=tanD[3]))                   //press Date & Clock Screen
         {
          waitForIt(tanD[0], tanD[1], tanD[2], tanD[3]);
          if ((timeDispH>=0) && (timeDispH<=11)) { AM_PM=1;}
          else { AM_PM=2;}          
          dispScreen=2;
          clearScreen();
          clockScreen();
          t_temp = rtc.getTime();
          t_temp.dow=calcDOW(rtcSetDy, rtcSetMon, rtcSetYr);
          showDOW(t_temp.dow);             
         } 
*/

       if ((y>=temC[1]) && (y<=temC[3]))                   //press H2O Temp Control
         {
          waitForIt(temC[0], temC[1], temC[2], temC[3]);
          dispScreen=3;
          clearScreen();
          tempScreen(true); 
         }

       if ((y>=WeatCtrl[1]) && (y<=WeatCtrl[3]))                   //press Weather Control screen 
         {
          waitForIt(WeatCtrl[0], WeatCtrl[1], WeatCtrl[2], WeatCtrl[3]);
		  dispScreen=25;
          clearScreen();
          wthScreen(true); 
         }

/*
       if ((y>=gSet[1]) && (y<=gSet[3]))                   //press General Settings
         {
          waitForIt(gSet[0], gSet[1], gSet[2], gSet[3]);
          dispScreen=14;
          clearScreen();
          generalSettingsScreen_1();
         }
*/

        if ((y>=prsM[1]) && (y<=prsM[3]))                   //press PRESET XX button
         {
          waitForIt(prsM[0], prsM[1], prsM[2], prsM[3]);
          PresetSwitch();
         }
 }

    if ((x>=tesT[0]) && (x<=tesT[2]))                      //second column
      {
        if ((y>=tesT[1]) && (y<=tesT[3]))                  //press LED Testing page
         {
          waitForIt(tesT[0], tesT[1], tesT[2], tesT[3]);
          dispScreen=4;
          clearScreen();
          ledTestOptionsScreen();
         }  
        if  ((y>=ledChM[1]) && (y<=ledChM[3]))             //press Change LED values
         {
          waitForIt(ledChM[0], ledChM[1], ledChM[2], ledChM[3]);
          dispScreen=7;
          clearScreen();
          ledColorViewScreen(); 
         }

		  if ((y>=gSet[1]) && (y<=gSet[3]))                   //press General Settings
         {
          waitForIt(gSet[0], gSet[1], gSet[2], gSet[3]);
          dispScreen=14;
          clearScreen();
          generalSettingsScreen_1();
         }
/*
        if  ((y>=aFeed[1]) && (y<=aFeed[3]))               //press Automatic Feeder screen
         {
          waitForIt(aFeed[0], aFeed[1], aFeed[2], aFeed[3]);
          dispScreen=12;
          clearScreen();
          autoFeederScreen();
         }
        if  ((y>=about[1]) && (y<=about[3]))               //press About sketch
         {
          waitForIt(about[0], about[1], about[2], about[3]);
          dispScreen=19;
          clearScreen();
          AboutScreen(); 
         }         
*/
      }
  break;
      
  case 2:     //--------------- SET TIME AND DATE -------------------------
/*
	  if ((x>=back[0]) && (x<=back[2]) && (y>=back[1]) && (y<=back[3])) 					//press back    
	{ 
		waitForIt(back[0], back[1], back[2], back[3]);
	    dispScreen=14;
        clearScreen();
        generalSettingsScreen_1();
	} 
*/
//	  else 
    if ((x>=prSAVE[0]) && (x<=prSAVE[2]) && (y>=prSAVE[1]) && (y<=prSAVE[3])) //press SAVE
      {
       waitForIt(prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3]);
       if (setTimeFormat==1)
         {
          if ((rtcSetHr==0) && (AM_PM==2))
            { rtcSetHr+=12;}
          if (((rtcSetHr>=1) && (rtcSetHr<=11)) && (AM_PM==2))
            { rtcSetHr+=12;}  
          if (((rtcSetHr>=12) && (rtcSetHr<=23)) && (AM_PM==1))
            { rtcSetHr-=12;}           
         }
       
        rtc.setTime(rtcSetHr, rtcSetMin, 0);
        rtc.setDate(rtcSetDy, rtcSetMon, rtcSetYr);
	    dispScreen=14;
        clearScreen();
        generalSettingsScreen_1();
      } 
//-------------- change Hour/Min ----------------------
    else
     {
      if ((y>=houU[1]) && (y<=houU[3]))                            //FIRST ROW (TIME UP)
        {
         if ((x>=houU[0]) && (x<=houU[2]))                         //press hour up
           {
//          waitForIt(houU[0], houU[1], houU[2], houU[3]);
            waitForIt_Wo_Touch(houU[0], houU[1], houU[2], houU[3]);
            rtcSetHr++;
            if (rtcSetHr>=24) 
              { rtcSetHr=0; }
           }
         if ((x>=minU[0]) && (x<=minU[2]))                         //press min up
           {
//          waitForIt(minU[0], minU[1], minU[2], minU[3]);
            waitForIt_Wo_Touch(minU[0], minU[1], minU[2], minU[3]);  
            rtcSetMin++;
            if (rtcSetMin>=60) {rtcSetMin = 0; }
           }
         if ((x>=ampmU[0]) && (x<=ampmU[2]) && (setTimeFormat==1)) //press AMPM up
           {
//          waitForIt(ampmU[0], ampmU[1], ampmU[2], ampmU[3]);
            waitForIt_Wo_Touch(ampmU[0], ampmU[1], ampmU[2], ampmU[3]);
            if (AM_PM==1) {AM_PM=2;}
            else {AM_PM=1;}
           }
		clockScreen(false); 
        }
      if ((y>=houD[1]) && (y<=houD[3]))                            //SECOND ROW (TIME DOWN)
        {
         if ((x>=houD[0]) && (x<=houD[2]))                         //press hour down
           {
//            waitForIt(houD[0], houD[1], houD[2], houD[3]);
			waitForIt_Wo_Touch(houD[0], houD[1], houD[2], houD[3]);
            rtcSetHr--;
            if (rtcSetHr<0) 
              { rtcSetHr=23; }
           }
         if ((x>=minD[0]) && (x<=minD[2]))                         //press min down
           {
//          waitForIt(minD[0], minD[1], minD[2], minD[3]);
			waitForIt_Wo_Touch(minD[0], minD[1], minD[2], minD[3]);
            rtcSetMin--;
            if (rtcSetMin<0) {rtcSetMin = 59; }
           }
         if ((x>=ampmD[0]) && (x<=ampmD[2]) && (setTimeFormat==1)) //press AMPM down
           {
//          waitForIt(ampmD[0], ampmD[1], ampmD[2], ampmD[3]);
            waitForIt_Wo_Touch(ampmD[0], ampmD[1], ampmD[2], ampmD[3]); 
            if (AM_PM==1) {AM_PM=2;}
            else {AM_PM=1;}
           }     
		 clockScreen(false); 
        }

//-------------- change Day/Mouth/Year ----------------------

      if ((y>=dayU[1]) && (y<=dayU[3]))                            //THIRD ROW (DATE UP)
        {
         if (setCalendarFormat==0)                                 //DD/MM/YYYY Format
           {
            if ((x>=dayU[0]) && (x<=dayU[2]))                      //press day up
                  {
//             waitForIt(dayU[0], dayU[1], dayU[2], dayU[3]);
			   waitForIt_Wo_Touch(dayU[0], dayU[1], dayU[2], dayU[3]);
               rtcSetDy++;
               rtcSetDy=validateDate(rtcSetDy, rtcSetMon, rtcSetYr);
			    t_temp = rtc.getTime();
			    t_temp.dow=calcDOW(rtcSetDy, rtcSetMon, rtcSetYr);
                showDOW(t_temp.dow);
		          }
            if ((x>=monU[0]) && (x<=monU[2]))                      //press month up
                  {
//             waitForIt(monU[0], monU[1], monU[2], monU[3]);
			   waitForIt_Wo_Touch(monU[0], monU[1], monU[2], monU[3]);
               rtcSetMon++;
			   if (rtcSetMon>12) {rtcSetMon=1;}   //#oleg
               rtcSetDy=validateDateForMonth(rtcSetDy, rtcSetMon, rtcSetYr);
  				t_temp = rtc.getTime();
				t_temp.dow=calcDOW(rtcSetDy, rtcSetMon, rtcSetYr);
				showDOW(t_temp.dow);
                  }
           } else {
         if (setCalendarFormat==1)                                 //MM/DD/YYYY Format
           {
            if ((x>=dayU[0]) && (x<=dayU[2]))                      //press month up
              {
//             waitForIt(dayU[0], dayU[1], dayU[2], dayU[3]);
			   waitForIt_Wo_Touch(dayU[0], dayU[1], dayU[2], dayU[3]);
               rtcSetMon++;
			   if (rtcSetMon>12) {rtcSetMon=1;}   //#oleg
               rtcSetDy=validateDateForMonth(rtcSetDy, rtcSetMon, rtcSetYr);
				t_temp = rtc.getTime();
				t_temp.dow=calcDOW(rtcSetDy, rtcSetMon, rtcSetYr);
				showDOW(t_temp.dow);
              }
            if ((x>=monU[0]) && (x<=monU[2]))                      //press day up
              {
//             waitForIt(monU[0], monU[1], monU[2], monU[3]);
			   waitForIt_Wo_Touch(monU[0], monU[1], monU[2], monU[3]);
               rtcSetDy++;
               rtcSetDy=validateDate(rtcSetDy, rtcSetMon, rtcSetYr);
				t_temp = rtc.getTime();
				t_temp.dow=calcDOW(rtcSetDy, rtcSetMon, rtcSetYr);
				showDOW(t_temp.dow);
              }
           }      }
         if ((x>=yeaU[0]) && (x<=yeaU[2]))                         //press year up
           {
//          waitForIt(yeaU[0], yeaU[1], yeaU[2], yeaU[3]);
            waitForIt_Wo_Touch(yeaU[0], yeaU[1], yeaU[2], yeaU[3]);
            rtcSetYr++;
            rtcSetDy=validateDateForMonth(rtcSetDy, rtcSetMon, rtcSetYr);
			t_temp = rtc.getTime();
			t_temp.dow=calcDOW(rtcSetDy, rtcSetMon, rtcSetYr);
		    showDOW(t_temp.dow);
           }
//         t_temp = rtc.getTime();
//        t_temp.dow=calcDOW(rtcSetDy, rtcSetMon, rtcSetYr);
//        showDOW(t_temp.dow);
		 clockScreen(false); 
        }
      if ((y>=dayD[1]) && (y<=dayD[3]))                            //FOURTH ROW (DATE DOWN)
        {
         if (setCalendarFormat==0)                                 //DD/MM/YYYY Format
           {
            if ((x>=dayD[0]) && (x<=dayD[2]))                      //press day down
              {
//             waitForIt(dayD[0], dayD[1], dayD[2], dayD[3]);
               waitForIt_Wo_Touch(dayD[0], dayD[1], dayD[2], dayD[3]);
               rtcSetDy--;
               rtcSetDy=validateDate(rtcSetDy, rtcSetMon, rtcSetYr);
			    t_temp = rtc.getTime();
				t_temp.dow=calcDOW(rtcSetDy, rtcSetMon, rtcSetYr);
				showDOW(t_temp.dow);
              }
            if ((x>=monD[0]) && (x<=monD[2]))                      //press month down
              {
//             waitForIt(monD[0], monD[1], monD[2], monD[3]);
               waitForIt_Wo_Touch(monD[0], monD[1], monD[2], monD[3]);
               rtcSetMon--;
			   if (rtcSetMon<1) {rtcSetMon=12;}
               rtcSetDy=validateDateForMonth(rtcSetDy, rtcSetMon, rtcSetYr);
			    t_temp = rtc.getTime();
				t_temp.dow=calcDOW(rtcSetDy, rtcSetMon, rtcSetYr);
				showDOW(t_temp.dow);
              }
           } else {
         if (setCalendarFormat==1)                                 //MM/DD/YYYY Format
           {
            if ((x>=dayD[0]) && (x<=dayD[2]))                      //press day down
              {
//             waitForIt(dayD[0], dayD[1], dayD[2], dayD[3]);
               waitForIt_Wo_Touch(dayD[0], dayD[1], dayD[2], dayD[3]);
               rtcSetMon--;
   			   if (rtcSetMon<1) {rtcSetMon=12;}
               rtcSetDy=validateDateForMonth(rtcSetDy, rtcSetMon, rtcSetYr);
			    t_temp = rtc.getTime();
				t_temp.dow=calcDOW(rtcSetDy, rtcSetMon, rtcSetYr);
				showDOW(t_temp.dow);
              }
            if ((x>=monD[0]) && (x<=monD[2]))                      //press month down
              {
//             waitForIt(monD[0], monD[1], monD[2], monD[3]);
               waitForIt_Wo_Touch(monD[0], monD[1], monD[2], monD[3]);
               rtcSetDy--;
               rtcSetDy=validateDate(rtcSetDy, rtcSetMon, rtcSetYr);
			    t_temp = rtc.getTime();
				t_temp.dow=calcDOW(rtcSetDy, rtcSetMon, rtcSetYr);
				showDOW(t_temp.dow);
              }
           }      }   
         if ((x>=yeaD[0]) && (x<=yeaD[2]))                         //press year down
           {
//          waitForIt(yeaD[0], yeaD[1], yeaD[2], yeaD[3]);
            waitForIt_Wo_Touch(yeaD[0], yeaD[1], yeaD[2], yeaD[3]);
            rtcSetYr--;
            rtcSetDy=validateDateForMonth(rtcSetDy, rtcSetMon, rtcSetYr);
			 t_temp = rtc.getTime();
			 t_temp.dow=calcDOW(rtcSetDy, rtcSetMon, rtcSetYr);
			 showDOW(t_temp.dow);
           }
//         t_temp = rtc.getTime();
//         t_temp.dow=calcDOW(rtcSetDy, rtcSetMon, rtcSetYr);
//         showDOW(t_temp.dow);
		 clockScreen(false); 
        }
//     clockScreen(false); 
     }       

  if ((x>=back[0]) && (x<=back[2]) && (y>=back[1]) && (y<=back[3])) 					//press back    
	{ 
		waitForIt(back[0], back[1], back[2], back[3]);
	    dispScreen=14;
        clearScreen();
        generalSettingsScreen_1();
	} 

  break;
  
  case 3:     //------------------ H20 TEMPERATURE CONTROL ---------------
    if ((x>=prSAVE[0]) && (x<=prSAVE[2]) && (y>=prSAVE[1]) && (y<=prSAVE[3])) //press SAVE
      {
       waitForIt(prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3]);
       setTempC = temp2beS;
       setTempF = temp2beS;
       offTempC = temp2beO;
       offTempF = temp2beO;
       alarmTempC = temp2beA;
       alarmTempF = temp2beA;
       if (setTempScale==0)                      //Celsius to Farenheit (Consistency Conversion)
         {
          setTempF=((1.8*setTempC)+32.05);
          offTempF=((1.8*offTempC)+0.05);
          alarmTempF=((1.8*alarmTempC)+0.05);
         }    
       if (setTempScale==1)                      //Farenheit to Celsius (Consistency Conversion)
         {
          setTempC=((.55556*(setTempF-32))+.05);
          offTempC=(.55556)*offTempF+.05;
          alarmTempC=(.55556)*alarmTempF+.05;
         }
       dispScreen=0;
       SaveTempToEEPROM();
       clearScreen();
       mainScreen(true);
       } else
         setFont(LARGE, 255, 255, 255, 0, 0, 0);
         {
          if ((x>=temM[0]) && (x<=temM[2]))                        //first column
            {
             if ((y>=temM[1]) && (y<=temM[3]))                     //press temp minus
               {
                temp2beS -= 0.1;
                if ((setTempScale==1) && (temp2beS <= 50)){
                  temp2beS = 50; }
                if ((setTempScale==0) && (temp2beS <= 10)) {
                  temp2beS = 10; }
                tempScreen();
				delay(150);
               }
             if ((y>=offM[1]) && (y<=offM[3]))                     //press offset minus
               {
                temp2beO -= 0.1;
			    if (temp2beO <= 0.1) {temp2beO = 0.1; }
                tempScreen();
				delay(150);
               }          
             if ((y>=almM[1]) && (y<=almM[3]))                     //press alarm minus
               {
                temp2beA -= 0.1;
				if (temp2beA <= 0.1) {temp2beA = 9.9;}
                tempScreen();
				delay(150);
               }
            }
          if ((x>=temP[0]) && (x<=temP[2]))                        //second column
            {
             if ((y>=temP[1]) && (y<=temP[3]))                     //press temp plus
               {
                temp2beS += 0.1;
                if ((setTempScale==1) && (temp2beS >= 104)){
                  temp2beS = 104; }
                if ((setTempScale==0) && (temp2beS >= 40)) {
                  temp2beS = 40; }
                tempScreen();
				delay(150);
               }
             if ((y>=offP[1]) && (y<=offP[3]))                     //press offset plus
               { 
                temp2beO += 0.1;
             if (temp2beO >= 5) {temp2beO = 5; }
                tempScreen();
				delay(150);
               }
             if ((y>=almP[1]) && (y<=almP[3]))                     //press alarm plus
               {
		   	    temp2beA += 0.1;
		      if (temp2beA >=10.0) {temp2beA = 0.1;}     
                tempScreen();
				delay(150);
               }
            }
         }
  break;
  
  case 4:     // -------------- LED TESTING OPTIONS SCREEN -----------------    
    if ((x>=tstLA[0]) && (x<=tstLA[2]) && (y>=tstLA[1]) && (y<=tstLA[3]))   //Rapid Test LED Array Output
      {
       waitForIt(tstLA[0], tstLA[1], tstLA[2], tstLA[3]); 
       dispScreen=5;
       clearScreen();
	   LEDtestTick= false;
 //    testArrayScreen(true);         // rapid test led array, draw all test window
	   AllColourGraph();

      }  
    if ((x>=cntIL[0]) && (x<=cntIL[2]) && (y>=cntIL[1]) && (y<=cntIL[3]))   //Control Individual LEDs
      {
       waitForIt(cntIL[0], cntIL[1], cntIL[2], cntIL[3]); 
       dispScreen=6;
       clearScreen();
       testIndLedScreen(true);        // test and control individual led
       colorLEDtest = true;
	   bitClear(GlobalStatus1Byte,3); // clear bit for " Save changes before exit "
	   bitClear(GlobalStatus1Byte,2); // clear bit for " Save changes before exit "
      }

	 if ((x>=PrButL[0]) && (x<=PrButL[2]) && (y>=PrButL[1]) && (y<=PrButL[3]))   //preset button LEDs
      {
       waitForIt(PrButL[0], PrButL[1], PrButL[2], PrButL[3]); 
       dispScreen=23;
       clearScreen();
       PresetLedScreen(true);     // preset led windows
//       colorLEDtest = true;
      }

  break;
        
  case 5:     //---------------- Rapid LED TEST------------------------
    if ((x>=back[0]) && (x<=back[2]) && (y>=back[1]) && (y<=back[3])   //press back    
       && (LEDtestTick==false))    
      {
       waitForIt(back[0], back[1], back[2], back[3]);
//     LEDtestTick = false;
//     ReadFromEEPROM();     
       dispScreen=4;
       clearScreen();
       ledTestOptionsScreen();        // display buttons "Rapid test" and "Control Individual Leds"
      }      
    if ((x>=canC[0]) && (x<=canC[2]) && (y>=canC[1]) && (y<=canC[3])   //press CANCEL
       && (LEDtestTick==false))    
      {
       waitForIt(canC[0], canC[1], canC[2], canC[3]);
//       LEDtestTick = false;
//     ReadFromEEPROM();     
       dispScreen=0;
       clearScreen();
       mainScreen(true);
      } 
    if ((x>=ledChV[0]) && (x<=ledChV[2]) && (y>=ledChV[1]) && (y<=ledChV[3]) && dispScreen==5)  //press start/stop test
      {
       waitForIt(ledChV[0], ledChV[1], ledChV[2], ledChV[3]); 
       printButton("STOP", ledChV[0], ledChV[1], ledChV[2], ledChV[3], SMALL); // buton start/stop test

       if (LEDtestTick == true) {
           LEDtestTick = false;      // stop test
         }
         else {
           LEDtestTick = true;       // start test         
		   myGLCD.setColor(0, 0, 0);
	       myGLCD.fillRect(26, BotSldY+8, 319, BotSldY+3);    // clear test bar
		   drawTestLedArrayScale();
         }
	}
  break;
        
  case 6:     // --------------- TEST INDIVIDUAL LED COLOR SCREEN ( dispScreen=6 )--------------    

//	  DrawStaticElement == true;   

  if ((x>=back[0]) && (x<=back[2]) && (y>=back[1]) && (y<=back[3]) && (bitRead(GlobalStatus1Byte,2) == false))      //press back, exit to "Test option screen"     
      {
       waitForIt(back[0], back[1], back[2], back[3]);
	   if (bitRead(GlobalStatus1Byte,3) == false)           // bit3 =0, no changes settings 
	        {
			dispScreen=4;
			clearScreen();
			ledTestOptionsScreen();
			colorLEDtest = false;
			LED_levels_output();                            //return to current values led before exit to main
	        }
	   else {colorLEDtest = true;
	          bitSet(GlobalStatus1Byte,2);                  // for detect button Yes/No in to "save and exit" windows
	          SaveAndExit();
            }
      }    
    if ((x>=No[0]) && (x<=No[2]) && (y>=No[1]) && (y<=No[3]) && (bitRead(GlobalStatus1Byte,2) == true)) //press "NO", exit to menu without save,  
      {
       waitForIt(No[0], No[1], No[2], No[3]);
//	   	LEDtestTick = false;
 		dispScreen=4;
		clearScreen();
		ledTestOptionsScreen();
		COLOR = 0;
		ReadLedFromEEPROM();
		bitClear(GlobalStatus1Byte,3);    // bit 3 - changes setting (0 - no change, 1 -change )
		bitClear(GlobalStatus1Byte,2);    // clear bit for " Save changes before exit "
		colorLEDtest = false;
		LED_levels_output();              //return to current values led before exit to main
	   }

	if ((x>=Yes[0]) && (x<=Yes[2]) && (y>=Yes[1]) && (y<=Yes[3]) && (bitRead(GlobalStatus1Byte,2) == true))   //press "Yes" for save all changes and exit 
      {
       waitForIt(Yes[0], Yes[1], Yes[2], Yes[3]);
//      LEDtestTick = false;
		clearScreen();
		setFont(LARGE, 255, 0, 0, 0, 0, 0);
        myGLCD.print("PLEASE WAIT", 72, 80);
		COLOR=0 ;				          // save all colour
	    SaveLEDToEEPROM();
		bitClear(GlobalStatus1Byte,3);    // clear bit for " Save changes before exit "
		bitClear(GlobalStatus1Byte,2);    // clear bit for " Save changes before exit "
	   	dispScreen=4;
		colorLEDtest = false;
		ReadLedFromEEPROM();
		clearScreen();
		LED_levels_output();              //return to current values led before exit to main
		ledTestOptionsScreen();
	  }

	   if ((x>=StopDay[0]) && (x<=StopDay[2]) && (y>=StopDay[1]) && (y<=StopDay[3]) && colorLEDtest==true 
  	   && (bitRead(GlobalStatus1Byte,2) == false))             //press SUNSET, jump to end "light day"
      {
       waitForIt(StopDay[0], StopDay[1], StopDay[2], StopDay[3]);

	   calculateStopTime();      // calculate SUNSET Time
	   temp_sector = StopTime;
	   testIndLedScreen(false);
	   }

	   if ((x>=StartDay[0]) && (x<=StartDay[2]) && (y>=StartDay[1]) && (y<=StartDay[3]) && colorLEDtest==true
		   && (bitRead(GlobalStatus1Byte,2) == false))               //press  SUNRISE, jump to start "light day"
      {
       waitForIt(StartDay[0], StartDay[1], StartDay[2], StartDay[3]);
	      calculateStartTime();      // calculate SUNRISE Time
		  temp_sector = StartTime;
		  testIndLedScreen(false);
	   }  	   

   	   if ((x>=canC[0]) && (x<=canC[2]) && (y>=canC[1]) && (y<=canC[3]) && colorLEDtest==true
		   && (bitRead(GlobalStatus1Byte,2) == false))              //press NEXT SECTOR, without exit from screen
      {
       waitForIt(canC[0], canC[1], canC[2], canC[3]);
	   temp_sector+=1;                       // insrease time sector   
//	    if (temp_sector>95) {temp_sector=95;}
   	   if (temp_sector > 95) {temp_sector=0;}
	   testIndLedScreen(false);
	   }
	   if ((x>=ledChV[0]) && (x<=ledChV[2]) && (y>=ledChV[1]) && (y<=ledChV[3]) && colorLEDtest==true
		   && (bitRead(GlobalStatus1Byte,2) == false))              //press  PREV SECTOR, without exit from screen
      {
       waitForIt(ledChV[0], ledChV[1], ledChV[2], ledChV[3]);
	   temp_sector-=1;                        // desrease time sector
//	   	      if (temp_sector<=0) {temp_sector=0;}
  	   if (temp_sector == 255) {temp_sector=95;}
		  testIndLedScreen(false);
	   }  	   

//*************************************************************************************
	
   if ((y>=TopSldY)&&(y<=BotSldY) && (colorLEDtest==true) && (bitRead(GlobalStatus1Byte,2) == false) )  //change value with Slider Bars touch
      {
//       waitForTouchRelease();						       //#oleg this line prevent "parasitic" slider jump    

       for (byte i=0; i<9; i++) 
        {   
            if ((x>=(i*35)+4+5) && (x<=(i*35)+34-5))    // desrease slider touchable area (5pix)
            {											// WHITE=1, BLUE=2, ROYAL=3, RED=4,
														// ULTRA=5, TV=6, MOON=7;
                  						             	// CYAN=8,  YELLOW=9
				sbX1=(i*35)+4; sbX2=(i*35)+34;			// slider width 30 pix, clearens between sliders 5pix
				TopSldY=53, BotSldY=TopSldY+100; 
				SliderSwitch  = false;

      	  if (i==0 && bitRead(LedShannelStatusByte,5) == true) 
		      { sbR= rgbCh6[0]; sbG= rgbCh6[1]; sbB= rgbCh6[2];	// TV colour	
		     tvcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}
	      if (i==1 && bitRead(LedShannelStatusByte,3) == true) 
		      { sbR= rgbCh5[0]; sbG= rgbCh5[1]; sbB= rgbCh5[2];      				   // DR colour	
		     rcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2); }
		  if (i==2 && bitRead(LedShannelStatusByte,0) == true) 
		      { sbR= rgbCh2[0]; sbG= rgbCh2[1]; sbB= rgbCh2[2]; 			   // CW colour	
		      wcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}
	      if (i==3 && bitRead(LedShannelStatusByte,1) == true) 
		      { sbR= rgbCh4[0]; sbG= rgbCh4[1]; sbB= rgbCh4[2]; 				   // BL colour
              bcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}
	      if (i==4 && bitRead(LedShannelStatusByte,2) == true) 
		      { sbR= rgbCh3[0]; sbG= rgbCh3[1]; sbB= rgbCh3[2]; 				   // RBL colour
              rbcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}
	      if (i==5 && bitRead(LedShannelStatusByte,4) == true)  
		      { sbR= rgbCh1[0]; sbG= rgbCh1[1]; sbB= rgbCh1[2];			   // UV colour
              uvcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}
	      if (i==6 && bitRead(LedShannelStatusByte,6) == true)  
		      { sbR= rgbCh0[0]; sbG= rgbCh0[1]; sbB= rgbCh0[2];			       // CY colour
              cycol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}
	      if (i==7 && bitRead(LedShannelStatusByte,7) == true)  
		      { sbR= rgbCh7[0]; sbG= rgbCh7[1]; sbB= rgbCh7[2];			       // Yellow colour
              yelcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}
	      if (i==8)  { sbR= rgbCh8[0]; sbG= rgbCh8[1]; sbB= rgbCh8[2];			   // MOON colour
             mooncol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}

         	tvled[temp_sector] = tvcol_out;  // save to buffer before store to eeprom
			bled[temp_sector] = bcol_out;
			wled[temp_sector] = wcol_out;
			rbled[temp_sector] = rbcol_out;
			rled[temp_sector] = rcol_out;
			uvled[temp_sector] = uvcol_out;
			cyled[temp_sector] = cycol_out;
			yeled[temp_sector] = yelcol_out;
			bitSet(GlobalStatus1Byte,3);        // set bit3=1 if setting changed, for " Save changes before exit "
		    LED_levels_output();			    // send calculated value to PWM
		  }
     }
  } else

    if ((y>=29+2) && (y<=44-2) && (colorLEDtest==true) && (bitRead(GlobalStatus1Byte,2) == false)) //UP Buttons were touched, desrease button touchable area (2pix)
      { 
          for (byte i=0; i<9; i++) 
        {   
            if ((x>=(i*35)+4) && (x<=(i*35)+34))        // slider width 30 pix, clearens 5pix
            {											// WHITE=1, BLUE=2, ROYAL=3, RED=4,
														// ULTRA=5, TV=6, MOON=7;
                  						             	// CYAN=8,  YELLOW=9
				sbX1=(i*35)+4; sbX2=(i*35)+34;
				TopSldY=53, BotSldY=TopSldY+100; 
				SliderSwitch  = true;

     	  if (i==0 && bitRead(LedShannelStatusByte,5) == true) 
		     { sbR= rgbCh6[0]; sbG= rgbCh6[1]; sbB= rgbCh6[2];	tSlide = tvcol_out; tSlide+=1; // TV colour	
		        tvcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
			     tSlide= tvcol_out; }
	      if (i==1 && bitRead(LedShannelStatusByte,3) == true) 
		     { sbR= rgbCh5[0]; sbG= rgbCh5[1]; sbB= rgbCh5[2]; tSlide= rcol_out; tSlide+=1;   // DR colour	
		        rcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
			     tSlide= rcol_out; } 
		  if (i==2 && bitRead(LedShannelStatusByte,0) == true) 
		     { sbR= rgbCh2[0]; sbG= rgbCh2[1]; sbB= rgbCh2[2]; tSlide= wcol_out; tSlide+=1; 			   // CW colour	
		        wcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		         tSlide= wcol_out; }
	      if (i==3 && bitRead(LedShannelStatusByte,1) == true) 
		     { sbR= rgbCh4[0]; sbG= rgbCh4[1]; sbB= rgbCh4[2]; tSlide= bcol_out; tSlide+=1; 				   // BL colour
                bcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		         tSlide= bcol_out;}
	      if (i==4 && bitRead(LedShannelStatusByte,2) == true) 
		     { sbR= rgbCh3[0]; sbG= rgbCh3[1]; sbB= rgbCh3[2]; tSlide= rbcol_out; tSlide+=1; 				   // RBL colour
                rbcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		         tSlide= rbcol_out;}
	      if (i==5 && bitRead(LedShannelStatusByte,4) == true)  
		     { sbR= rgbCh1[0]; sbG= rgbCh1[1]; sbB= rgbCh1[2]; tSlide= uvcol_out; tSlide+=1; 			   // UV colour
                uvcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		         tSlide= uvcol_out;}
	      if (i==6 && bitRead(LedShannelStatusByte,6) == true)  
		     { sbR= rgbCh0[0]; sbG= rgbCh0[1]; sbB= rgbCh0[2]; tSlide= cycol_out; tSlide+=1;  		       // CY colour
                cycol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		          tSlide= cycol_out; }
	      if (i==7 && bitRead(LedShannelStatusByte,7) == true)  
		     { sbR= rgbCh7[0]; sbG= rgbCh7[1]; sbB= rgbCh7[2]; tSlide= yelcol_out; tSlide+=1; 			       // Yellow colour
                yelcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		         tSlide= yelcol_out; }
	      if (i==8)  
		     { sbR= rgbCh8[0]; sbG= rgbCh8[1]; sbB= rgbCh8[2]; tSlide= mooncol_out; tSlide+=1; 			   // MOON colour
                mooncol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		          tSlide= mooncol_out; }

          	tvled[temp_sector] = tvcol_out;  // save to buffer before store to eeprom
			bled[temp_sector] = bcol_out;
			wled[temp_sector] = wcol_out;
			rbled[temp_sector] = rbcol_out;
			rled[temp_sector] = rcol_out;
			uvled[temp_sector] = uvcol_out;
			cyled[temp_sector] = cycol_out;
			yeled[temp_sector] = yelcol_out;
		      LED_levels_output();               // send calculated value to PWM
			  bitSet(GlobalStatus1Byte,3);       // set bit3=1  if setting changed, for " Save changes before exit "
		      delay(100);                        //delay 50msec after touch UP/DOWN button
             }
          }
              SliderSwitch  = false;   
      } else
    if ((y>=174+2) && (y<=187-2) && (colorLEDtest==true) && (bitRead(GlobalStatus1Byte,2) == false)) //DOWN Buttons were touched,desrease button touchable area (2pix)
      {  
             for (byte i=0; i<9; i++) 
        {   
            if ((x>=(i*35)+4) && (x<=(i*35)+34))        // slider width 30 pix, clearens 5pix
            {											// WHITE=1, BLUE=2, ROYAL=3, RED=4,
														// ULTRA=5, TV=6, MOON=7;
                  						             	// CYAN=8,  YELLOW=9
				sbX1=(i*35)+4; sbX2=(i*35)+34;
				TopSldY=53, BotSldY=TopSldY+100; 
				SliderSwitch  = true;
       	  if (i==0 && bitRead(LedShannelStatusByte,5) == true) 
		        { sbR= rgbCh6[0]; sbG= rgbCh6[1]; sbB= rgbCh6[2];	tSlide = tvcol_out; tSlide-=1;	          // TV colour	
		           tvcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		            tSlide = tvcol_out; }
	      if (i==1 && bitRead(LedShannelStatusByte,3) == true) 
		        { sbR= rgbCh5[0]; sbG= rgbCh5[1]; sbB= rgbCh5[2]; tSlide = rcol_out;	tSlide-=1;                 // DR colour	
		           rcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		            tSlide = rcol_out ; }
		  if (i==2 && bitRead(LedShannelStatusByte,0) == true) 
		        { sbR= rgbCh2[0]; sbG= rgbCh2[1]; sbB= rgbCh2[2]; tSlide = wcol_out; tSlide-=1;			   // CW colour	
		           wcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		             tSlide= wcol_out; }
	      if (i==3 && bitRead(LedShannelStatusByte,1) == true) 
		        { sbR= rgbCh4[0]; sbG= rgbCh4[1]; sbB= rgbCh4[2]; tSlide = bcol_out; tSlide-=1;				   // BL colour
                   bcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		             tSlide= bcol_out; }
  	      if (i==4 && bitRead(LedShannelStatusByte,2) == true) 
		        { sbR= rgbCh3[0]; sbG= rgbCh3[1]; sbB= rgbCh3[2]; tSlide = rbcol_out; tSlide-=1; 				   // RBL colour
                   rbcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		            tSlide= rbcol_out; } 
	      if (i==5 && bitRead(LedShannelStatusByte,4) == true)
		        { sbR= rgbCh1[0]; sbG= rgbCh1[1]; sbB= rgbCh1[2]; tSlide = uvcol_out; tSlide-=1;			   // UV colour
                   uvcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		             tSlide= uvcol_out; } 
	      if (i==6 && bitRead(LedShannelStatusByte,6) == true)
		        { sbR= rgbCh0[0]; sbG= rgbCh0[1]; sbB= rgbCh0[2]; tSlide = cycol_out; tSlide-=1;			       // CY colour
                    cycol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		              tSlide= cycol_out; } 
	      if (i==7 && bitRead(LedShannelStatusByte,7) == true)
		        { sbR= rgbCh7[0]; sbG= rgbCh7[1]; sbB= rgbCh7[2]; tSlide = yelcol_out; tSlide-=1;			       // Yellow colour
                    yelcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		              tSlide= yelcol_out; }
	      if (i==8)  { sbR= rgbCh8[0]; sbG= rgbCh8[1]; sbB= rgbCh8[2]; tSlide = mooncol_out; tSlide-=1;			   // MOON colour
					 mooncol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
					  tSlide= mooncol_out; }

          	tvled[temp_sector] = tvcol_out;    // save to buffer before store to eeprom
			bled[temp_sector] = bcol_out;
			wled[temp_sector] = wcol_out;
			rbled[temp_sector] = rbcol_out;
			rled[temp_sector] = rcol_out;
			uvled[temp_sector] = uvcol_out;
			cyled[temp_sector] = cycol_out;
			yeled[temp_sector] = yelcol_out;
		      LED_levels_output();              // send calculated value to PWM
			  bitSet(GlobalStatus1Byte,3);      // set bit3=1 if setting changed for, " Save changes before exit "
		      delay(100);                       //delay 50msec after touch UP/DOWN button
             }
          }
       }
	         SliderSwitch  = false;   
  break;
    
  case 7:     // ----------- INDIVIDUAL LED OUTPUT COLORS Choices -----------    
    if ((x>=10) && (x<=150))                             //first button column
     {  
       if ((y>=20) && (y<=45))                           //View TV LEDs Array
         { waitForIt(10, 20, 150, 45); COLOR = TV;}      // COLOR=6

       if ((y>=55) && (y<=80))                           //View DRed LEDs Array
         { waitForIt(10, 55, 150, 80); COLOR = RED;}     // COLOR=4

       if ((y>=90) && (y<=115))                         //View White LEDs Array
         { waitForIt(10, 90, 150, 115); COLOR = WHITE;} // COLOR=1 

	   if ((y>=125) && (y<=150))                         //View BLUE LEDs Array
         { waitForIt(10, 125, 150, 150); COLOR = BLUE;}  // COLOR=2
	      
       if ((y>=160) && (y<=185))                         //View Lunar LEDs Array
	     { waitForIt(10, 160, 150, 185); COLOR = MOON;}    // COLOR=7

         dispScreen=8;								
         clearScreen();
//		 ReadLedFromEEPROM();
		 if (COLOR == MOON) 
		 {MoonPictureScreen();}
		 else
		 {ledValuesScreen();}                             //print TOP NAME bar & horisontal buttons with timetable 12x8
	 }

    if ((x>=170) && (x<=310))                            //second column
      {
       if ((y>=20) && (y<=45))                           //View Royal Blue LEDs Array
         { waitForIt(170, 20, 310, 45); COLOR = ROYAL;}  // COLOR=3       

       if ((y>=55) && (y<=80))                           //View UV LEDs Array
         { waitForIt(170, 55, 310, 80); COLOR = ULTRA;}  // COLOR=6

       if ((y>=90) && (y<=115))                         //View Cyan LEDs Array
         { waitForIt(170, 90, 310, 115); COLOR = CYAN; }// COLOR=8        

	   if ((y>=125) && (y<=150))                         //View Yellow LEDs Array
         { waitForIt(170, 125, 310, 150); COLOR = YELLOW; }// COLOR=9         

	   if ((y>=160) && (y<=185))                         //View All colour LEDs Array
         { waitForIt(170, 160, 310, 185); COLOR = 0; }   // COLOR=0         

	     dispScreen=8;									// draw for second column
         clearScreen();
//		 ReadLedFromEEPROM();
  		 if (COLOR == 0) 
		 {
    		AllColourGraph();
//          testArrayScreen();
		  COLOR = 0;
		 }
		 else
		 {ledValuesScreen();}                             //print TOP NAME bar & horisontal buttons with timetable 12x8

      }

  break;    
    
  case 8:     // -----SHOW LED OUTPUT VALUES CURVE SCREEN and wait for button "<<BACK", "CHANGE", "SAVE"-------------//

	  if ((x>=110) && (x<=201) && (y>=0) && (y<=17) && (COLOR!=0))        //press ON/OFF button
	  {
        waitForIt(110, 0, 201, 17);
		    myGLCD.setColor(0, 0, 255); 
			myGLCD.fillRoundRect(111, 1, 200, 16);
			setFont(SMALL, 255, 255, 255, 0, 0, 255 );  

			if (LedShannelFlag_on_off == true) { 
			myGLCD.print("LED OFF", 129, 3);
			LedShannelFlag_on_off = false;
			SaveOnOffLedStatus(false);
			}
		else {
            myGLCD.print("LED ON", 129, 3);
			LedShannelFlag_on_off = true; 
			SaveOnOffLedStatus(true);}
	    }

    if ((x>=back[0]) && (x<=back[2]) && (y>=back[1]) && (y<=back[3]))   //press BACK for EXIT to other COLORS
      {
       waitForIt(back[0], back[1], back[2], back[3]);
       COLOR = 0;
	   ReadLedFromEEPROM(); 
//     ReadFromEEPROM();
       dispScreen=7;
       clearScreen();
       ledColorViewScreen(); // print led & Moon colour buttons
      } else 
    if ((x>=ledChV[0]) && (x<=ledChV[2]) && (y>=ledChV[1]) && (y<=ledChV[3]) && (COLOR!=7) && (COLOR!=0))   //press CHANGE
      {
       waitForIt(ledChV[0], ledChV[1], ledChV[2], ledChV[3]);
//     ReadFromEEPROM();
       dispScreen=9;
       clearScreen(); 
       ledChangeScreen(); //print TOP timetable & Vertical buttons, w/o slider
      } else 
    if ((x>=eeprom[0]) && (x<=eeprom[2]) && (y>=eeprom[1]) && (y<=eeprom[3]) && (COLOR!=7) && (COLOR!=0))  //press SAVE
      {
       waitForIt(eeprom[0], eeprom[1], eeprom[2], eeprom[3]);
       SaveLEDToEEPROM();
       dispScreen=7;
       clearScreen();
       ledColorViewScreen(); // print led & Moon colour buttons
      } else 
	if ((x>=canC[0]) && (x<=canC[2]) && (y>=canC[1]) && (y<=canC[3]) && (COLOR==0)) //press CANCEL - exit from ALL COLOR GPRAPH 
      { waitForIt(canC[0], canC[1], canC[2], canC[3]);
//     LEDtestTick = false;
       dispScreen=0;
       clearScreen();
       mainScreen(true);
      }

//************* Moon section button ***********************************	
	else 
    if ((x>=prSAVE[0]) && (x<=prSAVE[2]) && (y>=prSAVE[1]) && (y<=prSAVE[3]) && (COLOR==7)) //press SAVE and exit from MOON section
      { waitForIt(prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3]);
       SaveMoonLEDToEEPROM();
       dispScreen=7;
       clearScreen();
       ledColorViewScreen(); // print led & Moon colour buttons
      } else             
    if ((x>=canC[0]) && (x<=canC[2]) && (y>=canC[1]) && (y<=canC[3]) && (COLOR==7)) //press CANCEL from Moon 
      { waitForIt(canC[0], canC[1], canC[2], canC[3]);
//     ReadFromEEPROM();
	   COLOR =7;
	   ReadLedFromEEPROM();  //#oleg read led values only
//     LEDtestTick = false;
       dispScreen=0;
       clearScreen();
       mainScreen(true);
      } else

	if (COLOR==7) {MoonChangeScreen();}    //change moon value brightness

  break;
      
  case 9:     //---------------- CHANGE Selected LED VALUES SCREEN ---------------

    if ((x>=8) && (x<=26) && (y>=66) && (y<=140))                  //press OK, exit from "chande led output value" to "LED output table" menu 
      {
       waitForIt(8, 66, 26, 140);
	   dispScreen=8;

  if (COLOR==1) {
    for (byte i=0; i<96; i++)
	{wled[i] = tled[i]; sbR= rgbCh2[0]; sbG= rgbCh2[1]; sbB= rgbCh2[2]; }}
  if (COLOR==2) {
    for (byte i=0; i<96; i++)
	{bled[i]=tled[i];  sbR= rgbCh4[0]; sbG= rgbCh4[1]; sbB= rgbCh4[2];}}
  if (COLOR==3) {
    for (byte i=0; i<96; i++)
	{rbled[i] = tled[i]; sbR= rgbCh3[0]; sbG= rgbCh3[1]; sbB= rgbCh3[2];}}
  if (COLOR==4) {
    for (byte i=0; i<96; i++)
	{rled[i] = tled[i]; sbR= rgbCh5[0]; sbG= rgbCh5[1]; sbB= rgbCh5[2];}}  
  if (COLOR==5) {
    for (byte i=0; i<96; i++)
	{uvled[i] = tled[i]; sbR= rgbCh1[0]; sbG= rgbCh1[1]; sbB= rgbCh1[2];}}
  if (COLOR==6) {
    for (byte i=0; i<96; i++)
	{tvled[i] = tled[i]; sbR= rgbCh6[0]; sbG= rgbCh6[1]; sbB= rgbCh6[2];}}
  if (COLOR==8) {
    for (byte i; i<96; i++)
	{cyled[i] = tled[i]; sbR= rgbCh0[0]; sbG= rgbCh0[1]; sbB= rgbCh0[2];}}
  if (COLOR==9) {
    for (byte i=0; i<96; i++)
	{yeled[i] = tled[i]; sbR= rgbCh7[0]; sbG= rgbCh7[1]; sbB= rgbCh7[2];}}

         DrawStaticElement = false;
		 oldLCT = 0;
		 myGLCD.setColor(64, 64, 64);					                // fill with background bottom time|date bar
         myGLCD.fillRect(1, 226, 318, 240);
		 clearScreen();
         ledValuesScreen();									        //print TOP NAME bar & horisontal buttons, with LED GRAPH
		 TimeDateBar(true);

      } else
    if ((x>=8) && (x<=26) && (y>=145) && (y<=219))                  //press CANCEL, exit to "main display" 
     {
       waitForIt(8, 145, 26, 219);
       waveMakerOff = false;     
       DrawStaticElement = false;
	   oldLCT = 0;
	   COLOR = 0;
	   ReadLedFromEEPROM();  //#oleg read led values only 
       dispScreen=0;
	   myGLCD.setColor(64, 64, 64);					                // fill with background bottom time|date bar
       myGLCD.fillRect(1, 226, 318, 240);
       clearScreen();
	   TimeDateBar(true);
       mainScreen(true);
     }  else
    if ((y>=15) && (y<=41))                //top row with times was touched
      {
        if ((x>=4) && (x<=316))
          {
              if (DrawStaticElement==false)
              {
                 myGLCD.setColor(0, 0, 0);
                myGLCD.fillRect(50, 110, 318, 146);
                for (byte b=0; b<8; b++)                             //draw UP Buttons
                  { drawUpButtonSlide((b*36)+34, 45);}
                for (byte b=0; b<8; b++)                             //draw DOWN Buttons
                  { drawDownButtonSlide((b*36)+34, 200);}
				  TopSldY=71; BotSldY=185;
/*
                setFont(SMALL, sbR, sbG, sbB, 0, 0, 0); 
                for (int i=0; i<8; i++)                             //draw color Slider Bar Outlines
                  { myGLCD.drawRect((i*36)+34, TopSldY, (i*36)+64, BotSldY);}
*/
				   for (byte i=0; i<8; i++)                        // draw white bar outline rectangle
         		     { sbX1=(i*36)+34; sbX2=(i*36)+64;
	                   setFont(SMALL, 255, 255, 255, 0, 0, 0); 
		               myGLCD.drawRect(sbX1, TopSldY-1, sbX2, BotSldY);}

				 myGLCD.setColor(140, 140, 140);                    // print vertical divider 
				 myGLCD.fillRect(174, 42, 176, 240);

               }

 // # oleg change function 00 time ( LedChangTime shifted +1 )
		          DrawStaticElement=true;
	              LedChangTime = map(x, 3, 320, 1, 13);
            if ( oldLCT != LedChangTime)								//highlight and refresh touched time only first touch current time
              { 
                  if (oldLCT !=0)
				  {
                  myGLCD.setColor(0, 0, 0);
                  myGLCD.fillRect((oldLCT-1)*26+5, 17, (oldLCT-1)*26+29, 41);
                  myGLCD.setColor(100, 100, 100);
                  myGLCD.drawRect((oldLCT-1)*26+4, 16 , (oldLCT-1)*26+30, 41);
                  setFont(SMALL, 0, 255, 255, 0, 0, 0);
		      
                if ((oldLCT-1)<5) {
                  myGLCD.printNumI(((oldLCT-1)*2), ((oldLCT-1)*26)+15, 17);
                  myGLCD.printNumI((((oldLCT-1)*2)+1), ((oldLCT-1)*26)+15, 28);}
                else {
                  myGLCD.printNumI(((oldLCT-1)*2), ((oldLCT-1)*26)+11, 17);
                  myGLCD.printNumI((((oldLCT-1)*2)+1), ((oldLCT-1)*26)+11, 28);}
				  }

                  myGLCD.setColor(255, 0, 0);
                if ((LedChangTime-1)<5) {
                  myGLCD.fillRect(((LedChangTime-1)*26)+5, 17, ((LedChangTime-1)*26)+29, 41);
                  setFont(SMALL, 255, 255, 255, 255, 0, 0);
				  myGLCD.printNumI(((LedChangTime-1)*2), ((LedChangTime-1)*26)+15, 17);
                  myGLCD.printNumI((((LedChangTime-1)*2)+1), ((LedChangTime-1)*26)+15, 28);}
                else {
                  myGLCD.fillRect(((LedChangTime-1)*26)+5, 17, ((LedChangTime-1)*26)+29, 41);
                  setFont(SMALL, 255, 255, 255, 255, 0, 0);
				  myGLCD.printNumI(((LedChangTime-1)*2), ((LedChangTime-1)*26)+11, 17);
                  myGLCD.printNumI((((LedChangTime-1)*2)+1), ((LedChangTime-1)*26)+11, 28);}
                  oldLCT= LedChangTime; 				

    		  for (byte i=0; i<=3; i++)                        // print botttom additional time bar 0/15/30/45min
				  {   setFont(SMALL, 255, 255, 255, 0, 0, 0);
					  myGLCD.printNumI(i*15, (i*36+40), 225, 2, '00');
					  myGLCD.print("m",i*36+55 , 225);
  					  myGLCD.printNumI(i*15, (i*36+40+144), 225, 2, '00');
					  myGLCD.print("m",i*36+55+144 , 225);
			  	     }
	  
                for (int i=0; i<8; i++)					  //print led values & slider value bars for highlighted time
                  {
                   int k=((LedChangTime-1)*8)+i;
//                  waitForTouchRelease();			      //#oleg this line prevent "parasitic" slider jump
					sbX1=(i*36)+34; sbX2=(i*36)+64;
					TopSldY=71; BotSldY=185;
					SliderSwitch  = true;
					tSlide=tled[k];
					SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
				   }
              }
	       }

      } else
   if ((y>=TopSldY)&&(y<=BotSldY) && (DrawStaticElement==true))    //Slider Bars touch
      {
//       waitForTouchRelease();						     //#oleg this line prevent "parasitic" slider jump  

       for (int i=0; i<8; i++) 
         {
          if ((x>=(i*36)+34+5) && (x<=(i*36)+64-5))      // decrease on 5pix slider touch area
            {
             int k=((LedChangTime-1)*8)+i;
             sbX1=(i*36)+34; sbX2=(i*36)+64;
			 TopSldY=71; BotSldY=185;
			 SliderSwitch  = false;   
  			 tled[k]= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
            }
         }
       } else
    if ((y>=45) && (y<=67) && (DrawStaticElement==true))           //UP Buttons were touched
      {
        for (int i=0; i<8; i++) 
          {                
           if ((x>=(i*36)+34) && (x<=(i*36)+64)) 
             {
              int k= ((LedChangTime-1)*8)+i;
			  TopSldY=71; BotSldY=185;
			  sbX1=(i*36)+34; sbX2=(i*36)+64;
			  SliderSwitch  = true; 
     	  	  tSlide = tled[k]; 
			  tSlide+=1; 
		      tled[k] = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);

			  delay(100); //delay 50msec after touch UP/DOWN button

             }
          }
      } else
    if ((y>=200) && (y<=222) && (DrawStaticElement==true))             //DOWN Buttons were touched
      {
        for (int i=0; i<8; i++) 
          {                
           if ((x>=(i*36)+34) && (x<=(i*36)+64)) 
             {
              int k= ((LedChangTime-1)*8)+i;

			  TopSldY=71; BotSldY=185;
			  sbX1=(i*36)+34; sbX2=(i*36)+64;
			  SliderSwitch  = true; 
     	  	  tSlide = tled[k]; 
			  tSlide-=1; 
		      tled[k] = SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);

			  delay(100); //delay 50msec after touch UP/DOWN button
             }
          }
      }
    break;
    
    case 10: //-------------------- WAVEMAKER SCREEN -------------------
/*
      if ((x>=5) && (x<=155) && (y>=20) && (y<=40))      //press Alternating Mode
        {
         waitForIt(5, 20, 155, 40);
         Synch=0;
         WAVE=1;
         dispScreen=11;
         clearScreen();
         WaveMakerSettingsScreen();
         waveMakerOff=true;
         digitalWrite(WaveMakerTop, LOW);
         digitalWrite(WaveMakerBottom, LOW);    
        } else
      if ((x>=165) && (x<=315) && (y>=20) && (y<=40))    //press Synchronous Mode
        {
         waitForIt(165, 20, 315, 40);
         WAVE=2;
         dispScreen=11;
         clearScreen();
         WaveMakerSettingsScreen();
         synchronousSynch();    
         waveMakerOff=true;
         digitalWrite(WaveMakerTop, LOW);
         digitalWrite(WaveMakerBottom, LOW);    
        } else             
      if ((x>=165) && (x<=315) && (y>=46) && (y<=66))    //press Turn Pumps OFF/ON
        {
         waitForIt(165, 46, 315, 66);
         if (WAVE==3) {
//           ReadFromEEPROM();
           waveMakerOff=false;
           WaveMakerStatusScreen();
           }
           else {
             MODE=WAVE;
             WAVE=3;
             WaveMakerStatusScreen();
           }
        } else 
      if ((x>=5) && (x<=155) && (y>=46) && (y<=66))      //press Feeding Mode
        {
         waitForIt(5, 46, 155, 66);
         if (WAVE==4) {
 //          ReadFromEEPROM();
           waveMakerOff=false;
           WaveMakerStatusScreen();
           }
           else {
//             ReadFromEEPROM();
             MODE=WAVE;
             WAVE=4;
             countDown  = 5*60 + 0;     //Reset countdown for 5 minutes and zero seconds
             MIN_O = 5;                 //Reset start time at 5 Minutes
             SEC_T = 0;
             SEC_O = 0;
             WaveMakerStatusScreen();
           }
        } 
*/
    break;

    case 11: 
/*		
		         //---------------- WAVEMAKER SETTINGS SCREEN --------------
      if ((y>=200) && (y<=220))                          //Bottom Row
        {
         if ((x>=5) && (x<=105))                         //press BACK
           {
            waitForIt(5, 200, 105, 220);
//           ReadFromEEPROM();
            waveMakerTest=false;
            waveMakerOff=false;
            dispScreen=10;
            clearScreen();
            WaveMakerScreen();
            WaveMakerStatusScreen();
           } else
         if ((x>=110) && (x<=210))                       //press TEST
           {
            waitForIt(110, 200, 210, 220);
            myGLCD.setColor(0, 255, 0);
            myGLCD.fillRoundRect(110, 200, 210, 220);    //TEST Button in Green
            setFont(SMALL, 0, 0, 0, 0, 255, 0);
            myGLCD.print("TESTING", 132, 204);
            myGLCD.setColor(255, 255, 255);            
            myGLCD.drawRoundRect(110, 200, 210, 220);
            waveMakerOff=false;
            waveMakerTest=true;
            } else
         if ((x>=210) && (x<=315))                       //press SAVE
           {
            waitForIt(215, 200, 315, 220);
            if (WAVE==1) { Pump1m=Min1; Pump1s=Sec1; Pump2m=Min2; Pump2s=Sec2;}
            if (WAVE==2) { OnForTm=Min1; OnForTs=Sec1; OffForTm=Min2; OffForTs=Sec2;}
            SaveWaveToEEPROM();
            waveMakerTest=false;
            waveMakerOff=false;
            dispScreen=10;
            clearScreen();
            WaveMakerScreen();
            WaveMakerStatusScreen();
           }
        }
      else 
        {
         if (WAVE==1)                                    //Alternating Mode Settings
           { 
            waveModePlusMinus();
           }
        
         if (WAVE==2)                                    //Synchronous Mode Settings
           {
            if ((x>=5) && (x<=155) && (y>=20) && (y<=40))   //Constantly ON
              {
               waitForIt(5, 20, 155, 40);
               Synch=1;
               synchronousSynch();
              } else 
            if ((x>=165) && (x<=315) && (y>=20) && (y<=40)) //Pulsating Mode
              {
               waitForIt(165, 20, 315, 40);
               Synch=2;
               synchronousSynch();
              }
            if (Synch==2)                                //Synchronous-Pulsating Settings
              {
               waveModePlusMinus();
              }
           }
        }
*/
    break;

    case 12:   
/*
		//--------------- AUTOMATIC FISH FEEDER PAGE --------------
      if ((x>=5) && (x<=155) && (y>=20) && (y<=40))      //press Feeding Time 1
        {
         waitForIt(5, 20, 155, 40);
         feedTime=1;
         dispScreen=13;
         clearScreen();
         setFeederTimesScreen();
        } else
      if ((x>=165) && (x<=315) && (y>=20) && (y<=40))    //press Feeding Time 2
        {
         waitForIt(165, 20, 315, 40);
         feedTime=2;
         dispScreen=13;
         clearScreen();
         setFeederTimesScreen();
        } else
      if ((x>=5) && (x<=155) && (y>=168) && (y<=188))    //press Feeding Time 3
        {
         waitForIt(5, 168, 155, 188);
         feedTime=3;
         dispScreen=13;
         clearScreen();
         setFeederTimesScreen();
        } else
      if ((x>=165) && (x<=315) && (y>=168) && (y<=188))  //press Feeding Time 4
        {
         waitForIt(165, 168, 315, 188);
         feedTime=4;
         dispScreen=13;
         clearScreen();
         setFeederTimesScreen();
        } else
      if ((x>=85) && (x<=235) && (y>=94) && (y<=114))    //press Feeding Fish Now!
        {
         waitForIt(85, 94, 235, 114);
         myGLCD.setColor(0, 255, 0);
         myGLCD.fillRoundRect(85, 94, 235, 114);
         myGLCD.setColor(255, 255, 255);
         myGLCD.drawRoundRect(85, 94, 235, 114); 
         setFont(SMALL, 0, 0, 0, 0, 255, 0);
//       myGLCD.print("Now Feeding", 118, 98); 
		 strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[34]))); 
         myGLCD.print(buffer, 118, 98);
         digitalWrite(autoFeeder, HIGH);
         delay(5000);
         myGLCD.setColor(153, 0, 102);
         myGLCD.fillRoundRect(85, 94, 235, 114);
         myGLCD.setColor(255, 255, 255);
         myGLCD.drawRoundRect(85, 94, 235, 114); 
         setFont(SMALL, 255, 255, 255, 153, 0, 102);
//       myGLCD.print("Feed Fish Now!", 106, 98);
         strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[33]))); 
         myGLCD.print(buffer, 106, 98);
         digitalWrite(autoFeeder, LOW);
        } 
*/
    break;

    case 13:  
/*
		//------------ SET AUTOMATIC FISH FEEDER TIMES ------------
      if ((x>=back[0]) && (x<=back[2]) && (y>back[1]) && (y<=back[3]))          //press back    
        {
         waitForIt(back[0], back[1], back[2], back[3]);
 //        ReadFromEEPROM();
         if ((timeDispH>=0) && (timeDispH<=11)) { AM_PM=1;}
         else { AM_PM=2;}
         dispScreen=12;
         clearScreen();
         autoFeederScreen();
        } else
      if ((x>=prSAVE[0]) && (x<=prSAVE[2]) && (y>=prSAVE[1]) && (y<=prSAVE[3])) //press SAVE
        {
         waitForIt(prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3]);
         if (setTimeFormat==1)
           {
            if ((rtcSetHr==0) && (AM_PM==2))
              { rtcSetHr+=12;}
            if (((rtcSetHr>=1) && (rtcSetHr<=11)) && (AM_PM==2))
              { rtcSetHr+=12;}  
            if (((rtcSetHr>=12) && (rtcSetHr<=23)) && (AM_PM==1))
              { rtcSetHr-=12;}           
           }                  
         if (feedTime==1)
           { feedFish1H=rtcSetHr; feedFish1M=rtcSetMin;}
         if (feedTime==2)
           { feedFish2H=rtcSetHr; feedFish2M=rtcSetMin;}
         if (feedTime==3)
           { feedFish3H=rtcSetHr; feedFish3M=rtcSetMin;}
         if (feedTime==4)
           { feedFish4H=rtcSetHr; feedFish4M=rtcSetMin;}        
         SaveFeedTimesToEEPROM();
         dispScreen=12;
         clearScreen();
         autoFeederScreen();
        } else
      if ((x>=70) && (x<=250) && (y>=150) && (y<=170))   //Feeding ON/OFF
        {
         waitForIt(70, 150, 250, 170);
         if (feedTime==1) 
           { if (FEEDTime1==1) { FEEDTime1=0;} 
             else { FEEDTime1=1;}}
         if (feedTime==2) 
           { if (FEEDTime2==1) { FEEDTime2=0;} 
             else { FEEDTime2=1;}}
         if (feedTime==3) 
           { if (FEEDTime3==1) { FEEDTime3=0;} 
             else { FEEDTime3=1;}}
         if (feedTime==4) 
           { if (FEEDTime4==1) { FEEDTime4=0;} 
             else { FEEDTime4=1;}}
         feedingTimeOnOff();
        } 
      else      
        {
         if ((y>=houP[1]) && (y<=houP[3]))               //FIRST ROW
           {
            if ((x>=houP[0]) && (x<=houP[2]))            //press hour up
              {
               waitForIt(houP[0], houP[1], houP[2], houP[3]);
               rtcSetHr++;
               if (rtcSetHr>=24) 
                 { rtcSetHr=0; }
              }
            if ((x>=minP[0]) && (x<=minP[2]))            //press min up
              {
               waitForIt(minP[0], minP[1], minP[2], minP[3]);
               rtcSetMin++;
               if (rtcSetMin>=60) {rtcSetMin=0; }
              }
            if ((x>=ampmP[0]) && (x<=ampmP[2])           //press AMPM up
               && (setTimeFormat==1))         
              {
               waitForIt(ampmP[0], ampmP[1], ampmP[2], ampmP[3]);
               if (AM_PM==1) {AM_PM=2;}
               else {AM_PM=1;}
              }
           }
         if ((y>=houM[1]) && (y<=houM[3]))               //SECOND ROW
           {
            if ((x>=houM[0]) && (x<=houM[2]))            //press hour down
              {
               waitForIt(houM[0], houM[1], houM[2], houM[3]);             
               rtcSetHr--;
               if (rtcSetHr<0) 
                 { rtcSetHr=23; }
              }
            if ((x>=minM[0]) && (x<=minM[2]))            //press min down
              {
               waitForIt(minM[0], minM[1], minM[2], minM[3]);
               rtcSetMin--;
               if (rtcSetMin<0) {rtcSetMin=59; } 
              }
            if ((x>=ampmM[0]) && (x<=ampmM[2])           //press AMPM down
                && (setTimeFormat==1))        
              {
               waitForIt(ampmM[0], ampmM[1], ampmM[2], ampmM[3]);
               if (AM_PM==1) {AM_PM=2;}
               else {AM_PM=1;}
              }  
           } 
         setFeederTimesScreen(false);
        }
*/
    break;
    
    case 14:     //------------- GENERAL SETTINGS (PAGE 1) -----------------
      if ((x>=backGS[0]) && (x<=backGS[2]) && (y>=backGS[1]) && (y<=backGS[3]))  //press back    
        {
         waitForIt(backGS[0], backGS[1], backGS[2], backGS[3]);
//       LEDtestTick = false;
         waveMakerOff = false;          
 //      ReadFromEEPROM();
         dispScreen=1;
         clearScreen();
         menuScreen();
        } else
      if ((x>=nextGS[0]) && (x<=nextGS[2]) && (y>=nextGS[1]) && (y<=nextGS[3]))  //press next
        {
         waitForIt(nextGS[0], nextGS[1], nextGS[2], nextGS[3]);
         dispScreen=15;
         clearScreen();
         generalSettingsScreen_2();
        } else        
      if ((x>=prSAVEgs[0]) && (x<=prSAVEgs[2]) && (y>=prSAVEgs[1]) && (y<=prSAVEgs[3])) //press SAVE
        {
         waitForIt(prSAVEgs[0], prSAVEgs[1], prSAVEgs[2], prSAVEgs[3]);
         SaveGenSetsToEEPROM();
         SaveLEDsFailsafeToEEPROM();         
//       dispScreen=1;
//       clearScreen();
//       menuScreen();
        }
      if ((x>=canCgs[0]) && (x<=canCgs[2]) && (y>=canCgs[1]) && (y<=canCgs[3]))  //press cancel 
        {
         waitForIt(canCgs[0], canCgs[1], canCgs[2], canCgs[3]);
         waveMakerOff = false;     
         dispScreen=0;
         clearScreen();
         mainScreen(true);
        } else        

      if ((x>=185) && (x<=305) && (y>=19) && (y<=39))    //press Time/Date Button
        {
         waitForIt(185, 19, 305, 39);
         if ((timeDispH>=0) && (timeDispH<=11)) { AM_PM=1;}
         else { AM_PM=2;}          
         dispScreen=2;
         clearScreen();
         clockScreen();
         t_temp = rtc.getTime();
         t_temp.dow=calcDOW(rtcSetDy, rtcSetMon, rtcSetYr);
         showDOW(t_temp.dow); 
        }

      if ((x>=185) && (x<=305) && (y>=45) && (y<=65))    //change "Month DD, YYYY" or "DD/MM/YYYY" format
        {
         waitForIt(185, 49, 305, 69);
		  myGLCD.setColor(255, 255, 255);
          myGLCD.drawRoundRect(185, 49, 305, 69);		// calendar
		 if (setCalendarFormat ==1) 
		 { setCalendarFormat=0;
           setFont(SMALL, 255, 255, 255, 0, 0, 255);     
           myGLCD.print(" DD/MM/YYYY ", 199, 53);
		 }
		 else {
		   setCalendarFormat = 1;
           setFont(SMALL, 255, 255, 255, 0, 0, 255);     
	       myGLCD.print("MTH DD, YYYY", 199, 53);   
		      }
        }

      if ((x>=185) && (x<=229) && (y>=79) && (y<=99))
        {
            waitForIt(185, 79, 229, 99);
         	myGLCD.setColor(255, 255, 255);
            myGLCD.drawRoundRect(185, 79, 229, 99);

		if (displayDOW == 1) 
		   { displayDOW =0;
             setFont(SMALL, 255, 255, 255, 0, 0, 255);     
             myGLCD.print("OFF", 199, 83);
		   }
		 else {
		     displayDOW = 1;
             setFont(SMALL, 255, 255, 255, 0, 0, 255);     
	         myGLCD.print(" ON ", 193, 83);   
		      }
		  }

   if ((x>=185) && (x<=229) && (y>=109) && (y<=129))
        {
            waitForIt(185, 109, 229, 129);
         	myGLCD.setColor(255, 255, 255);
            myGLCD.drawRoundRect(185, 109, 229, 129);

		if (setTimeFormat == 1) 
		   { setTimeFormat =0;
             setFont(SMALL, 255, 255, 255, 0, 0, 255);     
             myGLCD.print("24HR", 191, 113);   
		   }
		 else {
		     setTimeFormat = 1;
             setFont(SMALL, 255, 255, 255, 0, 0, 255);     
	         myGLCD.print("12HR", 191, 113);   
		      }
	    }

   if ((x>=185) && (x<=229) && (y>=139) && (y<=159))
        {
            waitForIt(185, 139, 229, 159);
         	myGLCD.setColor(255, 255, 255);
            myGLCD.drawRoundRect(185, 139, 229, 159);

		if (setTempScale == 1) 
		   { setTempScale = 0;
             setFont(SMALL, 255, 255, 255, 0, 0, 255);     
             myGLCD.print("C", 205, 142);   
             myGLCD.drawCircle(200, 144, 1);
		   }
		 else {
		     setTempScale = 1;
             setFont(SMALL, 255, 255, 255, 0, 0, 255);     
	         myGLCD.print("F", 205, 142);   
             myGLCD.drawCircle(200, 144, 1);
		      }
	    }
   
     if ((x>=185) && (x<=305) && (y>=169) && (y<=189))  //press CHANGE TEMPS
        {
         waitForIt(185, 169, 305, 189);
         dispScreen=16;
         clearScreen();
         ChangeFanTempsScreen(true);
        }
    break;

    case 15:     //------------- GENERAL SETTINGS (PAGE 2) -----------------

		if ((x>=backGS[0]) && (x<=backGS[2]) && (y>=backGS[1]) && (y<=backGS[3]))  //press back    
        {
         waitForIt(backGS[0], backGS[1], backGS[2], backGS[3]);
         dispScreen=14;
         clearScreen();
         generalSettingsScreen_1();
        } else

         if ((x>=nextGS[0]) && (x<=nextGS[2]) && (y>=nextGS[1]) && (y<=nextGS[3]))  //press next
        {
         waitForIt(nextGS[0], nextGS[1], nextGS[2], nextGS[3]);
		 dispScreen=20;
		 clearScreen();
		 generalSettingsScreen_3();
		 } else

 if ((x>=prSAVEgs[0]) && (x<=prSAVEgs[2]) && (y>=prSAVEgs[1]) && (y<=prSAVEgs[3])) //press SAVE
        {
         waitForIt(prSAVEgs[0], prSAVEgs[1], prSAVEgs[2], prSAVEgs[3]);
         SaveGenSetsToEEPROM();
         SaveLEDsFailsafeToEEPROM();         
//       dispScreen=1;
//       clearScreen();
//       menuScreen();
         }
     if ((x>=canCgs[0]) && (x<=canCgs[2]) && (y>=canCgs[1]) && (y<=canCgs[3]))  //press cancel 
        {
         waitForIt(canCgs[0], canCgs[1], canCgs[2], canCgs[3]);
         waveMakerOff = false;     
         dispScreen=0;
         clearScreen();
         mainScreen(true);
        } else        

      if (((x>=185) && (x<=305) && (y>=19) && (y<=39)) && setDimLEDsOnOff ==1 )  //press CHANGE TEMP (Dim LEDs), if ON pressed
        {
         waitForIt(185, 19, 305, 39); 
         dispScreen=17;
         clearScreen();
         DimLEDsAtTempScreen();
        }

	  if ((x>=130) && (x<=174) && (y>=19) && (y<=39))  //press ON/OFF led DIM setting
	  {
		 waitForIt(130, 19, 174, 39);
         myGLCD.setColor(255, 255, 255);
         myGLCD.drawRoundRect(130, 19, 174, 39);
		 myGLCD.drawRoundRect(185, 19, 305, 39);

		if (setDimLEDsOnOff == 1) 
		   { setDimLEDsOnOff =0;
             setFont(SMALL, 255, 255, 255, 0, 0, 255);     
             myGLCD.print("OFF", 144, 23);
	 		 myGLCD.setColor(64, 64, 64);
		     myGLCD.fillRoundRect(185, 19, 305, 39);
		     setFont(SMALL, 255, 255, 255, 64, 64, 64);
		     myGLCD.print("Change Temp", 203, 23);
			 myGLCD.setColor(255, 255, 255);
             myGLCD.drawRoundRect(185, 19, 305, 39);       // dim led 
  
		   }
		 else {
		     setDimLEDsOnOff = 1;
			 myGLCD.setColor(0, 0, 255);
             myGLCD.fillRoundRect(185, 19, 305, 39);
			 myGLCD.setColor(255, 255, 255);
			 myGLCD.drawRoundRect(185, 19, 305, 39);       
             setFont(SMALL, 255, 255, 255, 0, 0, 255);     
	         myGLCD.print(" ON ", 138, 23);
		     myGLCD.print("Change Temp", 203, 23);

		      }
	  }

      if (((x>=185) && (x<=305) && (y>=49) && (y<=69)) && setScreensaverOnOff==1)  //press SETTINGS (Screensaver)
        {
         waitForIt(185, 49, 305, 69);
         dispScreen=18;
         clearScreen();
         ScreensaverSettingsScreen();
        }

	  	  if ((x>=130) && (x<=174) && (y>=49) && (y<=69))  //press ON/OFF screensaver
	  {
		 waitForIt(130, 49, 174, 69);
         myGLCD.setColor(255, 255, 255);
         myGLCD.drawRoundRect(130, 49, 174, 69);
		 myGLCD.drawRoundRect(185, 49, 305, 69);

		if (setScreensaverOnOff == 1) 
		   { setScreensaverOnOff = 0;
             setFont(SMALL, 255, 255, 255, 0, 0, 255);     
             myGLCD.print("OFF", 144, 53);
	 		 myGLCD.setColor(64, 64, 64);
		     myGLCD.fillRoundRect(185, 49, 305, 69);
		     setFont(SMALL, 255, 255, 255, 64, 64, 64);
//		     myGLCD.print("Setting", 217, 53);
			 myGLCD.print(print_text[21], 217, 53);
			 myGLCD.setColor(255, 255, 255);
             myGLCD.drawRoundRect(185, 49, 305, 69);       // screen saver 
		   }
		 else {
		     setScreensaverOnOff = 1;
			 myGLCD.setColor(0, 0, 255);
             myGLCD.fillRoundRect(185, 49, 305, 69);
			 myGLCD.setColor(255, 255, 255);
			 myGLCD.drawRoundRect(185, 49, 305, 69);       
             setFont(SMALL, 255, 255, 255, 0, 0, 255);     
	         myGLCD.print(" ON ", 138, 53);
//		     myGLCD.print("Setting", 217, 53);
			 myGLCD.print(print_text[21], 217, 53);
	      }
	  }

      if ((x>=185) && (x<=229) && (y>=79) && (y<=99))  //display MAX temp ON/OFF
        {
            waitForIt(185, 79, 229, 99);
         	myGLCD.setColor(255, 255, 255);
            myGLCD.drawRoundRect(185, 79, 229, 99);
		if (MAX_Temp_on_off == 1) 
		   { MAX_Temp_on_off =0;
             setFont(SMALL, 255, 255, 255, 0, 0, 255);     
             myGLCD.print("OFF", 199, 83);
		   }
		 else {MAX_Temp_on_off = 1;
             setFont(SMALL, 255, 255, 255, 0, 0, 255);     
	         myGLCD.print(" ON ", 193, 83);   
		      }
	     }

	      if ((x>=185) && (x<=229) && (y>=109) && (y<=129))  //Led Soft start on_off
        {
            waitForIt(185, 109, 229, 129);
			PercentSoftStart = 1;
         	myGLCD.setColor(255, 255, 255);
            myGLCD.drawRoundRect(185, 109, 229, 129);
		if (SoftStartON ==1) 
		   { SoftStartON = 0;
             setFont(SMALL, 255, 255, 255, 0, 0, 255);     
             myGLCD.print("OFF", 199, 113);
		   }
		 else {SoftStartON =1;
             setFont(SMALL, 255, 255, 255, 0, 0, 255);     
	        myGLCD.print(" ON ", 193, 113);   
		      }
	     }

	      if ((x>=185) && (x<=305) && (y>=139) && (y<=159))  //Buzzer ON/OFF
        {
            waitForIt(185, 139, 305, 159);
			myGLCD.setColor(255, 255, 255);
            myGLCD.drawRoundRect(185, 139, 305, 159);
			AlarmLevel+=1;
			if (AlarmLevel >=3) {AlarmLevel =0 ;}
			setFont(SMALL, 255, 255, 255, 0, 0, 255);
			strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[56+AlarmLevel]))); // 
	        myGLCD.print(buffer, 193, 143);
			if (AlarmLevel==0) { 
             digitalWrite(tempAlarmPin, LOW);    // OFF alarm
			 tempAlarmflagW = false;    // clear all error flag
	         tempAlarmflagH1 = false;
	         tempAlarmflagH2 = false;}

	     }

    break;

    case 16:     //------------------ CHANGE Heatsink FAN TEMP ---------------------
      if ((x>=back[0]) && (x<=back[2]) && (y>=back[1]) && (y<=back[3]))  //press back    
        {
         waitForIt(back[0], back[1], back[2], back[3]);
         dispScreen=14;
         clearScreen();
         generalSettingsScreen_1();
        } else
      if ((x>=prSAVE[0]) && (x<=prSAVE[2]) && (y>=prSAVE[1]) && (y<=prSAVE[3])) //press SAVE
        {
         waitForIt(prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3]);
         setTempToBeginHeatsink1FanC=temp2beHFan;
         setTempToBeginHeatsink1FanF=temp2beHFan;
         setTempToBeginHeatsink2FanC=temp2beSFan;
         setTempToBeginHeatsink2FanF=temp2beSFan;
         if (setTempScale==0)
           { setTempToBeginHeatsink1FanF=((1.8*setTempToBeginHeatsink1FanC)+32.05);
             setTempToBeginHeatsink2FanF=((1.8*setTempToBeginHeatsink2FanC)+32.05);}
         if (setTempScale==1)
           { setTempToBeginHeatsink1FanC=((.55556*(setTempToBeginHeatsink1FanF-32))+.05);
             setTempToBeginHeatsink2FanC=((.55556*(setTempToBeginHeatsink2FanF-32))+.05);}
         dispScreen=14;       
         SaveGenSetsToEEPROM();
		 SaveTempToEEPROM();
         clearScreen();
         generalSettingsScreen_1();
        } else
      if ((x>=canC[0]) && (x<=canC[2]) && (y>=canC[1]) && (y<=canC[3]))  //press cancel 
        {
         waitForIt(canC[0], canC[1], canC[2], canC[3]);
//       LEDtestTick = false;
         waveMakerOff = false;     
//       ReadFromEEPROM();     
         dispScreen=0;
         clearScreen();
         mainScreen(true);
        } else      
      setFont(LARGE, 255, 255, 255, 0, 0, 0);
      if ((x>=HoodFanTm[0]) && (x<=HoodFanTm[2]))              //first column
        {
         if ((y>=HoodFanTm[1]) && (y<=HoodFanTm[3]))           //press Heatsink1 Fan Temp -0.1
           {
            temp2beHFan -= 0.1;
            if ((setTempScale==1) && (temp2beHFan <= 68.0)){
              temp2beHFan = 68.0; }
            if ((setTempScale==0) && (temp2beHFan <= 20.0)) {
              temp2beHFan = 20.0; }
            ChangeFanTempsScreen();
			delay(150);
           }
         if ((y>=SumpFanTm[1]) && (y<=SumpFanTm[3]))           //press Heatsink2 Fan Temp -0.1
           {
            temp2beSFan -= 0.1;             
            if ((setTempScale==1) && (temp2beSFan <= 68.0)){
              temp2beSFan = 68.0; }
            if ((setTempScale==0) && (temp2beSFan <= 20.0)) {
              temp2beSFan = 20.0; }
            ChangeFanTempsScreen();
			delay(150);
           }  
		 if ((y>=SoundAlarmTm[1]) && (y<=SoundAlarmTm[3]))        // press Sound Alarm -
           {
            if (setTempScale==1) { setTempToSoundAlarmF -= 1;
			    if (setTempToSoundAlarmF > 210) {setTempToSoundAlarmF = 104;}   
				if (setTempToSoundAlarmF < 104.0) { setTempToSoundAlarmF = 210; }
                                 }
			if (setTempScale==0) { setTempToSoundAlarmC -= 1;
			    if (setTempToSoundAlarmC > 99) {setTempToSoundAlarmC = 40;}
			    if ( setTempToSoundAlarmC < 40.0) { setTempToSoundAlarmC = 99;} 
                                 }
            ChangeFanTempsScreen();
			delay(150);
		   }
        }
      if ((x>=HoodFanTp[0]) && (x<=HoodFanTp[2]))              //second column
        {
         if ((y>=HoodFanTp[1]) && (y<=HoodFanTp[3]))           //press Heatsink1 Fan Temp +0.1
           {
            temp2beHFan += 0.1;
            if ((setTempScale==1) && (temp2beHFan >= 122.0)){
              temp2beHFan = 122.0; }
            if ((setTempScale==0) && (temp2beHFan >= 50.0)) {
              temp2beHFan = 50.0; }
            ChangeFanTempsScreen();
			delay(150);
           }
         if ((y>=SumpFanTp[1]) && (y<=SumpFanTp[3]))           //press Heatsink2 Fan Temp +0.1
           {
            temp2beSFan += 0.1;             
            if ((setTempScale==1) && (temp2beSFan >= 122.0)){
              temp2beSFan = 122.0; }
            if ((setTempScale==0) && (temp2beSFan >= 50.0)) {
              temp2beSFan = 50.0; }
            ChangeFanTempsScreen();
			delay(150);
           }
		 if ((y>=SoundAlarmTp[1]) && (y<=SoundAlarmTp[3]))        // press Sound Alarm +
           {
            if (setTempScale==1) { setTempToSoundAlarmF += 1;
				if (setTempToSoundAlarmF > 210) {setTempToSoundAlarmF = 104;}   
				if (setTempToSoundAlarmF < 104.0) { setTempToSoundAlarmF = 210; }
           
                                 }
			if (setTempScale==0) { setTempToSoundAlarmC += 1;
   	           if (setTempToSoundAlarmC > 99)  { setTempToSoundAlarmC = 40; } // OFF alarm
	           if (setTempToSoundAlarmC < 40.0) { setTempToSoundAlarmC = 99;}
			                     }
            ChangeFanTempsScreen();
			delay(150);
		  }
        }
    break;
    case 17:     //------------------ DIM LEDs AT TEMP ---------------------
      if ((x>=back[0]) && (x<=back[2]) && (y>=back[1]) && (y<=back[3]))  //press back    
        {
         waitForIt(back[0], back[1], back[2], back[3]);
         dispScreen=15;
         clearScreen();
         generalSettingsScreen_2();
        } else
      if ((x>=prSAVE[0]) && (x<=prSAVE[2]) && (y>=prSAVE[1]) && (y<=prSAVE[3])) //press SAVE
        {
         waitForIt(prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3]);
         setLEDsDimTempC=TempLEDsDimTemp;
         setLEDsDimTempF=TempLEDsDimTemp;       
         if (setTempScale==0)
           { setLEDsDimTempF=((1.8*setLEDsDimTempC)+32.5);}
         if (setTempScale==1)
           { setLEDsDimTempC=((.55556*(setLEDsDimTempF-32))+.5);}         
         setLEDsDimPercent=TempLEDsDimPercent;   
         SaveLEDsFailsafeToEEPROM();
         dispScreen=15;
         clearScreen();
         generalSettingsScreen_2();
        } else
      if ((x>=canC[0]) && (x<=canC[2]) && (y>=canC[1]) && (y<=canC[3]))  //press cancel 
        {
         waitForIt(canC[0], canC[1], canC[2], canC[3]);
//         LEDtestTick = false;
         waveMakerOff = false;     
 //        ReadFromEEPROM();     
         dispScreen=0;
         clearScreen();
         mainScreen(true);
        } else

      if ((x>=235) && (x<=260) && (y>=36) && (y<=61))    //press TEMP UP button
        {
         TempLEDsDimTemp++;
         setFont(LARGE, 0, 255, 0, 0, 0, 0);
         if (setTempScale ==0 && TempLEDsDimTemp>=99)
           { TempLEDsDimTemp=99;}
		 else 
			 if(setTempScale ==1 && TempLEDsDimTemp>=210)
				 { TempLEDsDimTemp=210;}
		   myGLCD.printNumI(TempLEDsDimTemp, 181, 55); //189
		 delay(200);
        } else  
      if ((x>=235) && (x<=260) && (y>=66) && (y<=91))    //press TEMP DOWN button
        {
         TempLEDsDimTemp--;
         setFont(LARGE, 0, 255, 0, 0, 0, 0);
		  if (setTempScale ==0 && TempLEDsDimTemp<=40)
           { TempLEDsDimTemp=40;}
		 else 
			 if(setTempScale ==1 && TempLEDsDimTemp<=104)
				 { TempLEDsDimTemp=104;}
             myGLCD.printNumI(TempLEDsDimTemp, 181, 55); 
		 delay(200);
        } else        

      if ((x>=235) && (x<=260) && (y>=117) && (y<=142))  //press % UP button
        {
         TempLEDsDimPercent++;
         setFont(LARGE, 0, 255, 0, 0, 0, 0);
         if (TempLEDsDimPercent>=80)
           { TempLEDsDimPercent=80;}
          myGLCD.printNumI(TempLEDsDimPercent, 181, 136);
          delay(200);
        } else  
      if ((x>=235) && (x<=260) && (y>=147) && (y<=172))  //press % DOWN button
        {
         TempLEDsDimPercent--;
         setFont(LARGE, 0, 255, 0, 0, 0, 0);
         if (TempLEDsDimPercent<=10)
           { TempLEDsDimPercent=10;}
         myGLCD.printNumI(TempLEDsDimPercent, 181, 136);
	     delay(200);
        }        
    break;   

    case 18:     //-------------- SET SCREENSAVER WAIT TIME ----------------
      if ((x>=back[0]) && (x<=back[2]) && (y>=back[1]) && (y<=back[3]))  //press back    
        {
         waitForIt(back[0], back[1], back[2], back[3]);
         dispScreen=15;
         clearScreen();
         generalSettingsScreen_2();
        } else
      if ((x>=prSAVE[0]) && (x<=prSAVE[2]) && (y>=prSAVE[1]) && (y<=prSAVE[3])) //press SAVE
        {
         waitForIt(prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3]);
         setSSmintues=TempSSminutes;
         SaveGenSetsToEEPROM();
         dispScreen=15;
         clearScreen();
         generalSettingsScreen_2();
        } else
      if ((x>=canC[0]) && (x<=canC[2]) && (y>=canC[1]) && (y<=canC[3]))  //press cancel 
        {
         waitForIt(canC[0], canC[1], canC[2], canC[3]);
//         LEDtestTick = false;
         waveMakerOff = false;     
 //        ReadFromEEPROM();     
         dispScreen=0;
         clearScreen();
         mainScreen(true);
        } else  

    if ((x>=206) && (x<=310) && (y>=20) && (y<=40))								 //press "Choose type of screensaver"
        {
          waitForIt(206, 20, 310, 40);
		  ClockType +=1;
		  if (ClockType >3) {ClockType = 0;}
		  ScreensaverSelect();
	   }

	if ((x>=206) && (x<=260) && (y>=51) && (y<=71))								 //press "ON/OFF Screensaver lock"
        { 
		waitForIt(206, 51, 260, 71);
	if (setLockScreen==1) { setLockScreen =0;
		printButton(" OFF", 206, 51, 260, 71, SMALL); }
	else 
		{setLockScreen =1;
		printButton(" ON ", 206, 51, 260, 71, SMALL); }
	    } 

         if ((x>=206) && (x<=260) && (y>=82) && (y<=102))                         //press Brightness button
           { 
            waitForIt(206, 82, 260, 102);
			BrigthnessCount +=1;
			if (BrigthnessCount >4) {BrigthnessCount = 0;}
			setFont(SMALL, 255, 255, 255, 0, 0, 255);
            strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[59+BrigthnessCount]))); // counter = 0/1/2/3/4 -> 0%-25%-50%-75%-100%
			myGLCD.print(buffer, 217, 86);
           }         

      if ((x>=175) && (x<=200) && (y>=107+10) && (y<=132+10))  //press Minute UP button
        {
         TempSSminutes++;
         setFont(LARGE, 0, 255, 0, 0, 0, 0);
         if (TempSSminutes>=99)
           { TempSSminutes=99;}
         if (TempSSminutes>=10)
           { myGLCD.printNumI(TempSSminutes, 129, 126+10);}
         else { myGLCD.printNumI(TempSSminutes, 137, 126+10);}         
		 delay(200);
        } else  
      if ((x>=175) && (x<=200) && (y>=137+10) && (y<=162+10))  //press Minute DOWN button
        {
         TempSSminutes--;
         setFont(LARGE, 0, 255, 0, 0, 0, 0);
         if (TempSSminutes<=1)
           { TempSSminutes=1;}
         if (TempSSminutes>=10)
           { myGLCD.printNumI(TempSSminutes, 129, 126+10);}
         else { myGLCD.printNumI(TempSSminutes, 137, 126+10);
                myGLCD.setColor(0, 0, 0);
                myGLCD.fillRect(129, 126+10, 136, 142+10);
                myGLCD.fillRect(153, 126+10, 161, 142+10);}
		   delay(200);
        }        
    break;    

    case 19:     // ************* not used ******************


	              
    break;

	case 20:   //---------------General setting PAGE 3 ------------------------
				if ((x>=backGS[0]) && (x<=backGS[2]) && (y>=backGS[1]) && (y<=backGS[3]))  //press back    
             {
         waitForIt(backGS[0], backGS[1], backGS[2], backGS[3]);
         dispScreen=15;
         clearScreen();
         generalSettingsScreen_2();
             } else

               if ((x>=canCgs[0]) && (x<=canCgs[2]) && (y>=canCgs[1]) && (y<=canCgs[3]))  //press cancel 
            {
         waitForIt(canCgs[0], canCgs[1], canCgs[2], canCgs[3]);
         waveMakerOff = false;     
         dispScreen=0;
         clearScreen();
         mainScreen(true);
			 } else

               if (x>=205 && x<=305 && y>=19 && y<=39)  //press DETECT button 
			   {
                waitForIt(205, 19, 305, 39);
				clearScreen();
				dispScreen=21;
                DetectDallalsSensors(true);
			   }

               if (x>=205 && x<=305 && y>=49 && y<=69)  //press BACKUP button 
			   {
                waitForIt(205, 49, 305, 69);
				clearScreen();
				dispScreen=22;
			    Backup();}

               if (x>=205 && x<=305 && y>=79 && y<=99 && bitRead(GlobalStatus1Byte,0) == false)  //press RESET button 
			   {
				waitForIt(205, 79, 305, 99);
			    myGLCD.setColor(0, 0, 0);                    
            	myGLCD.fillRoundRect(205, 79, 305, 99);    // clear button position
				bitSet(GlobalStatus1Byte,0);                // set bit for check Y/N button

				myGLCD.setColor(0, 0, 255);                    
				myGLCD.fillRoundRect(205, 79, 245, 99);       // YES
	            myGLCD.fillRoundRect(265, 79, 305, 99);       // NO
				myGLCD.setColor(255, 255, 255);                    
				myGLCD.drawRoundRect(205, 79, 245, 99);       // YES
				myGLCD.drawRoundRect(265, 79, 305, 99);       // NO

				setFont(SMALL, 255, 255, 255, 0, 0, 255);
				myGLCD.print("YES", 205+8, 83);
			    myGLCD.print("NO", 265+16, 83);
			    myGLCD.print("Are You Sure Y/N?       ", 5, 83);
			   } else
               
			    if (x>=205 && x<=245 && y>=88 && y<=108 && bitRead(GlobalStatus1Byte,0) == true)  //press Yes button 
			     { waitForIt(205, 79, 245, 99);

			    EEPROM.write(0, 0);                         // clear fisrs eeprom byte
                setFont(SMALL, 255, 0, 0, 0, 0, 0);
				myGLCD.print(print_text[8], CENTER, 120);   // "Please press on the shield Reset Button"
                myGLCD.print(print_text[9], CENTER, 135);   // "or turn off 
				myGLCD.print(print_text[10],CENTER, 150);   //  and then turn on the controller"
				bitClear(GlobalStatus1Byte,0);              // clear bit for check Y/N button
				} else

				if (x>=265 && x<=305 && y>=79 && y<=99 && bitRead(GlobalStatus1Byte,0) == true)  //press NO button 
				{  waitForIt(265, 79, 305, 99); 
				dispScreen=20;
				clearScreen();
				generalSettingsScreen_3();
                bitClear(GlobalStatus1Byte,0);                // clear bit for check Y/N button
				}

        break;

case 21:  // ----------- autodetect Dallas sensor page -----------------
		
  if ((x>=back[0]) && (x<=back[2]) && (y>=back[1]) && (y<=back[3]) && dispScreen==21 ) 				//press back    
	 {
     waitForIt(back[0], back[1], back[2], back[3]);
       dispScreen=20;
       clearScreen();
       generalSettingsScreen_3();

     } else
	 if ((x>=prSAVE[0]) && (x<=prSAVE[2]) && (y>=prSAVE[1]) && (y<=prSAVE[3]))						//press SAVE
      {
       waitForIt(prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3]);
	     DetectDallalsSensors(false);
	     SaveDallasAddress ();
         dispScreen=0;
         clearScreen();
         mainScreen(true);
	 } else
	    if (x>=200 && x<=300 && y>=20 && y<=40)  // Refresh  button
			   {
                waitForIt(200, 20, 300, 40);      // re-read all sensor data
				DetectDallalsSensors(false);
				}
	 
          if ((x>=165) && (x<=225) && (y>=83+20) && (y<=83+40) && numberOfDevices >=1)	  // sensor N1 button 
		  {
			waitForIt(165, 83+20, 225, 83+40);
			setFont(SMALL, 255, 255, 255, 0, 0, 255); 
			counterB1 +=1;
     		if (counterB1  > 3) {counterB1 = 0;}
			    strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[2+counterB1]))); // counterBX = 0/1/2/3 -> NC/Water/H.Sink1/H.Sink2
	            myGLCD.print(buffer, 169, 83+24);
		  } else

          if ((x>=165) && (x<=225) && (y>=83+50) && (y<=83+70) && numberOfDevices >=2)	  // sensor N2 button 
		  {
			waitForIt(165, 83+50, 225, 83+70);
    		setFont(SMALL, 255, 255, 255, 0, 0, 255);  
			counterB2 +=1;
			if (counterB2  > 3) {counterB2 = 0;}
                strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[2+counterB2]))); // counterBX = 0/1/2/3 -> NC/Water/H.Sink1/H.Sink2
	            myGLCD.print(buffer, 169, 83+54);
		  } else

		  if ((x>=165) && (x<=225) && (y>=83+80) && (y<=83+100) && numberOfDevices ==3)	  // sensor N3 button 
		  {
			waitForIt(165, 83+80, 225, 83+100);
			setFont(SMALL, 255, 255, 255, 0, 0, 255);  
			counterB3 +=1;
			if (counterB3  > 3) {counterB3 = 0;}
                strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[2+counterB3]))); // counterBX = 0/1/2/3 -> NC/Water/H.Sink1/H.Sink2
	            myGLCD.print(buffer, 169, 83+84);
		  } 
        break;

case 22:  // ----------- BACKUP ALL EEPROM SETTING -----------------
	         if ((x>=back[0]) && (x<=back[2]) && (y>=back[1]) && (y<=back[3]) && dispScreen==22 ) 				//press back    
	            {
               waitForIt(back[0], back[1], back[2], back[3]);
				dispScreen=20;

   				clearScreen();
				generalSettingsScreen_3();
			   } else 
//-----------------------------------------
				 if ((x>=205 && x<=305 && y>=74 && y<=94) && dispScreen==22)  //press BACKUP button 
			         { waitForIt(205, 74, 305, 94);

			        myGLCD.setColor(0, 0, 0);								 // clear text area
					myGLCD.fillRoundRect(2, 14, 318, 55);

					 sd.remove("Backup.txt");            // remove old file from card
					 myFile.open("Backup.txt", O_CREAT | O_EXCL | O_WRITE) ;

 					 if (myFile.isOpen())  { 
						 setFont(SMALL, 0, 255, 0, 0, 0, 0);
//             			 myGLCD.print("Writing to file Backup.txt", 5, 24);
						 strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[0]))); 
						 myGLCD.print(buffer, 5, 24);

						 for (int i=0; i<=4095; i++) 
                        { byte TEMP = EEPROM.read(i);   // readed data in DEC format 
                           myFile.print(TEMP, DEC);     // store to file in DEC   
						   myFile.print(','); }         // store separator "," between bytes

   							myFile.close();
							setFont(SMALL, 0, 255, 0, 0, 0, 0);
//							myGLCD.print("Backup done.                 ", 5, 41); 
							strcpy_P(buffer, (char*)pgm_read_word_near(&(Text_table[1]))); 
						    myGLCD.print(buffer, 5, 41);

					        } else
					          {	setFont(SMALL, 255, 0, 0, 0, 0, 0);
								myGLCD.print("error opening file Backup.txt", 5, 41); }
         	        } else

//------------------------------------------------------------------------------                  
 				  if ((x>=15 && x<=115 && y>=74 && y<=94) && dispScreen==22)  //press RESTORE button 
			         { waitForIt(15, 74, 115, 94);

				       myGLCD.setColor(0, 0, 0);								 // clear text area
					   myGLCD.fillRoundRect(2, 14, 318, 55);

// re-open the file for reading:

				if (myFile.open("Backup.txt", O_READ)) {
                    setFont(SMALL, 0, 255, 0, 0, 0, 0);
             	    myGLCD.print("Open file Backup.txt      ", 5, 24);
					myGLCD.print("Please Wait.....          ", 5, 41);

					int TEMP;
					int i=0;
                    byte SD_buff[3];
					byte k=0;
// read from the file until there's nothing else in it:
				    while ((TEMP = myFile.read()) > 0)  // readed data in ASCII only, need convert ASCII to DEC
					{
//					Serial.write((char)TEMP);		    // output to serial port 			
					if (TEMP != 44 && k<=2) {
						TEMP= TEMP -'0';                //convert ASCII to DEC
						SD_buff[k]= TEMP;
						k++; 
					  }else 
					    {
						int Result = SD_buff[0]*100 + SD_buff[1]*10 + SD_buff[2];  // convert three consecutive bytes to one decimal
						if (k ==2 ) {Result = Result/10;}                          // before save to eeprom    
						if (k ==1 ) {Result = Result/100;}

       					EEPROM.write(i, Result);        // store data to EEPROM

						i +=1; k=0;
						SD_buff[0]=0;                   // clean buffer before new read
						SD_buff[1]=0;
						SD_buff[2]=0;
					   }
					}
					myFile.close();
					ReadDallasAddress ();				// read temp sensor address from eeprom
					ReadLedFromEEPROM();				// read led setting from EEPROM
					ReadFromEEPROM();					// read other setting from eeprom
					
					setFont(SMALL, 0, 255, 0, 0, 0, 0);
				    myGLCD.print("Restore done.                ", 5, 41); 
				}  else{
    				setFont(SMALL, 255, 0, 0, 0, 0, 0);
				    myGLCD.print("error opening file Backup.txt", 5, 41);}	 
			}
	    break;

//---------------- LED Preset -----------------------------------
case 23:
	 if ((x>=back[0]) && (x<=back[2]) && (y>=back[1]) && (y<=back[3]))   //press back    
      {
       waitForIt(back[0], back[1], back[2], back[3]);
       dispScreen=4;
       clearScreen();
       ledTestOptionsScreen();        // display buttons "Rapid test"/"Control Individual Leds"/"Preset"
      }      
/*
    if ((x>=canC[0]) && (x<=canC[2]) && (y>=canC[1]) && (y<=canC[3]))   //press CANCEL
      {
       waitForIt(canC[0], canC[1], canC[2], canC[3]);
       dispScreen=0;
       clearScreen();
       mainScreen(true);
      }
*/
	if ((x>=prSAVE[0]) && (x<=prSAVE[2]) && (y>=prSAVE[1]) && (y<=prSAVE[3]))						//press SAVE
      {
       waitForIt(prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3]);
	   if (bitRead(GlobalStatus2Byte,0)== 1) {AddressShift=0;}
	   if (bitRead(GlobalStatus2Byte,1)== 1) {AddressShift=9;}
	   if (bitRead(GlobalStatus2Byte,2)== 1) {AddressShift=18;}
	   if (bitRead(GlobalStatus2Byte,3)== 1) {AddressShift=27;}
//     if ((GlobalStatus2Byte & 0x0F) !=0 ) {SaveLEDPresetToEEPROM();} 
	   SaveLEDPresetToEEPROM();
	  }

	if ((x>=LedPres1[0]) && (x<=LedPres1[2]) && (y>=LedPres1[1]) && (y<=LedPres1[3]))   //press Preset N1
      {
		  waitForIt(LedPres1[0], LedPres1[1], LedPres1[2], LedPres1[3]);
		  if (bitRead(GlobalStatus2Byte,0)== 0){
		  printButton("Preset 1", LedPres1[0], LedPres1[1], LedPres1[2], LedPres1[3], SMALL, GREEN_BAC); // ON preset 1 
		  printButton("Preset 2", LedPres2[0], LedPres2[1], LedPres2[2], LedPres2[3], SMALL);  
		  printButton("Preset 3", LedPres3[0], LedPres3[1], LedPres3[2], LedPres3[3], SMALL);  
		  printButton("Preset 4", LedPres4[0], LedPres4[1], LedPres4[2], LedPres4[3], SMALL);
		  GlobalStatus2Byte = (GlobalStatus2Byte & 0xF0 | 0x1); //set flag Preset1, clear 2..4
		  colorLEDtest = true;
		  }
		  else {printButton("Preset 1", LedPres1[0], LedPres1[1], LedPres1[2], LedPres1[3], SMALL); // OFF preset
		  colorLEDtest = false;
		  bitClear(GlobalStatus2Byte,0);} // clear flag Preset1
		  AddressShift = 0;
		  ReadLEDPresetFromEEPROM();
		  PresetLedScreen(false);         // preset led windows
	  }
	  
	if ((x>=LedPres2[0]) && (x<=LedPres2[2]) && (y>=LedPres2[1]) && (y<=LedPres2[3]))   //press Preset N2
      {
		  waitForIt(LedPres2[0], LedPres2[1], LedPres2[2], LedPres2[3]);
		  if (bitRead(GlobalStatus2Byte,1)== 0){
		  printButton("Preset 1", LedPres1[0], LedPres1[1], LedPres1[2], LedPres1[3], SMALL);
		  printButton("Preset 2", LedPres2[0], LedPres2[1], LedPres2[2], LedPres2[3], SMALL, GREEN_BAC); // ON preset 2   
		  printButton("Preset 3", LedPres3[0], LedPres3[1], LedPres3[2], LedPres3[3], SMALL);  
		  printButton("Preset 4", LedPres4[0], LedPres4[1], LedPres4[2], LedPres4[3], SMALL);
  		  GlobalStatus2Byte = (GlobalStatus2Byte & 0xF0 | 0x2); //set flag Preset2, clear 1,3,4  
		  colorLEDtest = true;
		  }
		  else {printButton("Preset 2", LedPres2[0], LedPres2[1], LedPres2[2], LedPres2[3], SMALL); // OFF preset
		  colorLEDtest = false;
		  bitClear(GlobalStatus2Byte,1);} // clear flag Preset2
		  AddressShift = 9;
		  ReadLEDPresetFromEEPROM(); 
		  PresetLedScreen(false);         // preset led windows
	  }

	if ((x>=LedPres3[0]) && (x<=LedPres3[2]) && (y>=LedPres3[1]) && (y<=LedPres3[3]))   //press Preset N3
      {
		  waitForIt(LedPres3[0], LedPres3[1], LedPres3[2], LedPres3[3]);
		  if (bitRead(GlobalStatus2Byte,2)== 0){
		  printButton("Preset 1", LedPres1[0], LedPres1[1], LedPres1[2], LedPres1[3], SMALL);
		  printButton("Preset 2", LedPres2[0], LedPres2[1], LedPres2[2], LedPres2[3], SMALL);  
		  printButton("Preset 3", LedPres3[0], LedPres3[1], LedPres3[2], LedPres3[3], SMALL, GREEN_BAC); // ON preset 3   
		  printButton("Preset 4", LedPres4[0], LedPres4[1], LedPres4[2], LedPres4[3], SMALL);
		  GlobalStatus2Byte = (GlobalStatus2Byte & 0xF0| 0x4); //set flag Preset3, clear 1,2,4  
		  colorLEDtest = true;
		  }
		  else {printButton("Preset 3", LedPres3[0], LedPres3[1], LedPres3[2], LedPres3[3], SMALL); // OFF preset
		  colorLEDtest = false;
		  bitClear(GlobalStatus2Byte,2);} // clear flag Preset3
		  AddressShift = 18;
		  ReadLEDPresetFromEEPROM(); 
		  PresetLedScreen(false);         // preset led windows
	  }

	if ((x>=LedPres4[0]) && (x<=LedPres4[2]) && (y>=LedPres4[1]) && (y<=LedPres4[3]))   //press Preset N4
      {
		  waitForIt(LedPres4[0], LedPres4[1], LedPres4[2], LedPres4[3]);
		  if (bitRead(GlobalStatus2Byte,3)== 0){
		  printButton("Preset 1", LedPres1[0], LedPres1[1], LedPres1[2], LedPres1[3], SMALL);
		  printButton("Preset 2", LedPres2[0], LedPres2[1], LedPres2[2], LedPres2[3], SMALL);  
		  printButton("Preset 3", LedPres3[0], LedPres3[1], LedPres3[2], LedPres3[3], SMALL);  
		  printButton("Preset 4", LedPres4[0], LedPres4[1], LedPres4[2], LedPres4[3], SMALL, GREEN_BAC); // ON preset 4 
		  GlobalStatus2Byte = (GlobalStatus2Byte & 0xF0 | 0x8);   //set flag Preset4, clear 1..3  
		  colorLEDtest = true;
		  }
		  else {printButton("Preset 4", LedPres4[0], LedPres4[1], LedPres4[2], LedPres4[3], SMALL); // OFF preset
		  colorLEDtest = false;
		  bitClear(GlobalStatus2Byte,3);} // clear flag Preset4
		  AddressShift = 27;
		  ReadLEDPresetFromEEPROM(); 
		  PresetLedScreen(false);         // preset led windows
	  }

	if ((y>=TopSldY)&&(y<=BotSldY) && (colorLEDtest==true))  //change value with Slider Bars touch
	{
		TopSldY=53, BotSldY=TopSldY+100; 
		SliderSwitch  = false;
      for (byte i=0; i<8; i++) 
        {    sbX1=(i*35)+4+18; sbX2=(i*35)+34+18;
           if (x>=sbX1+5 && x<=sbX2-5)                  // desrease slider touchable area (-5pix)
            {											// WHITE=1, BLUE=2, ROYAL=3, RED=4,
														// ULTRA=5, TV=6, MOON=7;
                  						             	// CYAN=8,  YELLOW=9
														// slider width 30 pix, clearens between sliders 5pix

      	  if (i==0 && bitRead(LedShannelStatusByte,5) == true) 
		      { sbR= rgbCh6[0]; sbG= rgbCh6[1]; sbB= rgbCh6[2];	 			       // TV colour	
		     tvcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}
	      if (i==1 && bitRead(LedShannelStatusByte,3) == true) 
		      { sbR= rgbCh5[0]; sbG= rgbCh5[1]; sbB= rgbCh5[2];      				   // DR colour	
		     rcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2); }
		  if (i==2 && bitRead(LedShannelStatusByte,0) == true) 
		      { sbR= rgbCh2[0]; sbG= rgbCh2[1]; sbB= rgbCh2[2]; 			   // CW colour	
		      wcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}
	      if (i==3 && bitRead(LedShannelStatusByte,1) == true) 
		      { sbR= rgbCh4[0]; sbG= rgbCh4[1]; sbB= rgbCh4[2]; 				   // BL colour
              bcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}
	      if (i==4 && bitRead(LedShannelStatusByte,2) == true) 
		      { sbR= rgbCh3[0]; sbG= rgbCh3[1]; sbB= rgbCh3[2]; 				   // RBL colour
              rbcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}
	      if (i==5 && bitRead(LedShannelStatusByte,4) == true)  
		      { sbR= rgbCh1[0]; sbG= rgbCh1[1]; sbB= rgbCh1[2];			   // UV colour
              uvcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}
	      if (i==6 && bitRead(LedShannelStatusByte,6) == true)  
		      { sbR= rgbCh0[0]; sbG= rgbCh0[1]; sbB= rgbCh0[2];			       // CY colour
              cycol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}
	      if (i==7 && bitRead(LedShannelStatusByte,7) == true)  
		      { sbR= rgbCh7[0]; sbG= rgbCh7[1]; sbB= rgbCh7[2];			       // Yellow colour
              yelcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);}

			  LED_levels_output();
		  }
     }
  } else

    if ((y>=29+2) && (y<=44-2) && (colorLEDtest==true)) //UP Buttons were touched, desrease button touchable area (2pix)
      { 
 			TopSldY=53, BotSldY=TopSldY+100; 
			SliderSwitch  = true;

          for (byte i=0; i<8; i++) 
        { 	sbX1=(i*35)+4+18; sbX2=(i*35)+34+18;
          if (x>=sbX1 && x<=sbX2)                       // slider width 30 pix, clearens 5pix
            {											// WHITE=1, BLUE=2, ROYAL=3, RED=4,
														// ULTRA=5, TV=6, MOON=7;
                  						             	// CYAN=8,  YELLOW=9
     	  if (i==0 && bitRead(LedShannelStatusByte,5) == true) 
		     { sbR= rgbCh6[0]; sbG= rgbCh6[1]; sbB= rgbCh6[2];	tSlide = tvcol_out; tSlide+=1; // TV colour	
		        tvcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
			     tSlide= tvcol_out; }
	      if (i==1 && bitRead(LedShannelStatusByte,3) == true) 
		     { sbR= rgbCh5[0]; sbG= rgbCh5[1]; sbB= rgbCh5[2]; tSlide= rcol_out; tSlide+=1;   // DR colour	
		        rcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
			     tSlide= rcol_out; } 
		  if (i==2 && bitRead(LedShannelStatusByte,0) == true) 
		     { sbR= rgbCh2[0]; sbG= rgbCh2[1]; sbB= rgbCh2[2]; tSlide= wcol_out; tSlide+=1; 			   // CW colour	
		        wcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		         tSlide= wcol_out; }
	      if (i==3 && bitRead(LedShannelStatusByte,1) == true) 
		     { sbR= rgbCh4[0]; sbG= rgbCh4[1]; sbB= rgbCh4[2]; tSlide= bcol_out; tSlide+=1; 				   // BL colour
                bcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		         tSlide= bcol_out;}
	      if (i==4 && bitRead(LedShannelStatusByte,2) == true) 
		     { sbR= rgbCh3[0]; sbG= rgbCh3[1]; sbB= rgbCh3[2]; tSlide= rbcol_out; tSlide+=1; 				   // RBL colour
                rbcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		         tSlide= rbcol_out;}
	      if (i==5 && bitRead(LedShannelStatusByte,4) == true)  
		     { sbR= rgbCh1[0]; sbG= rgbCh1[1]; sbB= rgbCh1[2]; tSlide= uvcol_out; tSlide+=1; 			   // UV colour
                uvcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		         tSlide= uvcol_out;}
	      if (i==6 && bitRead(LedShannelStatusByte,6) == true)  
		     { sbR= rgbCh0[0]; sbG= rgbCh0[1]; sbB= rgbCh0[2]; tSlide= cycol_out; tSlide+=1;  		       // CY colour
                cycol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		          tSlide= cycol_out; }
	      if (i==7 && bitRead(LedShannelStatusByte,7) == true)  
		     { sbR= rgbCh7[0]; sbG= rgbCh7[1]; sbB= rgbCh7[2]; tSlide= yelcol_out; tSlide+=1; 			       // Yellow colour
                yelcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		         tSlide= yelcol_out; }
		      delay(100);                        //delay 50msec after touch UP/DOWN button
		  	  LED_levels_output();
             }
          }
              SliderSwitch  = false;   

      } else
    if ((y>=174+2) && (y<=187-2) && (colorLEDtest==true)) //DOWN Buttons were touched,desrease button touchable area (2pix)
      {  
			TopSldY=53, BotSldY=TopSldY+100; 
			SliderSwitch  = true;
             for (byte i=0; i<8; i++) 
        { 	sbX1=(i*35)+4+18; sbX2=(i*35)+34+18;
          if (x>=sbX1 && x<=sbX2)                       // slider width 30 pix, clearens 5pix            		
		{	                                            // WHITE=1, BLUE=2, ROYAL=3, RED=4,
														// ULTRA=5, TV=6, MOON=7;
                  						             	// CYAN=8,  YELLOW=9
       	  if (i==0 && bitRead(LedShannelStatusByte,5) == true) 
		        { sbR= rgbCh6[0]; sbG= rgbCh6[1]; sbB= rgbCh6[2];	tSlide = tvcol_out; tSlide-=1;	          // TV colour	
		           tvcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		            tSlide = tvcol_out; }
	      if (i==1 && bitRead(LedShannelStatusByte,3) == true) 
		        { sbR= rgbCh5[0]; sbG= rgbCh5[1]; sbB= rgbCh5[2]; tSlide = rcol_out;	tSlide-=1;                 // DR colour	
		           rcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		            tSlide = rcol_out ; }
		  if (i==2 && bitRead(LedShannelStatusByte,0) == true) 
		        { sbR= rgbCh2[0]; sbG= rgbCh2[1]; sbB= rgbCh2[2]; tSlide = wcol_out; tSlide-=1;			   // CW colour	
		           wcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		             tSlide= wcol_out; }
	      if (i==3 && bitRead(LedShannelStatusByte,1) == true) 
		        { sbR= rgbCh4[0]; sbG= rgbCh4[1]; sbB= rgbCh4[2]; tSlide = bcol_out; tSlide-=1;				   // BL colour
                   bcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		             tSlide= bcol_out; }
  	      if (i==4 && bitRead(LedShannelStatusByte,2) == true) 
		        { sbR= rgbCh3[0]; sbG= rgbCh3[1]; sbB= rgbCh3[2]; tSlide = rbcol_out; tSlide-=1; 				   // RBL colour
                   rbcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		            tSlide= rbcol_out; } 
	      if (i==5 && bitRead(LedShannelStatusByte,4) == true)
		        { sbR= rgbCh1[0]; sbG= rgbCh1[1]; sbB= rgbCh1[2]; tSlide = uvcol_out; tSlide-=1;			   // UV colour
                   uvcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		             tSlide= uvcol_out; } 
	      if (i==6 && bitRead(LedShannelStatusByte,6) == true)
		        { sbR= rgbCh0[0]; sbG= rgbCh0[1]; sbB= rgbCh0[2]; tSlide = cycol_out; tSlide-=1;			       // CY colour
                    cycol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		              tSlide= cycol_out; } 
	      if (i==7 && bitRead(LedShannelStatusByte,7) == true)
		        { sbR= rgbCh7[0]; sbG= rgbCh7[1]; sbB= rgbCh7[2]; tSlide = yelcol_out; tSlide-=1;			       // Yellow colour
                    yelcol_out= SliderBarsForChange( TopSldY, BotSldY, y, sbR, sbG, sbB, sbX1, sbX2);
		              tSlide= yelcol_out; }
		      delay(100);                       //delay 50msec after touch UP/DOWN button
		  	  LED_levels_output();
             }
          }
       }
	         SliderSwitch  = false;   

break; 

case 24:     // ************* not used ******************
break;

case 25:     // ************* Weather control ******************

	  
	if ((x>=CloudCtrl[0]) && (x<=CloudCtrl[2]) && (y>=CloudCtrl[1]) && (y<=CloudCtrl[3]) && clouDonOff== 1) //press Cloud setting
        { waitForIt(CloudCtrl[0], CloudCtrl[1], CloudCtrl[2], CloudCtrl[3]);
          dispScreen=26; 
 //         timOBLtmp = timOBL;
 //         deltaOBLtmp = deltaOBL;
  //        razOBLtmp = razOBL;
          clearScreen();  
		  clouDScreen(true); }

	if ((x>=CloudCtrlON[0]) && (x<=CloudCtrlON[2]) && (y>=CloudCtrlON[1]) && (y<=CloudCtrlON[3]))    //press Cloud on/off
        { waitForIt(CloudCtrlON[0], CloudCtrlON[1], CloudCtrlON[2], CloudCtrlON[3]);

	if (clouDonOff== 1 ) 
	      {clouDonOff=0;          // cloud off
	        storMonOff=0;         // Storm off
			weeStart = 2;
			OBLoNoff=0;
            DimCloud = dimmW;}
	else {clouDonOff=1;           // cloud on
         	weezleONoff=1;  
			OBLoNoff=1;
            DimCloud = 100;}
			wthScreen ();
	     }

		 if ((x>=StormCtrl[0]) && (x<=StormCtrl[2]) && (y>=StormCtrl[1]+30) && (y<=StormCtrl[3]+30)) //press Start/Stop test
        { waitForIt(StormCtrl[0], StormCtrl[1]+30, StormCtrl[2], StormCtrl[3]+30);
		  if (bitRead(GlobalStatus3Byte,0) == 0){
			  bitSet(GlobalStatus3Byte,0);
			  printButton(print_text[39], StormCtrl[0], StormCtrl[1]+30, StormCtrl[2], StormCtrl[3]+30, SMALL, GREEN_BAC);  //"Start" (BLUE_BAC)
		  weeStart=1; 
		  clouDonOff =1;
		  DimCloud = 100;
		  RampRatioCalc();

		  }
		  else { bitClear(GlobalStatus3Byte,0);
//			  printButton(print_text[40], StormCtrl[0], StormCtrl[1]+30, StormCtrl[2], StormCtrl[3]+30, SMALL);  //"Stop" (BLUE_BAC)
		    printButton(print_text[40], StormCtrl[0], StormCtrl[1]+30, StormCtrl[2], StormCtrl[3]+30, SMALL, GREEN_BAC);  //"Stop" (BLUE_BAC)
			  weeStart=2;
//		      clouDonOff =0;
			    }
          }

	  
	if ((x>=StormCtrl[0]) && (x<=StormCtrl[2]) && (y>=StormCtrl[1]) && (y<=StormCtrl[3]) && clouDonOff== 1 && storMonOff== 1) //press Storm setting
        { waitForIt(StormCtrl[0], StormCtrl[1], StormCtrl[2], StormCtrl[3]);
          dispScreen=27; 
          timGROZtmp=timGROZ;
          clearScreen(); 
		  storMScreen(true); }

	if ((x>=StormCtrlON[0]) && (x<=StormCtrlON[2]) && (y>=StormCtrlON[1]) && (y<=StormCtrlON[3])&& clouDonOff== 1)    //press Storm on/off
        { waitForIt(StormCtrlON[0], StormCtrlON[1], StormCtrlON[2], StormCtrlON[3]);

	if (storMonOff== 1 ) 
	      {storMonOff=0;          // Storm off
//           weeStart = 2; 
//       	DimCloud = dimmW; 
            stormGR = 0;  }
	       else {storMonOff=1;          // Storm on
         	  stormGR = 1;}
			  wthScreen ();
	      }

break;

case 26:     // ************* Cloud Control ******************

// ---------------- increase/decrease values -------------	
		CloudDayQantity = PlusMinusCount (false, 200, 88, 1, 5, 1, CloudDayQantity);      // quant Cloud/day
		CloudDuration = PlusMinusCount (false, 200, 124, 15, 90, 1, CloudDuration); //duration cloud
		CloudWeekQantity = PlusMinusCount (false, 200, 163, 1, 7, 1, CloudWeekQantity);     // cloudy day
	
//CalcCoud();

	if ((x>=canCgs[0]) && (x<=canCgs[2]) && (y>=canCgs[1]) && (y<=canCgs[3]))   //press CANCEL
      {
			waitForIt(canCgs[0], canCgs[1], canCgs[2], canCgs[3]);
			dispScreen=0;
			clearScreen();
			mainScreen(true); }

        if ((x>=backGS[0]) && (x<=backGS[2]) && (y>=backGS[1]) && (y<=backGS[3]))           //press back    
        { waitForIt(backGS[0], backGS[1], backGS[2], backGS[3]);                                   
		      dispScreen=25; 
    		  clearScreen(); 
			  wthScreen (true);  }

        if ((x>=prSAVEgs[0]) && (x<=prSAVEgs[2]) && (y>=prSAVEgs[1]) && (y<=prSAVEgs[3])) //press SAVE
        { waitForIt(prSAVEgs[0], prSAVEgs[1], prSAVEgs[2], prSAVEgs[3]);
              timOBL = timOBLtmp;
              deltaOBL = deltaOBLtmp;
              razOBL = razOBLtmp;
			  planPOG ();
//        dispScreen=1; 
//		  clearScreen(); 
//		  menuScreen(); 
		        }

break;

case 27:     // ************* Storm Control ******************

// ---------------- increase/decrease values -------------	
		timGROZtmp = PlusMinusCount (true, 200, 88, 1, 10, 1, timGROZtmp);      // storm duration 
	
        if ((x>=backGS[0]) && (x<=backGS[2]) && (y>=backGS[1]) && (y<=backGS[3]))           //press back    
        { waitForIt(backGS[0], backGS[1], backGS[2], backGS[3]);                                    
          dispScreen=25;
		  clearScreen();
		  wthScreen (true);  }

	if ((x>=canCgs[0]) && (x<=canCgs[2]) && (y>=canCgs[1]) && (y<=canCgs[3]))   //press CANCEL
      {
			waitForIt(canCgs[0], canCgs[1], canCgs[2], canCgs[3]);
			dispScreen=0;
			clearScreen();
			mainScreen(true); }
          
        if ((x>=prSAVE[0]) && (x<=prSAVE[2]) && (y>=prSAVE[1]) && (y<=prSAVE[3])) //press SAVE
        { waitForIt(prSAVE[0], prSAVE[1], prSAVE[2], prSAVE[3]);
          timGROZ = timGROZtmp;
//        SaveLEDsFailsafeToEEPROM(); 
//        dispScreen=1;
//		  clearScreen();
//		  menuScreen();
		   }

          if ((StormCtrlONNight[0]) && (StormCtrlONNight[2]) && (StormCtrlONNight[1]) && (StormCtrlONNight[3]))
		  { waitForIt(StormCtrlONNight[0], StormCtrlONNight[1], StormCtrlONNight[2], StormCtrlONNight[3]);     //press ON

		  if (NightGR==1)                                                                                                             // Storm on/off
             { printButton(print_text[23], StormCtrlONNight[0], StormCtrlONNight[1], StormCtrlONNight[2], StormCtrlONNight[3], SMALL); //"OFF"
		        GROZANight=0; 
			    NightGR=0;   } 
       else  { printButton(print_text[22], StormCtrlONNight[0], StormCtrlONNight[1], StormCtrlONNight[2], StormCtrlONNight[3], SMALL); //"ON" 
                GROZANight=1;
     			NightGR=1;   }  
		   }

break;

case 28:     // ************* Weather test ******************

break;
	}
  }
}
/********************************* END of TOUCH SCREEN loop ****************************/


/**************************************** SETUP **************************************/
void setup()
{
//wdt_disable();

  Serial.begin(9600);

/* --------timer setting for change frequency--------
 Timer 0
 13             OC0A    
 4				OC0B    //Caution: this one directly effects major timing {i.e delay and millis} DO NOT CHANGE  
 Timer 1
 11				OC1A   
 12				OC1B   
 Timer 2 
 10				OC2A   
 9				OC2B
 Timer 3
 5				OC3A   
 2				OC3B   
 3				OC3C   
 Timer 4 
 6				OC4A   
 7				OC4B
 8				OC4C
 Timer 5
 46				OC5A   
 45				OC5B	
 44				OC5C    

//  Timers 0-5 clock for PWM via analogWrite(PIN, Value);
TIMER 0  CLKt=Fosc256 = 62500, Phase Correct PWM Mode
Value    Divisor     Frequency
0×01     1           62500 hz
0×02     8           7812.5 hz
0×03     64          976.5625 hz      // default
0×04     256         244.140625 hz
0×05     1024        61.03515625 hz
Code:    TCCR0B = (TCCR0B & 0xF8) | value ;

TIMER 1, 3, 4, 5  CLKt=Fosc/512 = 31250, Phase Correct PWM Mode
Value    Divisor     Frequency
0×01     1           31250 hz
0×02     8           3906.25 hz
0×03     64          488.28125 hz
0×04     256         122.0703125 hz
0×05     1024        30.517578125 hz
Code:    TCCR1B = (TCCR1B & 0xF8) | value ;
Code:    TCCR3B = (TCCR3B & 0xF8) | value ;
Code:    TCCR4B = (TCCR4B & 0xF8) | value ;
Code:    TCCR5B = (TCCR5B & 0xF8) | value ;

TIMER 2  CLKt=Fosc/512 = 31250, Phase Correct PWM Mode
Value    Divisor     Frequency
0×01     1           31250 hz
0×02     8           3906.25 hz
0×03     32          976.5625 hz
0×04     64          488.28125 hz
0×05     128         244.140625 hz
0×06     256         122.0703125 hz
0×07     1024        30.517578125 hz
Code:    TCCR2B = (TCCR2B & 0xF8) | value ;
*/


#ifdef Timers_8bit
  TCCR1B = (TCCR1B & 0xF8) | PWM_FRQ_Value; // pin 12, 13  
  TCCR2B = (TCCR2B & 0xF8) | PWM_FRQ_ValueT2; // pin 10    
  TCCR3B = (TCCR3B & 0xF8) | PWM_FRQ_Value; // pin 2,3,5
  TCCR4B = (TCCR4B & 0xF8) | PWM_FRQ_Value; // pin 6,7,8
  TCCR5B = (TCCR5B & 0xF8) | PWM_FRQ_Value_Fan; // 30hz  pin 44, 45, 46 for FANs
#endif

#ifdef Timers_8_11bit
  //**************** 8 and 11 bit timer setting **********************************

#ifdef Standard_shield
  TCCR2B = (TCCR2B & 0xF8) | PWM_FRQ_ValueT2;   // pin 10  8bit
  TCCR5B = (TCCR5B & 0xF8) | PWM_FRQ_Value_Fan; // 30hz  pin 44, 45, 46 for FANs 8bit

// set 11 bit timer setting
  TCCR1A = B00000010;		// mode 14Fast PWM timer 1
  TCCR4A = B00000010;		// mode 14Fast PWM timer4
//  TCCR1B = B00011010;		// clk/8 prescalering
//  TCCR4B = B00011010;		// clk/8 prescalering
// set timer mode
  TCCR4B = B00011000;
  TCCR1B = B00011000;
// set prescaler value
  TCCR1B = TCCR1B | PWM_FRQ_Value;  // pin 11, 12
  TCCR4B = TCCR4B | PWM_FRQ_Value;  // pin 6, 7, 8
    
  OCR1A = 0;
  OCR1B = 0;
  OCR4B = 0;
  OCR4C = 0;
  
  ICR1 = 2005;
  ICR4 = 2005;

  cbi_mix( PORTB, 5 ); //Timer1, port 11 
  sbi_mix( DDRB , 5 ); 
  cbi_mix( PORTB, 6 ); //Timer1, port 12
  sbi_mix( DDRB , 6 ); //
  cbi_mix( PORTH, 4 ); //Timer4, port 7 
  sbi_mix( DDRH , 4 ); //
  cbi_mix( PORTH, 5 ); //Timer4, port 8
  sbi_mix( DDRH , 5 ); //  

#else        // For Aquashield V2 and V3
// 8 bit timer setting
  TCCR2B = (TCCR2B & 0xF8) | PWM_FRQ_ValueT2;   // pin 9, 10  8bit
  TCCR5B = (TCCR5B & 0xF8) | PWM_FRQ_Value_Fan; // 30hz  pin 44, 45, 46 for FANs 8bit

// 11bit timer setting
// set timer mode 14 - fast PWM
  TCCR4A = B00000010;		// mode 14Fast PWM timer4   
  TCCR3A = B00000010;		// mode 14Fast PWM timer3   
  TCCR1A = B00000010;		// mode 14Fast PWM timer1
  TCCR4B = B00011000;
  TCCR3B = B00011000;
  TCCR1B = B00011000;
// set prescaler value
  TCCR1B = TCCR1B | PWM_FRQ_Value;  // pin 11, 12
  TCCR3B = TCCR3B | PWM_FRQ_Value;  // pin 2, 3, 
  TCCR4B = TCCR4B | PWM_FRQ_Value;  // pin 6,
    
  OCR1A = 0;
  OCR1B = 0;
  OCR3A = 0;
  OCR3B = 0;
  OCR3C = 0;
  OCR4A = 0;

  ICR1 = 2005;
  ICR3 = 2005;
  ICR4 = 2005;

  cbi_mix( PORTB, 5 ); //Timer1, port 11 
  sbi_mix( DDRB , 5 ); 
  cbi_mix( PORTB, 6 ); //Timer1, port 12
  sbi_mix( DDRB , 6 ); //

  cbi_mix( PORTE, 3 ); //Timer3, port 5
  sbi_mix( DDRE , 3 ); //
  cbi_mix( PORTE, 4 ); //Timer3, port 2
  sbi_mix( DDRE , 4 ); //
  cbi_mix( PORTE, 5 ); //Timer3, port 3
  sbi_mix( DDRE , 5 ); //
  cbi_mix( PORTH, 3 ); //Timer4, port 6
  sbi_mix( DDRH , 3 ); //
#endif
#endif

#ifdef Timers_11bit
  //**************** 11 bit timer setting **********************************

  TCCR2B = (TCCR2B & 0xF8) | PWM_FRQ_Value_Fan+2 ; // 30Hz  pin 10, 9  8bit
  TCCR5B = (TCCR5B & 0xF8) | PWM_FRQ_Value_Fan;    // 30hz  pin 44, 45, 46 for FANs 8bit

/* B00011001 - 8khz  TCCRXB register, no prescaling 
   B00011010 - 1khz  TCCRXB register, clkI/O/8
   B00011011 - 125hz TCCRXB register, clkI/O/64
   B00011100 - 31hz  TCCRXB register, clkI/O/256

  TCCR4A = B00000010;		// mode 14 Fast PWM timer4   WGM41=1, WGM40=0 
  TCCR4B = B00011010;		//  clkI/O/8                 WGM43=1, WGM42=1 + CS42..CS40 =10
  TCCR3A = B00000010;		// mode 14 Fast PWM timer3
  TCCR3B = B00011010;		//  clkI/O/8
  TCCR1A = B00000010;		// mode 14 Fast PWM timer 1
  TCCR1B = B00011010;		//  clkI/O/8
*/
// set timer mode 14 - fast PWM
  TCCR4A = B00000010;		// mode 14Fast PWM timer4   
  TCCR3A = B00000010;		// mode 14Fast PWM timer3   
  TCCR1A = B00000010;		// mode 14Fast PWM timer1
  TCCR4B = B00011000;
  TCCR3B = B00011000;
  TCCR1B = B00011000;
// set prescaler value
  TCCR1B = TCCR1B | PWM_FRQ_Value;  // pin 11, 12
  TCCR3B = TCCR3B | PWM_FRQ_Value;  // pin 2, 3, 
  TCCR4B = TCCR4B | PWM_FRQ_Value;  // pin 6, 7, 8

  OCR1A = 0;
  OCR1B = 0;
  OCR3A = 0;
  OCR3B = 0;
  OCR3C = 0;
  OCR4A = 0;
  OCR4B = 0;
  OCR4C = 0;

  ICR1 = 2005;
  ICR3 = 2005;
  ICR4 = 2005;

  cbi_mix( PORTB, 5 ); //Timer1, port 11 
  sbi_mix( DDRB , 5 ); 
  cbi_mix( PORTB, 6 ); //Timer1, port 12
  sbi_mix( DDRB , 6 ); //
  cbi_mix( PORTE, 3 ); //Timer3, port 5
  sbi_mix( DDRE , 3 ); //
  cbi_mix( PORTE, 4 ); //Timer3, port 2
  sbi_mix( DDRE , 4 ); //
  cbi_mix( PORTE, 5 ); //Timer3, port 3
  sbi_mix( DDRE , 5 ); //
  cbi_mix( PORTH, 3 ); //Timer4, port 6
  sbi_mix( DDRH , 3 ); //
  cbi_mix( PORTH, 4 ); //Timer4, port 7 
  sbi_mix( DDRH , 4 ); //
  cbi_mix( PORTH, 5 ); //Timer4, port 8
  sbi_mix( DDRH , 5 ); //
#endif

  pinMode(ledPinTV, OUTPUT);  
  pinMode(ledPinRed, OUTPUT);
  pinMode(ledPinWhite, OUTPUT);
  pinMode(ledPinBlue, OUTPUT);
  pinMode(ledPinRoyBlue, OUTPUT);
  pinMode(ledPinUV, OUTPUT);
  pinMode(ledPinCyan, OUTPUT);
  pinMode(ledPinYellow, OUTPUT);
  pinMode(ledPinMoon, OUTPUT);

  pinMode(Heatsink1_FansPWM, OUTPUT);
  pinMode(Heatsink2_FansPWM, OUTPUT);
  pinMode(Heatsink3_FansPWM, OUTPUT);
  pinMode(PowerSwitch2, OUTPUT);
  pinMode(tempHeatPin, OUTPUT);
  pinMode(tempChillPin, OUTPUT);
  pinMode(tempAlarmPin, OUTPUT);
  pinMode(SDchipSelect, OUTPUT);

#ifdef Aqua_shield_v2
  pinMode(WirelessSPI_CS, OUTPUT);
  pinMode(WirelessW_CE, OUTPUT);
  pinMode(WirelessW_IRQ, INPUT);
  pinMode(AnalogIN, INPUT);
#endif

#ifdef Aqua_shield_v3
  pinMode(WirelessSPI_CS, OUTPUT);
  pinMode(WirelessW_CE, OUTPUT);
  pinMode(WirelessW_IRQ, INPUT);
  pinMode(PowerSwitch3, OUTPUT);
  pinMode(Temp_SensorBus1, OUTPUT);
  pinMode(BackLite, OUTPUT);
#endif

//digitalWrite(BackLite,HIGH);
 analogWrite(BackLite, 255); 


  ReadDallasAddress ();
  sensors.begin();										     //start up temperature library
  sensors.setResolution(waterThermometer, resolution);       // set the resolution to 11 bit
  sensors.setResolution(Heatsink1Thermometer, resolution);
  sensors.setResolution(Heatsink2Thermometer, resolution);
  sensors.setWaitForConversion(false);
  sensors.requestTemperatures();
  delayInMillis = 750 / (1 << (12 - resolution)); 
  lastTempRequest = millis(); 

  myGLCD.InitLCD(LANDSCAPE);
  myGLCD.clrScr();

  EraseAllEEPROM_SaveDefault();  // check and erase eeprom for my format, save all default
  myGLCD.clrScr();
  
  myTouch.InitTouch(LANDSCAPE);
  myTouch.setPrecision(PREC_MEDIUM);
  myTouch.read();                          //dummy read, enale IRQ

  myGLCD.setColor(64, 64, 64);
  myGLCD.fillRect(0, 226, 319, 239);       //Bottom Bar
  rtc.halt(false);                         //Set the clock to run-mode
  
  COLOR=0;               // read all colors
  ReadLedFromEEPROM();   // read led setting from EEPROM
  ReadFromEEPROM();      // read other setting
  t = rtc.getTime();
  min_cnt= (t.hour*60)+t.min;

  calculateStartTime();  // calculate SUNRISE time 
  calculateStopTime();   // calculate SUNSET time

//--------ON OFF LED Analog Driver ----------
    if ((min_cnt/15 >= StartTime-1) && (min_cnt/15 <= StopTime))
		{digitalWrite(PowerSwitch2, LOW);}  //ON driver before StartTime - 15min
			else {digitalWrite(PowerSwitch2, HIGH);} //OFF driver before StartTime

  LED_levels_output();
  delay(1000);  // wait before first reading temperature data
  checkTempC(); 
  mainScreen(true);
  setScreenSaverTimer = setSSmintues * 12;       // 5sec*12=1 min, convert minutes to 5sec stepping
       
}
/*********************************** END of SETUP ************************************/


/********************************** BEGIN MAIN LOOP **********************************/

void loop()
{

		if ((myTouch.dataAvailable()) && (screenSaverCounter>=setScreenSaverTimer))  //exit from screen saver
		{ if (setLockScreen ==1) { analogWrite(BackLite, 255);}   // set normal brightness
				Exit_From_ScreenSaver();} 
		    else 
               { if (myTouch.dataAvailable() && (screenSaverCounter < setScreenSaverTimer)) 
                 { processMyTouch();} }

			Alarm();										// ON/OFF alarm signal and Fan starup process

			unsigned long currentMillis = millis();

#ifdef Timers_8bit

#else
//----------check LED levels every 1s for 8/11 & 11 bit version ---------------------------
 // unsigned long currentMillis = millis();
			if (currentMillis - previousMillisOne > 1000)   //check LED levels every 1s
			{ previousMillisOne = currentMillis;  
			     min_cnt= (t.hour*60)+t.min; 

//if (clouDonOff ==1) {  weezleLED();    }      // Wheater calculation

			     LED_levels_output();
			}
#endif

           if (currentMillis - previousMillisFive > 5000)	   //check time, temp and LED levels every 5s

			{ previousMillisFive = currentMillis;  

  		     checkTempC();	                       			// read current temperature


if (clouDonOff ==1) { timeStartOBL();  }  // опрос таймера на погоду


         if ((screenSaverCounter<setScreenSaverTimer) && (dispScreen == 0)) 
               { mainScreen(); }		                   // display MAIN Screen include TimeDateBar()

         if ((screenSaverCounter<setScreenSaverTimer) && dispScreen!=9 && dispScreen !=0)
               { TimeDateBar(); }		                       // display time and data in all windows exept dispScreen=9 and MAIN windows
          
		 if (screenSaverCounter>=setScreenSaverTimer || dispScreen ==9)    // check current time in Screen saver mode or dispScreen=9 
		       { t = rtc.getTime(); 
		         WaterTempCheckFunction();					// ON/OFF chiller, heater and display TEMP value and messages 
                 FanTempCheckFunction();

		 if  (tempAlarmflagW == true || tempAlarmflagH1 == true || tempAlarmflagH2 == true) // exit from screensaver in case of alarm
					{ 
					firstTouch  = false; 
					screenSaverCounter=0;
					dispScreen=0;
					clearScreen();
					myGLCD.setColor(64, 64, 64);
					myGLCD.fillRect(0, 226, 319, 239);                     
					mainScreen(true);
		            }
				} 
         min_cnt= (t.hour*60)+t.min;
//Serial.print("min_cnt="); Serial.println(min_cnt);

#ifdef Timers_8bit
			    LED_levels_output();
#endif

//--------------ON OFF LED Analog Driver --------------------------
       if  ((GlobalStatus2Byte & 0x0F) == 0) { 
         if ((min_cnt/15 >= StartTime-1) && (min_cnt/15 <= StopTime))
			{digitalWrite(PowerSwitch2, LOW);}						//ON driver before StartTime - 15min
		 else {digitalWrite(PowerSwitch2, HIGH);}}				//OFF driver before StartTime

//              feedingTimeOutput();

//-------------- Off PRESET 45min before the end of light day ------------------------------
              if (((GlobalStatus2Byte & 0x0F) !=0) && (min_cnt/15 == StopTime-3 ))  // !=0 if preset is ON
			  {GlobalStatus2Byte = (GlobalStatus2Byte & 0xF0);                        //clear flags Preset1..Preset4
        	  colorLEDtest = false;}
			  screenReturn();								   // return to Main window after preset is OFF or after 2min timeout
			  screenSaver();                                   // check screen time and display saver 

    } 
}

/********************************** END OF MAIN LOOP *********************************/


 

ilprohorowi4
Offline
Зарегистрирован: 22.02.2014

Прилаживаю ссылку на весь архив. http://reefcentral.ru/forum/topic/2016-akva-kontroller-ot-olega/page-36#...

JollyBiber
JollyBiber аватар
Offline
Зарегистрирован: 08.05.2012

Эта ветка _платных_ испонителей

Код вставлять научитесь, никто вашу простынь читать не будет

Вы правда считаете что у кого-то появиться желание проананлизировать просто так 10 ТЫСЯЧ строк кода?

kentik
Offline
Зарегистрирован: 28.03.2013

"Есть код для Ардуино мега 2560 с сенсорным экраном, но он дороговат..."

Цену хоть бы озвучили.

JollyBiber
JollyBiber аватар
Offline
Зарегистрирован: 08.05.2012

подозреваю под "дороговат" имеется ввиду 2560+сенсорный экран :)

ilprohorowi4
Offline
Зарегистрирован: 22.02.2014

Хмм, спойлера я не нашел... Дороговат - 3 рубля нашими.

kisoft
kisoft аватар
Offline
Зарегистрирован: 13.11.2012

madmax96
Offline
Зарегистрирован: 22.09.2011

Вам надо провести поиск по готовым проектам, которые вас удовлетворят. Либо самостоятельно разбираться. Подкинуть совет, что-то подсказать, ответить на вопрос - это одно дело. А что-то лопатить по вашему тз, да еще имитировать фазы луну - навряд ли кто-то бесплатно загорится желанием. И да, это ветка поиска работы. Любая работа это время и имхо должна быть оплачена так или иначе.

ilprohorowi4
Offline
Зарегистрирован: 22.02.2014

Спасибо всем за ответы. Раз уж можете подсказать, то подсказывайте :)

Вроде бы нашел проект: http://forum.arduino.cc/index.php?topic=63503.0 .

Только не понятно кое-что.

1. Нужен контроллер Ардуино Мега, только какой? 2560? 1280? Там вроде как не указано. В качестве дисплея - ЛСД 20:4 символа. Так же нужны часики.

2. Он приводит полный код, т.е. мне нужно просто купить контроллер, скопировать код и прошить? Или как?

3.  Я так понял, контроллер управляет тремя каналами: лунным светом, синим (заменю на теплый белый) и белым, так?

Всем заранее огромное спасибо

ilprohorowi4
Offline
Зарегистрирован: 22.02.2014

Да, еще вопросик. Светодиоды плавно включаются, или сразу на полную мощь (т.е. рассвет-закат присутствует?) СПС