BLYNK
HOME       📲 GETTING STARTED       📗 DOCS       ❓HELP CENTER       👉 SKETCH BUILDER

timer.setInterval and setSyncInterval togather not working

I have two sensors
LDR and PIR sensors.
LDR and PIR should work together.

The light should On only after 18:10:00 till 22:29:59 and after that, if there is any motion detected then turn on the light for 45 sec or continue until there is any motion detected by PIR.

Second part: If I turn off the light from the app it should turn off and wait until it detects motion to turn on. Then the app should switch the LED light to “RED”.

The LED light in the app is to how if the relay module is On or Off.

Problem: All of the above works fine. If I call the “blinkLedWidget()” where is the relay module is set to LOW or High.
if I set the timer.setInterval(1000L,blinkLedWidget()) and setSyncInterval(10*60) . There timer is not getting set.

It doesn’t moves beyond the below message

10:45:05.578 ->     ___  __          __
10:45:05.578 ->    / _ )/ /_ _____  / /__
10:45:05.613 ->   / _  / / // / _ \/  '_/
10:45:05.650 ->  /____/_/\_, /_//_/_/\_\
10:45:05.686 ->         /___/ v0.6.1 on Arduino Uno
10:45:05.724 -> 
10:45:06.160 -> [631] Connecting to 2.4-XXXXX
10:45:09.343 -> [3837] AT version:1.1.0.0(May 11 2016 18:09:56)
10:45:09.416 -> SDK version:1.5.4(baaeaebb)
10:45:09.451 -> Ai-Thinker Technology Co. Ltd.
10:45:09.451 -> Jun 13 2016 11:29:20
10:45:09.484 -> OK
10:45:16.647 -> [11129] +CIFSR:STAIP,"XXXXXX"
10:45:16.684 -> +CIFSR:STAMAC,"XXXXXXX"
10:45:16.721 -> [11138] Connected to WiFi
10:45:27.062 -> [21524] Ready (ping: 24ms).

Stuck here!!!


#define BLYNK_PRINT Serial
#include <Wire.h>
#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>
#include <SoftwareSerial.h>
#include <TimeLib.h>                                    /* Program code related to Real Time Clock (RTC). */
#include <WidgetRTC.h>                                  /* Communication code with Blynk Real Time Clock Widget */
#include "pitches.h"

void callPirSensior();
void callLDRSensor();
void LDRAndPIR();
bool calculateTimeGreater(int, int, int);
bool calculateTimeLesser(int, int, int);
// Your ESP8266 baud rate:
#define ESP8266_BAUD 9600

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

// Your WiFi credentials for home network
char ssid[] = "2.4-XXXX";
char pass[] = "XXXXX";

//Software Serial on Uno, Nano... - This is were the ESP-01 module will communicate
SoftwareSerial EspSerial(2, 3); // RX, TX

BlynkTimer timer;
WidgetRTC rtc;

ESP8266 wifi(&EspSerial);

//INPUT
int LDR = 13;
int pirPin = 4;

//OUTPUT
int relayModuleInput_2 = 8;
int buzzer = 7;

//Varibales
boolean dontBuzz = true;
boolean forceOff = false;
boolean forceOn = false;
boolean isRelayModuleOn = false;

WidgetLED led0(V1);
WidgetLED led1(V0);

BLYNK_CONNECTED() {
  // Synchronize time on connection
  rtc.begin();
  //Blynk.syncAll();
}

// Two Led in the blynk app- This is to know if the relay module is on or off. 
void blinkLedWidget()
{
  if (!isRelayModuleOn) {
    led0.off();
    led1.on();
  
  } else {
    led0.on();
    led1.off();
 
  }
}

void setup()
{
  // Debug console
  Serial.begin(9600);
  EspSerial.begin(ESP8266_BAUD);
  delay(10);
  Blynk.begin(auth, wifi, ssid, pass);
 
 //OUTPUT
  pinMode(relayModuleInput_2, OUTPUT);
  digitalWrite(relayModuleInput_2, HIGH);  
  
  timer.setInterval(60000L, blinkLedWidget);
  setSyncInterval(10 * 60); // Sync interval in seconds (10 minutes)
}

