Photocell Delayed Action

Im having trouble with my sketch. It is running on a Wemos D1 mini. What i am trying to do is control a door on a chicken coop. What I want to do is use a photocell because a chicken has an internal timer that tells it to get in the coop just before dark but not all chickens have the same internal clock some stay out later than others and wait until its completely dark to go in the coop. If you use the basic photocell without delay it reaches 1024 before its dark out and the chicken is shut outside the coop. What I want to do is close the door 45min-60min after it reaches 1024. I have looked the internet over for sometime and haven’t found how to achieve this I think you use millis but I cant seem to get it to work. Here is the function Im calling every second !!!Please HELP!!

void DayNight ()

{


  open_state = digitalRead(sensor1);
  Serial.println(open_state);

  // Read the sensor pin
  sensorValue = analogRead(sensorPin);
  Serial.println(sensorValue);


  // If light level is high is detected, Open Door
  if ((sensorValue < highTreshold) && (doorFlag == true))
  {
    doorFlag = false;
    Blynk.virtualWrite(V10, Relay_OFF);
    Blynk.virtualWrite(V11, Relay_ON);
    digitalWrite (Relay_2, Relay_OFF);    //DOOR OPEN
    digitalWrite (Relay_1, Relay_ON);


  }

  // Top door sensor
  else if (open_state == LOW)
  {
    digitalWrite (Relay_1, Relay_OFF);
  }
 

  closed_state = digitalRead(sensor2);
  Serial.println(closed_state);
  // If light level is low is detected, Close Door

  unsigned long currentMillis = millis();
  unsigned long previousMillis = 0;
  const long interval = 60 * 1000UL; //add 45* for 45 min currently set to 1 min

  if (sensorValue == lowThresholdTimer) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;
 



     if ((sensorValue >= lowThreshold) && (currentMillis - previousMillis >= interval) && (doorFlag == false))
    {
      doorFlag = true;
      Blynk.virtualWrite(V11, Relay_OFF);
      Blynk.virtualWrite(V10, Relay_ON);
      digitalWrite (Relay_1, Relay_OFF);     //DOOR CLOSED
      digitalWrite (Relay_2, Relay_ON);

    }


    // Bottom door sensor
    else if (closed_state == LOW)
    {
      digitalWrite (Relay_2, Relay_OFF);

    }
  
  }
}

The problem with posting a snippet of your code is that we can’t see how your DayNight function is being called from within the rest of your code.

Post the complete sketch.

Pete.

here is complete code

/*************************************************************
  Download latest Blynk library here:
    https://github.com/blynkkk/blynk-library/releases/latest

  Blynk is a platform with iOS and Android apps to control
  Arduino, Raspberry Pi and the likes over the Internet.
  You can easily build graphic interfaces for all your
  projects by simply dragging and dropping widgets.

    Downloads, docs, tutorials: http://www.blynk.cc
    Sketch generator:           http://examples.blynk.cc
    Blynk community:            http://community.blynk.cc

  Blynk library is licensed under MIT license
  This example code is in public domain.

 *************************************************************

  You’ll need:
   - Blynk App (download from AppStore or Google Play)
   - WeMos D1 board
   - Decide how to connect to Blynk
     (USB, Ethernet, Wi-Fi, Bluetooth, ...)

  There is a bunch of great example sketches included to show you how to get
  started. Think of them as LEGO bricks  and combine them as you wish.
  For example, take the Ethernet Shield sketch and combine it with the
  Servo example, or choose a USB sketch and add a code from SendData
  example.
 *************************************************************/



// Assign Arduino Friendly Names to GPIO pins
#define D0 16
#define D1 5 // I2C Bus SCL (clock)
#define D2 4 // I2C Bus SDA (data)
#define D3 0
#define D4 2 // Same as "LED_BUILTIN", but inverted logic
#define D5 14 // SPI Bus SCK (clock)
#define D6 12 // SPI Bus MISO 
#define D7 13 // SPI Bus MOSI
#define D8 15 // SPI Bus SS (CS)

/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Wire.h>
#define ONE_WIRE_BUS D3         // Your ESP8266 pin (ESP8266 GPIO 2 = WeMos D1 Mini pin D4)
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);



// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "xxxxxxxxxxxxxxxxxxxxx";

// Your WiFi credentials.
// Set password to "" for open networks.
const char* ssid = "xxxxxxxxxx";
const char* pass = "xxxxxxxxx";
const char* IP = "192.168.10.10";
float timeout = (millis() / 1000);
int tries = 0;



//Sensors
#define sensor1  D1
#define sensor2  D2

// Relays
#define Relay_1  D5
#define Relay_2  D6
#define Relay_3  D7
//#define Relay_4 D3


#define Relay_ON  LOW
#define Relay_OFF HIGH


// Photocell
const int sensorPin = A0;
const int lowThreshold = 1022;
const int highTreshold = 400;
const int lowThresholdTimer = 1009;
int sensorValue;

// Coop Door
bool doorFlag = true;
bool doorNotify = true;
int open_state; // 0 close - 1 open switch
int closed_state; // 0 close - 1 open switch


// Temperature
int CoopTemperature;   // Room temperature in F
bool heatFlag = true;
bool heatNotify = true;

// App Buttons
bool buttonFlag;






// the timer object
BlynkTimer timer;

// Blynk App Virtual Pins

BLYNK_WRITE(V10)
{
  int UpBttn = param[1].asInt();; // assigning incoming value from pin V10 to a variable

  //Motor Direction Up
  open_state = digitalRead(sensor1);
  Serial.println(open_state);

  if (UpBttn == 0)
  { digitalWrite (Relay_2, Relay_OFF);
    digitalWrite (Relay_1, Relay_ON);
    Blynk.virtualWrite(V11, Relay_ON);
  }

  // Top door sensor
  else if (open_state == LOW)
  {
    digitalWrite (Relay_1, Relay_OFF);
  }

}

BLYNK_WRITE(V11)
{
  int DownBttn = param[2].asInt(); // assigning incoming value from pin V11 to a variable
  //Motor Direction Down
  closed_state = digitalRead(sensor2);
  Serial.println(closed_state);

  if (DownBttn == 0)
  {
    digitalWrite (Relay_1, Relay_OFF);
    Blynk.virtualWrite(V10, Relay_ON);
    digitalWrite (Relay_2, Relay_ON);
  }

  // Bottom door sensor
  else if (closed_state == LOW)
  {
    digitalWrite (Relay_2, Relay_OFF);

  }

}


