Wednesday, 27 May 2026

AI-Based Animal Intrusion Detection for Agriculture Fields

AI-Based Animal Intrusion Detection for Agriculture Fields AI-Powered Agentic IoT System using ESP32 + n8n + Telegram Voice Alerts + Google Sheets + ThingSpeak
1. Project Overview This project is an intelligent agriculture security system that detects animal intrusion in farm fields using AI-enabled IoT automation. The system uses an ESP32 microcontroller connected to motion and distance sensors. When an animal enters the protected area: ESP32 captures intrusion data Sends alerts to cloud services Triggers AI-based automation using n8n Sends Telegram notifications with voice alerts Stores logs in Google Sheets Displays live analytics on ThingSpeak dashboard Predicts future power consumption using AI logic This system helps farmers: Prevent crop damage Monitor fields remotely Receive instant warnings Analyze intrusion patterns Reduce manual surveillance 2. System Architecture ┌────────────────────┐ │ Animal Movement │ └─────────┬──────────┘ │ ┌─────────▼──────────┐ │ PIR / Ultrasonic │ │ Sensors │ └─────────┬──────────┘ │ ┌─────────▼──────────┐ │ ESP32 │ │ WiFi + AI Logic │ └─────────┬──────────┘ │ HTTP/MQTT ┌─────────────────┼─────────────────┐ │ │ │ ▼ ▼ ▼ ┌────────────┐ ┌─────────────┐ ┌──────────────┐ │ ThingSpeak │ │ n8n Server │ │ Google Sheet │ └────────────┘ └──────┬──────┘ └──────────────┘ │ ┌──────────▼───────────┐ │ Telegram Bot Alerts │ │ Voice + Text Message │ └──────────────────────┘ 3. Features Core Features Animal intrusion detection Real-time Telegram alerts AI-based intrusion classification Voice warning notifications Cloud dashboard monitoring Google Sheets logging Automated workflows using n8n AI Features Power usage prediction Intrusion frequency analysis Smart alert prioritization Future threat prediction IoT Features WiFi connectivity Cloud synchronization Remote monitoring Edge-device automation 4. Required Components List Component Quantity Purpose ESP32 Dev Board 1 Main controller PIR Motion Sensor 1 Motion detection Ultrasonic Sensor HC-SR04 1 Distance sensing Buzzer 1 Local alarm LED Indicators 2 Status display Jumper Wires Several Connections Breadboard 1 Prototyping Power Supply 5V 1 System power WiFi Network 1 Internet connectivity Telegram Bot 1 Notifications ThingSpeak Account 1 Cloud dashboard Google Account 1 Sheets integration n8n Server 1 Automation workflows 5. Circuit Schematic Diagram ESP32 PIN CONNECTIONS PIR Sensor ----------- VCC -> 3.3V GND -> GND OUT -> GPIO 13 Ultrasonic Sensor HC-SR04 ------------------------- VCC -> 5V GND -> GND TRIG -> GPIO 12 ECHO -> GPIO 14 Buzzer ------- + -> GPIO 27 - -> GND LED --- + -> GPIO 26 - -> GND 6. Working Principle PIR sensor detects motion. Ultrasonic sensor measures object distance. ESP32 validates intrusion. Data uploaded to ThingSpeak. ESP32 triggers webhook to n8n. n8n: Sends Telegram text alert Generates voice notification Stores records in Google Sheets AI logic predicts power usage trends. Dashboard visualizes all activities. 7. Flowchart START │ Initialize ESP32 │ Connect WiFi │ Read PIR Sensor │ Motion Detected? ┌─No─────────────┐ │ │ │ Wait │ │ └────Yes─────────┘ │ Measure Distance │ Animal Detected? ┌─No─────────────┐ │ │ │ Continue │ │ └────Yes─────────┘ │ Activate Buzzer │ Send Data to ThingSpeak │ Trigger n8n Webhook │ Telegram Alert + Voice │ Store Data in Sheets │ Repeat 8. ESP32 Source Code (Arduino IDE) #include #include const char* ssid = "YOUR_WIFI_NAME"; const char* password = "YOUR_WIFI_PASSWORD"; String webhookURL = "YOUR_N8N_WEBHOOK_URL"; #define PIR_PIN 13 #define TRIG_PIN 12 #define ECHO_PIN 14 #define BUZZER 27 #define LED 26 long duration; float distance; void setup() { Serial.begin(115200); pinMode(PIR_PIN, INPUT); pinMode(TRIG_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT); pinMode(BUZZER, OUTPUT); pinMode(LED, OUTPUT); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting..."); } Serial.println("WiFi Connected"); } float getDistance() { digitalWrite(TRIG_PIN, LOW); delayMicroseconds(2); digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); duration = pulseIn(ECHO_PIN, HIGH); distance = duration * 0.034 / 2; return distance; } void loop() { int motion = digitalRead(PIR_PIN); if (motion == HIGH) { distance = getDistance(); if (distance < 150) { digitalWrite(BUZZER, HIGH); digitalWrite(LED, HIGH); sendAlert(distance); delay(5000); digitalWrite(BUZZER, LOW); digitalWrite(LED, LOW); } } delay(1000); } void sendAlert(float dist) { if(WiFi.status()== WL_CONNECTED){ HTTPClient http; String url = webhookURL + "?distance=" + String(dist); http.begin(url); int httpCode = http.GET(); Serial.println(httpCode); http.end(); } } 9. n8n Workflow Logic Workflow Steps Webhook Trigger │ ▼ AI Decision Node │ ▼ Telegram Message Node │ ▼ Google Sheets Node │ ▼ ThingSpeak Update Node │ ▼ Text-to-Speech Node │ ▼ Telegram Voice Send 10. Sample n8n Workflow JSON { "nodes": [ { "name": "Webhook", "type": "n8n-nodes-base.webhook", "parameters": { "path": "animal-alert" } }, { "name": "Telegram Alert", "type": "n8n-nodes-base.telegram", "parameters": { "text": "Animal detected in field!" } } ] } 11. Telegram Bot Setup Step 1: Create Bot Open Telegram and search: Telegram Then search for: BotFather Commands: /newbot Provide: Bot Name Username Copy generated API token. Step 2: Get Chat ID Send message to your bot. Open: https://api.telegram.org/botYOUR_BOT_TOKEN/getUpdates Copy: chat.id 12. Google Sheets Integration Steps Create new Google Sheet Add columns: | Timestamp | Distance | Alert Type | Power Usage | In n8n: Add Google Sheets node Authenticate Google account Select spreadsheet Append rows automatically Recommended columns: Timestamp Animal Type Distance Battery Voltage Alert Status 13. ThingSpeak Cloud Dashboard Setup Create account on: ThingSpeak Create Channel Fields Field Purpose Field 1 Distance Field 2 Motion Field 3 Battery Field 4 Intrusion Count Dashboard Widgets Live intrusion graph Daily activity chart Battery monitor AI prediction chart 14. AI Power Consumption Prediction Logic Objective Predict battery drain and optimize power usage. Inputs Sensor active time Alert frequency WiFi transmission count Buzzer usage duration Simple Prediction Formula The estimated power model: P daily ​ =P idle ​ +n(P wifi ​ +P sensor ​ +P buzzer ​ ) Where: P daily ​ = total daily consumption n = number of intrusion events AI Enhancement Use: Moving average prediction Linear regression Intrusion trend analysis Future AI models: TinyML on ESP32 Edge AI classification Animal species prediction 15. Voice Notification Automation Workflow Intrusion Detected │ ▼ n8n Receives Webhook │ ▼ Text-to-Speech API │ ▼ Generate MP3 Voice │ ▼ Send Telegram Voice Message Example Voice Message Warning! Animal detected in agricultural field sector 3. 16. AI Agentic Automation Concept The system behaves like an AI agent: AI Agent Capability Function Observe Sensor monitoring Analyze Intrusion validation Decide Threat classification Act Send alerts Learn Analyze intrusion history 17. Future Enhancements AI Improvements YOLO animal detection camera TinyML animal classification AI-based crop damage prediction Hardware Enhancements Solar-powered system GSM backup connectivity LoRa communication Cloud Enhancements Mobile app dashboard Firebase integration AWS IoT integration Security Improvements Multi-factor authentication Encrypted communication Edge anomaly detection 18. Deployment Guide Farm Installation Tips Mount sensors 2–3 feet above ground Use waterproof enclosure Install solar charging Ensure stable WiFi coverage Power Optimization Deep sleep mode on ESP32 Send alerts only on confirmed detection Reduce WiFi transmission intervals 19. Advantages Low-cost smart agriculture solution Real-time remote monitoring AI-assisted automation Easy cloud integration Scalable architecture Energy efficient 20. Applications Agricultural farms Forest boundary monitoring Smart villages Wildlife intrusion prevention Crop protection systems 21. Conclusion This AI-powered Agentic IoT system combines: ESP32 AI automation Cloud dashboards Telegram voice alerts n8n workflows Google Sheets analytics to create a complete smart agriculture protection platform capable of intelligent monitoring, automation, and predictive analytics. The project is highly scalable and can evolve into: AI wildlife monitoring Smart farm automation Precision agriculture systems Edge AI surveillance platforms

No comments:

Post a Comment

AI-Based ECG and Heart Disease Prediction System

AI-Based ECG & Heart Disease Prediction System Agentic IoT using ESP32 + AI + n8n Automation + Telegram Voice Alerts + Google Sheets + T...