// code for controlling servo motor using nodered dashboard
#include <WiFi.h>
#include <PubSubClient.h>
#include <ESP32Servo.h>
Servo myservo;// servo onject
Servo myservo2;// servo onject
Servo myservo3;// servo onject
Servo myservo4;// servo onject
Servo myservo5;// servo onject
Servo myservo6;// servo onject
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "test.mosquitto.org";// MQTT broker
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup() {
Serial.begin(115200);
myservo.attach(2);
myservo2.attach(4);
myservo3.attach(5);
myservo4.attach(18);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void setup_wifi() {
delay(10);
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* payload, unsigned int length) {
String string;
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
string+=((char)payload[i]);
}
Serial.print(string);
if (String(topic) == "Servo-nodered1") { /// esp32 subscribe topic
int degree = string.toInt(); // Convert the received data to an integer
Serial.print("Moving servo to degree: ");
Serial.println(degree);
myservo.write(degree); // Move the servo to the specified degree
delay(15);
}
else if (String(topic) == "Servo-nodered2") {
int degree = string.toInt(); // Convert the received data to an integer
Serial.print("Moving servo to degree: ");
Serial.println(degree);
myservo2.write(degree); // Move the servo to the specified degree
delay(15);
}
else if (String(topic) == "Servo-nodered3") {
int degree = string.toInt(); // Convert the received data to an integer
Serial.print("Moving servo to degree: ");
Serial.println(degree);
myservo3.write(degree); // Move the servo to the specified degree
delay(15);
}
else if (String(topic) == "Servo-nodered4") {
int degree = string.toInt(); // Convert the received data to an integer
Serial.print("Moving servo to degree: ");
Serial.println(degree);
myservo4.write(degree); // Move the servo to the specified degree
delay(15);
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESPClient")) {
Serial.println("connected");
client.subscribe("Servo-nodered1");
client.subscribe("Servo-nodered2");
client.subscribe("Servo-nodered3");
client.subscribe("Servo-nodered4");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}}}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
delay(100);
}