#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "your_SSID"; // replace with your WiFi SSID
const char* password = "your_PASSWORD"; // replace with your WiFi password
const char* server = "http://api.thingspeak.com/update"; // ThingSpeak server
const char* apiKey = "API KEY"; // replace with your ThingSpeak API key
const int ldrPin = 34; // GPIO pin for LDR
const int ledPin = 13; // GPIO pin for LED
const int threshold = 1000; // Threshold value for LDR
int count = 0;
void setup() {
Serial.begin(115200);
pinMode(ldrPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH); // Turn on the LED
connectToWiFi();
}
void loop() {
int ldrValue = analogRead(ldrPin);
if (ldrValue < threshold) {
count++;
Serial.print("Count: ");
Serial.println(count);
delay(500); // Debounce delay
sendToThingSpeak(count);
}
delay(100);
}
void connectToWiFi() {
Serial.begin(9600);
Serial.print("Connecting to WiFi");
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
}
void sendToThingSpeak(int value) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(server) + "?api_key=" + apiKey + "&field1=" + String(value);
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
Serial.printf("HTTP GET code: %d\n", httpCode);
} else {
Serial.printf("HTTP GET failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
} else {
Serial.println("WiFi disconnected");
connectToWiFi();
}
}