#include "ArduinoJson.h"
#include <WiFi.h>
#include "PubSubClient.h"
#include <LiquidCrystal_I2C.h>
// Define Constants
const char* SSID = "Wokwi-GUEST"; // Replace with your WiFi SSID
const char* PASSWORD = ""; // Replace with your WiFi password
const char* MQTTServer = "broker.hivemq.com"; // MQTT broker address
const char* MQTT_Topic_HienThi = "IOT/PhatTrien/HienThi";
const char* MQTT_Topic_Nguong = "IOT/PhatTrien/nguong";
const char* MQTT_ID = "08538910-a63d-45af-ab5b-3ca7131928c4";
const int Port = 1883; // MQTT port
const float GAMMA = 0.7; // LDR gamma value
const float RL10 = 50; // LDR RL10 value
const int ledPins[4] = {12, 13, 14, 15}; // Array for LED pins
const int ledldr = 23; // Pin for LDR-controlled LED
const int ldr_pin = 34; // Analog pin for the LDR
// Global Variables
WiFiClient espClient; // WiFi client
PubSubClient client(espClient); // MQTT client
LiquidCrystal_I2C lcd(0x27, 20, 4); // LCD display
float nguong = 0; // Threshold value (initialize to 0)
char trangThaiDen[10] = "Tắt"; // Initial LED state
// Function to connect to WiFi
void WIFIConnect() {
Serial.println("Connecting to SSID: " + String(SSID));
WiFi.begin(SSID, PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected");
Serial.print(", IP address: ");
Serial.println(WiFi.localIP());
}
// Function to reconnect to the MQTT broker
void MQTT_Reconnect() {
while (!client.connected()) {
if (client.connect(MQTT_ID)) {
Serial.print("MQTT Topics connected: ");
Serial.print(MQTT_Topic_HienThi);
Serial.print(", ");
Serial.print(MQTT_Topic_Nguong);
Serial.println("");
client.subscribe(MQTT_Topic_HienThi);
client.subscribe(MQTT_Topic_Nguong);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
// Function to handle incoming messages from the MQTT broker
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.println(topic);
// Parse JSON data for LED control
if (strcmp(topic, MQTT_Topic_Nguong) == 0) {
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, message, length);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
return;
}
// Xử lý LED
const JsonObject& ledData = doc["ledData"];
for (int i = 1; i <= 4; i++) {
if (ledData[String(i)].as<bool>()) {
digitalWrite(ledPins[i - 1], HIGH); // Turn on LED
} else {
digitalWrite(ledPins[i - 1], LOW); // Turn off LED
}
}
// Update threshold value
nguong = doc["nguong"].as<double>(); // Lấy giá trị ngưỡng
Serial.print("New threshold value: ");
Serial.println(nguong);
// Update LCD Display
lcd.setCursor(0, 0);
lcd.print("Threshold: ");
lcd.print(nguong);
// Check LDR value and control LEDLDR
if (ldr_display() > nguong) {
digitalWrite(ledldr, HIGH);
lcd.setCursor(0, 1);
lcd.print("LED status: ON");
} else {
digitalWrite(ledldr, LOW);
lcd.setCursor(0, 1);
lcd.print("LED status: OFF");
}
}
}
// Function to read the LDR value and convert it to lux
float ldr_display() {
delay(500);
int analogValue = analogRead(ldr_pin);
float voltage = analogValue / 1024.0 * 5.0; // Convert to voltage (assuming 5V reference)
float resistance = 10000.0 * voltage / (5.0 - voltage); // Calculate resistance (assuming a 10k resistor)
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA)); // Calculate lux using the LDR formula
return lux;
}
// Function to publish the LDR value to the MQTT broker
void publishLDR() {
float ldr_values = ldr_display();
lcd.setCursor(0, 2);
lcd.print("Light: ");
lcd.print(ldr_values);
if (ldr_display() > nguong) {
digitalWrite(ledldr, HIGH); // Turn on LDR-controlled LED
strcpy(trangThaiDen, "Bật");
} else {
digitalWrite(ledldr, LOW); // Turn off LDR-controlled LED
strcpy(trangThaiDen, "Tắt");
}
int h = digitalRead(ledldr);
String data_send = "{\"DoSang\":\"" + String(ldr_values) + "\",\"trangthai\":\"" + String(h) + "\"}";
client.publish(MQTT_Topic_HienThi, String(data_send).c_str()); // Publish to the "HienThi" topic
}
// Setup function
void setup() {
lcd.init();
lcd.backlight();
for (int i = 0; i < 4; i++) {
pinMode(ledPins[i], OUTPUT);
}
pinMode(ledldr, OUTPUT);
pinMode(ldr_pin, INPUT); // Define ldr_pin as an input
Serial.begin(115200);
WIFIConnect();
client.setServer(MQTTServer, Port);
client.setCallback(callback);
}
// Loop function
void loop() {
delay(100);
if (!client.connected()) {
MQTT_Reconnect();
}
client.loop();
publishLDR();
}