// ESP32 IoT Controller
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <DHT.h>
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Server URL (replace with your Flask server IP)
const char* serverUrl = "https://rasyid.elektrounpad.site";
// DHT22 sensor setup
#define DHTPIN 4 // DHT22 data pin
#define DHTTYPE DHT22 // DHT22 sensor type
DHT dht(DHTPIN, DHTTYPE);
// MQ2 gas sensor setup
#define MQ2PIN 34 // MQ2 analog input pin
// LED pins
#define LED1PIN 25
#define LED2PIN 26
#define LED3PIN 27
// Variables for sensor readings
float temperature = 0;
float humidity = 0;
int gasValue = 0;
// Variables for LED states
bool led1State = false;
bool led2State = false;
bool led3State = false;
// Timing variables
unsigned long previousMillis = 0;
const long interval = 1500; // Update every 5 seconds
void setup() {
Serial.begin(115200);
// Initialize LED pins as outputs
pinMode(LED1PIN, OUTPUT);
pinMode(LED2PIN, OUTPUT);
pinMode(LED3PIN, OUTPUT);
// Initialize all LEDs as OFF
digitalWrite(LED1PIN, LOW);
digitalWrite(LED2PIN, LOW);
digitalWrite(LED3PIN, LOW);
// Initialize DHT sensor
dht.begin();
// Connect to WiFi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
unsigned long currentMillis = millis();
// Check WiFi connection
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi disconnected. Reconnecting...");
WiFi.begin(ssid, password);
delay(5000); // Wait 5 seconds before checking again
return;
}
// Read sensors and update server every interval
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
// Read sensors
readSensors();
// Send sensor data to server
sendSensorData();
// Get LED status from server
getLEDStatus();
}
}
void readSensors() {
// Read temperature and humidity from DHT22
float newTemp = dht.readTemperature();
float newHumidity = dht.readHumidity();
// Check if readings are valid
if (!isnan(newTemp) && !isnan(newHumidity)) {
temperature = newTemp;
humidity = newHumidity;
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print("°C, Humidity: ");
Serial.print(humidity);
Serial.println("%");
} else {
Serial.println("Failed to read from DHT sensor!");
}
// Read gas value from MQ2
gasValue = analogRead(MQ2PIN);
Serial.print("Gas Value: ");
Serial.println(gasValue);
}
void sendSensorData() {
// Send DHT22 data
HTTPClient http;
http.begin(String(serverUrl) + "/api/sensor/dht22");
http.addHeader("Content-Type", "application/json");
// Create JSON document for DHT22 data
StaticJsonDocument<200> dhtDoc;
dhtDoc["temperature"] = temperature;
dhtDoc["humidity"] = humidity;
String dhtJson;
serializeJson(dhtDoc, dhtJson);
int dhtResponseCode = http.POST(dhtJson);
if (dhtResponseCode > 0) {
Serial.print("DHT22 data sent. Response code: ");
Serial.println(dhtResponseCode);
} else {
Serial.print("Error sending DHT22 data. Error: ");
Serial.println(http.errorToString(dhtResponseCode));
}
http.end();
// Send MQ2 data
http.begin(String(serverUrl) + "/api/sensor/mq2");
http.addHeader("Content-Type", "application/json");
// Create JSON document for MQ2 data
StaticJsonDocument<200> mq2Doc;
mq2Doc["gas_value"] = gasValue;
String mq2Json;
serializeJson(mq2Doc, mq2Json);
int mq2ResponseCode = http.POST(mq2Json);
if (mq2ResponseCode > 0) {
Serial.print("MQ2 data sent. Response code: ");
Serial.println(mq2ResponseCode);
} else {
Serial.print("Error sending MQ2 data. Error: ");
Serial.println(http.errorToString(mq2ResponseCode));
}
http.end();
}
void getLEDStatus() {
HTTPClient http;
http.begin(String(serverUrl) + "/api/led/status");
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String payload = http.getString();
Serial.println("LED status received");
// Parse JSON response
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, payload);
if (!error) {
// Update LED states
bool newLed1State = doc["led1"];
bool newLed2State = doc["led2"];
bool newLed3State = doc["led3"];
// Only update if states have changed
if (newLed1State != led1State) {
led1State = newLed1State;
digitalWrite(LED1PIN, led1State ? HIGH : LOW);
Serial.print("LED 1 is now ");
Serial.println(led1State ? "ON" : "OFF");
}
if (newLed2State != led2State) {
led2State = newLed2State;
digitalWrite(LED2PIN, led2State ? HIGH : LOW);
Serial.print("LED 2 is now ");
Serial.println(led2State ? "ON" : "OFF");
}
if (newLed3State != led3State) {
led3State = newLed3State;
digitalWrite(LED3PIN, led3State ? HIGH : LOW);
Serial.print("LED 3 is now ");
Serial.println(led3State ? "ON" : "OFF");
}
} else {
Serial.print("deserializeJson() failed: ");
Serial.println(error.c_str());
}
} else {
Serial.print("Error getting LED status. Error: ");
Serial.println(http.errorToString(httpResponseCode));
}
http.end();
}