Simple light detection project

I’m using a LDR sensor to detect when the light turns on and off, I’m also using a NTP Client to get the current time. Basically, what I wan’t to accomplish, is that as soon as the light turns on/off I keep a record of the time so latter on I can calculate the amount of time the light was kept on.

Code is below.

#include <NTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include "DHTesp.h"

// WIFI PARAMS
const char *ssid     = "****";
const char *password = "****";

// DATE PARAMS
const long utcOffsetInSeconds = -10800;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

// NTP CLIENT
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds);

// DEF DHT11 SENSOR
DHTesp dht;

// DEF LDR SENSOR
const int pinoLDR = A0;

void setup() {
  Serial.begin(115200);
  
  void timeUpdate();
  void lightTime();

  // INIT WIFI
  WiFi.begin(ssid, password);

  // WIFI CONNECTION
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  // TIME CLIENT INIT
  timeClient.begin();

  // DHT SENSOR INIT
  dht.setup(5, DHTesp::DHT11);

  // LDR SENSOR INIT
  pinMode(pinoLDR, INPUT);

}

void loop() {
  //TIME UPDATE
  timeUpdate();

  // DHT11 SENSOR READINGS
  delay(dht.getMinimumSamplingPeriod());
  float umidade = dht.getHumidity();
  float temperatura = dht.getTemperature();
  const float margemTemp = 0.10;
  const float margemUmi = 0.05;
  
  if (umidade >= 95){
     float trueUmidade = umidade - umidade * margemUmi;
     Serial.print("Umidade: ");
     Serial.print(trueUmidade);
     Serial.print("%");
  } else {
     Serial.print("Umidade: ");
     Serial.print(umidade);
     Serial.print("%");
  }
  
  float trueTemperatura = temperatura - temperatura * margemTemp;

  Serial.print("/ Temperatura: ");
  Serial.print(trueTemperatura, 2);
  Serial.println("*C");

  // LDR SENSOR READINGS
  int ldrReading = 0;
  ldrReading = analogRead(pinoLDR);
  lightTime(ldrReading);
  
  delay(1000);
}

void timeUpdate() {
  timeClient.update();
  Serial.print(daysOfTheWeek[timeClient.getDay()]);
  Serial.print(", ");
  Serial.print(timeClient.getHours());
  Serial.print(":");
  Serial.print(timeClient.getMinutes());
  Serial.print(":");
  Serial.println(timeClient.getSeconds());
  //  Serial.println(timeClient.getFormattedTime());
}

void lightTime(int ldrReading){
  int lightOnH, lightOffH, recordOn, recordOff = 0; 
  if ((recordOn == 0) && (recordOff == 0)){
    if(ldrReading >= 600){
      Serial.println("A luz está acesa!");
      lightOnH = timeClient.getHours();
      recordOn = 1;
      Serial.println(recordOn);
    } else {
      Serial.println("A luz está apagada!");
      lightOffH = timeClient.getHours();
      recordOff = 1;
      Serial.println(recordOff);
    }
  } else {
    Serial.print("Not enough samples.");
  }
}

A good project that others may find useful, thanks for posting.

1 Like

What’s the question?

Also - no need to ‘calculate’ the on / off times. You have the data already, just accumulate the duration data you need.

looks like you’ve mostly done this in lightTime(). but there are a couple things you should consider

use separate thresholds to detect when the light is on and off to avoid toggling between the two states. so maybe 600 and 550.

if the light is on when the code starts up, shouldn’t it record how long it’s been on since startup. so the initial on time should be the time at startup, this needs to be captured somewhere as well as updating it when the light is turned on.

i assume you want more resolution than hours, so shouldn’t lightTime() capture complete timestamps (day, hour, minute) when the light is turned on and off.

a routine is needed to calculate the time between on and off, duration, presumably in terms of hours: minutes where hours can be more than 24

when the light turns off, calculate the duration and record both the current time and duration

1 Like

First of all, thanks for the response!

My question then is, how do I store the recorded time, so then I can calculate the total lightOn time? Should I store the formated HH:MM into an array and then use it for the caulculatons?

Additionally, after all the data gathering, I want to export this same data as a CSV and then build graphs through a webApp.

