const int NTC_PIN = 34;
const int TRIG_PIN = 4;
const int ECHO_PIN = 35;
const int PH_PIN = 32;
const float BETA = 3950; // should match the Beta Coefficient of the thermistor
#include <WiFi.h>
#include <PubSubClient.h>
#include <iostream>
#include <iomanip>
#include <sstream>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
//***Set server***
const char* mqttServer = "0.tcp.ap.ngrok.io";
int port = 16537 ;
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
void wifiConnect() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" Connected!");
}
void mqttConnect() {
while (!mqttClient.connected()) {
Serial.println("Attemping MQTT connection...");
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
if (mqttClient.connect(clientId.c_str())) {
Serial.println("connected");
//***Subscribe all topic you need***
}
else {
Serial.println("try again in 5 seconds");
delay(5000);
}
}
}
//MQTT Receiver
void callback(char* topic, byte* message, unsigned int length) {
Serial.println(topic);
String strMsg;
for (int i = 0; i < length; i++) {
strMsg += (char)message[i];
}
Serial.println(strMsg);
//***Code here to process the received package***
}
float getDistance() {
unsigned long duration;
digitalWrite(TRIG_PIN, 0);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, 1);
delayMicroseconds(5);
digitalWrite(TRIG_PIN, 0);
duration = pulseIn(ECHO_PIN, HIGH);
return float(duration / 2 / 29.412);
}
void setup() {
Serial.begin (115200);
pinMode(NTC_PIN, INPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(PH_PIN, INPUT);
wifiConnect();
delay(1000);
analogReadResolution(10);
mqttClient.setServer(mqttServer, port);
mqttClient.setCallback(callback);
mqttClient.setKeepAlive( 90 );
}
void loop() {
if(!mqttClient.connected()) {
mqttConnect();
}
mqttClient.loop();
// put your main code here, to run repeatedly:
int analogValue = analogRead(NTC_PIN);
float celsius = 1 / (log(1 / (1023. / analogValue - 1)) / BETA + 1.0 / 298.15) - 273.15;
int pH = analogRead(PH_PIN);
float distance=getDistance();
pH = map(pH, 0, 1023, 0, 14);
Serial.print("Temperature: ");
Serial.print(celsius);
Serial.println(" ℃");
Serial.print("pH: ");
Serial.println(pH);
Serial.print("Water level: ");
Serial.println(distance);
char msgTemp[50];
char msgPh[50];
char msgLevel[50];
snprintf(msgTemp,50,"%.2f",celsius);
snprintf(msgPh,50,"%d",pH);
snprintf(msgLevel,50,"%.2f",distance);
mqttClient.publish("temperature",msgTemp);
mqttClient.publish("pH",msgPh);
mqttClient.publish("waterLevel",msgLevel);
delay(1000);
}