#include <DHT.h>
#include <Stepper.h>
#include <WiFi.h>
#include <PubSubClient.h>
#define TOTAL_STEPS 200
#define MOTOR_PIN1 2
#define MOTOR_PIN2 4
#define MOTOR_PIN3 5
#define MOTOR_PIN4 15 // Example pin, change it as per your ESP32 setup
#define DHT_PIN 14 // Example pin, change it as per your ESP32 setup
#define TEMP_THRESHOLD_1 23
#define TEMP_THRESHOLD_2 27
#define TEMP_THRESHOLD_3 35
#define MQTT_SERVER "broker.emqx.io"
#define MQTT_PORT 1883
#define MQTT_TOPIC_SPEED "motor_speed"
const char *ssid = "Wokwi-GUEST";
const char *password = "";
WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(DHT_PIN, DHT22);
Stepper stepper(TOTAL_STEPS, MOTOR_PIN1, MOTOR_PIN2, MOTOR_PIN3, MOTOR_PIN4);
int currentSpeed = 500; // Initial speed, you can adjust this as needed
void setup() {
Serial.begin(115200);
connectToWiFi();
client.setServer(MQTT_SERVER, MQTT_PORT);
client.setCallback(callback);
dht.begin();
stepper.setSpeed(currentSpeed);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
float temperature = dht.readTemperature(); // Read temperature from DHT sensor
if (!isnan(temperature)) { // Check if the reading is valid
// Do not adjust the stepper speed based on temperature here
}
}
void adjustStepperSpeed(int speedCommand) {
// Publish the current speed to MQTT
client.publish(MQTT_TOPIC_SPEED, String(speedCommand).c_str());
// Set the motor speed based on the received command
stepper.setSpeed(speedCommand);
currentSpeed = speedCommand; // Update the current speed variable
}
void connectToWiFi() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void reconnect() {
while (!client.connected()) {
if (client.connect("ESP32Client")) {
Serial.println("Connected to MQTT");
subscribeToCommands();
} else {
Serial.print("Failed, rc=");
Serial.print(client.state());
Serial.println(" Retrying in 5 seconds...");
delay(5000);
}
}
}
void subscribeToCommands() {
// Subscribe to the MQTT topic for motor speed control
client.subscribe(MQTT_TOPIC_SPEED);
}
void callback(char *topic, byte *payload, unsigned int length) {
String message = "";
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
Serial.print("Payload: ");
Serial.println(message);
// Check the received MQTT topic
if (strcmp(topic, MQTT_TOPIC_SPEED) == 0) {
// Set the motor speed based on the received command
int speedCommand = message.toInt();
adjustStepperSpeed(speedCommand);
}
}