Control motors,Leds,Relays or Motor Driver like lm298 using ESP8266 NodeMcu WiFi UDP with RoboRemo App



 //****************************************************  
 //   Android/fruitPhone Controlled WiFi Car  
 //****************************************************  
   
   
 // ESP 8266 NodeMcu V1.0 PWM Servo Control Via WiFi UDP  
   
   
 // Using Free Android or iOS App   "RoboRemo"  
   
   
 //****************************************************  
   
   // for Controlling LM298 module with 3 pins (one channel)
//I have uploaded another sketch after this one see this link with LM298 pins included
   
   //****************************************************  
   
   
   
   
   
   
   
 //***************************************************************  
   
   
 // PLEASE VISIT  
   
   
 //****************************************************************  
   
   
 //       My Blog :  https://amkDiyProjects.BlogSpot.com  
   
   
 //  My youtube Channel:  https://youtube.com/CrazyGuyOfficial  
   
   
   
 //****************************************************************  
   
   
   
   
   
   
   
   
   
   
   
 //************************************************************  
   
   
 //  Libraries Required for this to work  
   
 //************************************************************  
   
   
 #include <ESP8266WiFi.h>  
 #include <WiFiUdp.h>  
 #include <Servo.h>  
   
 //************************************************************  
   
   
   
   
   
   
   
   
   
   
   
   
 //************************************************************  
   
 // Settings for the WIFI:  
   
 //************************************************************  
   
   
 const char* ssid = "mywifi";      // Set WiFi Name of WiFi Router/AP/HotSpot AND Esp8266 will connect TO it  
 const char* password = "12345678";   // Set PassWord For WiFi  
   
   
 unsigned int localPort = 9876;     // Set port number       
                       
                       
                       
   // if it's not working first ensure the following things  
   // to use it in Local network i.e. in the same wifi "client Isolation" should be turned off in the Wifi Router's settings   
   // otherwise even if both the phone and the esp8266 are connected to the wifi they will not be able to "talk to each-other"  
   // to use it from the Internet the port should be forwarded in the WiFi router's settings  
   
 //************************************************************  
   
 // Settings for Servo using Servo library  
   
 //************************************************************  
   
   
   
 const int chCount = 4;           // 4 channels,total number of channels is 4 and 4 GPIOs will be used  
   
 Servo servoCh[chCount];  
   
 int chPin[] = {5, 4, 14, 12};       // ESP8266 12E NODE MCU DevKit V1.0 pins: GPIO 5, 4, 14, 12  
   
                       // on my NODE MCU board they are marked D1 D2 D5 D6 respectively  
   
                       // IN THE App first channel "ID" is Ch 0 = 5   ch 1 = 4  ch 2 = 14  ch 3 = 12  
   
 int chVal[] = {1600, 1600, 1600, 1600}; // default value in micro-seconds for PWM signals (middle)  
   
 int usMin = 700;             // min pulse micro seconds  
   
 int usMax = 2600;            // max pulse micro seconds  
   
   
   
   
 //************************************************************  
   
   
 char cmd[40];     // Make a character array/C string to store the Contents Read from the received UDP Packet  
             // Cmd is the name of the UDP packet Buffer in which the command which is received is stored  
   
 unsigned long lastCmdTime = 60000;  
   
   
 unsigned long aliveSentTime = 0;  
   
   
   
 //************************************************************  
   
   
 WiFiUDP port;  
   
   
   
   
   
   
   
   
   
 //************************************************************  
   
 //   SETUP BEGINS  
   
 //************************************************************  
   
   
 void setup() {  
   
  delay(1000);  
   
  Serial.begin(115200);  
   
  Serial.println("Connecting to ");  
   
  Serial.println(ssid);  
    
     
  WiFi.mode(WIFI_STA);         //Set Esp8266 in Station mode   
                     //it can work without this line but necessary for preventing Ap mode (happened in my case )  
    
    
  WiFi.begin(ssid, password);     // Connect to WiFi network  
   
   
    
    
  while (WiFi.status() != WL_CONNECTED) {  
    
   delay(500);  
     
   Serial.println("trying to connect");     
     
   delay(500);  
     
   // IF UNABLE TO CONNECT OR IF IT'S TAKING TOO LONG   
   //first CHECK the SSID,PASSWORD in the SKETCH it should be your WIFI name/ssid and PASSWORD  
   //second every-time after uploading a sketch reset esp8266 once or disconnect from power and connect again   
   //and in the second case to view the serial data again   
   //select the device port in Arduino IDE again and turn off/on Serial monitor   
                           
    
  }  
    
    
    
    
  Serial.println("");  
    
    
  Serial.println("WiFi connected");  
    
  port.begin(localPort);  
                              
                              
  Serial.print("Use this Ip and Port in RoboRemoApp to connect: ");     //Print the IP address and port number  
   
  Serial.print(WiFi.localIP());  
   
  Serial.print(":");  
    
  Serial.print(localPort);  
   
 }  
   
   
   
 void loop() {  
    
     
     
     
     
     
     
     
   if (millis() - lastCmdTime > 500) {     
     
     
     
     
     
     // All PWM values will Return to Default Values 500 milli seconds after the time of Last Received Command   
     
     // So all PWM signals will return to default values if there is No New Command  
   
     
     
     
     
     
     
     
     
   for (int i = 1; i <= 3; ) {         
      
      
      
    // set i to 0,1,2 or 3 (if connected to servo and want it to stay at the last commanded position)  
                             
   
      
    // and rest of the pins PWM signals will return to default values if there is No New Command  
   
   
   
   
   
   
   
   // Comment out these two lines  if you just want to turn the Pwm signals off immediately   
         
   // and Uncomment if you also want the servo to return to mid but then servo.detach below should be commented  
   
   // because servo.detach turns the pins off immediately and does'nt give the servo enough time to return to mid

 
  
   // servoCh[i].attach(chPin[i]);   
     
   // servoCh[i].writeMicroseconds(1600 );      
      
      
      
     
      
    servoCh[i].detach();    // Turns OFF the Pins      
      
      
      
      
    // comment it out if want the servo to Return to it's mid Position Quickly   
      
    // because this loop runs over and over again quickly and the servos need some time to   
      
    //physically move and PWM should be ON during that period   
      
    // because this line turns off the pin before moving to i++ and changing the pin number  
      
      
      
    i++;  
   }  
   
  }  
    
    
    
    
    
    
    
  int packetSize = port.parsePacket();  // Declaring an int for getting Packet Size  
   
   
    
    
    
    
    
    
    
  if (packetSize > 0) { // if Packet Size is more than zero or if there is some command received then  
   
   
   
   port.read(cmd, 40); // Read the Received UDP Packet   
              //and Put the Contents,the channel number and value in the Cmd (array/C string)  
   
   
    
    
    
    
    
    
   // Serial.println(cmd);   // Print the recieved cmd   
   
   
     
     
     
     
     
     
     
     
   if (cmd[0] == 'c' && cmd[1] == 'h') {    
                
              // if the command starts with the caracter c and the second character is h  
   
   
   
   
   
   
      
    exeCmd();     // Execute the execmd function which is at the end of the loop  
   
   }  
    
     
     
     
     
     
     
     
     
   if (millis() - aliveSentTime > 1000) {         
     
     
   // an "alive" signal is sent periodically to the phone to know the connection state  
   // in the RoboRemo app from "edit UI" option add an "led" or a "text log box" set the ID  
   // to "alive" or can be changed but for the text box if left empty the received text will be shown  
   
   
    exeReply();                    // Execute exeReply function At the end of the loop  
   
   }  
   
   
   
   
   
   
   
  }  
   
   
   
   
   
   
   
   
 }  
    
  void exeCmd() {     // exeCmd function when called from the loop Reads the channel number and value and sends PWM signals  
   
  lastCmdTime = millis();  
   
   
  int ch = cmd[2] - '0' ; // Channel Number  
  int chVl = 0;      // Channel Value temporarily store it in this and then move to Array chVal[] which is already declared at the top  
   
   
   
   
   
  int i = 4;  
  while ( isdigit( cmd[i] ) ) {    // if the 4th character in the Array is a Number  
                     //get the number and Calculate all the digits in to a single 4 digit number  
   chVl = (chVl * 10) + (cmd[i] - '0');  
   
   chVal[ch] = chVl;  
   i++;  
  }  
   
   
   
   
   
   
   
  if (ch >= 0 && ch <= 9 && cmd[3] == ' ') { //if channel value is between 0 and 9 send PWM Signals using Channel Value  
   if (!servoCh[ch].attached()) {  
    servoCh[ch].attach(chPin[ch], usMin, usMax);  
   }  
   servoCh[ch].writeMicroseconds(chVal[ch]);  
  }  
   
   
   
   
   
   
  Serial.print ("channel Number : ");  
  Serial.println (ch);  
   
   
  Serial.print ("channel Value : ");  
  Serial.println (chVal[ch]);  
   
  
   
   
   
   
 }  
   
   
   
 void exeReply() {  
   
   
   
   
   
   
 port.beginPacket(port.remoteIP(),localPort);   // Send "Alive 1" back to the App to light up the "led" in the App GUI   
                         // Alive is the "id" for "LED" and "1" is the On command /n" will be ignored   
   port.write("alive 1\n");  
     
   port.endPacket();  
     
   aliveSentTime = millis();  
     
   Serial.print("alive sent");  
   
 }  
   
   
   
   
   
   
    
   
    