BLYNK_WRITE(V14)
{

  if (param.asInt() == 0)
  {
    digitalWrite (Relay_3, Relay_ON);
  }

  // Bottom door sensor

  if (param.asInt() == 1)
  {
    digitalWrite (Relay_3, Relay_OFF);
  }

}

void setup()

{
  // Debug console
  Serial.begin(9600);

  //Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.config(auth, IPAddress(192, 168, 10, 10), 80);
  //Blynk.connectWiFi(ssid, pass);


  //if (WiFi.status() == WL_CONNECTED){
  //Serial.print("Wifi Connected"); }

  timer.setInterval(60000L, connectWiFi);
  //timer.setInterval(30000L,connectBlynk);
  timer.setInterval(65000L, CheckConnection);



  //Blynk.config(auth,IP, 80);
  //
  //
  //  if (WiFi.status() == WL_CONNECTED) {
  //    Blynk.connect(3333);}
  //
  // while (Blynk.connect() == false) {
  //    Serial.println("in while: Blynk.connect() == false");
  //    if (((millis() / 1000) - timeout) > 10)
  //      break;
  //  }
  //Blynk.notify("Chicken Coop Connected");

  pinMode(sensor1, INPUT_PULLUP);
  pinMode(sensor2, INPUT_PULLUP);
  pinMode (Relay_1, OUTPUT);
  pinMode (Relay_2, OUTPUT);
  pinMode (Relay_3, OUTPUT);
  //pinMode (Relay_4, OUTPUT);


  //-------( Initialize Pins so relays are inactive at reset)----
  digitalWrite(Relay_1, Relay_OFF);
  digitalWrite(Relay_2, Relay_OFF);
  digitalWrite(Relay_3, Relay_OFF);
  //digitalWrite(Relay_4, Relay_OFF);

  //sensors.begin();                        // Starts the DS18B20 sensor(s).
  //sensors.setResolution(10);              // More on resolution: http://www.homautomation.org/2015/11/17/ds18b20-how-to-change-resolution-9101112-bits/


  //Scheduled Timer Functions

  timer.setInterval(1000L, DayNight );
  timer.setInterval(1000L, SendLightGraph );
  timer.setInterval(10000L, sendTemps);    // Temperature sensor read interval. 10000 (ms) = 10 seconds.
  timer.setInterval(30000L, CoopTemp) ;
  timer.setInterval(2000L, CoopTempNotify);
  timer.setInterval(1000L, DoorNotify);

}

void loop()

{
  if (Blynk.connected()) {
    Blynk.run();
  }
  timer.run();
}
void connectBlynk()

{

  if ((WiFi.status() == WL_CONNECTED) && (((millis() / 1000) - timeout) > 30)) {
    Blynk.config(auth, IP, 80);
    Blynk.connect();
  }

}

void connectWiFi()

{
  BLYNK_LOG("Connecting to %s", ssid);
  if (pass && strlen(pass))
  {
    WiFi.begin(ssid, pass);
  }
  else {
    WiFi.begin(ssid);
  }

  //if (WiFi.status() == WL_CONNECTED) {
  //}
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("Wifi Connected");
  }

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    tries++;
    if (tries > 15)
      //offline
      break;
  }

}

void CheckConnection()

{ // check every 11s if connected to Blynk server
  if (!Blynk.connected()) {
    Serial.println("Not connected to Blynk server");
    Blynk.config(auth, IP, 80);
    Blynk.connect();  // try to connect to server with default timeout
  }

  else
  {
    Serial.println("Connected to Blynk server");
  }

}


void SendLightGraph ()

{
  sensorValue = analogRead(sensorPin);
  Blynk.virtualWrite(V5, sensorValue );
}


void DayNight ()

{


  open_state = digitalRead(sensor1);
  Serial.println(open_state);

  // Read the sensor pin
  sensorValue = analogRead(sensorPin);
  Serial.println(sensorValue);


  // If light level is high is detected, Open Door
  if ((sensorValue < highTreshold) && (doorFlag == true))
  {
    doorFlag = false;
    Blynk.virtualWrite(V10, Relay_OFF);
    Blynk.virtualWrite(V11, Relay_ON);
    digitalWrite (Relay_2, Relay_OFF);    //DOOR OPEN
    digitalWrite (Relay_1, Relay_ON);


  }

  // Top door sensor
  else if (open_state == LOW)
  {
    digitalWrite (Relay_1, Relay_OFF);
  }
 

  closed_state = digitalRead(sensor2);
  Serial.println(closed_state);
  // If light level is low is detected, Close Door

  unsigned long currentMillis = millis();
  unsigned long previousMillis = 0;
  const long interval = 60 * 1000UL; //add 45* for 45 min currently set to 1 min

  if (sensorValue == lowThresholdTimer) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;
 



     if ((sensorValue >= lowThreshold) && (currentMillis - previousMillis >= interval) && (doorFlag == false))
    {
      doorFlag = true;
      Blynk.virtualWrite(V11, Relay_OFF);
      Blynk.virtualWrite(V10, Relay_ON);
      digitalWrite (Relay_1, Relay_OFF);     //DOOR CLOSED
      digitalWrite (Relay_2, Relay_ON);

    }


    // Bottom door sensor
    else if (closed_state == LOW)
    {
      digitalWrite (Relay_2, Relay_OFF);

    }
  
  }
}







void DoorNotify()

{
  open_state = digitalRead(sensor1);
  closed_state = digitalRead(sensor2);

  if ((open_state == LOW) && (doorNotify == true))
  {
    doorNotify = false;
    Blynk.notify("Coop Door Open");
  }

  if ((closed_state == LOW) && (doorNotify == false))
  {
    doorNotify = true;
    Blynk.notify("Coop Door Closed");
  }
}

void sendTemps()
{
  sensors.requestTemperatures();                  // Polls the sensors.
  CoopTemperature = sensors.getTempFByIndex(0);// Stores temperature. Change to getTempCByIndex(0) for celcius.
  Serial.println(CoopTemperature);
  Blynk.virtualWrite(V13, CoopTemperature);         // Send Temperature to Blynk app Virtual pin 13.
}

void CoopTemp()

{

  if ((CoopTemperature <= 40 ) && (heatFlag == true))
  {
    heatFlag = false;
    digitalWrite (Relay_3, Relay_ON);//Coop Temperature Control Heat Light ON Below 40 Degrees
    Blynk.virtualWrite(V14, Relay_ON);
  }

  if ((CoopTemperature >= 45 ) && (CoopTemperature <= 46 ) && (heatFlag = false))


  {
    heatFlag = true;
    digitalWrite (Relay_3, Relay_OFF); //Coop Temperature Control Heat Light OFF Above 45 Degrees
    Blynk.virtualWrite(V14, Relay_OFF);
  }
}

