Skip to content

shield44-project/soil_moisture_iot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 

Repository files navigation

A comprehensive IoT-based smart irrigation system using ESP32 microcontroller and Flask web server. The smart irrigation system using ESP32 is a simple project that automatically takes care of the optimization of the basic soil conditions with real-time monitoring, automatic watering, and remote control capabilities. 🌱 Project Overview The heart of this project is the ESP32, as it continuously checks for values from different sensors and sends commands to the other components to work accordingly. The system monitors soil moisture levels and automatically controls a water pump through a relay module, with Flask server providing web-based monitoring and control interface. Key Features

  • 🔄 Automatic Irrigation: Smart watering based on soil moisture thresholds
  • 📱 Web Dashboard: Real-time monitoring via Flask web interface
  • 🌐 WiFi Connectivity: Remote monitoring and control
  • 📊 Data Logging: Historical data storage and visualization
  • 🔧 Manual Override: Switch between AUTO and MANUAL modes
  • ⚡ Safety Features: Pump timer protection and hysteresis control
  • 🔗 API Integration: RESTful API for external integrations

📋 Hardware Requirements Components List

  • ESP32 DevKit v1 (1x)
  • Capacitive Soil Moisture Sensor (1x) - We strongly advise purchasing the sensor with TLC555I Chip from the DIYables brand
  • 5V Relay Module (1x)
  • 12V Water Pump (1x)
  • 12V Power Supply (1x)
  • Jumper Wires
  • Water Tubing & Container

Pin Configuration cppDownloadCopy code#define RELAY_PIN 26 // GPIO26 for relay control #define MOISTURE_PIN 34 // GPIO34 for soil moisture sensor (ADC) Circuit Connections Connect the soil moisture sensor to D35 pin of ESP32, water level sensor to D34 pin and DHT22 to D4 Pin. In our case:

  • Soil Moisture Sensor → GPIO34 (ADC)
  • Relay Module → GPIO26
  • Power: 12V for pump, 3.3V for sensors

🔧 Software Requirements System Dependencies

  • Python 3.7+
  • Arduino IDE 2.0+
  • ESP32 Board Package for Arduino

Python Dependencies (Flask Server) bashDownloadCopy codepip install flask pip install requests Arduino Libraries (ESP32) cppDownloadCopy code#include <WiFi.h> #include <HTTPClient.h> #include <ArduinoJson.h> #include <WebServer.h> 📁 Project Structure ESP32-Smart-Irrigation-Flask/ │ ├── app.py # Main Flask application |__ templates/index.html ├── esp32-code/ │ ├── smart_irrigation.ino # Main ESP32 Arduino code └── README.md # This file

🚀 Installation Guide Step 1: DOwnload the Repository CLick Code button and click download zip and extract the zip in file explorer Open vscode and press ctrl+J cd soil_moisture Step 2: Hardware Setup(Over) Circuit Assembly

  1. Power Supply: Connect 12V power supply
  2. ESP32: Connect to 5V (use voltage regulator if needed)
  3. Soil Sensor: VCC→3.3V, GND→GND, Signal→GPIO34
  4. Relay Module: VCC→3.3V, GND→GND, Signal→GPIO26
  5. Water Pump: Connect through relay (12V supply)

Calibration Values Your calibrated sensor values are already set: cppDownloadCopy codeconst int DRY_THRESHOLD = 3500; // Dry soil reading const int WET_THRESHOLD = 1200; // Wet soil reading Step 3: Flask Server Setup

Install dependencies

pip install flask

Run Flask server

python app.py Server will start at: http://0.0.0.0:5000 or some other ip click it Step 4: Configure ESP32 Find Your Computer's IP Address Windows: cmdDownloadCopy codeipconfig Mac/Linux: bashDownloadCopy codeifconfig | grep inet Update ESP32 Configuration Edit the ESP32 code and update these variables: cppDownloadCopy code// Network Configuration const char* ssid = "YOUR_WIFI_NAME"; const char* password = "YOUR_WIFI_PASSWORD";