Arduino Nano micro-controller Grow-Box / Green-House Controller 2017[OUT-DATED] Sketch / Code Compiled / Tested with Arduino IDE 1.6.9


  /*   
   
    
   
    
   
  ************** UPDATED ON FEB 2017 *************  
   
  *** 
    THIS SKETCH IS OUT DATED . FOR LATEST SKETCH GO TO THE FOLLOWING LINK
   
                            https://amkdiyprojects.blogspot.com/2017/09/pre_25.html   
  ***
    
   
  ***MAKING A MODULAR SYSTEM FOR D.I.Y. GREENHOUSE   
     
   
    
      
  *****i WILL improve it as i learn more :)   
  //**********************//**********************//**********************   
     
     
     
  //**********************//**********************//**********************//**********************//**********************//**********************   
     
  // Arduino Nano Grow-box / Green-House Controller v 3.0 :)   
     
  //**********************//**********************//**********************//**********************//**********************//**********************   
     
     
     
     
     
     
  //       ***Made by Ali khan from Pakistan :)   
     
     
  //**********************//**********************//**********************   
     
  // **PARTS required (for this sketch to work as it is )   
     
  //**********************//**********************//**********************   
     
  1.Arduino Nano   
     
  2.A thermistor (i used A 10K WATERPROOF ONE)   
     
  3.A resistor (matching the value of the thermistor's "nominal resistance at 25 DEGREES C"
    for example: 5k resistor for 5k thermistor)   
     
  4.OLED display ssd1306 (mine is ssd1306 but got it working by using sh1106 constructor
    also got rid of the "white line problem")   
     
  5. DHT 22   + Pull up Resistor 5K ohm or close 4.7K
     
  6.RELAY MODULE LOW LEVEL TRIGGER TYPE (5 Relays required in total for all the pins 
    can be separate 4 CAN WORK TOO )   
     
  7. DS3231 RTC MODULE (RESISTOR from charging circuit REMOVED and charging DISABLED
     WITH CR2032(NON-rechargeable)Cell   
     
  8. An LED with appropriate RESISTOR for using it as a STATUS LED   

  9. Power Supply  (two if complete isolation is required)
     
  */   
     
     
     
     
     
  //**********************//**********************//**********************   
  //TEMPERATURE and HUMIDITY "CONTROL PARAMETERS"              
  //**********************//**********************//**********************   
     
  //Default Temperature and Humidity Settings   
     
  int Tmax   =  29 ;   // Set temperature Maximum point at which "Cooler" will turn ON   
  int setT   =  25 ;   // Set temperature point at which "heater" and "cooler" will turn OFF   
  int Tmin   =  19 ;   // Set temperature Minimum point at which Heater will turn ON   
  int setHmx =  80 ;   // set humidity max at which "bigfan" will turn ON   
  int setHnr =  65 ;   // Set humidity normal at which "bigfan" and "spray" will turn OFF   
  int setHlw =  55 ;   // Set humidity low at which "spray will turn ON   
     
     
  // Separate Temperature and Humidity Settings for Day and Night time can be done by Alarms function belowwww   
     
  //**********************//**********************//**********************   
  //  Light Timer ON/OFF Time Settings   
  //**********************//**********************//**********************   
     
     
  const int OnTime  = 14 ; // Hour when Light will turn ON (24 hr format NO zeros before single digits)   
  const int OffTime = 8 ; // Hour when Light will turn OFF (24 hr format NO zeros before single digits)   
     
     
  // SET RTC'S TIME USING DS1307 EXAMPLE SKETCH FROM ABOVE FILE > EXAMPLE > DS1307 > SETTIME   
  // THEN UPLOAD THIS SKETCH   
     
     
  //*****************************************************************************************************************   
     
     
  bool LightSts  = 0 ;    // DON'T CHANGE MANUALLY THESE ARE FOR STATUS UPDATES IN SERIAL MONITOR     
  bool CoolerSts = 0 ;   
  bool HeaterSts = 0 ;   
  bool BigFanSts = 0 ;   
  bool SpraySts  = 0 ;   
     
  //**********************//**********************//**********************   
  //  PINS AND CONNECTIONS   
  //**********************//**********************//**********************   
  // Five pins used in total for five relays   
  // usually a 4 Relay board is available so it can be used as only one of the pins for Heater/Cooler are required    
  // and they can be swapped according to the outdoor temperature in different seasons   
  // LOW-level Relay board will trigger the relay when the trigger pin is LOW/grounded   
  // so when something has to be turned ON the trigger pin will become LOW otherwise it will stay HIGH (as.a.mf.)   
  // if possible use two separate power supplies for relay board and arduino by removing JDVCC-VCC jumper    
 

  const byte Bigfan   = 4 ;  // Bigfan turns on at high humidity    
  const byte cooler   = 5 ;  // Cooler turn on at high temp (T1 from DHT)   
  const byte spray    = 6 ;  // Spray turns on at low humidity   
  const byte lightone = 7 ;  // Main Lights(for plants)    
     
  const byte heater   = 8 ;  // Heater turns ON at low temp (T1 from DHT)   
  const byte lighttwo = 3 ;  // pin for "status LED' inicating the loop is running when oled is turned OFF...   
   
          //i turn it off by removing two jumper wires manually    
          //blinks every ten second (change ten second timer)   
     
