#include <WiFi.h>
#include <HTTPClient.h>
// ---------- WiFi ----------
const char* WIFI_SSID = "Wokwi-GUEST";
const char* WIFI_PWD = "";
// ---------- ThingSpeak ----------
const char* TS_API_KEY = "UOO5LGZFY0EH4RN8";
const char* TS_URL_BASE = "http://api.thingspeak.com/update";
// ---------- ADC / LDR model ----------
const int LDR_ADC_PIN = 34;
const float ADC_MAX = 4095.0;
const float R_FIXED = 10000.0;
// ---------- LED ----------
const int LED_PIN = 2;
// ---------- Calibration ----------
const double A_CONST = 252618.1571708225;
const double B_CONST = 0.7012322813355019;
const double INV_B = 1.0 / B_CONST;
// ---------- Timing ----------
const unsigned long POST_INTERVAL_MS = 16000;
unsigned long lastPost = 0;
// ---------- Lux Conversion ----------
double luxFromADC(int adc) {
adc = constrain(adc, 1, 4094); // Prevent division by zero
double Rldr = R_FIXED * (double(adc) / (ADC_MAX - double(adc)));
return pow(A_CONST / Rldr, INV_B);
}
// ---------- WiFi Connection ----------
void connectWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PWD);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(300);
Serial.print(".");
}
Serial.println();
Serial.print("WiFi connected. IP: ");
Serial.println(WiFi.localIP());
}
// ---------- ThingSpeak Upload ----------
bool sendToThingSpeak(double lux, int ledStatus) {
String url = String(TS_URL_BASE) + "?api_key=" + TS_API_KEY +
"&field1=" + String(lux, 2) +
"&field3=" + String(ledStatus);
HTTPClient http;
http.begin(url);
int httpCode = http.GET();
Serial.print("Request URL: ");
Serial.println(url);
Serial.print("ThingSpeak response code: ");
Serial.println(httpCode);
String payload = http.getString();
Serial.println("Response payload: " + payload);
http.end();
return (httpCode == 200);
}
// ---------- Setup ----------
void setup() {
Serial.begin(115200);
analogReadResolution(12);
pinMode(LED_PIN, OUTPUT);
connectWiFi();
}
// ---------- Main Loop ----------
void loop() {
// Reconnect WiFi if disconnected
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi disconnected. Reconnecting...");
connectWiFi();
}
// Read ADC and convert to Lux
int adc = analogRead(LDR_ADC_PIN);
double lux = luxFromADC(adc);
Serial.print("ADC=");
Serial.print(adc);
Serial.print(" | Lux=");
Serial.println(lux, 2);
// LED control based on Lux
int ledStatus = (lux < 100.0) ? 1 : 0;
digitalWrite(LED_PIN, ledStatus ? HIGH : LOW);
// Post to ThingSpeak
unsigned long now = millis();
if (now - lastPost >= POST_INTERVAL_MS) {
sendToThingSpeak(lux, ledStatus);
lastPost = now;
}
delay(250);
}