BLYNK_WRITE(V5)
{
  int pinValue = param.asInt(); 
  if (pinValue == 1) {
    digitalWrite(relayModuleInput_2, LOW);
    forceOff = false;
    forceOn = true;
    isRelayModuleOn = true;
  }
  else if (pinValue == 0) {
    digitalWrite(relayModuleInput_2, HIGH);
    forceOff = true;
    forceOn = false;
    isRelayModuleOn = false;
  }
}

void loop()
{
  Blynk.run();
  timer.run();
  LDRAndPIR();
}

void LDRAndPIR() {
  if (forceOn) { // If light is On from the Blynk App.
     isRelayModuleOn = true;
     return;
  }

  bool trunOnLDRAndPIR = calculateTimeGreater (18, 10, 00);
  bool trunOnOnlyLDR = calculateTimeLesser (22, 29, 59);
  if (trunOnLDRAndPIR)
  {
    //PIR Sensior
    callPirSensior();

    //LDR Sensor
    if (trunOnOnlyLDR) {
      callLDRSensor();
    }
    else {
      digitalWrite(relayModuleInput_2, HIGH);
      isRelayModuleOn = false;
    }
  }  else if (!forceOn) {
    digitalWrite(relayModuleInput_1, HIGH);
    digitalWrite(relayModuleInput_2, HIGH);
    isRelayModuleOn = false;
  }

bool trunOffOnlyLDRNextDay = calculateTimeLesser (18, 10, 00); //00:00:00 to 18:10:00 hrs. 
if (trunOffOnlyLDRNextDay && !forceOn) {
    digitalWrite(relayModuleInput_2, HIGH);
    isRelayModuleOn = false;
}
  

  //From midnight to morning.
  bool trunOnOnlyPIR = calculateTimeGreater (00, 00, 00);
  bool trunOffOnlyPIR = calculateTimeLesser (06, 30, 00);
   
  if (trunOnOnlyPIR && trunOffOnlyPIR) {
    //PIR Sensior  
    callPirSensior();
  }  
  
  //The Alaram goes on at this time.
  bool trunOnBuzzer = calculateTimeGreater (7, 30, 00);
  bool trunOffBuzzer = calculateTimeLesser (7, 30, 30);
  //Only for buzzer.
  if (trunOnBuzzer && trunOffBuzzer)
  {
    for (int thisNote = 0; thisNote < 8; thisNote++) {
      int noteDuration = 1000 / noteDurations[thisNote];
      tone(buzzer, melody1[thisNote], noteDuration);
      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes);
      noTone(buzzer);
    }
  }
}

bool calculateTimeGreater(int inputHour, int inputMin, int inputSec) {
  if (hour() > inputHour) {
    return true;
  } else if (hour() == inputHour) {
    if (minute() > inputMin) {
      return true;
    }
    if (minute() == inputMin) {
      if (second() >= inputSec) {
        return true;
      }
    }
  }
  return false;
}

bool calculateTimeLesser(int inputHour, int inputMin, int inputSec) {
  if (hour() < inputHour) {
    return true;
  } else if (hour() == inputHour) {
    if (minute() < inputMin) {
      return true;
    }
    if (minute() == inputMin) {
      if (second() <= inputSec) {
        return true;
      }
    }
  }
  return false;
}

