#include <WiFi.h>
#include <PubSubClient.h>
#include <IRremote.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// WiFi and MQTT Settings
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int IR_RECEIVER_PIN = 15;
void setup_wifi() {
delay(10);
Serial.print("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected!");
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP32_IR_Transmitter")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
// Initialize I2C LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("press buttons");
IrReceiver.begin(IR_RECEIVER_PIN, ENABLE_LED_FEEDBACK);
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void loop() {
if (!client.connected()) reconnect();
client.loop();
if (IrReceiver.decode()) {
String command = "";
uint32_t code = IrReceiver.decodedIRData.command;
// Remote Mapping
if(code == 162) command = "0"; // Power -> OFF
else if(code == 48) command = "1"; // Button 1 -> Speed 1
else if(code == 24) command = "2"; // Button 2 -> Speed 2
else if(code == 122) command = "3"; // Button 3 -> Speed 3
if (command != "") {
// Update Local LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Sent:");
lcd.setCursor(0, 1);
lcd.print("Speed ");
lcd.print(command);
// Publish to MQTT
client.publish("home/fan/speed", command.c_str());
Serial.println("Published: " + command);
}
IrReceiver.resume();
}
}