#include <WiFi.h>
#include <PubSubClient.h>
#include <Servo.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// MQTT broker
const char* mqtt_server = "test.mosquitto.org";
const char* mqtt_username = "";
const char* mqtt_password = "";
// MQTT topics
const char* servo_topic = "rumah/servo";
const char* dht_topic = "rumah/dht";
// Pin assignments
const int potentiometer_pin = 27;
const int photoresistor_pin = 26;
const int servo_pin = 21;
const int dht_pin = 18;
// Servo setup
Servo servo;
// DHT setup
#define DHTTYPE DHT22
DHT dht(dht_pin, DHTTYPE);
// WiFi and MQTT setup
WiFiClient espClient;
PubSubClient client(espClient);
// Function prototypes
void setup_wifi();
void callback(char* topic, byte* payload, unsigned int length);
void reconnect();
void readSensorsAndPublish();
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
servo.attach(servo_pin);
dht.begin();
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
readSensorsAndPublish();
delay(1000); // Adjust as needed
}
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
// Handle incoming messages if needed
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP32Client", mqtt_username, mqtt_password)) {
Serial.println("connected");
client.subscribe(servo_topic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void readSensorsAndPublish() {
// Read potentiometer value
int pot_value = analogRead(potentiometer_pin);
// Read photoresistor value
int photoresistor_value = analogRead(photoresistor_pin);
// Read DHT22 sensor values
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Publish sensor readings
client.publish("rumah/potentiometer", String(pot_value).c_str());
client.publish("rumah/photoresistor", String(photoresistor_value).c_str());
client.publish("rumah/dht_temperature", String(temperature).c_str());
client.publish("rumah/dht_humidity", String(humidity).c_str());
}
// Example function to control servo based on MQTT command
void controlServo(char* payload) {
int angle = atoi(payload);
servo.write(angle);
}