#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 pirPin = 13;
const int buzzer = 19;
const int soilPin = 14;
Stepper motor(rotation, 17, 16);
// LEDC channel and timer configuration
const int ledcChannel = 0;
const int ledcTimer = 1;
const int ledcResolution = 13;
const int frequency = 5000;
void setup() {
// Set pin modes
pinMode(soilPin, INPUT);
pinMode(pirPin, INPUT);
pinMode(buzzer, OUTPUT);
// Initialize serial communication
Serial.begin(115200);
Serial.println("WELCOME TO SMART CROP PROTECTION AND IRRIGATION SYSTEM SIMULATION");
// Initialize LEDC peripheral
ledcSetup(ledcChannel, frequency, ledcResolution);
ledcAttachPin(buzzer, ledcChannel);
}
void loop() {
pir = digitalRead(pirPin);
if (pir == HIGH) {
digitalWrite(buzzer, HIGH);
ledcWriteTone(ledcChannel, 500); // start the tone
if (prev_pir == LOW) {
Serial.println("Motion detected!");
Serial.println("Buzzer ON!");
prev_pir = HIGH;
}
delay(15);
} else {
digitalWrite(buzzer, LOW);
ledcWriteTone(ledcChannel, 0); // Stop the tone
if (prev_pir == HIGH) {
Serial.println("Motion ended!");
Serial.println("Buzzer OFF!");
prev_pir = LOW;
}
}
soil = analogRead(soilPin);
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;
}
}
}