#include <WiFi.h>
#include <DHT.h>
#include <HTTPClient.h>
const float GAMMA = 0.7;
const float RL10 = 33;
// DHT22 Pin
#define DHT_PIN 15
#define DHT_TYPE DHT22
DHT dht(DHT_PIN, DHT_TYPE);
// LDR Pin (Analog input)
#define LDR_PIN 32
// LED Pin (Digital output)
#define LED_PIN 18
// WiFi credentials
const char *ssid = "Wokwi-GUEST";
const char *password = "";
// API URLs
const char *tempApiUrl = "https://afiq-onem2m.site/devices/temperature_0/data";
const char *humiApiUrl = "https://afiq-onem2m.site/devices/humidity_0/data";
const char *lumiApiUrl = "https://afiq-onem2m.site/devices/luminosity_0/data";
const char *lampApiUrl = "https://afiq-onem2m.site/devices/lamp_0/data";
// WiFi connection
void setup() {
Serial.begin(115200);
dht.begin();
// Initialize LED pin
pinMode(LED_PIN, OUTPUT);
// Connect to WiFi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to WiFi");
}
// Function to send HTTP POST request
void sendPostRequest(const char *url, String payload) {
HTTPClient http;
http.begin(url);
http.addHeader("Content-Type", "application/json");
int httpCode = http.POST(payload);
if (httpCode > 0) {
String response = http.getString();
Serial.println("Response: " + response);
} else {
Serial.println("Error sending POST request to " + String(url));
}
http.end();
}
void loop() {
// Read temperature and humidity from DHT22 sensor
float temp = dht.readTemperature();
float humidity = dht.readHumidity();
// Check if the readings are valid
if (isnan(temp) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Read the light level from LDR (analog value)
int ldrValue = analogRead(LDR_PIN);
float voltage = ldrValue / 4096. * 3.3;
float resistance = 2000 * voltage / (1 - voltage / 3.3);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
// Print the sensor data to the Serial Monitor
Serial.print("Temperature: ");
Serial.print(temp);
Serial.println(" °C");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
Serial.print("LDR Value: ");
Serial.println(lux);
// Send temperature data
String tempJson = String("{\"value\":") + temp + "}";
sendPostRequest(tempApiUrl, tempJson);
// Send humidity data
String humiJson = String("{\"value\":") + humidity + "}";
sendPostRequest(humiApiUrl, humiJson);
// Send light intensity (LDR) data
String lumiJson = String("{\"value\":") + lux + "}";
sendPostRequest(lumiApiUrl, lumiJson);
// Send LED status (turn LED on or off based on a simple condition)
String ledStatus = (lux < 300) ? "true" : "false"; // For example, turn on if light is low
digitalWrite(LED_PIN, ledStatus == "true" ? HIGH : LOW);
String lampJson = String("{\"value\":") + ledStatus + "}";
sendPostRequest(lampApiUrl, lampJson);
// Print LED status
Serial.print("LED Status: ");
Serial.println(ledStatus);
// Wait 10 seconds before sending the next data
delay(3000);
}