#include // Include the WiFi library #include // Include the MQTT library const char* ssid = "iPhone Ernesto (2)"; // WiFi network name (SSID) const char* password = "****"; // WiFi password const char* mqtt_server = "broker.hivemq.com"; // MQTT broker server address WiFiClient espClient; // Create a WiFi client instance PubSubClient client(espClient); // Create a MQTT client instance void setup() { pinMode(10, OUTPUT); // Set pin 10 as an output for LED Serial.begin(115200); // Start the serial communication setup_wifi(); // Setup WiFi connection client.setServer(mqtt_server, 1883); // Set the MQTT broker server and port client.setCallback(callback); // Set callback function to handle incoming messages } void setup_wifi() { delay(10); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); // Connect to WiFi network while (WiFi.status() != WL_CONNECTED) { // Wait for WiFi connection delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); // Print local IP address } void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message received ["); Serial.print(topic); Serial.print("] "); String msg; for (int i = 0; i < length; i++) { msg += (char)payload[i]; // Convert payload to string } Serial.println(msg); // Print received message if (msg == "H") { digitalWrite(10, HIGH); // Turn on LED if message is "H" Serial.println("LED turned on"); } else if (msg == "L") { digitalWrite(10, LOW); // Turn off LED if message is "L" Serial.println("LED turned off"); } } void reconnect() { while (!client.connected()) { Serial.print("Attempting MQTT connection..."); if (client.connect("ArduinoUnoR4ESP32S3")) { // Attempt to connect to MQTT broker Serial.println("connected"); client.subscribe("led/control"); // Subscribe to "led/control" topic } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" trying again in 5 seconds"); delay(5000); // Wait 5 seconds before retrying } } } void loop() { if (!client.connected()) { reconnect(); // If MQTT connection is lost, attempt to reconnect } client.loop(); // Maintain MQTT connection and handle incoming messages }