// ******** THERMISTOR AND DHT PINS BELOW *******   
// DS3231 RTC "SDA to A4", "SCL to A5" "Vcc to 5V arduino pin Gnd to Gnd"  
//**********************//**********************//*********************   
//THERMISTOR PIN and SETTINGS   
//**********************//**********************//**********************   
     
  #define THERMISTORPIN A0   // which analog pin to connect to thermistor and the resistor "joint"     
     
     
     
     
  #define THERMISTORNOMINAL 10000 // resistance at 25 degrees C     
     
  #define TEMPERATURENOMINAL 25  // temp. for nominal resistance (almost always 25 C)   
     
  #define NUMSAMPLES 5 // how many samples to take and average,takes longer gets 'smooth'   
     
  #define BCOEFFICIENT 3500 // The beta coefficient of the thermistor (usually 3000-4000)   
     
  #define SERIESRESISTOR 9700 // the value of the 'other' resistor should be close to the thermistors nominal value    
     
  int samples[NUMSAMPLES];   
     
     
  //**********************//**********************//**********************   
  // INCLUDE LIBRARIES   
  //**********************//**********************//**********************   
     
     
     
     
  #include "DHT.h"   //use older versions i haven't tried it with the new one 
     
  #include <U8glib.h> // OLED   
  #include <Wire.h> // I2C   
  #include <Time.h> // Time Manipulation   
  #include <DS1307RTC.h> // DS1307 RTC   
  #include <TimeAlarms.h> // time alarm library //Change Number of alarms "dtNBR_ALARMS to 24 "   
     //"BY EDITING TIMEALARM.H FILE IN LIBRARIES FOLDER.   
     //increasing this number increases size of the sketch too   
     //or remove alarms from the code below to match the max number defined in the library
     
     
  #define DS1307_ID 0x68 //Address of the RTC   
     
     
     
     
     
  //******************************************************** D H T 22 and pin ***************************************************************************   
  #define DHTPIN A1  // what pin we're connected to   
     
     
     
  #define DHTTYPE DHT22 // DHT 22 (AM2302)   
     
  DHT dht(DHTPIN, DHTTYPE, 6);   
     
     
     
     
     
     
  //**********************//**********************//**********************   
  // MAKING CHARACTER ARRAYS or C strings    
  //**********************//**********************//**********************   
     
  char timebuf[10]; // array for Time   
     
  char str[10]; // for Display   
     
  //char datebuf[10]; // Date   //un comment for using/displaying date with time    
  //int year2digit; // 2 digit year  // necessary for Date Specific Alarms    
            // for example triggering a water pump relay for watering the plants   
            // i didn't use it as my setup currently doesn't need date   
            
     
     
  //**********************//**********************//**********************   
  // OLED CONSTRUCTOR   
  //**********************//**********************//**********************   
  U8GLIB_SH1106_128X64 u8g(13, 11, 10, 9); // SPI SCK/clk to D13, MOSI = D11, CS = D10, DC = D9
  
   // OLED "constructor" and pins info.   
     
   //check out example sketch section for U8glib it has all the info    
     
     
     
     
  //**********************//**********************//**********************//**********************//**********************//**********************   
  //    SETUP BEGINS   
  //**********************//**********************//**********************//**********************//**********************//**********************   
     
  void setup() {   
     
  pinMode(Bigfan,  OUTPUT); // set output relay pins // add more if you have more relays or pins connected to something    
  pinMode(cooler,  OUTPUT);   
  pinMode(heater,  OUTPUT);   
  pinMode(spray,   OUTPUT);   
  pinMode(lightone,OUTPUT);   
  pinMode(lighttwo,OUTPUT);   
     
     
  digitalWrite(Bigfan,  HIGH); // When using "LOW level trigger" type Relay module, turning a pin "HIGH" will   
  digitalWrite(cooler,  HIGH); // turn the relay "OFF" and turning the pin "LOW" turns the relay "ON"    
  digitalWrite(heater,  HIGH); // THIS WILL PREVENT STARTUP RELAY TRIGGERING PROBLEM   
  digitalWrite(spray,   HIGH);   
  digitalWrite(lightone,HIGH);   
     
  analogReference(EXTERNAL); // AREF connected to 3.3 ON BOARD for accuracy of thermistor    
          //(go to adafruit using a thermistor tutorial )   
     
     
     
     
  u8g.firstPage();     // //START SCREEN "Picture loop" for OLED   
     
  do {   
     
   u8g.setFont(u8g_font_unifont);   
     
   u8g.drawFrame(10, 12, 108, 31);   
   u8g.drawFrame(0, 0, 128, 64);   
   u8g.drawStr(15, 25, "Grow Box 3.0");   
   u8g.drawStr( 16, 40, "Controller");   
   u8g.drawStr(30, 56, "Made by:AMK");        
     
  }   
     
  while ( u8g.nextPage() );   
     
     
  //**********************//**********************//***********************//**********************   
  //Check to see if the RTC is present.if yes then Set the ARDUINO's INTERNAL clock accordingly   
  //**********************//**********************//***********************//**********************   
     
     
  // when using timer library the Arduino's "internal clock " is used for getting "current time"    
  // Arduino's internal clock is NOT so accurate and gets off time so we use time from RTC (which IS    
  // accurate at least for our use) and we sync Arduino's internal Clock with the time from RTC and we    
  // have to do this periodically (at-least once in every 24 hrs )so our tasks can be completed according    
  // to the correct time we can put the sync command in the Loop and Alarm Functions too    
     
  Wire.beginTransmission(DS1307_ID);   
  Wire.write((uint8_t)0x00);   
     
     
     
  if (Wire.endTransmission() == 0) //Did the RTC respond?   
  {   
   setSyncProvider(RTC.get);  //Yes it did, get the time from the RTC   
     
     
     
   Serial.begin(9600);    // for initializing serial monitor   
     
   Serial.println("TIME SYNCHRONIZED");   
  }   
     
     
     
     
   Serial.println("AMK GROW BOX Controller! V3.0 "); //ONLY ONCE AT START UP in serial monitor only   
     
   Serial.println("AmkDiyProjects.Blogspot.com"); //ONLY ONCE AT START UP in serial monitor only   
     
   Serial.println("Subscribe to My Channel "); //ONLY ONCE AT START UP in serial monitor only   
     
   Serial.println("Youtube.com/CrazyGuyOfficial "); //ONLY ONCE AT START UP in serial monitor only   
     
     
     
     
     
     
     
  //***********************//**********************//***********************//**********************   
     
  // TIMER ALARM THAT RUNS OVER AND OVER AFTER SECONDS    
     
  //***********************//**********************//***********************//**********************   
     
     
     
  Alarm.timerRepeat(10, Repeats); // timer for every 10 seconds blinking LIGHT TWO (status LED) it blinks only when   
           // loop is running normally and (below in the sketch ) if DHT sensor has problems    
           //the loop stops and light two led lights up constantly indicating sensor problem   
              
                
     
     
  }   
     
  //**********************//**********************//**********************   
  //        SETUP END   
  //**********************//**********************//**********************   
     
     
     
  //***********************//**********************//***********************//**********************   
  //************// Function Called When Repeating Timer alarm triggers //*******************   
  //***********************//**********************//***********************//**********************   
     
     
     
     
  void Repeats() {   
     
     
  Serial.println("*****>>10 second timer<<*****");   
     
  digitalWrite(lighttwo, HIGH); // it is also used to indicate Dht read failed
  //and lights up continuously below in dht part   
     
  Alarm.delay(30);   
     
  digitalWrite(lighttwo, LOW);   
     
  digitalClockDisplay();  // Update the Clock Display IN SERAL MONITOR   
      
               // this calls the function digitalClockDisplay at the end   
     
     
     
     
     
     
     
     
  if (LightSts ==1) {   
     
  Serial.println ("< Lights ON >");   
     
     
     
     
  }   
     
     
  else {   
      
   Serial.println ("< Lights OFF >");   
     
      
  }   
     
     
  if (CoolerSts ==1) {   
     
  Serial.println ("< Cooler ON >");   
     
     
     
     
  }   
     
     
  else {   
      
   Serial.println ("< Cooler OFF >");   
     
      
  }   
     
     
  if (HeaterSts ==1) {   
     
  Serial.println ("< Heater ON >");   
     
     
     
     
  }   
     
     
  else {   
      
   Serial.println ("< Heater OFF >");   
     
      
  }   
     
  if (BigFanSts ==1) {   
     
  Serial.println ("< BigFan ON >");   
     
     
     
     
  }   
     
     
  else {   
      
   Serial.println ("< Bigfan OFF >");   
     
      
  }   
     
     
  if (SpraySts ==1) {   
     
  Serial.println ("< Spray ON >");   
     
     
     
     
  }   
     
     
  else {   
      
   Serial.println ("< Spray OFF >");   
     
      
  }   
     
  }   
     
     
  //***********************//**********************//***********************   
     
     
     
     
  //**********************//**********************//**********************   
     
  //        LOOP BEGINS   
     
  //**********************//**********************//**********************   
     
     
     
  void loop() {   
     
     
     
     
  if (hour() == 0 && minute() == 0 && second() == 0) //If it is 00:00:00 MIDNIGHT UPDATE the Arduino's INTERNAL Clock   
  {   
   setSyncProvider(RTC.get);       //It's time, sync the Arduino's INTERNAL Clock to the RTC   
  }   
     
     
     
     
     
     
     
     
     
     
  //***********************//**********************//***********************//**********************   
     
     
  //   LET THERE BE LIGHT    
     
     
  //**************************************************************************************************   
  // This will make sure that the light one (for plants) stays ON after reset or power down/up cycle    
  // because Alarms will trigger on a given time and will turn the pin HIGH but if after the alarm is    
  // triggered AND there is a reset the pin will turn off until next alarm that turns it ON again    
  // which can interrupt photo-period for plants So, this line makes sure that LIGHTS turn ON immediately    
  // after reset which happens DURING the LIGHT period for plants   
     
     
     
     
  //**********************************************************   
     
  // Turn Lights On/Off   
     
  //**********************************************************   
     
  if (OffTime > OnTime) {  // Same Day     //GETS THE JOB DONE :)   
     
     
   if (hour() >= OnTime && hour () <= OffTime - 1) {    
            
         // if current hour is equal or greater than ON time   
         // AND equal to or less than OFF time minus 1 then turn the   
         // lights ON (by turning pins LOW because of using LOW level Relays)   
         // Minus 1 from OFF time because we are not using Minutes here   
         // For Example turn off time is "16" (4 PM) the hour number will be "16" from   
         // 16:00 till 16:59 (4:00 till 4:59)   
     
   digitalWrite(lightone, LOW);   
     
     
      
     
    LightSts = 1 ;    
      
      
   }   
     
      
     
   else {   
     
   digitalWrite(lightone, HIGH);   
     
     
     
   LightSts = 0 ;   
      
      
   }   
     
     
     
  }   
     
     
  //**********************************************************   
     
     
  if (OffTime < OnTime) {  // Different Day   
     
     
     
   if (hour() >= OnTime || hour () <= OffTime - 1) {     
      
         // if current hour is equal or greater than ON time   
         // OR equal to or less than OFF time minus 1 then turn the   
         // lights ON (by turning pins LOW because of using LOW level Relays)   
         // Minus 1 from OFF time because we are not using Minutes here   
         // For Example turn off time is "16" (4 PM) the hour number will be "16" from   
         // 16:00 till 16:59 (4:00 till 4:59)   
         // Minutes,Seconds even day,date,year can be used by adding code   
     
     
   digitalWrite(lightone, LOW);   
     
     
     
      
     
     
     
   LightSts = 1;   
     
     
   }   
     
     
     
   else {   
     
     
     
     
     
   digitalWrite(lightone, HIGH);   
     
     
     
     
     
     
     
      
   LightSts = 0 ;   
     
     
     
     
   }   
     
     
     
     
     
     
     
  }   
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
  //********************************************************************************************************************************************   
  // *******************************************************************************************************************************************   
  // DAILY TIMED ALARMS THAT TRIGGER ON SPECIFIED TIMES   
     
  // these alarms will trigger once and will do "stuff" mentioned in the alarm functions at the end of the loop   
     
  // *******************************************************************************************************************************************   
  Alarm.alarmRepeat(3, 0, 0, ONAlarm); // daily Alarm 1 for example // for triggering an alarm on ""03:00:00"" in the morning   
     
     
     
  Alarm.alarmRepeat(4, 0, 0, ONAlarm); // daily Alarm 2 or for example // for triggering an alarm on ""04:00:00"" in the morning   
     
     
     
  Alarm.alarmRepeat(5, 0, 0, ON2Alarm); // daily Alarm 3   
     
     
     
  Alarm.alarmRepeat(6, 0, 0, ONAlarm); // daily Alarm 4   
     
     
     
  Alarm.alarmRepeat(7, 0, 0, ONAlarm); // daily Alarm 5   
     
     
     
  Alarm.alarmRepeat(8, 0, 0, ON2Alarm); // daily Alarm 6   
     
     
     
     
     
     
     
     
     
     
  Alarm.alarmRepeat(9, 0, 0, ONAlarm); // daily Alarm 7   
     
     
     
  Alarm.alarmRepeat(10, 0, 0, ONAlarm); // daily Alarm 8   
     
     
  Alarm.alarmRepeat(11, 0, 0, ON2Alarm); // daily Alarm 9   
     
     
     
  Alarm.alarmRepeat(12, 0, 0, ONAlarm); // daily Alarm 10   
     
     
  Alarm.alarmRepeat(13, 0, 0, ONAlarm); // daily Alarm 11   
     
     
     
  Alarm.alarmRepeat(14, 0, 0, ON2Alarm); // daily Alarm 12   
     
     
     
     
     
     
     
     
  Alarm.alarmRepeat(15, 0, 0, ONAlarm); // daily Alarm 13   
     
     
     
  Alarm.alarmRepeat(16, 0, 0, ONAlarm); // daily Alarm 14   
     
     
     
  Alarm.alarmRepeat(17, 0, 0, ON2Alarm); // daily Alarm 15   
     
     
     
  Alarm.alarmRepeat(18, 0, 0, ONAlarm); // daily Alarm 16   
     
     
     
  Alarm.alarmRepeat(19, 0, 0, ONAlarm); // daily Alarm 17   
     
     
     
  Alarm.alarmRepeat(20, 0, 0, ON2Alarm); // daily Alarm 18   
     
     
     
  Alarm.alarmRepeat(21, 0, 0, OFFAlarm); // daily Alarm 19   
     
     
     
  Alarm.alarmRepeat(22,0, 0, OFFAlarm); // daily Alarm 20   
     
     
     
     
  Alarm.alarmRepeat(23, 0, 0, OFF2Alarm); // daily Alarm 21   
     
     
     
  Alarm.alarmRepeat(0, 0, 0, OFFAlarm); // daily Alarm 22   
     
     
     
  Alarm.alarmRepeat(1, 0, 0, OFFAlarm); // daily Alarm 23   
     
     
     
  Alarm.alarmRepeat(2, 0, 0, OFF2Alarm); // daily Alarm 24   
     
     
     
     
     
     
  //***********************//**********************//***********************//**********************   
     
  //      DHT 22****** TEMPERATURE HUMIDITY CALCULATIONS   
     
  //***********************//**********************//***********************//**********************   
     
     
     
     
     
  float h = dht.readHumidity(); // READ HUMIDITY   
     
  float t = dht.readTemperature();// Read temperature as Celsius   
     
     
     
     
     
     
     
     
     
  // Check if any reads failed and exit early (to try again)   
     
     
     
  if (isnan(h) || isnan(t) ) {   
     
     
    Alarm.delay(1000);   
     
   Serial.println("Failed to read from DHT sensor!");   
   Serial.println("Wait for 2 secs if it doesn't start check circuit");   
     
   digitalWrite (lighttwo,HIGH);   
     
     
   return;   
  }   
     
     
     
     
     
  /*Serial.print("Humidity: ");   
  Serial.print(h);   
  Serial.print(" %\t");   
     
  Serial.print("T1: ");   
  Serial.print(t);   
  Serial.print(" *C ");   
  */   
  //***************************************************************************************************************   
     
  //        THERMISTOR CALCULATIONS   
     
  //***************************************************************************************************************   
     
     
     
     
     
  uint8_t i;   
  float average;   
     
     
  for (i = 0; i < NUMSAMPLES; i++) {  // take "N" number of samples in (milivolts) in a row, with a slight delay   
   samples[i] = analogRead(THERMISTORPIN);   
   Alarm.delay(10);   
  }   
     
     
     
     
  average = 0;   
  for (i = 0; i < NUMSAMPLES; i++) {  // average all the samples out   
   average += samples[i];   
  }   
  average /= NUMSAMPLES;   
     
     
     
     
     
  average = 1023 / average - 1;    // convert the value to resistance   
  average = SERIESRESISTOR / average;   
     
  //Serial.print("Thermistor resistance ");   
     
  //Serial.println(average);   
     
  float steinhart;       // Calculate temperature from that resistance value   
     
     
     
     
  steinhart = average / THERMISTORNOMINAL;  // (R/Ro)   
  steinhart = log(steinhart);     // ln(R/Ro)   
  steinhart /= BCOEFFICIENT;     // 1/B * ln(R/Ro)   
  steinhart += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)   
  steinhart = 1.0 / steinhart;     // Invert   
  steinhart -= 273.15;                // convert to C   
     
  /*Serial.print("T2 ");     // FOR SERIAL MONITOR   
  Serial.print(steinhart);   
  Serial.println(" *C");   
  */   
     
     
     
     
     
     
     
     
     
     
     
     
     
  //***********************//**********************//***********************//**********************   
     
  // CONTROL PART turning things ON and OFF according to Temperature(from DHT) and Humidity (THE GOOD STUFF) "ifs"   
     
  //***********************//**********************//***********************//**********************   
     
     
  if (t >= Tmax)      // TURN COOLER ON IF TEMPERATURE IS EQUAL TO OR EXCEEDS "Tmax" (HEATER remains OFF)   
  {   
   digitalWrite(cooler, LOW);   
   CoolerSts = 1 ;   
  }   
     
     
  if (t <= setT )  // Turn OFF the COOLER when TEMP GETS DOWN TO "setT" OR GOES BELOW   
     
     
  { digitalWrite(cooler, HIGH);   
     
   CoolerSts = 0 ;   
      
  }   
     
     
  if (t <= Tmin) // TURN HEATER "ON" WHEN TEMPERATURE GETS TO "Tmin" OR BELOW (cooler remains OFF)   
  {   
   digitalWrite(heater, LOW);   
   HeaterSts = 1 ;   
  }   
     
     
  if (t >= setT ) // TURN OFF HEATER WHEN TEMP GETS TO "setT" (and REMAINS LOWER THAN "Tmax")   
  { digitalWrite (heater, HIGH);   
  HeaterSts = 0 ;   
  }   
     
  //***********************//**********************//***********************//**********************   
     
     
     
  //************************************  Control for HUMIDITY ******************************   
     
     
  //***********************//**********************//***********************//**********************   
     
     
     
  if (h>=setHmx)   
     
  {   
     
  digitalWrite(Bigfan,LOW);  // Turn fan on when humidity is high   
     
     
  BigFanSts = 1 ;   
     
  }   
     
     
  if (h<=setHnr )   
     
  {   
  digitalWrite(Bigfan,HIGH);   
     
     
  BigFanSts=0;   
     
     
  }   
     
     
     
  if (h<=setHlw)   
  {   
     
  digitalWrite(spray,LOW);  // Turn Spray on when humidity is low   
     
  SpraySts= 1 ;   
     
     
  }   
     
  if (h>=setHnr)   
     
  {   
     
  digitalWrite(spray,HIGH); // Turn Spray off when humidity is normal or high   
  SpraySts = 0 ;   
     
  }   
     
     
     
     
     
     
     
     
     
     
  //***********************//**********************   
     
  // OLED PART   
     
  //DISPLAY ON THE OLED   
     
  //***********************//**********************   
     
     
     
     
  tmElements_t tm;           //formatting time and date before displaying   
     
     
  if (RTC.read(tm)) {   
      
   sprintf(timebuf, "%02d:%02d", tm.Hour, tm.Minute); // format time   
      
      
      
     
     
     
     
     
     
     
   u8g.firstPage();     // PICTURE LOOP FOR OLED it's is a doer :)   
      
      
      
   do {   
      
      
   u8g.setFont(u8g_font_helvB08); // set font for oled display   
     
     
     
     
     
     
     
     
     
   if (t >= Tmax)  //conditions for showing temperature status in the first line (high ,upper range ,normal range,low )   
      
      
   {   
    u8g.drawFrame(0, 0, 128, 20);   
    u8g.drawStr( 73, 14, "*HI TEMP*");   
     
   }   
     
   if (t <= Tmax && t > setT)   
     
   { u8g.drawFrame(0, 0, 128, 20);   
    u8g.drawStr( 80, 14, "*^^U^^*");   
   }   
     
   if   
   (t <= setT && t > Tmin)   
     
   { u8g.drawFrame(0, 0, 128, 20);   
    u8g.drawStr( 80, 14, "> N <");   
   }   
   if   
   (t <= Tmin)   
     
   { u8g.drawFrame(0, 0, 128, 20);   
    u8g.drawStr( 73, 14, "*LO TEMP*");   
   }   
     
     
     
   if (h>=setHmx)   
     
   { u8g.drawFrame(0, 0, 128, 20);   
    u8g.drawStr( 32, 14, "HMx");   
   }   
     
   if (h>setHnr && h< setHmx)   
   { u8g.drawFrame(0, 0, 128, 20);   
    u8g.drawStr( 32, 14, "Hur");   
   }   
       
    if (h>setHlw && h<=setHnr)   
    { u8g.drawFrame(0, 0, 128, 20);   
    u8g.drawStr( 32, 14, "Hn");   
   }   
     
   if (h<=setHlw)   
   { u8g.drawFrame(0, 0, 128, 20);   
    u8g.drawStr( 32, 14, "HL");   
   }   
     
     
      
      
     
     
     
     
     
     
     
     
     
     
  //************// Display Time on OLED//**************//   
      
      
      
   u8g.drawFrame(0, 0, 128, 20); // Draw frame   
     
     
     
     
     
     
   u8g.setPrintPos(3, 14); // set position for displaying time   
   u8g.print(timebuf);  //display time   
     
     
     
     
     
     
     
     
  //******// Display CURRENT Temperature1&2,humidity , Set Tmax ,Set Tnor and Set Tmin on OLED//*********************   
     
      
      
      
   u8g.drawStr(0, 34, "T1:"); // first digit is screen coordinate for X-axis and second for Y-axis   
           // (it starts on left bottom corner of the text which is to be shown on the oled)   
      
           // T1 for temperature from DHT22 and T2 is from Thermistor   
      
   u8g.drawStr( 26, 34, dtostrf(t, 5, 2, str));    
   u8g.drawStr( 56, 34, "\260C");   
      
   u8g.drawStr( 70, 34, "T2:");   
   u8g.drawStr( 88, 34, dtostrf(steinhart, 5, 2, str)); //stienhart is the final Celsius reading   
   u8g.drawStr( 118, 34, "\260C");   
      
      
   u8g.drawStr( 70, 44, "H:");   
   u8g.drawStr( 88, 44, dtostrf(h, 5, 2, str));   
   u8g.drawStr( 119, 44, "%");   
      
     
      
   u8g.drawStr( 0, 44, "Mx:");   
   u8g.drawStr( 26, 44, dtostrf(Tmax, 5, 2, str));   
   u8g.drawStr( 56, 44, "\260C");   
     
   u8g.drawStr( 0, 54, "Nr :");   
   u8g.drawStr( 26, 54, dtostrf(setT, 5, 2, str));   
   u8g.drawStr( 56, 54, "\260C");   
     
   u8g.drawStr( 0, 64, "Mn:");   
   u8g.drawStr( 26, 64, dtostrf(Tmin, 5, 2, str));   
   u8g.drawStr( 56, 64, "\260C");   
     
      
     
      
      
     
     
     
     
   Alarm.delay(500);   
     
     
   } while ( u8g.nextPage() );   
  }   
     
     
     
     
     
     
  }   
     
     
     
  //**********************//**********************//**********************   
  //        LOOP END   
  //**********************//**********************//**********************   
     
     
     
     
     
     
     
     
  //**********************//**********************//**********************//**********************   
     
  //Functions called when daily time specific alarms (above in the loop) triggers:    
     
  //***********************************************//**********************//**********************   
     
     
  void ONAlarm() {   
     
     
     
  /* Tmax = 29;         // set day time temperatures   
  setT = 25;   
  Tmin = 19;   
  */   
     
  }   
     
     
  void ON2Alarm() {   
     
     
     
  setSyncProvider(RTC.get);   //It's time, sync the Arduino's INTERNAL Clock to the RTC   
     
     
  }   
     
     
  void OFFAlarm() {   
     
     
     
  /* Tmax = 26;        // set night time temperatures   
  setT = 23;   
  Tmin = 19;   
  */   
  }   
     
     
     
  void OFF2Alarm() {   
     
     
     
  setSyncProvider(RTC.get);   //It's time, sync the Arduino's INTERNAL Clock to the RTC   
     
     
  }   
     
     
     
     
  //**********************//**********************//**********************//**********************   
     
  //Function for digital clock display (in the SERIAL MONITOR )    
     
  //**********************//**********************//**********************//**********************   
     
     
     
     
  void digitalClockDisplay() { // digital clock display of the time 24hr format   
     
     
     
     
     
     
  Serial.print(hour());   
     
  printDigits(minute());   
     
  printDigits(second());   
     
  Serial.println("");   
     
  Serial.println(dayStr(weekday()));   
     
  Serial.print(monthStr(month()));   
     
  Serial.print(" ");   
     
  Serial.print(day());   
     
  Serial.print(" ");   
     
  Serial.println(year());   
  }   
     
     
     
     
  void printDigits(int digits) {   
  Serial.print(":");   
  if (digits < 10)   
   Serial.print('0');   
  Serial.print(digits);   
  }   
     
  //***********************************************//**********************//**********************   
     
     
     
  // Un comment the function below and comment the above only one can be used in the code or change names   
  // 12hrs display function   
     
     
     
     
     
  /*void digitalClockDisplay()  //// digital clock display of the time 12hr format   
     
  {   
     
     
  Serial.print(hourFormat12());   
     
     
  printDigits(minute());   
     
  printDigits(second());   
     
  Serial.println("");   
     
  Serial.println(dayStr(weekday()));   
     
  Serial.print(monthStr(month()));   
     
  Serial.print(" ");   
     
  Serial.print(day());   
     
  Serial.print(" ");   
     
  Serial.println(year());   
     
  //Alarm.delay(1000);   
     
  }   
     
     
     
  void printDigits(int digits)   
  {   
     
  Serial.print(":");   
     
     
  if (digits < 10) {   
     
     
   Serial.print('0');   
     
     
  }   
     
     
  Serial.print(digits);   
     
     
  }   
  */   
     
  //That's all folks taaaaan tantan taan .....taetan taetan taetan tantaaaaaaannnnn