#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include "DHT.h"
#define DHTTYPE DHT11 // type of the temperature sensor
const int DHTPin = 5; //--> The pin used for the DHT11 sensor is Pin D1 = GPIO5
DHT dht(DHTPin, DHTTYPE); //--> Initialize DHT sensor, DHT dht(Pin_used, Type_of_DHT_Sensor);
// Pin definitions for HC-SR04
const int trigPin = 12; // D6 - GPIO12
const int echoPin = 14; // D5 - GPIO14
// Pin definition for Soil Moisture Sensor
const int soilMoisturePin = A0; // Analog pin A0
// Pin definitions for new features
const int buzzerPin = 4; // D2 - GPIO4 untuk buzzer
const int pumpPin = 0; // D3 - GPIO0 untuk kontrol pompa air
const int pestRepellerPin = 2; // D4 - GPIO2 untuk pengusir hama (ON_Board_LED dipindah)
#define ON_Board_LED 16 // D0 - GPIO16 untuk indikator WiFi
const char* ssid = "www.asun86.com"; //--> Your wifi name or SSID.
const char* password = ""; //--> Your wifi password.
//----------------------------------------Host & httpsPort
const char* host = "script.google.com";
const int httpsPort = 443;
//----------------------------------------
WiFiClientSecure client; //--> Create a WiFiClientSecure object.
String GAS_ID = "AKfycby8-0iT7w4AE5Gf_ehlAlvcDiZ05LcBcCRxOgah2WUekD8XSD7frjl5cT8EZFZUEX20"; //--> spreadsheet script ID
// Variables for pest repeller timing
unsigned long previousPestMillis = 0;
const long pestInterval = 10000; // 10 detik
bool pestState = false;
unsigned long pestStartTime = 0;
// Variables for buzzer control
unsigned long previousBuzzerMillis = 0;
long buzzerInterval = 1000; // Default 1 detik
bool buzzerState = false;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
delay(500);
// Initialize DHT sensor
dht.begin(); //--> Start reading DHT11 sensors
delay(500);
// Initialize HC-SR04 pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize new pins
pinMode(buzzerPin, OUTPUT);
pinMode(pumpPin, OUTPUT);
pinMode(pestRepellerPin, OUTPUT);
// Soil moisture sensor is analog, no need to set pin mode
// Initialize all outputs to LOW
digitalWrite(buzzerPin, LOW);
digitalWrite(pumpPin, LOW);
digitalWrite(pestRepellerPin, LOW);
WiFi.begin(ssid, password); //--> Connect to your WiFi router
Serial.println("");
pinMode(ON_Board_LED,OUTPUT); //--> On Board LED port Direction output
digitalWrite(ON_Board_LED, HIGH); //--> Turn off Led On Board
//----------------------------------------Wait for connection
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
//----------------------------------------Make the On Board Flashing LED on the process of connecting to the wifi router.
digitalWrite(ON_Board_LED, LOW);
delay(250);
digitalWrite(ON_Board_LED, HIGH);
delay(250);
//----------------------------------------
}
//----------------------------------------
digitalWrite(ON_Board_LED, HIGH); //--> Turn off the On Board LED when it is connected to the wifi router.
Serial.println("");
Serial.print("Successfully connected to : ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
//----------------------------------------
client.setInsecure();
}
// Function to read distance from HC-SR04
float readDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
float distance = duration * 0.034 / 2; // Calculate distance in cm
return distance;
}
// Function to read soil moisture
int readSoilMoisture() {
int sensorValue = analogRead(soilMoisturePin);
// Convert to percentage (0% = dry, 100% = wet)
// Note: You might need to calibrate these values based on your sensor
int moisturePercent = map(sensorValue, 0, 1023, 0, 100);
return moisturePercent;
}
// Function to control buzzer based on soil moisture
void controlBuzzer(int soilMoisture) {
unsigned long currentMillis = millis();
if (soilMoisture >= 80) {
// Tanah basah - buzzer berbunyi 1 detik sekali
buzzerInterval = 1000;
}
else if (soilMoisture >= 60 && soilMoisture < 80) {
// Tanah lembab - buzzer lebih cepat (500ms)
buzzerInterval = 500;
}
else if (soilMoisture >= 40 && soilMoisture < 60) {
// Tanah mulai kering - buzzer lebih cepat lagi (250ms)
buzzerInterval = 250;
}
else {
// Tanah kering - buzzer terus menyala
digitalWrite(buzzerPin, HIGH);
return;
}
// Kontrol buzzer dengan interval
if (currentMillis - previousBuzzerMillis >= buzzerInterval) {
previousBuzzerMillis = currentMillis;
buzzerState = !buzzerState;
digitalWrite(buzzerPin, buzzerState);
}
}
// Function to control water pump based on soil moisture
void controlPump(int soilMoisture) {
if (soilMoisture <= 50) {
// Kelembapan <= 50% - nyalakan pompa
digitalWrite(pumpPin, HIGH);
Serial.println("Pompa AIR: ON - Kelembapan tanah rendah");
}
else if (soilMoisture >= 80) {
// Kelembapan >= 80% - matikan pompa
digitalWrite(pumpPin, LOW);
Serial.println("Pompa AIR: OFF - Kelembapan tanah cukup");
}
// Between 50-80% maintain current state
}
// Function to control pest repeller
void controlPestRepeller() {
unsigned long currentMillis = millis();
if (currentMillis - previousPestMillis >= pestInterval) {
previousPestMillis = currentMillis;
// Aktifkan pengusir hama selama 5 detik
digitalWrite(pestRepellerPin, HIGH);
pestState = true;
pestStartTime = currentMillis;
Serial.println("Pengusir Hama: AKTIF");
}
// Matikan setelah 5 detik
if (pestState && (currentMillis - pestStartTime >= 5000)) {
digitalWrite(pestRepellerPin, LOW);
pestState = false;
Serial.println("Pengusir Hama: NON-AKTIF");
}
}
void loop() {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
int h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read distance from ultrasonic sensor
float distance = readDistance();
// Read soil moisture
int soilMoisture = readSoilMoisture();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor !");
delay(500);
return;
}
// Kontrol semua perangkat berdasarkan sensor
controlBuzzer(soilMoisture);
controlPump(soilMoisture);
controlPestRepeller();
String Temp = "Temperature : " + String(t) + " °C";
String Humi = "Humidity : " + String(h) + " %";
String Dist = "Distance : " + String(distance) + " cm";
String Soil = "Soil Moisture : " + String(soilMoisture) + " %";
Serial.println(Temp);
Serial.println(Humi);
Serial.println(Dist);
Serial.println(Soil);
// Tampilkan status perangkat
Serial.print("Buzzer: "); Serial.println(digitalRead(buzzerPin) ? "ON" : "OFF");
Serial.print("Pompa: "); Serial.println(digitalRead(pumpPin) ? "ON" : "OFF");
Serial.print("Pengusir Hama: "); Serial.println(digitalRead(pestRepellerPin) ? "ON" : "OFF");
Serial.println();
sendData(t, h, distance, soilMoisture); //--> Calls the sendData Subroutine with all sensor data
delay(6000); // Wait for 6 seconds before sending data again
}
// Subroutine for sending data to Google Sheets
// Modified to include distance and soil moisture parameters
void sendData(float tem, int hum, float dist, int soil) {
Serial.println("==========");
Serial.print("connecting to ");
Serial.println(host);
//----------------------------------------Connect to Google host
if (!client.connect(host, httpsPort)) {
Serial.println("connection failed");
return;
}
//----------------------------------------
//----------------------------------------Processing data and sending data
String string_temperature = String(tem);
String string_humidity = String(hum, DEC);
String string_distance = String(dist, 2); // 2 decimal places for distance
String string_soil_moisture = String(soil, DEC);
String url = "/macros/s/" + GAS_ID + "/exec?temperature=" + string_temperature +
"&humidity=" + string_humidity +
"&distance=" + string_distance +
"&soil=" + string_soil_moisture;
Serial.print("requesting URL: ");
Serial.println(url);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: BuildFailureDetectorESP8266\r\n" +
"Connection: close\r\n\r\n");
Serial.println("request sent");
//----------------------------------------
//----------------------------------------Checking whether the data was sent successfully or not
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
Serial.println("headers received");
break;
}
}
String line = client.readStringUntil('\n');
if (line.startsWith("{\"state\":\"success\"")) {
Serial.println("esp8266/Arduino CI successfull!");
} else {
Serial.println("esp8266/Arduino CI has failed");
}
Serial.print("reply was : ");
Serial.println(line);
Serial.println("closing connection");
Serial.println("==========");
Serial.println();
//----------------------------------------
}
Buzzer: GPIO4 (D2)
Pompa Air: GPIO0 (D3)
Pengusir Hama: GPIO2 (D4)
LED Indicator: GPIO16 (D0)
≥80% (Basah): Buzzer berbunyi 1 detik sekali
60-79% (Lembab): Buzzer lebih cepat (500ms)
40-59% (Mulai Kering): Buzzer sangat cepat (250ms)
<40% (Kering): Buzzer menyala terus
≤50%: Pompa ON (HIGH)
≥80%: Pompa OFF (LOW)
50-80%: Pertahankan state sebelumnya
Setiap 10 detik pin akan HIGH
Aktif selama 5 detik
Kemudian LOW kembali
Logging data ke Google Sheets setiap 6 detik
Pembacaan semua sensor (DHT11, HC-SR04, Soil Moisture)
Koneksi WiFi dan error handling
Struktur utama program tidak berubah
Semua fitur baru bekerja paralel dengan sistem logging yang sudah ada tanpa mengganggu pengiriman data ke spreadsheet.
// app script dht11 hcsr04 dan soil
//Pastikan spreadsheet Anda memiliki header kolom yang sesuai dengan urutan berikut:
//Kolom A: Date
//Kolom B: Time
//Kolom C: Temperature
//Kolom D: Humidity
//Kolom E: Distance
//Kolom F: Soil Moisture
// https://script.google.com/macros/s/AKfycbyFq3MPJ9xb8_pk7PgKiEs2Q6RrGqhvqtdcA_IQ_F4iwjKFlX34CwWVHHfeeG0X-p-B/exec?temperature=28.5&humidity=65&distance=12.75&soil=38
function doGet(e) {
Logger.log(JSON.stringify(e));
var result = 'Ok';
if (e.parameter == 'undefined') {
result = 'No Parameters';
} else {
var sheet_id = '1C-vTu5FvwgM8IHQTaqrLUNUHAR3L5AD18IsPWiReYis'; // Spreadsheet ID
var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet();
var newRow = sheet.getLastRow() + 1;
var rowData = [];
var Curr_Date = new Date();
rowData[0] = Curr_Date; // Date in column A
var Curr_Time = Utilities.formatDate(Curr_Date, "Asia/Jakarta", 'HH:mm:ss');
rowData[1] = Curr_Time; // Time in column B
// Initialize all columns with empty values
rowData[2] = ''; // Temperature
rowData[3] = ''; // Humidity
rowData[4] = ''; // Distance
rowData[5] = ''; // Soil Moisture
for (var param in e.parameter) {
Logger.log('In for loop, param=' + param);
var value = stripQuotes(e.parameter[param]);
Logger.log(param + ':' + e.parameter[param]);
switch (param) {
case 'temperature':
rowData[2] = value; // Temperature in column C
result = 'Temperature Written on column C';
break;
case 'humidity':
rowData[3] = value; // Humidity in column D
result += ' ,Humidity Written on column D';
break;
case 'distance':
rowData[4] = value; // Distance in column E
result += ' ,Distance Written on column E';
break;
case 'soil':
rowData[5] = value; // Soil Moisture in column F
result += ' ,Soil Moisture Written on column F';
break;
default:
result = "unsupported parameter";
}
}
Logger.log(JSON.stringify(rowData));
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
return ContentService.createTextOutput(result);
}
function stripQuotes(value) {
return value.replace(/^["']|['"]$/g, "");
}