#include <Servo.h>
#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <WiFi.h>
#include <PubSubClient.h> // For MQTT
#include <ArduinoJson.h> // For JSON
Servo myservo;
DHT dht(7, DHT22); // Connect the DHT sensor to pin 7
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address and LCD size (16x2)
#define WIFI_AP "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define TOKEN "tanamantoken" // Replace with your actual token
char thingsboardServer[] = "thingsboard.cloud";
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient); // Use PubSubClient as the MQTT client
void setup() {
myservo.attach(9); // Connect the servo motor to pin 9
myservo.write(0); // Initial position of the servo motor
dht.begin();
lcd.init();
lcd.backlight();
Serial.begin(9600);
InitWiFi();
mqttClient.setServer(thingsboardServer, 1883); // Default port for non-SSL MQTT
}
void loop() {
if (!mqttClient.connected()) {
reconnect();
}
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
if (humidity >= 0 && temperature >= 0) {
// If humidity and temperature are within the desired range, activate the servo motor
myservo.write(180); // Watering position
Serial.println("Sedang menyiram tanaman.");
lcd.setCursor(0, 0);
lcd.print("Humidity: ");
lcd.print(humidity);
lcd.print(" %");
lcd.setCursor(0, 1);
lcd.print("Temperature: ");
lcd.print(temperature);
lcd.print(" C");
delay(3000); // Allow watering for 3 seconds
myservo.write(0); // Return to the initial position
lcd.clear();
// Send data to ThingsBoard via MQTT
sendDataToThingsboard(temperature, humidity);
}
delay(60000); // Wait for 1 minute before reading sensors again
}
void sendDataToThingsboard(float temperature, float humidity) {
Serial.println("Sending sensor data to ThingsBoard");
// Create JSON Object
StaticJsonDocument<200> jsonBuffer;
jsonBuffer["temperature"] = temperature;
jsonBuffer["humidity"] = humidity;
char JSONmessageBuffer[100];
serializeJson(jsonBuffer, JSONmessageBuffer);
mqttClient.publish("v1/devices/me/telemetry", JSONmessageBuffer);
}
void InitWiFi() {
Serial.println("Connecting to WiFi...");
WiFi.begin(WIFI_AP, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to WiFi!");
}
void reconnect() {
while (!mqttClient.connected()) {
Serial.print("Connecting to ThingsBoard server...");
// Use token as MQTT client ID
if (mqttClient.connect("ServoClientID", TOKEN, NULL)) {
Serial.println("[SUCCESS]");
} else {
Serial.print("[FAILED] [ rc = ");
Serial.print(mqttClient.state());
Serial.println(" ] [Retry in 5 seconds]");
// Wait 5 seconds before retrying
delay(5000);
}
}
}