#include <WiFi.h>
#include <HTTPClient.h>
#include "DHT.h"
const float GAMMA = 0.7;
const float RL10 = 33;
#define DHTPIN 4 // Pin where DHT22 is connected
#define DHTTYPE DHT22 // Type of DHT sensor
#define LDRPIN 34 // Pin where LDR is connected
#define LEDPIN 2 // LED pin
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* server1 = "http://localhost:8369/devices/lumi/data";
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
dht.begin();
pinMode(LEDPIN, OUTPUT);
}
void loop() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print("ºC ");
Serial.print("Humidity: ");
Serial.println(humidity);
int lightIntensity = analogRead(LDRPIN);
float voltage = lightIntensity / 4096. * 3.3;
float resistance = 2000 * voltage / (1 - voltage / 3.3);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
// Control LED based on light intensity
Serial.print("Room: ");
if (lux < 500) {
digitalWrite(LEDPIN, HIGH); // Turn on LED
Serial.print("Light! ");
} else {
digitalWrite(LEDPIN, LOW); // Turn off LED
Serial.print("Dark ");
}
Serial.print("Lux: ");
Serial.println(lux);
lumi_onem2m(lux); // Send data to server
delay(5000); // Delay 5 seconds
}
void lumi_onem2m(float lux) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(server1); // Use the correct server
http.addHeader("Content-Type", "application/json");
String payload = String("{\"Luminosity\": ") + lux + "}";
int httpResponseCode = http.POST(payload);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("Response: " + response);
} else {
Serial.println("Error sending data");
}
http.end();
} else {
Serial.println("WiFi not connected");
}
}