#define BLYNK_TEMPLATE_ID "TMPL6lEedMvT5"
#define BLYNK_TEMPLATE_NAME "testing blynk integration with google sheets"
#define BLYNK_AUTH_TOKEN "NXZVecinE_ChMkG5La-WCipxcP8wl0VM"
// Including libraries
#include "WiFi.h"
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <DHTesp.h>
#include <BlynkSimpleEsp32.h>
// Defining constants and pins
#define On_Board_LED_PIN 21
#define DHTPIN 15
#define DHTTYPE DHT11
// PIR sensor settings
#define PIR 5 // D5 PIR Motion Sensor
int PIR_ToggleValue;
const int buzzerPin = 12;
const int SOIL_MOISTURE_PIN = 34;
const int TRIG_PIN = 4; // Ultrasonic sensor TRIG pin
const int ECHO_PIN = 2; // Ultrasonic sensor ECHO pin
const float TANK_HEIGHT_CM = 100.0; // Tank height in cm
// Wi-Fi and Blynk credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* auth = BLYNK_AUTH_TOKEN;
// Google script Web App URL
String Web_App_URL = "https://script.google.com/macros/s/AKfycbwhTKwx7Ot2MKJn11OE-r62ix0ribebI8tsq53zkG9xZ7RFnPSVoOy4H7T6jTUOSltI/exec";
// Variables for sensor readings
float Temp;
float Humd;
int soilmoisture = 0;
float waterLevelPercentage = 0;
String Status_Read_Sensor = "Failed";
String Status_Read_Sensor1 = "Failed";
String Status_Read_Sensor2 = "Failed";
// Timer for periodic tasks
BlynkTimer timer;
// DHT sensor object
DHTesp dht;
// Function to read DHT11 sensor data
void Getting_DHT11_Sensor_Data() {
Humd = dht.getHumidity();
Temp = dht.getTemperature();
if (isnan(Humd) || isnan(Temp)) {
Serial.println("Failed to read from DHT sensor!");
Status_Read_Sensor = "Failed";
Temp = 0.0;
Humd = 0.0;
} else {
Status_Read_Sensor = "Success";
}
Serial.print("Temp: ");
Serial.print(Temp);
Serial.print(" °C, Humidity: ");
Serial.print(Humd);
Serial.println(" %");
}
// Function to read soil moisture sensor data
void soil_moisture_data() {
int rawValue = analogRead(SOIL_MOISTURE_PIN);
int soilMoisturePercentage = map(rawValue, 0, 4095, 0, 100);
if (rawValue < 0 || rawValue > 4095) {
Serial.println("Failed to read from soil moisture sensor!");
Status_Read_Sensor1 = "Failed";
soilmoisture = 0;
} else {
Status_Read_Sensor1 = "Success";
soilmoisture = soilMoisturePercentage;
}
Serial.print("Soil Moisture: ");
Serial.print(soilmoisture);
Serial.println(" %");
}
// Function to read ultrasonic sensor data
void ultrasonic_sensor_data() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH);
float distance = duration * 0.034 / 2; // Calculate distance in cm
if (distance < 0 || distance > TANK_HEIGHT_CM) {
Serial.println("Failed to read from ultrasonic sensor!");
Status_Read_Sensor2 = "Failed";
waterLevelPercentage = 0;
} else {
Status_Read_Sensor2 = "Success";
waterLevelPercentage = ((TANK_HEIGHT_CM - distance) / TANK_HEIGHT_CM) * 100;
}
Serial.print("Water Level: ");
Serial.print(waterLevelPercentage);
Serial.println(" %");
}
// Function to handle PIR sensor (Non-blocking)
void PIRsensor() {
bool value = digitalRead(PIR); // Read PIR sensor state
WidgetLED LED(V6);
if (value == HIGH) { // Motion detected
Blynk.logEvent("pirmotion", "WARNING! Motion Detected!"); // Log event on Blynk app
LED.on();
tone(buzzerPin, 1000); // Turn on the buzzer at 1000 Hz
digitalWrite(On_Board_LED_PIN, HIGH); // Turn on onboard LED
} else { // No motion detected
LED.off();
noTone(buzzerPin); // Turn off the buzzer
digitalWrite(On_Board_LED_PIN, LOW); // Turn off onboard LED
}
}
// Blynk virtual pin control (for turning PIR detection on/off)
BLYNK_WRITE(V5) {
PIR_ToggleValue = param.asInt(); // Store the toggle value
}
// Timer function to run PIR sensor check at intervals
void sendPIR() {
if (PIR_ToggleValue == 1) {
PIRsensor(); // Check PIR sensor if toggled on
} else {
WidgetLED LED(V6);
LED.off(); // Turn off the LED when PIR is toggled off
}
}
// Function to send data to Google Sheets
void sendToGoogleSheets() {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Wi-Fi not connected. Skipping Google Sheets update.");
return;
}
String Send_Data_URL = Web_App_URL + "?sts=write";
Send_Data_URL += "&srs=" + Status_Read_Sensor;
Send_Data_URL += "&temp=" + String(Temp, 2);
Send_Data_URL += "&humd=" + String(Humd, 2);
Send_Data_URL += "&swtc1=" + String(soilmoisture);
Send_Data_URL += "&swtc2=" + String(waterLevelPercentage, 2);
Serial.println("Sending data to Google Sheets...");
Serial.println("URL: " + Send_Data_URL);
WiFiClientSecure client;
client.setInsecure(); // Disable SSL certificate validation for testing
HTTPClient http;
http.begin(client, Send_Data_URL);
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
Serial.println("Payload: " + payload);
} else {
Serial.print("HTTP GET failed, error: ");
Serial.println(http.errorToString(httpCode));
}
http.end();
}
// Function to send data to Blynk
void sendToBlynk() {
Blynk.virtualWrite(V0, Temp);
Blynk.virtualWrite(V1, Humd);
Blynk.virtualWrite(V2, soilmoisture);
Blynk.virtualWrite(V3, waterLevelPercentage);
}
// Wi-Fi connection setup
void connectToWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("\nWi-Fi connected!");
}
// Setup function
void setup() {
Serial.begin(115200);
pinMode(On_Board_LED_PIN, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(PIR, INPUT); // Initialize PIR sensor pin as input
dht.setup(DHTPIN, DHTesp::DHT22);
Blynk.begin(auth, ssid, password);
connectToWiFi();
timer.setInterval(5000L, Getting_DHT11_Sensor_Data);
timer.setInterval(5000L, soil_moisture_data);
timer.setInterval(5000L, ultrasonic_sensor_data);
timer.setInterval(8000L, sendToGoogleSheets);
timer.setInterval(5000L, sendToBlynk);
timer.setInterval(3000L, sendPIR); // Call PIR sensor check every 3 seconds
}
// Main loop
void loop() {
Blynk.run();
timer.run();
}