#include <WiFi.h>
#include <HTTPClient.h>
// Replace with your network credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Replace with your ThingSpeak API key and channel ID
const char* apiKey = "4FYHOC44964FT48P";
const char* channelID = "2413566";
// Analog pin connected to LDR
const int ldrPin = 34; // Change this to the actual pin you've connected the LDR to
void setup() {
Serial.begin(115200);
connectWiFi();
}
void loop() {
// Read LDR value
int ldrValue = analogRead(ldrPin);
// Print LDR value to serial monitor
Serial.print("LDR Value: ");
Serial.println(ldrValue);
// Send data to ThingSpeak
sendDataToThingSpeak(ldrValue);
// Wait for 15 seconds before sending the next data
delay(15000);
}
void connectWiFi() {
Serial.println("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting...");
}
Serial.println("Connected to WiFi");
}
void sendDataToThingSpeak(int value) {
HTTPClient http;
String url = "http://api.thingspeak.com/update?api_key=" + String(apiKey) + "&field1=" + String(value);
Serial.println("Sending data to ThingSpeak...");
Serial.println(url);
if (http.begin(url)) {
int httpResponseCode = http.GET();
if (httpResponseCode == 200) {
Serial.println("Data sent successfully to ThingSpeak!");
} else {
Serial.print("Error in sending data. HTTP Response code: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("Error in HTTP begin.");
}
}