#include <WiFi.h>
#include <PubSubClient.h>
#include "DHTesp.h"
#include <ESP32Servo.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PW ""
#define MQTT_BROKER "broker.hivemq.com"
#define MQTT_PORT 1883
const int DHT_PIN = 15;
int i=0, intOrOFRAutor=0;
int pos=0;
float T=0, H=0;
WiFiClient espClient;
PubSubClient client(espClient);
DHTesp dhtSensor;
Servo myservo;
void setup() {
Serial.begin(115200);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
myservo.attach(32);
WiFi.begin(WIFI_SSID, WIFI_PW);
while (WiFi.status() != WL_CONNECTED) {
delay(250);
Serial.println(".");
}
Serial.println("Hello from ESP8266");
Serial.print("Connected to hotspot: ");
Serial.println(WIFI_SSID);
Serial.print("IP address is: ");
Serial.println(WiFi.localIP());
Serial.println("-------------------------");
client.setSocketTimeout(60);
client.setKeepAlive(5);
client.setServer(MQTT_BROKER, MQTT_PORT);
client.setCallback(callback);
reconnect();
client.publish("OrOfrAutor", String(intOrOFRAutor).c_str());
client.subscribe("OrOfrAutor");
}
void loop() {
myservo.write(pos);
TempAndHumidity data = dhtSensor.getTempAndHumidity();
T=data.temperature;
H=data.humidity;
switch (intOrOFRAutor) {
case 0:
pos=0;
break;
case 1:
pos=180;
break;
case 2:
if ((T<14)&&(H>=0)&&(H<=40)){
pos = map(H, 0, 40, 0, 0);
}
else
if ((T>14)&&(H>=0)&&(H<=40)){
pos=map(H, 0, 40, 5, 25);
}
else
if ((T>18)&&(H>=0)&&(H<=40)){
pos=map(H, 0, 40, 25, 90);
}
else
if ((T<14)&&(H>40)&&(H<=60)){
pos= map(H, 40, 60, 0, 10);
}
else
if ((T>14)&&(H>40)&&(H<=60)){
pos= map(H, 40, 60, 10, 45);
}
else
if ((T>18)&&(H>40)&&(H<=60)){
pos= map(H, 40, 60, 45, 180);
}
else
if ((T<14)&&(H>60)&&(H<=100)){
pos= map(H, 60, 100, 10, 25);
}
else
if ((T>14)&&(H>60)&&(H<=100)){
pos= map(H, 60, 100, 25, 120);
}
if ((T>18)&&(H>60)&&(H<=100)){
pos= map(H, 60, 100, 120, 180);
}
break;
}
Serial.println("Temp: " + String(data.temperature, 2) + "°C");
Serial.println("Humidity: " + String(data.humidity, 2) + "%");
Serial.println("<: " + String(pos));
if (!client.connected()) {
reconnect();
}
client.loop();
client.publish("FXX-T", String(data.temperature, 2).c_str());
client.publish("FXX-H", String(data.humidity, 2).c_str());
client.publish("servoDegg", String(pos).c_str());
delay(1000);
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
if(String(topic) == "OrOfrAutor") {
String strPayload = String((char)payload[0]);
switch (int i=strPayload.toInt()) {
case 0:
Serial.println("Ofr");
intOrOFRAutor=0;
break;
case 1:
Serial.println("Or");
intOrOFRAutor=1;
break;
case 2:
Serial.println("Autor");
intOrOFRAutor=2;
break;
}
}
Serial.println("-----------------------");
}
void reconnect() {
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESPRBB", "bobcat", "bobcat1234" )) {
Serial.println("Connected to broker");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}