void CoopTempNotify()

{
  if ((CoopTemperature <= 40 ) && (heatNotify == true))
  {
    heatNotify = false;
    Blynk.notify("Coop Heat Lamp ON");
  }

  else if ((CoopTemperature >= 45 ) && (heatNotify == false))

  {
    heatNotify = true;
    Blynk.notify("Coop Heat Lamp OFF");
  }
}
1 Like

Okay, so your DayNight function is being called every second 24/7 and each time it’s called your current/previous millis values are being reset.

If it was me, I’d create two flag variables:
Previous_DayNight_value
Current_DayNight_value

Then have a function that simply checks the light sensor value and compares it to your threshold value. The Current_DayNight_value is set to something that represents nighttime if the reading is more (or should that be less) than your threshold value.

You then compare the Current_DayNight_value to the Previous_DayNight_value. If they are the same, then it hasn’t changed from day to night in the the time since you last checked, so you do nothing.
However, if it has changed from day to night then you need to do something. You start by making Current_DayNight_value and Previous_DayNight_value the same, then you start a Blynk timeout timer for 45 minutes. When the timeout timer completes it operates the relay etc that close-up the chicken coup and notify that your ladies are tucked-up in bed :chicken: chicken: chicken:

Personally, I’d do this light level check quite infrequently, say every 5 minutes, so that minor variation in readings don’t cause silly results.

You’ll probably want to do some similar sort of processing around sunrise, but I’m guessing that you may not want the 45 minute delay. In this case you’ll need to do different things if Current_DayNight_value is day rather than night, which would require a slightly enhanced If statement.

Hope this makes sense!

Pete.

1 Like

While browsing the “project made” section I found another chicken-coop-door-photo sensor-thingy :smiley: I have no idea if it’s helpful, but you could always check it out:

https://community.blynk.cc/t/chicken-coop-automatic-door-with-cds/31287

1 Like

Thanks I tried the link but sketch wasn’t available

Pete

What are you calling a Blynk timeout timer?

Read this tutorial from @Gunner:
C++ Blynk - Code Examples for Basic Tasks (Work in Progress)

Pete.

Pete
Is the timer your speaking of the #20 - Variable timer? if so i moved my function into this timer but i cant seem to get it to work. i can put a button on my app press the button and get it to work but there is no delay. I don’t really want to use a button to initiate the timer because i may forget to turn it on and the door not close. It works as it did before with no delay see if you can tell me what im doing wrong. Im still a amateur at programming

/*************************************************************
  Download latest Blynk library here:
    https://github.com/blynkkk/blynk-library/releases/latest

  Blynk is a platform with iOS and Android apps to control
  Arduino, Raspberry Pi and the likes over the Internet.
  You can easily build graphic interfaces for all your
  projects by simply dragging and dropping widgets.

    Downloads, docs, tutorials: http://www.blynk.cc
    Sketch generator:           http://examples.blynk.cc
    Blynk community:            http://community.blynk.cc

  Blynk library is licensed under MIT license
  This example code is in public domain.

 *************************************************************

  You’ll need:
   - Blynk App (download from AppStore or Google Play)
   - WeMos D1 board
   - Decide how to connect to Blynk
     (USB, Ethernet, Wi-Fi, Bluetooth, ...)

  There is a bunch of great example sketches included to show you how to get
  started. Think of them as LEGO bricks  and combine them as you wish.
  For example, take the Ethernet Shield sketch and combine it with the
  Servo example, or choose a USB sketch and add a code from SendData
  example.
 *************************************************************/



// Assign Arduino Friendly Names to GPIO pins
#define D0 16
#define D1 5 // I2C Bus SCL (clock)
#define D2 4 // I2C Bus SDA (data)
#define D3 0
#define D4 2 // Same as "LED_BUILTIN", but inverted logic
#define D5 14 // SPI Bus SCK (clock)
#define D6 12 // SPI Bus MISO 
#define D7 13 // SPI Bus MOSI
#define D8 15 // SPI Bus SS (CS)

/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Wire.h>
#define ONE_WIRE_BUS D3         // Your ESP8266 pin (ESP8266 GPIO 2 = WeMos D1 Mini pin D4)
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);



// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "xxxxxxxxxx";

// Your WiFi credentials.
// Set password to "" for open networks.
const char* ssid = "xxxxxxx";
const char* pass = "xxxxxxx";
const char* IP = "192.168.10.10";
float timeout = (millis() / 1000);
int tries = 0;



//Sensors
#define sensor1  D1
#define sensor2  D2

// Relays
#define Relay_1  D5
#define Relay_2  D6
#define Relay_3  D7
//#define Relay_4 D3


#define Relay_ON  LOW
#define Relay_OFF HIGH


// Photocell
const int sensorPin = A0;
const int NightValue = 1022;
const int DayValue = 400;
const int lowThresholdTimer = 1009;
int sensorValue;

// Coop Door
bool doorFlag = true;
bool doorNotify = true;
int open_state; // 0 close - 1 open switch
int closed_state; // 0 close - 1 open switch


// Temperature
int CoopTemperature;   // Room temperature in F
bool heatFlag = true;
bool heatNotify = true;

// App Buttons
bool buttonFlag;







// the timer object
BlynkTimer timer;

// Blynk App Virtual Pins

BLYNK_WRITE(V10)
{
  int UpBttn = param[1].asInt();; // assigning incoming value from pin V10 to a variable

  //Motor Direction Up
  open_state = digitalRead(sensor1);
  Serial.println(open_state);

  if (UpBttn == 0)
  { digitalWrite (Relay_2, Relay_OFF);
    digitalWrite (Relay_1, Relay_ON);
    Blynk.virtualWrite(V11, Relay_ON);
  }

  // Top door sensor
  else if (open_state == LOW)
  {
    digitalWrite (Relay_1, Relay_OFF);
  }

}

BLYNK_WRITE(V11)
{
  int DownBttn = param[2].asInt(); // assigning incoming value from pin V11 to a variable
  //Motor Direction Down
  closed_state = digitalRead(sensor2);
  Serial.println(closed_state);

  if (DownBttn == 0)
  {
    digitalWrite (Relay_1, Relay_OFF);
    Blynk.virtualWrite(V10, Relay_ON);
    digitalWrite (Relay_2, Relay_ON);
  }

  // Bottom door sensor
  else if (closed_state == LOW)
  {
    digitalWrite (Relay_2, Relay_OFF);

  }

}