void showTime()
{
  Serial.print("Time:");
  Serial.print(hour());
  Serial.print(':');
  Serial.print(minute());
  Serial.print(':');
  Serial.print(second());
  Serial.print("    ");
  Serial.print(" ");
  Serial.println();
}
/**
This will call from 18:10:00 to the next day morning at 6:30:00 morning. If there is any motion detected it will get on. If we force off from the Blynk app turn off the light. 
**/
void callPirSensior() {
  long timer = 0;
  if (digitalRead(pirPin) == HIGH && digitalRead(LDR) == HIGH) {
    timer = (millis() / 1000);
    isRelayModuleOn = true;
    while ((millis() / 1000) < (timer + 45))
    {
      digitalWrite(relayModuleInput_2, LOW);
      if ((millis() / 1000) > (timer + 15) && digitalRead(pirPin) == HIGH)
      {
        timer = (millis() / 1000);
      }
      Blynk.run(); // If I force off from Blynk app.
      if (forceOff) {         
        break;
      }
    }
  }
  if (forceOff && calculateTimeGreater (22, 30, 00) || calculateTimeLesser (6, 29, 59)) {
    forceOff = false;
    isRelayModuleOn = false;
  }
}

/**
 This method will be called only during the 18:10:00 to 22:30:00 hours. If force off from the Blynk app turn off the light.
**/
void callLDRSensor() {
  if (digitalRead(LDR) == HIGH && !forceOff) {
    digitalWrite(relayModuleInput_2, LOW);
    isRelayModuleOn = true;
  } else if (digitalRead(LDR) == LOW) {
    digitalWrite(relayModuleInput_2, HIGH);
    isRelayModuleOn = false;
  }
}

You’d be best off cleaning up your void loop. Maybe figure out if you could run it on a timer every 1/2 second or so, that would free the processor for the blynk calls.

But your actual problem is unclear to me…

When I add setSyncInterval(10 * 60); and timer.setInterval(60000L, blinkLedWidget); the loop() dont gets called.

Do you mean that your void loop() isn’t executing?
If so, how do you know this?

Pete.

Also, the code you posted doesn’t compile, so obviously isn’t the code that you’re actually running, so trying to debug it is a waste of our time.

Pete.

#define BLYNK_PRINT Serial
#include <Wire.h>
#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>
#include <SoftwareSerial.h>
#include <TimeLib.h>                                    /* Program code related to Real Time Clock (RTC). */
#include <WidgetRTC.h>                                  /* Communication code with Blynk Real Time Clock Widget */

void callPirSensior();
void callLDRSensor();
void LDRAndPIR();
bool calculateTimeGreater(int, int, int);
bool calculateTimeLesser(int, int, int);
// Your ESP8266 baud rate:
#define ESP8266_BAUD 9600

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

// Your WiFi credentials for home network
char ssid[] = "2.4-XXXX";
char pass[] = "XXXXX";

//Software Serial on Uno, Nano... - This is were the ESP-01 module will communicate
SoftwareSerial EspSerial(2, 3); // RX, TX

BlynkTimer timer;
WidgetRTC rtc;

ESP8266 wifi(&EspSerial);

//INPUT
int LDR = 13;
int pirPin = 4;

//OUTPUT
int relayModuleInput_2 = 8;
int buzzer = 7;

//Varibales
boolean dontBuzz = true;
boolean forceOff = false;
boolean forceOn = false;
boolean isRelayModuleOn = false;

WidgetLED led0(V1);
WidgetLED led1(V0);

BLYNK_CONNECTED() {
  // Synchronize time on connection
  rtc.begin();
  //Blynk.syncAll();
}

// Two Led in the blynk app- This is to know if the relay module is on or off. 
void blinkLedWidget()
{
  if (!isRelayModuleOn) {
    led0.off();
    led1.on();
  
  } else {
    led0.on();
    led1.off();
 
  }
}

void setup()
{
  // Debug console
  Serial.begin(9600);
  EspSerial.begin(ESP8266_BAUD);
  delay(10);
  Blynk.begin(auth, wifi, ssid, pass);
 
 //OUTPUT
  pinMode(relayModuleInput_2, OUTPUT);
  digitalWrite(relayModuleInput_2, HIGH);  
  
  timer.setInterval(60000L, blinkLedWidget);
  setSyncInterval(10 * 60); // Sync interval in seconds (10 minutes)
}

