#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <LiquidCrystal_I2C.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "broker.hivemq.com";
// GANTI BAGIAN INI DENGAN IDENTITAS MASING-MASING
const char* mqtt_topic = "kelas/iot/waterquality/301230024";
WiFiClient espClient;
PubSubClient client(espClient);
// Inisialisasi LCD pada alamat 0x27 dengan ukuran 16 kolom 2 baris
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Definisi Pin
#define PIN_NTC 32
#define PIN_TDS 34
#define PIN_PH 35
// Konstanta Sensor Suhu NTC
const float BETA = 3950;
void setup_wifi() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("WiFi Conn...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
lcd.setCursor(0, 1);
lcd.print("WiFi Connected!");
delay(1000);
}
void reconnect() {
while (!client.connected()) {
String clientId = "ESP32Water-" + String(random(0, 0xffff), HEX);
if (client.connect(clientId.c_str())) {
// Terhubung
} else {
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
// Setup LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Water Quality");
lcd.setCursor(0, 1);
lcd.print("System Booting..");
delay(2000);
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void loop() {
if (!client.connected()) { reconnect(); }
client.loop();
// 1. Baca Suhu dari NTC Thermistor
int ntcValue = analogRead(PIN_NTC);
// Rumus Steinhart-Hart untuk mengkonversi nilai analog NTC menjadi Celcius
float tempC = 1 / (log(1 / (4095. / ntcValue - 1)) / BETA + 1.0 / 298.15) - 273.15;
// 2. Baca TDS (Simulasi Potensiometer 0 - 1000 ppm)
int tdsRaw = analogRead(PIN_TDS);
int tdsValue = map(tdsRaw, 0, 4095, 0, 1000);
// 3. Baca pH (Simulasi Potensiometer 0.0 - 14.0)
int phRaw = analogRead(PIN_PH);
float phValue = phRaw * (14.0 / 4095.0);
// --- TAMPILKAN KE LCD EDGE ---
lcd.clear();
// Baris 1: Suhu & pH
lcd.setCursor(0, 0);
lcd.print("T:"); lcd.print(tempC, 1); lcd.print("C ");
lcd.print("pH:"); lcd.print(phValue, 1);
// Baris 2: TDS
lcd.setCursor(0, 1);
lcd.print("TDS: "); lcd.print(tdsValue); lcd.print(" ppm");
// --- KIRIM KE CLOUD (JSON) ---
StaticJsonDocument<200> doc;
doc["suhu"] = tempC;
doc["tds"] = tdsValue;
doc["ph"] = phValue;
char jsonBuffer[512];
serializeJson(doc, jsonBuffer);
client.publish(mqtt_topic, jsonBuffer);
Serial.println(jsonBuffer);
delay(3000); // interval pengiriman 3 detik
}Loading
esp32-devkit-c-v4
esp32-devkit-c-v4