D.I.Y. Make RCA/AV Cable for Raspberry pi (using earphones/headphones audio lead)

   Make RCA cable for Raspberry pi



I used  an old cell phone's hands-free earphones kit and a female RCA connectors cable to make an AV (audio/video) Cable for the Raspberry Pi.


First, I tried to use a "ready-made" AV cable that I had for a long time and it came with another cell phone (Nokia N95 8GB music edition) but it didn't work at first because the Raspberry pi and that cellphone have different pin-out in the Audio Jack.


So, when I plugged it in the Raspberry Pi 3 and in the TV ,I just got weird noises and no Video . After thinking about it for sometime,I tested it with a multimeter by putting it in the "continuity mode" and in that mode if you touch both of the leads of the multimeter together it shows the number "0" and if there is no connection between the two leads it shows the alphabet "l" which means out-of-limit or range. It actually measures the resistance between it's two leads.So, if there is no connection between the two points i.e. the audio jack's metal pin and the corresponding wires the resistance will be infinite or  too high for the meter to measure.


So, if you connect one lead of the multimeter (black or red doesn't matter in this case) to one of the four metal contacts of the Audio lead and the other lead of the multimeter to the RCA connector's outer metal part (Ground) or the center part (which is for the Signal) you can see which part of the Audio lead is connected to which part of the RCA connector.


In my case what was happening was that the Raspberry Pi's Video signal was going to the Ground of the Rca Cable and because ground is common for all the signals (Audio Left,Audio Right ,Video) all the three RCA connectors (red,white,yellow) had Video signal in their outer metal part of the connector and the "Actual Ground" was only on the Signal part in the center of the Yellow connector because of the different pin-out. 


However, I made it to work also, just to test the Video output of the Raspberry pi by using a single Male RCA connector with it's wire stripped and by wrapping it on both the outer part of the yellow connector (of that cell phones AV cable) to get the Video Signal and the center part to get the Ground and then it worked but it was too messy.

So,then i felt the need to make a proper AV cable for the pi  because I also fixed a cheap LCD display  and that display was part of a car's Headrest and meant to be used with the DVD player it came along with(the chinese car DVD player with built-in lcd  came with two head rests with LCDs in them ) and  it has two analog video inputs so it can work with the Rpi too.


How i made the AV cable can be seen in the picture below.


Raspberry Pi Audio Jack/RCA Connections Pin-out


Cell phone hands-free earphones with button and a Mic and four connector lead
Cellphone Earphones with Button and Mic for Calls
Female RCA connectors Cable

Female RCA Connectors Separated from the "other" lead


Separate all the wires and test with a multimeter (on continuity mode) because sometimes the wires are insulated and they have to be "burned" to remove the insulation

 Test all the wires before proceeding any further just to be sure because it will become  difficult to troubleshoot later if there is any problem with the connections 
Join the related wires together

Solder them together and Test them Again

Tape the wires separately and then together to make it all neat


Then I used Male-to-Male RCA cable to connect this to the TV. 

You can also use Male to Male RCA cable then cut it,strip it and join with the audio lead the same way and then it will directly connect to the TV giving the same results .

I did it this way because I also had the useless female connectors .




Car Head-rest Rear LCD for DVD player Front View



Back Cover Removed View of LCD and it's control board

Main IC on the control board of LCD

Back View of LCD control Board and Connectors




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    
     
   
Building an "Automated Green House" is not so easy ,if you don't have any previous experience of gardening,electronics or programming or in general  the "D.I.Y."(do It yourself) experience and you don't want to "read and learn a little" 
   

  In the process of  "trying" to make a greenhouse I read a-lot of things on-line and learned a-lot too, and after some time I thought it would be easy if at first I make a small "Grow-box". Making a small Grow-box is much easier,safer and quite cheap as the "environment" you want to control is much smaller and  "failure-points"or things which can go wrong also reduce in number and if there are any plants inside they can die or will give less "harvest",so the losses will  be less too as compared to a much larger greenhouse having a larger environment to control,much more "failure" points and if anything goes wrong all the plants in the larger greenhouse will be effected so for a person with less/no previous experience of gardening and less/no knowledge about the "local climate" and "plant's growth requirements", making a small grow-box is the right path to take.





Understanding How it all works :






Step 01: LIGHTS



                                                  To make an efficient grow box first you need to "understand the plants", the plant or plants you want to grow have specific requirements to grow properly and be healthy,for example: naturally during the day time plants need regular exposure to "sunlight" to make food for themselves ( Photosynthesis) and the duration of exposure changes gradually over the year as the days get shorter or longer and it has an affect on the plant's growth and it also gives the plants necessary "signals" to start or end the different stages of their complete "growth cycle"




"Sunlight" is composed of waves of  different wavelengths which can be seen in the form of a "Rainbow"(visible spectrum) and the sunlight is also intense or strong so in a grow box the plant will need a "light source".






     Selecting the right light source is very important,as any type of light will do the job for example: C.F.L.bulbsfluorescent tube lights,L.E.D.sHalogen bulbs, etc you just need to make sure that the "light source" can give off proper spectrum of light (learn about Color temperature also mentioned as a number printed on bulbsand proper "intensity of light" which is measured in" LUXluminous flux per unit area and the unit is "lumen" for luminous flux per square meter so, the intensity of light should be according to the requirements of the plant not more or less than that.





    If you read the printed text on a normal household "cfl bulb" there will be a number mentioned    e.g. 3700lm/W , 360lm/W , etc. which is the "light bulb efficiency" and it's measured in terms of "lumens per watt" (the amount of light produced per watt of electricity consumed). 



More lumens per watt means more light for your money and because it will consume electricity to run continuously so,the efficiency matters for both the plants and you the human.

Also, know the amount of heat the lights inside the grow box will produce e.g: C.F.L.s or leds give off very less heat as compared to halogen bulbs.






Step 02: Temperature and humidity:



Every type of plant has it's own temperature and humidity requirements and you will have to mimic and maintain them inside the grow box to let your plants grow and stay healthy.

As fluctuating temperatures outside the grow-box will affect the inside temperature and therefore a proper system for sensing of inside/outside temperature and humidity and for controlling the environment inside a fan, heating/cooling , humidifying/dehumidifying  should be in place.


For sensing and controlling you will need some sensors,relays (type of switches for controller)and a micro-controller like an Arduino .


Temperature sensing can be done using a thermistor ,(as it is easily available,cheap and can also be obtained/harvested/salvaged from an old laptop battery).


For humidity you can use a humidity sensor or DHT22 or 11(less accurate) which can sense both temperature and humidity, displaying that data in real-time on an lcd or an Oled display will be a good idea.









Step 03: Nutrients/Fertilizer :



Every type of plant has it's own specific nutrient requirements and they absorb those nutrients from their roots which are buried under a nutrient retaining medium 
e.g: soil or just water in the case of an aquaponic/ hydroponic system.






The basic mineral nutrients almost every plant requires are  N,P,K  (nitrogen,phosphorus,potassium)
   and the amount matters,too much or too less will harm the plants.







Step 04: The Box :



Finally,you'll have to make a box or a pre-made enclosure will do the job.It will be the boundary between the outside environment and the inside environment.







An important thing is to consider the "Fire hazard" as the lights or other high power devices or bad/sloppy wiring job can cause fireworks. or DEATH.







Size of the Box or the enclosure should be decided according to the plant's expected height and the distance of the plant's top part from the lights inside the top of the box and it will also need some space to "breath" as the plants grow sideways too.





The walls of the grow box should be reflective from the inside so the light can be efficiently distributed among the plant leaves,the box should have spaces or "vents"from which air can be sucked in and blown out which is not necessary to do continuously but occasionally it will have to be done,some holes in the walls for sensors and to attach a fan inside(not too powerful) to move the air around inside.


If the required "inside environment" is very different than the outside environment then 


proper insulation will be required also , so that the environment variables like temperature and 

humidity can easily be maintained.



So, the materials that can be used to make a box can be a thick/thin plastic/wood/metal or a


 wooden frame with walls made of polyethylene sheet or cardboard.If it is transluscent  the 

natural sunlight can also be used when available which can reduce electricity usage.