#include <WiFi.h>
#include <HTTPClient.h>
#include <ThingSpeak.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* thingSpeakServer = "api.thingspeak.com/update";
const char* writeAPIKey = "39SNENCWNDY86C1Z";
#define ldr 32
int LDR;
void setup() {
Serial.begin(115200);
pinMode(32, INPUT);
pinMode(5, OUTPUT);
WiFi. begin(ssid, password);
while(WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(". ");
}
Serial.print("Connected");
}
void loop() {
int LDR = analogRead(ldr); // Read LDR value
if (LDR > 1121) { // Low light
digitalWrite(5, HIGH);
} else if (LDR < 1020) { // High ligh
digitalWrite(5, LOW);
}
int Light = digitalRead(5);
Serial.println("value:");
Serial.println(LDR);
Serial.println(Light);
delay(1000);
// Connect to WiFi
// Uncomment if you need to send data to ThingSpea
if(LDR != 0)
{
sendDataToThingSpeak(LDR, Light);
delay(5000);
}
}
void sendDataToThingSpeak(int lux, int a)
{
HTTPClient http;
// Construct the URL
String url = String("http://") + thingSpeakServer + "?api_key=" + writeAPIKey + "&field1=" + String(lux) + "&field2=" + String(a);
http.begin(url); // Initiate the HTTP request
int httpCode = http.GET(); // Send the request and get the response code
if (httpCode > 0) { // Check if the request was successful
String payload = http.getString(); // Get the response payload
Serial.println("ThingSpeak response: " + payload);
} else {
Serial.println("Error in HTTP request: " + String(httpCode));
}
http.end(); // End the HTTP request
}