Hello,
I am trying to built a message screen using LCD 20X04 and MQTT. The idea is to get messages to appear on the screen but to have the screen back light off until the message appears but after 15 seconds to turn off the LCD until next message. I managed to do this partialy. I can get the backlight on when an MQTT message is recieved and I can get the screen to turn off every 15 seconds.
But the two prcoesses are not linked meaning the screen can turn on when a messgae is recieved but it will turn off even after a second if the 15 seconds counter is done.
I thought that all I need to do is to reset the counter of the 15 seconds each time a MQTT message is recieved but it doesn't work (I wanted to put it where I worte "***********"). i guess i am doing something wrong.
Here is my code. if someone can help I will appreciate it very much:
I am only a beginner so if someone has an idea and can make it simple enough for me it would be great.
const char* ssid = "XXX"; // SSID of local network
const char* password = "XXX"; // Password on network
const char* mqttServer = "XXX";
const int mqttPort = XXX;
const char* mqttUser = "XXX";
const char* mqttPassword = "XXX";
unsigned long previousMillis = 0;
const long interval = 15000;
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
lcd.begin(20,4);
int cursorPosition=0;
lcd.backlight();
lcd.print("Connecting ....");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
lcd.setCursor(cursorPosition,1);
lcd.print(".");
cursorPosition++;
}
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Connected!");
delay(1000);
lcd.clear();
lcd.setCursor(5, 0);
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
lcd.clear();
lcd.setCursor(5, 0);
lcd.print("Connecting to MQTT...");
if (client.connect("ESP8266Client", mqttUser, mqttPassword )) {
Serial.println("connected");
lcd.clear();
lcd.setCursor(5, 0);
lcd.print("Connected to MQTT...");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
lcd.clear();
lcd.setCursor(5, 0);
lcd.print("failed with state ");
delay(2000);
}
}
client.publish("esp/test", "Hello from ESP8266");
client.subscribe("esp/test");
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
lcd.clear();
lcd.setCursor(5, 0);
lcd.print("Message arrived:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload*);*
_ lcd.print((char)payload*);_
_ lcd.backlight();_
_ *************************************************_
_ }_
}
void loop() {
* client.loop();*
* unsigned long currentMillis = millis();*
* if (currentMillis - previousMillis >= interval) {*
* previousMillis = currentMillis;*
* lcd.noBacklight();*
* }*
}