// IMPORTANT: Update with your computer's IP! const char* flaskServerURL = "http://192.168.1.XXX:5000"; Step 5: Upload ESP32 Code

  1. Open Arduino IDE
  2. Install ESP32 board package
  3. Select "ESP32 Dev Module"
  4. Choose correct COM port
  5. Upload smart_irrigation.ino
  6. Open Serial Monitor (115200 baud)

▶️ Running the System

  1. Start Flask Server bashDownloadCopy codecd flask-server python app.py Expected output:
  1. Power Up ESP32 Monitor Serial output for: WiFi connected successfully! ESP32 IP address: 192.168.1.YYY Smart Irrigation System Ready!

  2. Access Interfaces Flask Web Dashboard

ESP32 Web Interface

  • Direct ESP32: http://ESP32_IP_ADDRESS

🎛️ Configuration & Settings Moisture Thresholds Default thresholds in Flask server: pythonDownloadCopy codeMOISTURE_THRESHOLDS = { 'high': 70, # Above this = WET 'moderate': 40 # Below this = DRY } ESP32 Safety Settings cppDownloadCopy codeconst int PUMP_DURATION = 5000; // 5 seconds max run time const int HYSTERESIS = 200; // Prevent rapid switching Data Update Intervals cppDownloadCopy code// Sensor readings every 2 seconds if (currentTime - lastSensorReading >= 2000)

// Flask server updates every 10 seconds
if (currentTime - lastServerUpdate >= 10000) 📊 Web Dashboard Features Real-time Monitoring

  • Soil Moisture: Percentage and raw ADC values
  • Pump Status: ON/OFF with runtime display
  • System Mode: AUTO/MANUAL switching
  • Flask Connection: Server connectivity status
  • WiFi Signal: Signal strength monitoring

Control Features

  • Mode Toggle: Switch between AUTO and MANUAL
  • Manual Pump Control: Start/stop pump in manual mode
  • Flask Connection Test: Verify server connectivity
  • Auto-refresh: Page updates every 15 seconds

Data Visualization

  • Moisture Progress Bar: Visual moisture level indicator
  • Historical Data: Last 50 readings stored
  • Status Cards: Color-coded system status

🔌 API Documentation Flask Server Endpoints GET /api/data Get current sensor data jsonDownloadCopy code{ "raw_adc": 2100, "moisture_level": 65, "soil_status": "MODERATE", "pump_status": "OFF", "mode": "AUTO", "last_updated": "2025-12-13 10:30:15" } POST /api/update ESP32 sends sensor data (used internally) jsonDownloadCopy code{ "raw_adc": 2100, "moisture_level": 65, "device_id": "ESP32_001" } POST /api/pump/control Manual pump control jsonDownloadCopy code{ "action": "ON" // or "OFF" } POST /api/mode/toggle Switch between AUTO and MANUAL modes GET/POST /api/thresholds Get or update moisture thresholds ESP32 Web API Endpoints GET /api/status Complete system status including WiFi and sensor data POST /api/toggle-mode Toggle between AUTO and MANUAL modes POST /api/pump Manual pump control (manual mode only) 📱 Usage Instructions Automatic Mode (Default)

  1. System monitors soil moisture continuously
  2. When moisture drops below threshold (dry soil), pump activates
  3. Pump stops when soil reaches adequate moisture level
  4. Built-in hysteresis prevents rapid switching

Manual Mode

  1. Click "Switch to MANUAL Mode" on either interface
  2. Use "Start/Stop Pump" button for manual control
  3. System disables automatic watering in manual mode
  4. Switch back to AUTO mode when needed

Monitoring

  1. Flask Dashboard: Comprehensive monitoring and control
  2. ESP32 Interface: Direct device control and status
  3. Serial Monitor: Debug information and logs
  4. Historical Data: View past 50 sensor readings

🔧 Troubleshooting ESP32 Connection Issues WiFi Connection Failed: // Check Serial Monitor output Connecting to WiFi.........

  • Verify SSID and password
  • Ensure 2.4GHz WiFi (ESP32 doesn't support 5GHz)
  • Check WiFi signal strength

Flask Server Connection: ✗ Server communication error: -1 Check if Flask server is running and IP address is correct!

  • Verify Flask server is running on specified IP
  • Update flaskServerURL in ESP32 code
  • Check firewall settings

Flask Server Issues Port Already in Use: bashDownloadCopy code# Check what's using port 5000 netstat -ano | findstr :5000

Kill process or use different port

python app.py --port 5001 No Data from ESP32:

  • Verify ESP32 IP address in Flask URL
  • Check Flask server console for incoming requests
  • Ensure both devices on same network

Sensor Reading Problems Incorrect Moisture Values:

  1. Verify sensor wiring (VCC, GND, Signal)
  2. Check calibration values:

cppDownloadCopy code// Test sensor in dry soil vs wet soil // Update thresholds accordingly const int DRY_THRESHOLD = 3500; const int WET_THRESHOLD = 1200; Pump Not Activating:

  1. Check relay wiring and power supply
  2. Verify pump power requirements
  3. Test manual mode first
  4. Monitor Serial output for pump commands

Network Access Issues Can't Access from Other Devices:

  • Ensure Flask runs on 0.0.0.0:5000
  • Check Windows Firewall settings
  • Verify IP address is correct
  • Use computer's actual IP, not localhost

🛡️ Safety Features Hardware Safety

  • Pump Timer: Maximum 5-minute continuous operation
  • Hysteresis Control: Prevents rapid on/off cycling
  • Power Protection: Proper voltage regulation for sensors

Software Safety

  • Connection Monitoring: Automatic retry on WiFi disconnection
  • Error Handling: Graceful failure recovery
  • Data Validation: Input sanitization and bounds checking

📈 Data Management Storage

  • JSON File: Local storage in sensor_data.json
  • Memory Management: Automatic cleanup (keep last 1000 entries)
  • Real-time Updates: Live data streaming to web interface

Export Options Historical data can be exported via API: bashDownloadCopy codecurl http://localhost:5000/api/history > irrigation_data.json 🌟 Future Enhancements Planned Features

  • Weather Integration: API-based weather data for smart watering
  • Mobile App: Dedicated smartphone application
  • Multi-zone Support: Multiple sensor and pump control
  • Database Integration: SQLite or PostgreSQL backend
  • Push Notifications: Email/SMS alerts for system events

Hardware Upgrades

  • Solar Power: Battery and solar panel integration
  • Additional Sensors: pH, NPK, light sensors
  • Camera Module: Plant growth monitoring
  • LoRa Communication: Long-range wireless connectivity

💡 Customization Tips Adding New Sensors

  1. Define new pins in ESP32 code
  2. Add sensor reading functions
  3. Update Flask API to handle new data
  4. Modify web dashboard for display

Changing Thresholds pythonDownloadCopy code# In Flask app.py MOISTURE_THRESHOLDS = { 'high': 80, # Your preferred wet level 'moderate': 30 # Your preferred dry level } Styling the Web Interface Modify the CSS in generateWebPage() function for custom styling. 📞 Support & Contributing Getting Help

  1. Check Serial Monitor for ESP32 debug output
  2. Review Flask Console for server errors
  3. Verify Wiring against circuit diagram
  4. Test Components individually
  5. Create GitHub Issue with detailed logs

Contributing

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/new-feature)
  3. Commit changes (git commit -am 'Add new feature')
  4. Push to branch (git push origin feature/new-feature)
  5. Create Pull Request

📄 License This project is licensed under the MIT License. See LICENSE file for details. 🙏 Acknowledgments

  • ESP32 community for hardware documentation
  • Flask framework developers
  • Arduino IDE and library contributors
  • IoT project inspirations from maker community

Ready to Smart Irrigate! 🌱💧🤖 Once this system is set to your place, there is no need to worry about watering your plants manually, and you can monitor the plant's health in terms of moisture and humidity Quick Start Checklist

  • Hardware assembled and wired
  • Flask server running on computer
  • ESP32 code updated with WiFi credentials and Flask IP
  • ESP32 programmed and connected to WiFi
  • Web dashboard accessible
  • Soil sensor calibrated
  • Pump tested in manual mode
  • System running in AUTO mode

Happy Automated Gardening! 🎉

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published