#include <Arduino.h>
#include <Stepper.h>
// Variables
int pir = 0;
int soil = 0;
int prev_soil = LOW;
int prev_pir = LOW;
const int rotation = 100;
// Pin definitions
const int cam = 5;
const int pirPin = 13;
const int buzzer = 19;
const int soilPin = 35;
Stepper motor(rotation, 17, 16);
// Blynk
#define BLYNK_TEMPLATE_ID "TMPL6EpW42Ybx"
#define BLYNK_TEMPLATE_NAME "scpais"
#define BLYNK_AUTH_TOKEN "4L5ueZLfZh1ZbRyVeQdiLugVJswPfns-" // token Blynk
#define BLYNK_PRINT Serial
#include <WiFi.h> // Library WiFi
#include <WiFiClient.h> // Library WiFiClient
#include <BlynkSimpleEsp32.h> // Library BlynkESP32
char ssid[] = "Wokwi-GUEST"; // Nama WiFi yang digunakan
char pass[] = ""; // Password WiFi yang digunakan
BlynkTimer timer; // code push data
void blynk() {
Blynk.virtualWrite(V0, soil);
if (pir == HIGH) {
Blynk.virtualWrite(V1, 1); // blynk motion detect - ON
Blynk.virtualWrite(V4, 0);
} else {
Blynk.virtualWrite(V1, 0); // blynk motion detect - OFF
Blynk.virtualWrite(V4, 1);
}
if (soil <= 2000) {
Blynk.virtualWrite(V2, 1); // blynk soil moisture detect - ON
Blynk.virtualWrite(V3, 0);
} else {
Blynk.virtualWrite(V2, 0); // blynk soil moisture detect - OFF
Blynk.virtualWrite(V3, 1);
}
}
void setup() {
// Blynk
Serial.begin(115200); // Menginisiasi serial monitor
Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);
timer.setInterval(2000L, blynk);
// Set pin modes
pinMode(soilPin, INPUT);
pinMode(pirPin, INPUT);
pinMode(buzzer, OUTPUT);
pinMode(cam, OUTPUT);
// Initialize serial communication
Serial.println("WELCOME TO SMART CROP PROTECTION AND IRRIGATION SYSTEM SIMULATION");
}
void loop() {
pir = digitalRead(pirPin); // read motion
if (pir == HIGH) {
digitalWrite(cam, HIGH);
digitalWrite(buzzer, HIGH);
Blynk.logEvent("motion_detect"); // notification
tone(buzzer, 1000); // Play a 1kHz tone on the buzzer
if (prev_pir == LOW) {
Serial.println("Motion detected!");
Serial.println("Buzzer ON!");
prev_pir = HIGH;
}
delay(15);
} else {
digitalWrite(cam, LOW);
digitalWrite(buzzer, LOW);
noTone(buzzer); // Stop the tone
if (prev_pir == HIGH) {
Serial.println("Motion ended!");
Serial.println("Buzzer OFF!");
prev_pir = LOW;
}
}
soil = analogRead(soilPin); // read value soil moisture
if (soil <= 2000) { // when value soil under 2000
motor.step(rotation); // start the motor
if (prev_soil == LOW) {
Serial.print("value soil moisture : ");
Serial.println(soil);
Serial.println("Motor ON!");
prev_soil = HIGH;
}
delay(10);
} else {
motor.step(0); // stop the motor
if (prev_soil == HIGH) {
Serial.print("value soil moisture : ");
Serial.println(soil);
Serial.println("Motor OFF!");
prev_soil = LOW;
}
}
Blynk.run();
timer.run();
delay(10);
}