#include <Wire.h>
#include <WiFi.h>
#include <DHT.h>
#include <PubSubClient.h>
#include <Arduino.h>
#define DHT_PIN 12
#define TDS_PIN 35
#define PH_PIN 21
#define MQTT_SERVER "broker.emqx.io"
#define MQTT_PORT 1883
const char *ssid = "Wokwi-GUEST";
const char *password = "";
#define MQTT_TOPIC_PH "phValue"
#define MQTT_TOPIC_TDS "tdsValue"
#define MQTT_TOPIC_TEMP "tempValue"
#define MQTT_TOPIC_HUM "humValue"
WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(DHT_PIN, DHT22);
void setup() {
Wire.begin(23, 22);
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
connectToWiFi();
client.setServer(MQTT_SERVER, MQTT_PORT);
client.setCallback(callback);
dht.begin();
}
void loop() {
if (!client.connected()) {
reconnect();
}
float temperature = dht.readTemperature();
float humidity = dht.readHumidity(); // Read temperature from DHT sensor
//Read alnalog value from ADC converter
int16_t tdsValue = analogRead(TDS_PIN);
//Find voltage at the pin
float voltage = tdsValue * (5 / 4095.0);
//Find actual value as sensor's max voltage is 2.3
int mappedTdsValue = (voltage / 2.3) * 1000;
//ph
int16_t phValue = analogRead(PH_PIN);
Serial.print("TDS: ");
Serial.print(mappedTdsValue);
Serial.print(" Voltage: ");
Serial.print(voltage);
Serial.print(" Temp: ");
Serial.print(temperature);
Serial.print(" Humidity: ");
Serial.print(humidity);
Serial.print(" ph: ");
Serial.println(phValue);
delay(5000);
// put your main code here, to run repeatedly:
client.publish(MQTT_TOPIC_PH, String(7).c_str());
client.publish(MQTT_TOPIC_TDS, String(mappedTdsValue).c_str());
client.publish(MQTT_TOPIC_TEMP, String(temperature).c_str());
client.publish(MQTT_TOPIC_HUM, String(humidity).c_str());
Serial.print("Sent mtqq data");
delay(10); // this speeds up the simulation
}
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("esp32_neopixel_controller")) {
Serial.println("Connected to MQTT");
// subscribeToCommands();
} 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);
// Check the received MQTT topic
if (strcmp(topic, "MQTT_TOPIC_SPEED") == 0) {
if (message.equals("0")) {
// Set the motor speed based on the received command
int speedCommand = message.toInt();
}
}
else if (strcmp(topic," MQTT_TOPIC_LIGHT") == 0) {
if (message.equals("off")) {
Serial.println("Neopixel turned OFF");
}
}
}