#include <WiFi.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include "ThingSpeak.h"
#include <LiquidCrystal_I2C.h> // Include the library for the LCD
// Constants for pins
const int LDR_PIN = 34; // Pin for the photoresistor (analog pin)
const int LED_PIN = 13; // Pin for the LED
const int ONE_WIRE_BUS = 2; // Pin for the DS18B20 data line
// Wi-Fi and ThingSpeak credentials
const char* WIFI_NAME = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
const int myChannelNumber = 2647114;
const char* myApiKey = "CPHZI3P1T1S7OWH5";
// Create instances
WiFiClient client;
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
LiquidCrystal_I2C lcd(0x27, 16, 2); // Change the I2C address if needed (0x27 is common)
// Setup function
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
// Start the LCD
lcd.begin();
lcd.backlight(); // Turn on the backlight
// Start the DallasTemperature library
sensors.begin();
// Connect to Wi-Fi
WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Wifi not connected");
}
Serial.println("Wifi connected!");
Serial.println("Local IP: " + String(WiFi.localIP()));
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
}
void loop() {
// Read light value from LDR
int lightValue = analogRead(LDR_PIN);
// Read temperature from DS18B20
sensors.requestTemperatures();
float temperature = sensors.getTempCByIndex(0); // Get temperature in Celsius
// Send data to ThingSpeak
ThingSpeak.setField(1, lightValue); // Set light value to field 1
ThingSpeak.setField(2, temperature); // Set temperature to field 2
// LED control based on light value
if (lightValue < 200) { // Adjust this threshold as needed
digitalWrite(LED_PIN, HIGH); // Turn on LED if it's dark
} else {
digitalWrite(LED_PIN, LOW); // Turn off LED if it's bright
}
int x = ThingSpeak.writeFields(myChannelNumber, myApiKey);
// Print data to Serial Monitor
Serial.println("Light Value: " + String(lightValue));
Serial.println("Temperature: " + String(temperature, 2) + "°C");
// Display on LCD
lcd.clear(); // Clear the LCD
lcd.setCursor(0, 0); // Set cursor to first row
lcd.print("LDR: " + String(lightValue)); // Print light value
lcd.setCursor(0, 1); // Set cursor to second row
lcd.print("Temp: " + String(temperature, 1) + "C"); // Print temperature
if (x == 200) {
Serial.println("Data pushed successfully");
} else {
Serial.println("Push error: " + String(x));
}
Serial.println("---");
delay(5000); // Wait for 5 seconds before the next reading
}