BLYNK_WRITE(V14)
{

  if (param.asInt() == 0)
  {
    digitalWrite (Relay_3, Relay_ON);
  }

  // Bottom door sensor

  if (param.asInt() == 1)
  {
    digitalWrite (Relay_3, Relay_OFF);
  }

}

long variableTime = 10000; // default interval time of 1 second
int varTimer;  // Setup Timeout Timer ID 

BLYNK_WRITE(V0) { // Widget for interval timing
  variableTime = param.asInt();
  if (variableTime <= 0) { // prevents a timer from becoming 0 or less
    variableTime = 1;
  }
  timerLoop();  // Call your timed loop
}



void timerLoop() {
  timer.deleteTimer(varTimer);  // Cancel previous Timeout Timer
    
  //  Do your stuff here every (variableTime) seconds

// If light level is low is detected, Close Door
  closed_state = digitalRead(sensor2);
  Serial.println(closed_state);
  

   if ((sensorValue >= NightValue)  && (doorFlag == false))
  {
    doorFlag = true;
    Blynk.virtualWrite(V11, Relay_OFF);
    Blynk.virtualWrite(V10, Relay_ON);
    digitalWrite (Relay_1, Relay_OFF);     //DOOR CLOSED
    digitalWrite (Relay_2, Relay_ON);
    

  }


  // Bottom door sensor
  else if (closed_state == LOW)
  {
    digitalWrite (Relay_2, Relay_OFF);

  }

   varTimer = timer.setTimeout(variableTime, timerLoop);  // Set new Timeout timer
}

void setup()

{
  // Debug console
  Serial.begin(9600);

  //Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.config(auth, IPAddress(192, 168, 10, 10), 80);
  //Blynk.connectWiFi(ssid, pass);


  //if (WiFi.status() == WL_CONNECTED){
  //Serial.print("Wifi Connected"); }

  timer.setInterval(60000L, connectWiFi);
  //timer.setInterval(30000L,connectBlynk);
  timer.setInterval(65000L, CheckConnection);



  //Blynk.config(auth,IP, 80);
  //
  //
  //  if (WiFi.status() == WL_CONNECTED) {
  //    Blynk.connect(3333);}
  //
  // while (Blynk.connect() == false) {
  //    Serial.println("in while: Blynk.connect() == false");
  //    if (((millis() / 1000) - timeout) > 10)
  //      break;
  //  }
  //Blynk.notify("Chicken Coop Connected");

  pinMode(sensor1, INPUT_PULLUP);
  pinMode(sensor2, INPUT_PULLUP);
  pinMode (Relay_1, OUTPUT);
  pinMode (Relay_2, OUTPUT);
  pinMode (Relay_3, OUTPUT);
  //pinMode (Relay_4, OUTPUT);


  //-------( Initialize Pins so relays are inactive at reset)----
  digitalWrite(Relay_1, Relay_OFF);
  digitalWrite(Relay_2, Relay_OFF);
  digitalWrite(Relay_3, Relay_OFF);
  //digitalWrite(Relay_4, Relay_OFF);

  //sensors.begin();                        // Starts the DS18B20 sensor(s).
  //sensors.setResolution(10);              // More on resolution: http://www.homautomation.org/2015/11/17/ds18b20-how-to-change-resolution-9101112-bits/


  //Scheduled Timer Functions

  //timer.setInterval(1000L, MillisReset);
  timer.setInterval(5000L, Day );
  //timer.setInterval(2000L, Night );
  timer.setInterval(1000L, SendLightGraph );
  timer.setInterval(10000L, sendTemps);    // Temperature sensor read interval. 10000 (ms) = 10 seconds.
  timer.setInterval(30000L, CoopTemp) ;
  timer.setInterval(2000L, CoopTempNotify);
  timer.setInterval(3000L, DoorNotify);
  
}

void loop()

{
  if (Blynk.connected()) {
    Blynk.run();
  }
  timer.run();
}
void connectBlynk()

{

  if ((WiFi.status() == WL_CONNECTED) && (((millis() / 1000) - timeout) > 30)) {
    Blynk.config(auth, IP, 80);
    Blynk.connect();
  }

}

void connectWiFi()

{
  BLYNK_LOG("Connecting to %s", ssid);
  if (pass && strlen(pass))
  {
    WiFi.begin(ssid, pass);
  }
  else {
    WiFi.begin(ssid);
  }

  //if (WiFi.status() == WL_CONNECTED) {
  //}
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("Wifi Connected");
  }

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    tries++;
    if (tries > 15)
      //offline
      break;
  }

}

void CheckConnection()

{ // check every 11s if connected to Blynk server
  if (!Blynk.connected()) {
    Serial.println("Not connected to Blynk server");
    Blynk.config(auth, IP, 80);
    Blynk.connect();  // try to connect to server with default timeout
  }

  else
  {
    Serial.println("Connected to Blynk server");
  }

}


void SendLightGraph ()

{
  sensorValue = analogRead(sensorPin);
  Blynk.virtualWrite(V5, sensorValue );
}




void Day()

{


  open_state = digitalRead(sensor1);
  Serial.println(open_state);

  // Read the sensor pin
  sensorValue = analogRead(sensorPin);
  Serial.println(sensorValue);


  // If light level is high is detected, Open Door
  if ((sensorValue < DayValue) && (doorFlag == true))
  {
    doorFlag = false;
    Blynk.virtualWrite(V10, Relay_OFF);
    Blynk.virtualWrite(V11, Relay_ON);
    digitalWrite (Relay_2, Relay_OFF);    //DOOR OPEN
    digitalWrite (Relay_1, Relay_ON);


  }

  // Top door sensor
  else if (open_state == LOW)
  {
    digitalWrite (Relay_1, Relay_OFF);
  }



}


void Night () {

// If light level is low is detected, Close Door
  closed_state = digitalRead(sensor2);
  Serial.println(closed_state);
  

   if ((sensorValue > NightValue)  && (doorFlag == false))
  {
    doorFlag = true;
    Blynk.virtualWrite(V11, Relay_OFF);
    Blynk.virtualWrite(V10, Relay_ON);
    digitalWrite (Relay_1, Relay_OFF);     //DOOR CLOSED
    digitalWrite (Relay_2, Relay_ON);
    

  }


  // Bottom door sensor
  else if (closed_state == LOW)
  {
    digitalWrite (Relay_2, Relay_OFF);

  }

}



void DoorNotify()

{
  open_state = digitalRead(sensor1);
  closed_state = digitalRead(sensor2);

  if ((open_state == LOW) && (doorNotify == true))
  {
    doorNotify = false;
    Blynk.notify("Coop Door Open");
  }

  if ((closed_state == LOW) && (doorNotify == false))
  {
    doorNotify = true;
    Blynk.notify("Coop Door Closed");
  }
}

