// Gamma Formula:
// https://www.statistikian.com/2013/02/rumus-gamma.html
// Library
#include <WiFi.h> // include WIFI Library
#include <PubSubClient.h> // Include MQTT Library to connect and communicate
#include <DHT.h> // Include DHT library to interface DHT Sensor
// LDR Constanta
const float GAMMA = 0.7; // Define gamma constant for LDRlux calculations.
const float RL10 = 33; // Resistance value of the LDR at 10 lux in kilo-ohms.
// WiFi Connection
const char* ssid = "Wokwi-GUEST"; // Define SSID of the Wi-Fi network to connect to.
const char* password = ""; // Define Password for the Wi-Fi network.
// MQTT Protocol Declaration
const char* mqtt_server = "broker.emqx.io"; // MQTT broker address.
const int mqtt_port = 1883; // MQTT broker port.
const char* mqtt_username = "emqx"; // MQTT username for authentication.
const char* mqtt_password = "public"; // MQTT password for authentication.
// Topic Declaration
const char* temperatureTopic = "emqx/suhuxyz"; // MQTT topic to publish temperature data.
const char* humidityTopic = "emqx/humdxyz"; // MQTT topic to publish humidity data.
const char* cahayaTopic = "emqx/cahayaxyz"; // MQTT topic to publish light intensity data.
// LDR Declaration
#define ldr 26 // Defines GPIO pin 26 for the LDR sensor input.
#define led 23 // Defines GPIO pin 23 to control an LED.
// DHT22 Declaration
#define DHTPIN 15 // Defines GPIO pin 15 for the DHT22 sensor.
#define DHTTYPE DHT22 // Specifies the type of DHT sensor used.
DHT dht(DHTPIN, DHTTYPE); // Creates a DHT object for interacting with the sensor.
//variable for storing the pushbutton status
long now = millis(); // Stores the current system time in milliseconds.
long lastMeasure = 0; // Tracks the last measurement time.
// WiFi & Client Publish Declaration
WiFiClient espClient; // Initializes the WiFi client for the ESP32.
PubSubClient client(espClient); // Initializes the MQTT client using the WiFi client.
// Topic Calling
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: "); // Prints the received topic.
Serial.println(topic); // Prints the topic name.
Serial.print("Message: ");
for (int i = 0; i < length; i++) { // Loops through the payload to print each character.
Serial.print((char) payload[i]);
}
Serial.println(); // Ends the line for readability.
}
void setup(){
Serial.begin(9600); // Initializes serial communication at 9600 baud rate.
pinMode(led, OUTPUT); // Configures the LED pin as an output.
pinMode(ldr, INPUT); // Configures the LDR pin as an input.
// Connecting to a WiFi network
WiFi.begin(ssid, password); // Start connecting to the Wi-Fi network using the provided SSID and password.
while (WiFi.status() != WL_CONNECTED) { // Keep checking the connection status.
delay(1000); // Wait for 1 second before retrying.
Serial.println("Connecting to WiFi.."); // Print the current connection status for debugging.
}
Serial.println("Connected to the Wi-Fi network"); // Print a success message after connecting.
//Connecting to a mqtt server
client.setServer(mqtt_server, mqtt_port); // Sets the MQTT server and port for the client.
client.setCallback(callback); // Registers the callback function for MQTT messages.
//Connecting Proccess
while (!client.connected()) {
// Check if the MQTT client is connected. If not, keep retrying until it connects.
String client_id = "esp32-client-"; // Create a unique client ID string, starting with "esp32-client-".
client_id += String(WiFi.macAddress()); // Append the ESP32's MAC address to the client ID for uniqueness.
Serial.printf("The client %s connects to the public MQTT broker\n", client_id.c_str()); // Print a debug message showing the client ID attempting to connect.
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
// Attempt to connect to the MQTT broker using the client ID, username, and password.
Serial.println("Public EMQX MQTT broker connected");
// If the connection succeeds, print a success message.
} else {
Serial.print("failed with state ");
// If the connection fails, print a failure message.
Serial.print(client.state());
// Display the error code that indicates why the connection failed.
delay(2000);
// Wait for 2 seconds before retrying the connection.
}
}
//Starting DHT11 scanning
dht.begin();
}
void loop() {
//mengulang pengiriman data sensor
client.loop();
//untuk menjalankan waktu internal setiap milli seconds
//pada ESP32 secara independent..
//ketika millis di baca maka millis akan terus
//menghitung waktu walau pun ESP32 nya sedang menjalan kan
//program yang lain
now = millis();
//Scanning Process
if (now - lastMeasure > 2000) { // If 2 seconds have passed since the last measurement:
lastMeasure = now; // Update the last measurement time.
float h = dht.readHumidity(); // Reads humidity from the DHT22 sensor.
float t = dht.readTemperature(); // Reads temperature from the DHT22 sensor.
if (isnan(h) || isnan(t)) { // Checks for sensor read errors.
Serial.println("Failed to read from DHT sensor!"); // Error message.
return;
}
int analogValue = analogRead(ldr); // Reads the analog value from the LDR.
float voltage = analogValue / 4096.0 * 3.3; // Converts the analog value to voltage.
float resistance = 2000 * voltage / (1 - voltage / 3.3); // Calculates the resistance.
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA)); // Computes lux.
if (lux > 50) { // If light intensity exceeds 50 lux:
digitalWrite(led, HIGH); // Turn on the LED.
Serial.print("Light! ");
} else { // If light intensity is 50 lux or less:
digitalWrite(led, LOW); // Turn off the LED.
Serial.print("Dark ");
}
Serial.print("Lux: ");
Serial.println(lux); // Prints the calculated lux value.
client.publish(humidityTopic, String(h).c_str()); // Publishes humidity data to MQTT.
client.publish(temperatureTopic, String(t).c_str());// Publishes temperature data to MQTT.
client.publish(cahayaTopic, String(lux).c_str()); // Publishes light intensity data to MQTT.
Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(F("% Temperature: "));
Serial.print(t);
Serial.println(" *C "); // Prints the temperature and humidity to the serial monitor.
}
}