I have an RTC clock built with an ESP32 and a 16x2 LCD connected with an I2C backpack attached. I'm trying to get my backlight to turn off and on at specific times. nothing I do in void loop() does anything but if I change lcd.backlight() to lcd.noBacklight() in the void setup() it will turn the backlight off.
I'm using the <hd44780ioclass/hd44780_I2Cexp.h>
library.
other than the backlight problem I'm currently trying to figure out everything works well and have no other issues. below is my code (ssid and password have been changed)
#include <Wire.h>
#include <WiFi.h>
#include <NTPClient.h>
#include <TimeLib.h>
#include <hd44780.h>
#include <hd44780ioclass/hd44780_I2Cexp.h>
hd44780_I2Cexp lcd(0x27, 16, 2);
const char *ssid = "NETWORK_NAME"; /*Replace with your network SSID*/
const char *password = "network_password"; /*Replace with network password*/
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "time.nist.gov", -21600, 60000);
char Time[ ] = "TIME:00:00:00";
char Date[ ] = "DATE:00/00/2000";
byte last_second, second_, minute_, hour_, month_, day_;
int year_;
unsigned long turnOffTime, turnOntime;
void setup(){
Serial.begin(115200);
lcd.init(); /*Initialize LCD display*/
lcd.backlight(); /*ON LCD Backlight*/
lcd.setCursor(0, 0); /*Set cursor*/
lcd.print("Time"); /*print time on LCD*/
lcd.setCursor(0, 1); /*Set LCD cursor*/
lcd.print(Date); /*Print date*/
WiFi.begin(ssid, password); /*begin WiFi*/
Serial.print("Connecting.");
while ( WiFi.status() != WL_CONNECTED ) {
delay(500);
Serial.print(".");
}
Serial.println("connected");
timeClient.begin();
delay(1000);
lcd.clear(); /*clear LCD display*/
}
void loop(){
timeClient.update();
unsigned long unix_epoch = timeClient.getEpochTime(); // Get Unix epoch time from the NTP server
const int turnOffTime = 2100;
const int turnOnTime = 800;
second_ = second(unix_epoch);
if (last_second != second_) {
minute_ = minute(unix_epoch);
hour_ = hour(unix_epoch);
day_ = day(unix_epoch);
month_ = month(unix_epoch);
year_ = year(unix_epoch);
Time[12] = second_ % 10 + 48;
Time[11] = second_ / 10 + 48;
Time[9] = minute_ % 10 + 48;
Time[8] = minute_ / 10 + 48;
Time[6] = hour_ % 10 + 48;
Time[5] = hour_ / 10 + 48;
Date[5] = month_ / 10 + 48;
Date[6] = month_ % 10 + 48;
Date[8] = day_ / 10 + 48;
Date[9] = day_ % 10 + 48;
Date[13] = (year_ / 10) % 10 + 48;
Date[14] = year_ % 10 % 10 + 48;
Serial.println(Time); /*Prints time on serial monitor*/
Serial.println(Date); /*Print date on serial monitor*/
if (hour() >= turnOffTime && hour() < turnOnTime) { lcd.noBacklight();
}
else
{ lcd.backlight();
lcd.setCursor(0, 0); /*Set LCD cursor*/
lcd.print(Time); /*display time on LCD*/
lcd.setCursor(0, 1); /*Set LCD cursor*/
lcd.print(Date); /*Display date on LCD*/
last_second = second_;
}
delay(200);
}
}