#include <WiFi.h>
#include "ThingSpeak.h"
const uint8_t LDR = 14; // Define pin for LDR
const uint8_t TEMP_PIN = 34; // Define pin for analog temperature sensor
// Define WiFi credentials
const char* ssid = "Wokwi-GUEST"; // Your network SSID (name)
const char* pass = ""; // Your network password
WiFiClient client;
// ThingSpeak channel details
unsigned long myChannelNumber = 2418295; // Channel number taken from cloud
const char* myWriteAPIKey = "FCCIVQOAYL7Q2IXV"; // Write API key of cloud
const char* myCounterReadAPIKey = "UCRV5PQONTN6M9MF"; // Read API key from cloud
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Initialize ThingSpeak
ThingSpeak.begin(client);
// Set pin modes for various pins
pinMode(LDR, INPUT);
pinMode(15, OUTPUT);
pinMode(2, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
}
void loop() {
// Connect or reconnect to WiFi
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
while (WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid, pass); // Connect to WPA/WPA2 network. Change this line if using open or WEP network
Serial.print(".");
delay(5000);
}
Serial.println("\nConnected.");
}
// Read temperature from analog temperature sensor
int temperature = analogRead(TEMP_PIN);
float t = map(temperature, 0, 4095, 0, 100); // Convert ADC reading to temperature in Celsius
// Read light status from LDR
int L = digitalRead(LDR);
// Set ThingSpeak fields with sensor values
ThingSpeak.setField(1, t);
ThingSpeak.setField(2, L);
// Write to the ThingSpeak channel
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (x == 200) {
Serial.println("Channel update successful.");
}
// Control LEDs based on conditions
digitalWrite(2, L == 0 ? HIGH : LOW); // Turn on LED if LDR reads low light
digitalWrite(15, t >= 25 ? HIGH : LOW); // Turn on LED if temperature is higher than or equal to 25°C
// Read and control additional fields from ThingSpeak channel
int C = ThingSpeak.readLongField(myChannelNumber, 7, myCounterReadAPIKey);
digitalWrite(4, C); // Control pin 4 based on ThingSpeak field value
int D = ThingSpeak.readLongField(myChannelNumber, 8, myCounterReadAPIKey);
digitalWrite(5, D); // Control pin 5 based on ThingSpeak field value
delay(10000); // Wait for 10 seconds before updating again
}