BLYNK_WRITE(V5)
{
  int pinValue = param.asInt(); 
  if (pinValue == 1) {
    digitalWrite(relayModuleInput_2, LOW);
    forceOff = false;
    forceOn = true;
    isRelayModuleOn = true;
  }
  else if (pinValue == 0) {
    digitalWrite(relayModuleInput_2, HIGH);
    forceOff = true;
    forceOn = false;
    isRelayModuleOn = false;
  }
}

void loop()
{
  Blynk.run();
  timer.run();
  LDRAndPIR();
}

void LDRAndPIR() {
  if (forceOn) { // If light is On from the Blynk App.
     isRelayModuleOn = true;
     return;
  }

  bool trunOnLDRAndPIR = calculateTimeGreater (18, 10, 00);
  bool trunOnOnlyLDR = calculateTimeLesser (22, 29, 59);
  if (trunOnLDRAndPIR)
  {
    //PIR Sensior
    callPirSensior();

    //LDR Sensor
    if (trunOnOnlyLDR) {
      callLDRSensor();
    }
    else {
      digitalWrite(relayModuleInput_2, HIGH);
      isRelayModuleOn = false;
    }
  }  else if (!forceOn) {
    digitalWrite(relayModuleInput_2, HIGH);
    isRelayModuleOn = false;
  }

bool trunOffOnlyLDRNextDay = calculateTimeLesser (18, 10, 00); //00:00:00 to 18:10:00 hrs. 
if (trunOffOnlyLDRNextDay && !forceOn) {
    digitalWrite(relayModuleInput_2, HIGH);
    isRelayModuleOn = false;
}
  

  //From midnight to morning.
  bool trunOnOnlyPIR = calculateTimeGreater (00, 00, 00);
  bool trunOffOnlyPIR = calculateTimeLesser (06, 30, 00);
   
  if (trunOnOnlyPIR && trunOffOnlyPIR) {
    //PIR Sensior  
    callPirSensior();
  }  
  
  //The Alaram goes on at this time.
  bool trunOnBuzzer = calculateTimeGreater (7, 30, 00);
  bool trunOffBuzzer = calculateTimeLesser (7, 30, 30);
  //Only for buzzer.
  if (trunOnBuzzer && trunOffBuzzer)
  {
   /* for (int thisNote = 0; thisNote < 8; thisNote++) {
      int noteDuration = 1000 / noteDurations[thisNote];
      tone(buzzer, melody1[thisNote], noteDuration);
      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes);
      noTone(buzzer);
    }*/
  }
}

bool calculateTimeGreater(int inputHour, int inputMin, int inputSec) {
  if (hour() > inputHour) {
    return true;
  } else if (hour() == inputHour) {
    if (minute() > inputMin) {
      return true;
    }
    if (minute() == inputMin) {
      if (second() >= inputSec) {
        return true;
      }
    }
  }
  return false;
}

bool calculateTimeLesser(int inputHour, int inputMin, int inputSec) {
  if (hour() < inputHour) {
    return true;
  } else if (hour() == inputHour) {
    if (minute() < inputMin) {
      return true;
    }
    if (minute() == inputMin) {
      if (second() <= inputSec) {
        return true;
      }
    }
  }
  return false;
}

void showTime()
{
  Serial.print("Time:");
  Serial.print(hour());
  Serial.print(':');
  Serial.print(minute());
  Serial.print(':');
  Serial.print(second());
  Serial.print("    ");
  Serial.print(" ");
  Serial.println();
}
/**
This will call from 18:10:00 to the next day morning at 6:30:00 morning. If there is any motion detected it will get on. If we force off from the Blynk app turn off the light. 
**/
void callPirSensior() {
  long timer = 0;
  if (digitalRead(pirPin) == HIGH && digitalRead(LDR) == HIGH) {
    timer = (millis() / 1000);
    isRelayModuleOn = true;
    while ((millis() / 1000) < (timer + 45))
    {
      digitalWrite(relayModuleInput_2, LOW);
      if ((millis() / 1000) > (timer + 15) && digitalRead(pirPin) == HIGH)
      {
        timer = (millis() / 1000);
      }
      Blynk.run(); // If I force off from Blynk app.
      if (forceOff) {         
        break;
      }
    }
  }
  if (forceOff && calculateTimeGreater (22, 30, 00) || calculateTimeLesser (6, 29, 59)) {
    forceOff = false;
    isRelayModuleOn = false;
  }
}

