#include <WiFi.h>
#include <PubSubClient.h>
#include <IRremote.h>
#include <ESP32Servo.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
//MqTT broker address
const char* mqtt_server = "broker.hivemq.com";
//Pin assignments
const int irPin = 18; // IR pin
const int servoPin = 19; // Servo pin
//declarations for object
WiFiClient espClient;
PubSubClient client(espClient);
IRrecv irrecv(irPin);
decode_results results;
Servo myServo;
// to connect to WiFi
void setup_wifi() {
delay(10); // Initial small delay for stability
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
Serial.println("Connected to WiFi");
}
//to reconnect to MQTT broker
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP32Client")) {
Serial.println("connected");
client.subscribe("servo/control"); // Subscribe to servo control topic
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000); // for Wait before retrying
}
}
}
// MQTT callback function for messages
void callback(char* topic, byte* payload, unsigned int length) {
String msg = "";
for (int i = 0; i < length; i++) {
msg += (char)payload[i];
}
int angle = msg.toInt(); // Convert payload to integer
if (angle >= 0 && angle <= 180) {
myServo.write(angle); // Set servo position
}
}
void setup() {
Serial.begin(115200); // Start serial communication
setup_wifi(); // Connect WiFi
client.setServer(mqtt_server, 1883); //Set MQTT broker
client.setCallback(callback); //Set callback for incoming MQTT messages
irrecv.enableIRIn(); // Start IR
myServo.attach(servoPin); // Attach servo to pin
}
void loop() {
if (!client.connected()) {
reconnect(); // Reconnect to MQTT if not connected
}
client.loop(); //for Handle MQTT communication
// Check if IR signal is received
if (irrecv.decode(&results)) {
long int decCode = results.value;
char message[50];
snprintf(message, 50, "%ld", decCode); //Convert IR code to string
Serial.print("Sending code: ");
Serial.println(message);
client.publish("sensor/ir", message); // TO Publish IR code to MQTT topic
irrecv.resume(); // to Resume listening for IR signals
}
}