#include <WiFi.h>
#include <DHTesp.h>
#include <PubSubClient.h>
#include <Arduino.h>
#include <Adafruit_NeoPixel.h>
#include <Stepper.h>
#define NUMPIXELS 16
#define NEOPIXEL_PIN 23
#define DHT_PIN 32
#define MOTOR_PIN1 2
#define MOTOR_PIN2 4
#define MOTOR_PIN3 5
#define MOTOR_PIN4 15
#define TOTAL_STEPS 200
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, NEOPIXEL_PIN, NEO_GRB + NEO_KHZ800);
#define MQTT_SERVER "broker.emqx.io"
#define MQTT_PORT 1883
#define MQTT_TOPIC_SET_LIGHT "/Light/Set"
#define MQTT_TOPIC_GET_LIGHT "/Light/Get"
#define MQTT_TOPIC_TEMPERATURE "/Temperature"
#define MQTT_TOPIC_HUMIDITY "/Humidity"
const char *ssid = "Wokwi-GUEST";
const char *password = "";
WiFiClient espClient;
PubSubClient client(espClient);
DHTesp dht;
Stepper stepper(TOTAL_STEPS, MOTOR_PIN1, MOTOR_PIN2, MOTOR_PIN3, MOTOR_PIN4);
// Create stepperSpeed variable and set it to -1
int stepperSpeed = -1;
void setup() {
Serial.begin(115200);
pixels.begin();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
client.setServer(MQTT_SERVER, MQTT_PORT);
client.setCallback(callback);
dht.setup(DHT_PIN, DHTesp::DHT22);
// Set Stepper speeds
stepper.setSpeed(200);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
TempAndHumidity data = dht.getTempAndHumidity();
float temperature = data.temperature;
float humidity = data.humidity;
client.publish(MQTT_TOPIC_TEMPERATURE, String(temperature).c_str());
client.publish(MQTT_TOPIC_HUMIDITY, String(humidity).c_str());
// Check humidity less then 70 and temp less then 30
if(humidity<70 && temperature<30){
// Set stepperSpeed to 0
stepperSpeed=0;
}
// Check humidity greter then 70 and is less then 9
else if(humidity>70 && humidity<=90){
// Set stepper speed to -1
stepperSpeed=-1;
}
// Check if humidity greater then 9o or temp greater then 35
else if(humidity>90 || temperature >35){
// Set stepper speed to -5
stepperSpeed=-5;
}
stepper.step(stepperSpeed);
delay(10);
}
void reconnect() {
while (!client.connected()) {
if (client.connect("mqttx_3c24a783")) {
Serial.println("Connected to MQTT");
client.subscribe(MQTT_TOPIC_GET_LIGHT);
} else {
Serial.print("Failed, rc=");
Serial.print(client.state());
Serial.println(" Retrying in 5 seconds...");
delay(5000);
}
}
}
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.print("Command Received: ");
Serial.println(message);
if (strcmp(topic, MQTT_TOPIC_GET_LIGHT) == 0) {
updateColor(message);
}
}
void updateColor(String color) {
for (int i = 0; i < NUMPIXELS; i++) {
int hexColor = strtol(color.c_str(), NULL, 16);
pixels.setPixelColor(i, hexColor);
pixels.show();
}
}