//Libraries
#include <WiFi.h> // Library for Wi-Fi connectivity
#include <PubSubClient.h> // Library for MQTT protocol support
#include <ESP32Servo.h> // Library for controlling servo motors on ESP32
// LDR settings
const int LDR_PIN = 34; // Pin for LDR sensor
// MQTT settings
const char* ssid = "Wokwi-GUEST"; // SSID of the Wi-Fi network
const char* password = ""; // Password of the Wi-Fi network
const char* mqttServer = "broker.hivemq.com"; // MQTT broker address
const int mqttPort = 1883; // MQTT port number
// Servo motor settings
Servo myservo; // Create a Servo object
const int servoPin = 5; // Pin for the servo motor
WiFiClient espClient; // Create a Wi-Fi client
PubSubClient client(espClient); // Create an MQTT client
unsigned long lastMsg = 0; // Last message timestamp for LDR publishing
// Function to connect to Wi-Fi
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA); // Set Wi-Fi mode to station (client)
WiFi.begin(ssid, password); // Start Wi-Fi connection
while (WiFi.status() != WL_CONNECTED) { // Wait until connected
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP()); // Print local IP address
}
// Function to handle incoming MQTT messages
void callback(char* topic, byte* payload, unsigned int length) {
String message;
Serial.print("Message arrived [");
Serial.print(topic); // Print the topic of the message
Serial.print("] ");
for (int i = 0; i < length; i++) { // Convert payload to string
message += (char)payload[i];
}
Serial.println(message);
// Check if the message is for the servo control topic
if (String(topic) == "/ThinkIOT/Servo-nodered") {
int status = message.toInt(); // Convert message to integer
int pos = map(status, 1, 100, 0, 180); // Map status to servo angle
Serial.println(pos); // Print the calculated position
myservo.write(pos); // Move servo to the position
delay(15); // Allow servo to reach the position
}
}
// Function to reconnect to MQTT broker
void reconnect() {
// Loop until connected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX); // Generate a random client ID
if (client.connect(clientId.c_str())) { // Attempt to connect
Serial.println("connected");
client.subscribe("/ThinkIOT/Servo-nodered"); // Subscribe to the topic
} else {
Serial.print("failed, rc=");
Serial.print(client.state()); // Print the error code
Serial.println(" try again in 5 seconds");
delay(5000); // Wait before retrying
}
}
}
void setup() {
Serial.begin(115200); // Start serial communication
myservo.attach(servoPin); // Initialize the servo motor
pinMode(LDR_PIN, INPUT); // Set LDR sensor pin as input
setup_wifi(); // Connect to Wi-Fi
client.setServer(mqttServer, mqttPort); // Set MQTT server and port
client.setCallback(callback); // Set the MQTT callback function
}
void loop() {
if (!client.connected()) { // Check if not connected to MQTT
reconnect(); // Attempt to reconnect
}
client.loop(); // Handle incoming MQTT messages
unsigned long now = millis();
if (now - lastMsg > 2000) { // Check if 2 seconds have passed
lastMsg = now;
// Read LDR sensor value
int ldrValue = analogRead(LDR_PIN);
String ldrStatus = String(ldrValue);
// Publish LDR sensor value via MQTT
client.publish("/ThinkIOT/ldr", ldrStatus.c_str());
Serial.print("LDR Value: ");
Serial.println(ldrStatus); // Print LDR value to Serial Monitor
}
}