#include <WiFi.h>
#include <ThingSpeak.h>
// Define the pins
const int relayPin = 23; // Pin connected to the relay module (change as needed)
const int tempPin = 34;
const int ledPin =18;
// Pin connected to the analog temperature sensor
// Define temperature threshold
const float TEMP_THRESHOLD = 100.0; // Temperature in Celsius to turn the light on
// Wi-Fi credentials
char ssid[] = "Wokwi-GUEST"; // network SSID (name)
char pass[] = ""; // network password
WiFiClient client;
// ThingSpeak settings
const unsigned long CHANNEL_ID = 2632350; // Replace with your Channel ID
const char* WRITE_API_KEY = "0NSOZG90XD1QW0SA"; // Replace with your Write API Key
const char* server = "api.thingspeak.com";
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Initialize relay pin as output
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, LOW);
// Connect to Wi-Fi
WiFi.begin(ssid, pass);
Serial.print("Connecting to ");
Serial.print(ssid);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected!");
// Initialize ThingSpeak
ThingSpeak.begin(client);
}
void loop() {
// Read the temperature sensor
int sensorValue = analogRead(tempPin);
// Convert the sensor value to temperature in Celsius
// The ESP32 ADC reads values from 0 to 4095, and the reference voltage is 3.3V
float voltage = (sensorValue / 4095.0) * 3.3;
float temperature = voltage * 100.0; // Assuming 10mV/°C for LM35 or similar
// Print the temperature to the Serial Monitor
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" C");
// Control the relay based on temperature
bool isLightOn = temperature > TEMP_THRESHOLD;
digitalWrite(relayPin, isLightOn ? HIGH:LOW);
// Initialize LED pin as output
pinMode(18, OUTPUT); // Set the LED pin as an OUTPUT
digitalWrite(18,HIGH); // Ensure the LED
delay(10000);
digitalWrite(18, LOW);
delay(10000);
// Print the status of the street light (LED) to the Serial Monitor
if (isLightOn) {
Serial.println("Street light ON");
} else {
Serial.println("Street light OFF");
}
// Send data to ThingSpeak
ThingSpeak.setField(1, temperature); // Field 1 for temperature
ThingSpeak.setField(2, isLightOn ? 1 : 0); // Field 2 for light status
// Update ThingSpeak
int httpCode = ThingSpeak.writeFields(CHANNEL_ID, WRITE_API_KEY);
if (httpCode == 200) {
Serial.println("Data sent to ThingSpeak successfully.");
} else {
Serial.print("Error sending data: ");
Serial.println(httpCode);
}
// Wait before taking another reading
delay(2000); // 20 seconds delay
}