/**
 This method will be called only during the 18:10:00 to 22:30:00 hours. If force off from the Blynk app turn off the light.
**/
void callLDRSensor() {
  if (digitalRead(LDR) == HIGH && !forceOff) {
    digitalWrite(relayModuleInput_2, LOW);
    isRelayModuleOn = true;
  } else if (digitalRead(LDR) == LOW) {
    digitalWrite(relayModuleInput_2, HIGH);
    isRelayModuleOn = false;
  }
}

This code compiles, I removed the unused code. I spent a lot of time debugging the blynk api. But not able to reach a conclusion.

I put Serial.print in the beginning of the loop and end of the loop. It did not get printed.

I dont wanted to flood the Blynk Server with the above code. I want the blinkLedWidget() to be called on a interval bases so that it tells if the light is on or off.

When you say “the loop” do you mean your void loop() ?

Does your app show the device as online at any point?

Have you tried running a simpler sketch from the sketch builder?

Pete.

When I tell loop it is void loop().The app connects and disconnects after some time, but when it is connected I send instructions it dont responds. I didn’t try using the sketch builder.

I removed the timer.run(); It works.

I just removed the Blynk timer and added DS3231 code for time it worked.

In that case, you are mistaken about the void loop() not executing.

Pete.

First , you have to delete LDRAndPIR(); from void loop()

1 Like

You want me to move the LDRAndPIR. but do you want me to use setInterval(500L, LDRAndPIR)

Now it is working. I didn’t do anything. I just corrected these lines BLYNK_CONNECTED() { // Synchronize time on connection rtc.begin(); Blynk.syncAll(); } and setSyncInterval(300); // Sync interval in seconds timer.setInterval(60L, blinkLedWidget); timer.setInterval(100L, LDRAndPIR); This is only change I did.

Now my void loop() looks like below

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

Fine !
The void loop is clean, all is ok now !

So if you add timer we should not have any function called from the void loop :thinking:

If you’re using Blynk then you need to avoid a cluttered void loop and functions which take a long time to execute (as these starve the Blynk library of processor time).
The simplest way t6o achieve this is to move functions out of the void loop and call them with a timer. This explains more:

Also, when you are monitoring an input for a change of state (such as a physical button/switch, ort the contacts on your PIR sensor) then you have two options. The first is to poll the input pin on a regular basis (evert 100ms maybe?) and check if the pin is now in its ‘activated’ state.
The option second is to attach an interrupt to the pin (with suitable debouncing code to allow for the fact that when the contacts of the switch/relay close they won’t do this cleanly). The interrupt handler routine will be called when whatever type of interrupt you’ve attached to the pin (RISING, FALLING, CHANGE) is detected.

Pete.

1 Like

Sure Thx a lot. The problem comes only when added the Blynk Timer. I hope this takes much longer to execute.

I was thinking to put an interrupt in the place of an interval.

this is the reason why you think that your timer caused the issue.
Try this

timer.setInterval(500L, blinkLedWidget); \\blink every 500 milliseconds 
timer.setInterval(2200L, LDRAndPIR);\\call every 2.2 "

It is working now as expected.

Can we use like this //Real Time Date DateTime dateTime; RTC_DS3231 rtc; BlynkTimer simpleTimer;

I wanted to get the Blynk server time once in day and sync the DS3231 timer. Can we do it? I tried It didn’t work.

  Blynk.run();
  simpleTimer.run();
}``` But his is not running. The blynk app is disconnected.