#include #include #include const char* ssid = "ANLI"; const char* password = "Actua1455"; const char* mqtt_server = "broker.emqx.io"; const char* mqtt_Client = "ANDRUClient2025"; const char* mqtt_Topic_Sub ="FabAcademy/week11"; WiFiClient espClient; PubSubClient client(espClient); // Servo setup Servo myServo; const int servoPin = D5; void setup() { // put your setup code here, to run once: Serial.begin(115200); setup_wifi(); client.setServer(mqtt_server, 1883); client.setCallback(callback); myServo.attach(servoPin); } void setup_wifi() { delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void callback(char* topic, byte* message, unsigned int length) { Serial.print("Message arrived on topic: "); Serial.print(topic); Serial.print(". Message: "); String messageTemp; for (int i = 0; i < length; i++) { Serial.print((char)message[i]); messageTemp += (char)message[i]; } Serial.println(); if (String(topic) == mqtt_Topic_Sub) { int angle = messageTemp.toInt(); angle = constrain(angle, 0, 180); Serial.print("Moving servo to "); Serial.print(angle); Serial.println(" degrees"); myServo.write(angle); } } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect(mqtt_Client)) { Serial.println("connected"); // Subscribe client.subscribe(mqtt_Topic_Sub); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } void loop() { // put your main code here, to run repeatedly: if (!client.connected()) { reconnect(); } client.loop(); }