#include <WiFi.h>
#include <WiFiClient.h>
#include "DHTesp.h"
#include <PubSubClient.h>
//Credenciais Wifi
const char* WIFI_SSID = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
//configurar broker MQTT
const char* MQTT_SERVER = "broker.hiveqm.com";
const int MQTT_PORT = 1883;
const char* MQTT_CLIENT_ID = "arduino_client";
const int DHT_PIN = 15;
const int potentiometerPin = 34;
const int motorPumpPin = 5;
int waterBottle = 0;
DHTesp dhtSensor;
WiFiClient espClient;
PubSubClient client(espClient);
void callback(char* topic, byte* payload, unsigned int length) {
if (strcmp(topic, "sensors/motor-pump") == 0) {
if (payload[0] == '1') {
digitalWrite(motorPumpPin, HIGH); // Turn on the motor pump (LED) Serial.println("Pump on");
waterBottle += 2;
} else if (payload[0] == '0') {
digitalWrite(motorPumpPin, LOW); // Turn off the motor pump (LED) Serial.println("pump off");
}
}
}
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Connect to MQTT broker
client.setServer(MQTT_SERVER, MQTT_PORT);
client.setCallback(callback);
while (!client.connected()) {
if (client.connect(MQTT_CLIENT_ID)) {
Serial.println("Connected to MQTT broker");
} else {
Serial.print("Failed to connect to MQTT broker, rc=");
Serial.print(client.state());
Serial.println(" Retrying in 5 seconds...");
delay(5000);
}
}
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
// Set motor pump pin as output
pinMode(motorPumpPin, OUTPUT);
// Subscribe to the motor pump topic
client.subscribe("sensors/motor-pump");
}
void loop() {
// Handle incoming MQTT messages
client.loop();
// Read sensor data
TempAndHumidity data = dhtSensor.getTempAndHumidity();
int potentiometerValue = analogRead(potentiometerPin);
// Print sensor data to serial monitor
Serial.println("Temperature: " + String(data.temperature, 2) + "°C");
Serial.println("Humidity: " + String(data.humidity, 1) + "%"); Serial.println("Soil Moisture: " + String(potentiometerValue));
// Publish sensor data to MQTT topics
char temperatureTopic[] = "sensors/temperature";
char humidityTopic[] = "sensors/humidity";
char potentiometerTopic[] = "sensors/potentiometer";
char waterTopic[] = "sensors/water";
client.publish(temperatureTopic, String(data.temperature, 2).c_str());
client.publish(humidityTopic, String(data.humidity, 1).c_str());
client.publish(potentiometerTopic, String(potentiometerValue).c_str());
if (waterBottle >= 2){
client.publish(waterTopic, String("1").c_str());
} else {
client.publish(waterTopic, String("0").c_str());
}
// Delay before next iteration
delay(3000);
}
//client.publish(potentiometerTopic, String(potentiometerValue).c_str());
//if (waterBottle >= 2){
//client.publish(waterTopic, String("1").c_str());
//}
//else {
//client.publish(waterTopic, String("0").c_str());
//}