#include #include #include const char* ssid = "iPhone Ernesto (2)"; // Wi-Fi network name const char* password = "****";// Wi-Fi network password const char* mqtt_server = "broker.hivemq.com";// MQTT broker address WiFiClient espClient;// WiFi client to connect to the MQTT server PubSubClient client(espClient);// MQTT client that uses the WiFi client Servo myServo; // Servo object to control a servo motor void setup() { myServo.attach(9); // Pin 9 is used to control the servo Serial.begin(115200);// Initialize serial communication at 115200 baud setup_wifi();// Connect to Wi-Fi client.setServer(mqtt_server, 1883);// Set the MQTT server and port client.setCallback(callback);// Set the callback function for incoming messages } void setup_wifi() { delay(10); Serial.println(); Serial.print("Conectando a "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi conectado"); Serial.println("Dirección IP: "); // Print the local IP address Serial.println(WiFi.localIP()); } void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Mensaje recibido ["); Serial.print(topic); Serial.print("] "); String msg; for (int i = 0; i < length; i++) { msg += (char)payload[i]; } Serial.println(msg); int angle = msg.toInt(); // Convert the message to an integer if (angle >= 0 && angle <= 180) {// Check if the angle is within the valid range myServo.write(angle);// Move the servo to the specified angle Serial.print("Servo movido a: "); Serial.println(angle);// Print the angle to which the servo was moved } } } void reconnect() {// Try to reconnect to the MQTT broker until successful while (!client.connected()) { Serial.print("Intentando conexión MQTT..."); if (client.connect("ArduinoUnoR4ESP32S3")) { Serial.println("conectado"); client.subscribe("servo/angle"); } else { Serial.print("falló, rc="); Serial.print(client.state());// Print the MQTT client state if the connection fails Serial.println(" intentando de nuevo en 5 segundos"); delay(5000); } } } void loop() { // Check if the client is connected to the MQTT broker if (!client.connected()) { reconnect(); } client.loop(); }