/*
based on the project
https://wokwi.com/projects/321525495180034642
I haven't finished this work
for now it can get the time from NTP pool.ntp.org,
and transfer the minutes and seconds to the mqtt server.
broker.mqttdashboard.com
Topic - My_LED.
Websockets Client Showcase
https://www.hivemq.com/demos/websocket-client/
*/
#include <WiFi.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <PubSubClient.h>
#include <ModbusRTU.h>
LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2);
WiFiClient ethClient;
PubSubClient mqttClient(ethClient);
#define NTP_SERVER "pool.ntp.org"
#define UTC_OFFSET 0
#define UTC_OFFSET_DST 0
void spinner() {
static int8_t counter = 0;
const char* glyphs = "\xa1\xa5\xdb";
LCD.setCursor(15, 1);
LCD.print(glyphs[counter++]);
if (counter == strlen(glyphs)) {
counter = 0;
}
}
void printLocalTime() {
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
LCD.setCursor(0, 1);
LCD.println("Connection Err");
return;
}
LCD.setCursor(8, 0);
LCD.println(&timeinfo, "%H:%M:%S");
char printBuffer[5];
sprintf(printBuffer, "%d:%d", timeinfo.tm_min, timeinfo.tm_sec );
//Serial.println(printBuffer);
mqttClient.publish("My_LED",printBuffer);//
LCD.setCursor(0, 1);
LCD.println(&timeinfo, "%d/%m/%Y %Z");
}
void setup() {
Serial.begin(115200);
Serial2.begin(38400); //RX-16:Tx-17 SERIAL_8N1 web terminal out
Serial2.println("Hello Serial 2");
mqttClient.setServer("broker.mqttdashboard.com",1883);
// client is now ready for use
LCD.init();
LCD.backlight();
LCD.setCursor(0, 0);
LCD.print("Connecting to"); //Connecting to
LCD.setCursor(0, 1);
LCD.print("WiFi ");
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(250);
spinner();
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
delay(1000);
if(mqttClient.connect ("LED-demo",NULL,NULL)) {
Serial.print ("Connected to MQTT Broker");
} else {
Serial.print("MQTT Broker connection failed");
Serial.print (mqttClient.state());
delay(200);
}
delay(3000);
LCD.clear();
LCD.setCursor(0, 0);
LCD.println("Online");
LCD.setCursor(0, 1);
LCD.println("Updating time...");
configTime(UTC_OFFSET, UTC_OFFSET_DST, NTP_SERVER);
}
void loop() {
printLocalTime();
Serial2.println("Hello Serial2 !!");
delay(1000);
}