void sendTemps()
{
  sensors.requestTemperatures();                  // Polls the sensors.
  CoopTemperature = sensors.getTempFByIndex(0);// Stores temperature. Change to getTempCByIndex(0) for celcius.
  Serial.println(CoopTemperature);
  Blynk.virtualWrite(V13, CoopTemperature);         // Send Temperature to Blynk app Virtual pin 13.
}

void CoopTemp()

{

  if ((CoopTemperature <= 40 ) && (heatFlag == true))
  {
    heatFlag = false;
    digitalWrite (Relay_3, Relay_ON);//Coop Temperature Control Heat Light ON Below 40 Degrees
    Blynk.virtualWrite(V14, Relay_ON);
  }

  if ((CoopTemperature >= 45 ) && (CoopTemperature <= 46 ) && (heatFlag = false))


  {
    heatFlag = true;
    digitalWrite (Relay_3, Relay_OFF); //Coop Temperature Control Heat Light OFF Above 45 Degrees
    Blynk.virtualWrite(V14, Relay_OFF);
  }
}

void CoopTempNotify()

{
  if ((CoopTemperature <= 40 ) && (heatNotify == true))
  {
    heatNotify = false;
    Blynk.notify("Coop Heat Lamp ON");
  }

  else if ((CoopTemperature >= 45 ) && (heatNotify == false))

  {
    heatNotify = true;
    Blynk.notify("Coop Heat Lamp OFF");
  }
}```

I wasn’t suggestthat you use @Gunner’s code in its entirety, simply pointing you to a tutorial about the timeout timer.
If you go back and read my comments again, and this time bear in mind that the timeout timer is initiated using the timer.setTimeout(delay in millis, function to be called when timeout is reached) command, it will hopefully make more sense.

Pete.

I got it to work!! here is what I did- I separated Day from Night with Day function and Night function. I also created a DoorState function because the door has to be checked every second so the door sensor would work instantly. If anything longer than a second the reed switch would pass the magnet and motor would continuously run and not turn off so I couldn’t run the function every 5min like suggested the way it was. As for the timer I used the (timer.setTimer(45 * 60 * 1000L, DoorTimer, 1); in the Night function to allow the 45min delay and called it once every time sensorValue >= NightValue. The Day and Night function in the sketch below are set to one sec for testing purposes I plan to set these to 5 min like suggested.

/*************************************************************
  Download latest Blynk library here:
    https://github.com/blynkkk/blynk-library/releases/latest

  Blynk is a platform with iOS and Android apps to control
  Arduino, Raspberry Pi and the likes over the Internet.
  You can easily build graphic interfaces for all your
  projects by simply dragging and dropping widgets.

    Downloads, docs, tutorials: http://www.blynk.cc
    Sketch generator:           http://examples.blynk.cc
    Blynk community:            http://community.blynk.cc

  Blynk library is licensed under MIT license
  This example code is in public domain.

 *************************************************************

  You’ll need:
   - Blynk App (download from AppStore or Google Play)
   - WeMos D1 board
   - Decide how to connect to Blynk
     (USB, Ethernet, Wi-Fi, Bluetooth, ...)

  There is a bunch of great example sketches included to show you how to get
  started. Think of them as LEGO bricks  and combine them as you wish.
  For example, take the Ethernet Shield sketch and combine it with the
  Servo example, or choose a USB sketch and add a code from SendData
  example.
 *************************************************************/



// Assign Arduino Friendly Names to GPIO pins
#define D0 16
#define D1 5 // I2C Bus SCL (clock)
#define D2 4 // I2C Bus SDA (data)
#define D3 0
#define D4 2 // Same as "LED_BUILTIN", but inverted logic
#define D5 14 // SPI Bus SCK (clock)
#define D6 12 // SPI Bus MISO 
#define D7 13 // SPI Bus MOSI
#define D8 15 // SPI Bus SS (CS)

/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Wire.h>
#define ONE_WIRE_BUS D3         // Your ESP8266 pin (ESP8266 GPIO 2 = WeMos D1 Mini pin D4)
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);



// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "xxxxxxxxxxxxxxx";

// Your WiFi credentials.
// Set password to "" for open networks.
const char* ssid = "xxxxxxxxxx";
const char* pass = "xxxxxxxxx";
const char* IP = "192.168.10.10";
float timeout = (millis() / 1000);
int tries = 0;



//Sensors
#define sensor1  D1
#define sensor2  D2

// Relays
#define Relay_1  D5
#define Relay_2  D6
#define Relay_3  D7
//#define Relay_4 D3


#define Relay_ON  LOW
#define Relay_OFF HIGH


// Photocell
const int sensorPin = A0;
const int NightValue = 1022;
const int DayValue = 400;
int sensorValue;

// Coop Door
bool doorFlag = true;
bool doorNotify = true;
int open_state; // 0 close - 1 open switch
int closed_state; // 0 close - 1 open switch


// Temperature
int CoopTemperature;   // Room temperature in F
bool heatFlag = true;
bool heatNotify = true;

// App Buttons
bool buttonFlag;

//Day-Night Flags
bool TimerFlag = false;// interval at which to blink (milliseconds)



// the timer object
BlynkTimer timer;

// Blynk App Virtual Pins

BLYNK_WRITE(V10)
{
  int UpBttn = param[1].asInt();; // assigning incoming value from pin V10 to a variable

  //Motor Direction Up
  open_state = digitalRead(sensor1);
  Serial.println(open_state);

  if (UpBttn == 0)
  { digitalWrite (Relay_2, Relay_OFF);
    digitalWrite (Relay_1, Relay_ON);
    Blynk.virtualWrite(V11, Relay_ON);
  }

  // Top door sensor
  else if (open_state == LOW)
  {
    digitalWrite (Relay_1, Relay_OFF);
  }

}

BLYNK_WRITE(V11)
{
  int DownBttn = param[2].asInt(); // assigning incoming value from pin V11 to a variable
  //Motor Direction Down
  closed_state = digitalRead(sensor2);
  Serial.println(closed_state);

  if (DownBttn == 0)
  {
    digitalWrite (Relay_1, Relay_OFF);
    Blynk.virtualWrite(V10, Relay_ON);
    digitalWrite (Relay_2, Relay_ON);
  }

  // Bottom door sensor
  else if (closed_state == LOW)
  {
    digitalWrite (Relay_2, Relay_OFF);

  }

}


BLYNK_WRITE(V14)
{

  if (param.asInt() == 0)
  {
    digitalWrite (Relay_3, Relay_ON);
  }

  // Bottom door sensor

  if (param.asInt() == 1)
  {
    digitalWrite (Relay_3, Relay_OFF);
  }

}


void setup()

{
  // Debug console
  Serial.begin(9600);

  timer.setInterval(60000L, connectWiFi);
  //timer.setInterval(30000L,connectBlynk);
  timer.setInterval(65000L, CheckConnection);

  pinMode(sensor1, INPUT_PULLUP);
  pinMode(sensor2, INPUT_PULLUP);
  pinMode (Relay_1, OUTPUT);
  pinMode (Relay_2, OUTPUT);
  pinMode (Relay_3, OUTPUT);
  //pinMode (Relay_4, OUTPUT);


  //-------( Initialize Pins so relays are inactive at reset)----
  digitalWrite(Relay_1, Relay_OFF);
  digitalWrite(Relay_2, Relay_OFF);
  digitalWrite(Relay_3, Relay_OFF);
  //digitalWrite(Relay_4, Relay_OFF);

  sensors.begin();                        // Starts the DS18B20 sensor(s).
  sensors.setResolution(10);              // More on resolution: http://www.homautomation.org/2015/11/17/ds18b20-how-to-change-resolution-9101112-bits/


  //Scheduled Timer Functions

  
  timer.setInterval(1000L, Day );
  timer.setInterval(1020L, Night );
  timer.setInterval(1000L, DoorState );
  timer.setInterval(4000L, SendLightGraph );
  timer.setInterval(10000L, sendTemps);    // Temperature sensor read interval. 10000 (ms) = 10 seconds.
  timer.setInterval(30000L, CoopTemp) ;
  timer.setInterval(2000L, CoopTempNotify);
  timer.setInterval(3000L, DoorNotify);

}

void loop()

{
  if (Blynk.connected()) {
    Blynk.run();
  }
  timer.run();
}

void connectBlynk()

{

  if ((WiFi.status() == WL_CONNECTED) && (((millis() / 1000) - timeout) > 30)) {
    Blynk.config(auth, IP, 80);
    Blynk.connect();
  }

}

void connectWiFi()

{
  BLYNK_LOG("Connecting to %s", ssid);
  if (pass && strlen(pass))
  {
    WiFi.begin(ssid, pass);
  }
  else {
    WiFi.begin(ssid);
  }

  //if (WiFi.status() == WL_CONNECTED) {
  //}
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("Wifi Connected");
  }

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    tries++;
    if (tries > 15)
      //offline
      break;
  }

}

void CheckConnection()

{ // check every 11s if connected to Blynk server
  if (!Blynk.connected()) {
    Serial.println("Not connected to Blynk server");
    Blynk.config(auth, IP, 80);
    Blynk.connect();  // try to connect to server with default timeout
  }

  else
  {
    Serial.println("Connected to Blynk server");
  }

}


void SendLightGraph ()

{
  sensorValue = analogRead(sensorPin);
  Blynk.virtualWrite(V5, sensorValue );
}


void Day()

{


  open_state = digitalRead(sensor1);
  Serial.println(open_state);

  // Read the sensor pin
  sensorValue = analogRead(sensorPin);
  Serial.println(sensorValue);


  // If light level is high is detected, Open Door
  if ((sensorValue < DayValue) && (doorFlag == true))
  {
    doorFlag = false;
    Blynk.virtualWrite(V10, Relay_OFF);
    Blynk.virtualWrite(V11, Relay_ON);
    digitalWrite (Relay_2, Relay_OFF);    //DOOR OPEN
    digitalWrite (Relay_1, Relay_ON);
  }

}


void Night () {

  // If light level is low is detected, Close Door
  closed_state = digitalRead(sensor2);
  Serial.println(closed_state);
  // Read the sensor pin
  sensorValue = analogRead(sensorPin);
  Serial.println(sensorValue);
  int setTimer(long d, timer_callback f, int n);


  if ((sensorValue >= NightValue)  && (doorFlag == false) && (TimerFlag == false))
  { TimerFlag = true;
    timer.setTimer(45 * 60 * 1000L, DoorTimer, 1);
  }

}

void DoorState() {

  // Top door sensor
  if (open_state == LOW)
  {
    digitalWrite (Relay_1, Relay_OFF);
  }

  //Bottom door semsor
  if (closed_state == LOW)
  {
    digitalWrite (Relay_2, Relay_OFF);
  }

}

void DoorTimer() {

  if (TimerFlag == true) {
    doorFlag = true;
    TimerFlag = false;
    Blynk.virtualWrite(V11, Relay_OFF);
    Blynk.virtualWrite(V10, Relay_ON);
    digitalWrite (Relay_1, Relay_OFF);     //DOOR CLOSED
    digitalWrite (Relay_2, Relay_ON);
  }

}


void DoorNotify()

{
  open_state = digitalRead(sensor1);
  closed_state = digitalRead(sensor2);

  if ((open_state == LOW) && (doorNotify == true))
  {
    doorNotify = false;
    Blynk.notify("Coop Door Open");
  }

  if ((closed_state == LOW) && (doorNotify == false))
  {
    doorNotify = true;
    Blynk.notify("Coop Door Closed");
  }
}

void sendTemps()
{
  sensors.requestTemperatures();                  // Polls the sensors.
  CoopTemperature = sensors.getTempFByIndex(0);// Stores temperature. Change to getTempCByIndex(0) for celcius.
  Serial.println(CoopTemperature);
  Blynk.virtualWrite(V13, CoopTemperature);         // Send Temperature to Blynk app Virtual pin 13.
}

void CoopTemp()

{

  if ((CoopTemperature <= 40 ) && (heatFlag == true))
  {
    heatFlag = false;
    digitalWrite (Relay_3, Relay_ON);//Coop Temperature Control Heat Light ON Below 40 Degrees
    Blynk.virtualWrite(V14, Relay_ON);
  }

  if ((CoopTemperature >= 45 ) && (CoopTemperature <= 46 ) && (heatFlag = false))


  {
    heatFlag = true;
    digitalWrite (Relay_3, Relay_OFF); //Coop Temperature Control Heat Light OFF Above 45 Degrees
    Blynk.virtualWrite(V14, Relay_OFF);
  }
}

void CoopTempNotify()

{
  if ((CoopTemperature <= 40 ) && (heatNotify == true))
  {
    heatNotify = false;
    Blynk.notify("Coop Heat Lamp ON");
  }

  else if ((CoopTemperature >= 45 ) && (heatNotify == false))

  {
    heatNotify = true;
    Blynk.notify("Coop Heat Lamp OFF");
  }
}

Using an external interrupt should eliminate that excessive need.

https://www.google.com/search?q=esp8266+interrupts

You also have most of your timers that will coincide with other timers along their path, periodically running multiple functions at the same time.

Evey timer starts counting down at the same time, thus Day() and DoorState() will run simultaneously every second and will be joined by CoopTempNotify() every 2nd iteration, DoorNotify() every 3rd and SendLightGraph() along with CoopTempNotify() again every 4th, … and so on…

1 Like

Gunner

I got the interrupts to work but the problem i am having is if the wemos D1 mini reboots and the door is closed the motor that opens the door keeps running because there wasnt a fall,rise or change in the pin. I tried to use High and low but they did nothing any ideas how to monitor sensor state pin on boot up

/*************************************************************
  Download latest Blynk library here:
    https://github.com/blynkkk/blynk-library/releases/latest

  Blynk is a platform with iOS and Android apps to control
  Arduino, Raspberry Pi and the likes over the Internet.
  You can easily build graphic interfaces for all your
  projects by simply dragging and dropping widgets.

    Downloads, docs, tutorials: http://www.blynk.cc
    Sketch generator:           http://examples.blynk.cc
    Blynk community:            http://community.blynk.cc

  Blynk library is licensed under MIT license
  This example code is in public domain.

 *************************************************************

  You’ll need:
   - Blynk App (download from AppStore or Google Play)
   - WeMos D1 board
   - Decide how to connect to Blynk
     (USB, Ethernet, Wi-Fi, Bluetooth, ...)

  There is a bunch of great example sketches included to show you how to get
  started. Think of them as LEGO bricks  and combine them as you wish.
  For example, take the Ethernet Shield sketch and combine it with the
  Servo example, or choose a USB sketch and add a code from SendData
  example.
 *************************************************************/



// Assign Arduino Friendly Names to GPIO pins
#define D0 16
#define D1 5 // I2C Bus SCL (clock)
#define D2 4 // I2C Bus SDA (data)
#define D3 0
#define D4 2 // Same as "LED_BUILTIN", but inverted logic
#define D5 14 // SPI Bus SCK (clock)
#define D6 12 // SPI Bus MISO 
#define D7 13 // SPI Bus MOSI
#define D8 15 // SPI Bus SS (CS)

/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Wire.h>
#define ONE_WIRE_BUS D3         // Your ESP8266 pin (ESP8266 GPIO 2 = WeMos D1 Mini pin D4)
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);



// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "xxxxxxxxxxxx";

// Your WiFi credentials.
// Set password to "" for open networks.
const char* ssid = "xxxxxxxx";
const char* pass = "xxxxxxxx";
const char* IP = "192.168.10.10";
float timeout = (millis() / 1000);
int tries = 0;



//Sensors
const byte sensor1 = D1;
const byte sensor2 = D2;

// Relays
#define Relay_1  D5
#define Relay_2  D6
#define Relay_3  D7
//#define Relay_4 D3


#define Relay_ON  LOW
#define Relay_OFF HIGH


// Photocell
const int sensorPin = A0;
const int NightValue = 1022;
const int DayValue = 400;
int sensorValue;

// Coop Door
bool doorFlag = true;
bool doorNotify = true;
volatile byte open_state; // 0 close - 1 open switch
volatile byte closed_state; // 0 close - 1 open switch


// Temperature
int CoopTemperature;   // Room temperature in F
bool heatFlag = true;
bool heatNotify = true;

// App Buttons
bool buttonFlag;

//Day-Night Flags
bool TimerFlag = false;// interval at which to blink (milliseconds)



// the timer object
BlynkTimer timer;

// Blynk App Virtual Pins

BLYNK_WRITE(V10)
{
  int UpBttn = param[1].asInt();; // assigning incoming value from pin V10 to a variable

  //Motor Direction Up
  open_state = digitalRead(sensor1);
  Serial.println(open_state);

  if (UpBttn == 0)
  { digitalWrite (Relay_2, Relay_OFF);
    digitalWrite (Relay_1, Relay_ON);
    Blynk.virtualWrite(V11, Relay_ON);
  }

  // Top door sensor
  else if (open_state == LOW)
  {
    digitalWrite (Relay_1, Relay_OFF);
  }

}

BLYNK_WRITE(V11)
{
  int DownBttn = param[2].asInt(); // assigning incoming value from pin V11 to a variable
  //Motor Direction Down
  closed_state = digitalRead(sensor2);
  Serial.println(closed_state);

  if (DownBttn == 0)
  {
    digitalWrite (Relay_1, Relay_OFF);
    Blynk.virtualWrite(V10, Relay_ON);
    digitalWrite (Relay_2, Relay_ON);
  }

  // Bottom door sensor
  else if (closed_state == LOW)
  {
    digitalWrite (Relay_2, Relay_OFF);

  }

}


BLYNK_WRITE(V14)
{

  if (param.asInt() == 0)
  {
    digitalWrite (Relay_3, Relay_ON);
  }

 

  if (param.asInt() == 1)
  {
    digitalWrite (Relay_3, Relay_OFF);
  }

}


void setup()

{
  // Debug console
  Serial.begin(9600);

  timer.setInterval(60000L, connectWiFi);
  //timer.setInterval(30000L,connectBlynk);
  timer.setInterval(65000L, CheckConnection);

  pinMode(sensor1, INPUT_PULLUP);
  pinMode(sensor2, INPUT_PULLUP);
  pinMode (Relay_1, OUTPUT);
  pinMode (Relay_2, OUTPUT);
  pinMode (Relay_3, OUTPUT);
  //pinMode (Relay_4, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(sensor1), DoorStateOpen, FALLING);
  attachInterrupt(digitalPinToInterrupt(sensor2), DoorStateClosed, FALLING);
  
  //-------( Initialize Pins so relays are inactive at reset)--
  digitalWrite(Relay_1, Relay_OFF);
  digitalWrite(Relay_2, Relay_OFF);
  digitalWrite(Relay_3, Relay_OFF);
  //digitalWrite(Relay_4, Relay_OFF);

  sensors.begin();                        // Starts the DS18B20 sensor(s).
  sensors.setResolution(10);              // More on resolution: http://www.homautomation.org/2015/11/17/ds18b20-how-to-change-resolution-9101112-bits/


  //Scheduled Timer Functions

  
  timer.setInterval(1000L, Day );
  timer.setInterval(1000L, Night );
  //timer.setInterval(1000L, DoorState );
  timer.setInterval(4000L, SendLightGraph );
  timer.setInterval(10000L, sendTemps);    // Temperature sensor read interval. 10000 (ms) = 10 seconds.
  timer.setInterval(30000L, CoopTemp) ;
  timer.setInterval(2000L, CoopTempNotify);
  timer.setInterval(3000L, DoorNotify);

}

void loop()

{
  if (Blynk.connected()) {
    Blynk.run();
  }
  timer.run();
}

void connectBlynk()

{

  if ((WiFi.status() == WL_CONNECTED) && (((millis() / 1000) - timeout) > 30)) {
    Blynk.config(auth, IP, 80);
    Blynk.connect();
  }

}

void connectWiFi()

{
  BLYNK_LOG("Connecting to %s", ssid);
  if (pass && strlen(pass))
  {
    WiFi.begin(ssid, pass);
  }
  else {
    WiFi.begin(ssid);
  }

  //if (WiFi.status() == WL_CONNECTED) {
  //}
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("Wifi Connected");
  }

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    tries++;
    if (tries > 15)
      //offline
      break;
  }

}

void CheckConnection()

{ // check every 11s if connected to Blynk server
  if (!Blynk.connected()) {
    Serial.println("Not connected to Blynk server");
    Blynk.config(auth, IP, 80);
    Blynk.connect();  // try to connect to server with default timeout
  }

  else
  {
    Serial.println("Connected to Blynk server");
  }

}


void SendLightGraph ()

{
  sensorValue = analogRead(sensorPin);
  Blynk.virtualWrite(V5, sensorValue );
}


void Day()

{


  open_state = digitalRead(sensor1);
  Serial.println(open_state);

  // Read the sensor pin
  sensorValue = analogRead(sensorPin);
  Serial.println(sensorValue);


  // If light level is high is detected, Open Door
  if ((sensorValue < DayValue) && (doorFlag == true))
  {
    doorFlag = false;
    Blynk.virtualWrite(V10, Relay_OFF);
    Blynk.virtualWrite(V11, Relay_ON);
    digitalWrite (Relay_2, Relay_OFF);    //DOOR OPEN
    digitalWrite (Relay_1, Relay_ON);
  }

}


void Night () {

  // If light level is low is detected, Close Door
  closed_state = digitalRead(sensor2);
  Serial.println(closed_state);
  // Read the sensor pin
  sensorValue = analogRead(sensorPin);
  Serial.println(sensorValue);
  int setTimer(long d, timer_callback f, int n);


  if ((sensorValue >= NightValue)  && (doorFlag == false) && (TimerFlag == false))
  { TimerFlag = true;
    timer.setTimer(1000L, DoorTimer, 1);
  }

}

void DoorTimer() {

  if (TimerFlag == true) {
    doorFlag = true;
    TimerFlag = false;
    Blynk.virtualWrite(V11, Relay_OFF);
    Blynk.virtualWrite(V10, Relay_ON);
    digitalWrite (Relay_1, Relay_OFF);     //DOOR CLOSED
    digitalWrite (Relay_2, Relay_ON);
  }

}

void DoorStateOpen() {

  // Top door sensor
  if (open_state == HIGH)
  {
    digitalWrite (Relay_1, Relay_OFF);
  }


}

void DoorStateClosed() {


  //Bottom door semsor
  if (closed_state == HIGH)
  {
    digitalWrite (Relay_2, Relay_OFF);
  }

}

void DoorNotify()

{
  open_state = digitalRead(sensor1);
  closed_state = digitalRead(sensor2);

  if ((open_state == LOW) && (doorNotify == true))
  {
    doorNotify = false;
    Blynk.notify("Coop Door Open");
  }

  if ((closed_state == LOW) && (doorNotify == false))
  {
    doorNotify = true;
    Blynk.notify("Coop Door Closed");
  }
}

void sendTemps()
{
  sensors.requestTemperatures();                  // Polls the sensors.
  CoopTemperature = sensors.getTempFByIndex(0);// Stores temperature. Change to getTempCByIndex(0) for celcius.
  Serial.println(CoopTemperature);
  Blynk.virtualWrite(V13, CoopTemperature);         // Send Temperature to Blynk app Virtual pin 13.
}

void CoopTemp()

{

  if ((CoopTemperature <= 40 ) && (heatFlag == true))
  {
    heatFlag = false;
    digitalWrite (Relay_3, Relay_ON);//Coop Temperature Control Heat Light ON Below 40 Degrees
    Blynk.virtualWrite(V14, Relay_ON);
  }

  if ((CoopTemperature >= 45 ) && (CoopTemperature <= 46 ) && (heatFlag = false))


  {
    heatFlag = true;
    digitalWrite (Relay_3, Relay_OFF); //Coop Temperature Control Heat Light OFF Above 45 Degrees
    Blynk.virtualWrite(V14, Relay_OFF);
  }
}

void CoopTempNotify()

{
  if ((CoopTemperature <= 40 ) && (heatNotify == true))
  {
    heatNotify = false;
    Blynk.notify("Coop Heat Lamp ON");
  }

  else if ((CoopTemperature >= 45 ) && (heatNotify == false))

  {
    heatNotify = true;
    Blynk.notify("Coop Heat Lamp OFF");
  }
}

I don’t see how any system (either your original one ofchecking the reed switch every second, or @Gunner’s interrupt suggestion) will be able to handle this situation.

If I understand correctly, your reed switch is mounted along the path of the door flap, and is momentarily activated as the flap lowers and raises - is that correct?
In this situation, you can’t tell if the flap is open or closed when your device powers-up.

A better scenario would be to have sensor switches at the top and bottom of the door’s travel range, so that the position of the door can be detected t each end of its travel.

I’m guessing that the reason you didn’t do this is the reliability of sensing the door position when it’s in a real life environment and may not always come to rest in exactly the same position each time?

I think that you probably need to resolve this engineering problem, and have reliable sensors to detect fully open and fully closed door situations rather than trying to solve the problem within your code.

Pete.

Door has 2 sensors one at top and one at bottom

Without the interrupts when wemos boots up it works perfect. Interrupts would be great if I could check the status of the sensor on bootup and disable the door motor if contacts are together. I have been using this setup for about 6 months and it works great except for the delay to let the chickens in and Im using a ds18b20 to monitor Outdoor temp for a water heater and heat lamp and for what ever reason the temp sensor will go to -196 after about 2-3hrs. You can reboot the wemos and it will work again for about 2-3 hours. I can’t for the life of me figure out why.

Okay, I understand now, and your setup makes it easy.
Just do a digital read of your top and bottom sensors in your void setup to set the values for your day and night variables.

Pete.