you can always store each timestamp and duration as a string
dd:hh:m,hh:m
you can use sprintf to format the string.

not sure how you plan on storing the measurements and off-loading them

So here’s an update to this project, I finally was able to gather and record the time sample properly, but now, it seems to simply ignore my if else statement and keeps updating the last recorded time, could anyone help me solve this problem?

#include <ArduinoJson.h>
#include <Firebase.h>
#include <FirebaseArduino.h>
#include <FirebaseCloudMessaging.h>
#include <FirebaseError.h>
#include <FirebaseHttpClient.h>
#include <FirebaseObject.h>
#include <NTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include "DHTesp.h"

// WIFI PARAMS
const char *ssid     = "**************";
const char *password = "*************";

// FIREBASE PARAMS
const char *FIREBASE_HOST = "***************************";
const char *FIREBASE_AUTH = "***************************";

// DATE PARAMS
const long utcOffsetInSeconds = -10800;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

// NTP CLIENT
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds);

// DEF DHT11 SENSOR
DHTesp dht;

// DEF LDR SENSOR
const int pinoLDR = A0;

void setup() {
  Serial.begin(115200);
  
  void timeUpdate();
  void weatherUpdate();
  int timeRecord();

  // INIT WIFI
  WiFi.begin(ssid, password);
  Serial.print("Connecting");

  // WIFI CONNECTION
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }
  Serial.println();
  Serial.print("Connected, Ip Adress: ");
  Serial.println(WiFi.localIP());

  //FIREBASSE INIT
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

  // TIME CLIENT INIT
  timeClient.begin();

  // DHT SENSOR INIT
  dht.setup(5, DHTesp::DHT11);

  // LDR SENSOR INIT
  pinMode(pinoLDR, INPUT);

}

void loop() {
  //TIME UPDATE
  timeUpdate();

  // DHT11 SENSOR READINGS
  weatherUpdate();

  // LDR SENSOR READINGS
  int ldrReading, timeOn, timeOff = 0;
  ldrReading = analogRead(pinoLDR);
  if ((timeOn == 0) or (timeOff == 0)) {
    if (ldrReading >= 600){
      Serial.println("A luz está acesa!");
      timeOn = timeRecord();
      //Serial.println(timeOn);
    } else if(ldrReading < 600) {
      //Serial.println("A luz está apagada!");
      timeOff = timeRecord();
      Serial.println(timeOff);
    } 
   } else if(timeOn != 0){
    Serial.println("A luz está acesa, tempo já registrado.");
   } else if(timeOff != 0){
    Serial.println("A luz está apagada, tempo já registrado.");
   } else {
    Serial.println("There was an error during data gathering.");
   }
  delay(1000);
}

void timeUpdate() {
  timeClient.update();
  Serial.print(daysOfTheWeek[timeClient.getDay()]);
  Serial.print(", ");
  Serial.print(timeClient.getHours());
  Serial.print(":");
  Serial.print(timeClient.getMinutes());
  Serial.print(":");
  Serial.println(timeClient.getSeconds());
  //  Serial.println(timeClient.getFormattedTime());
}

void weatherUpdate() {
  delay(dht.getMinimumSamplingPeriod());
  float umidade = dht.getHumidity();
  float temperatura = dht.getTemperature();
  const float margemTemp = 0.10;
  const float margemUmi = 0.05;
  
  if (umidade >= 95){
     float trueUmidade = umidade - umidade * margemUmi;
     Serial.print("Umidade: ");
     Serial.print(trueUmidade);
     Serial.print("%");
  } else {
     Serial.print("Umidade: ");
     Serial.print(umidade);
     Serial.print("%");
  }

  float trueTemperatura = temperatura - temperatura * margemTemp;

  Serial.print(" / Temperatura: ");
  Serial.print(trueTemperatura, 2);
  Serial.println("*C");
}

int timeRecord() {
  int currentH = timeClient.getHours();
  int currentM = timeClient.getMinutes();
  int temp = currentM;
  do {
    temp /= 100;
    currentH *= 100;
  } while (temp > 0);
  int currentTimeINT = currentH + currentM;
  return currentTimeINT;
}