diff --git a/README.md b/README.md index 3d34f43..1a05d40 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,322 @@ -# Smart-Irrigation-System-Using-Arduino -Smart Irrigation System using Arduino that automates plant watering based on real-time soil moisture levels. It uses a soil sensor, relay, and water pump to ensure efficient irrigation, reduce water wastage, and minimize manual effort for smart farming and gardening applications. +# Smart Irrigation System Using Arduino + +An automated plant-watering system that reads real-time soil moisture levels +and controls a water pump via a relay module — no manual watering required. + +--- + +## Table of Contents + +1. [Project Overview](#project-overview) +2. [Features](#features) +3. [Components List](#components-list) +4. [Circuit Diagram](#circuit-diagram) +5. [Working Principle](#working-principle) +6. [Project Structure](#project-structure) +7. [Setup Instructions](#setup-instructions) +8. [Configuration](#configuration) +9. [Serial Monitor Output](#serial-monitor-output) +10. [Simulation](#simulation) +11. [IoT Upgrade – ESP8266](#iot-upgrade--esp8266) +12. [Future Enhancements](#future-enhancements) +13. [Troubleshooting](#troubleshooting) +14. [License](#license) + +--- + +## Project Overview + +The Smart Irrigation System monitors soil moisture continuously and activates a +water pump whenever the soil becomes too dry. Once adequate moisture is +detected the pump is switched off automatically, preventing overwatering and +saving water. + +This project is ideal for: +- Home plant pots and indoor gardens +- Small vegetable patches and terrace gardens +- Learning Arduino sensor integration and relay control +- A foundation for a full IoT-connected smart-farm system + +--- + +## Features + +- Automatic pump control based on configurable moisture threshold +- Real-time readings printed to the Arduino Serial Monitor +- Non-blocking design using `millis()` (no `delay()` in the main loop) +- Built-in LED mirrors pump state for quick visual feedback +- Fully commented, beginner-friendly Arduino code +- Optional ESP8266 Wi-Fi upgrade with MQTT remote control + +--- + +## Components List + +### Required + +| Component | Specification | Qty | +|-----------|---------------|-----| +| Arduino Uno R3 | ATmega328P, 5 V, 16 MHz | 1 | +| Soil Moisture Sensor | Capacitive or Resistive, analog output | 1 | +| 5 V Relay Module | Single-channel, active-LOW | 1 | +| Mini Submersible Water Pump | 3–5 V DC | 1 | +| Silicone Tubing | 6 mm inner diameter, ~1 m | 1 | +| Jumper Wires | Male-to-Male & Male-to-Female | 1 set | +| Breadboard | 830-point | 1 | +| USB-A to USB-B Cable | For programming | 1 | +| 5 V Power Supply / Power Bank | >= 1 A | 1 | + +See [`docs/components.md`](docs/components.md) for the full list including +optional add-ons, cost estimates, and sourcing advice. + +--- + +## Circuit Diagram + +### Quick-Reference Wiring + +| From | To | Notes | +|------|----|-------| +| Sensor VCC | Arduino 5V | Power | +| Sensor GND | Arduino GND | Ground | +| Sensor AO | Arduino A0 | Analog moisture reading | +| Relay VCC | Arduino 5V | Power | +| Relay GND | Arduino GND | Ground | +| Relay IN | Arduino D7 | Control signal | +| Relay COM | Pump (+) | Switched power | +| Relay NO | PSU (+) | Power supply positive | +| Pump (−) | PSU (−) | Power supply negative | + +Full ASCII schematic and safety notes: [`docs/circuit_diagram.md`](docs/circuit_diagram.md) + +Add your Fritzing/Tinkercad diagrams to the [`images/`](images/) folder. + +--- + +## Working Principle + +``` +┌──────────────────────────────────────────────────────┐ +│ │ +│ Soil Moisture Sensor ──► Arduino A0 │ +│ (analog 0–1023) │ +│ │ │ +│ ▼ │ +│ Is raw value > THRESHOLD? │ +│ (soil too dry?) │ +│ │ │ +│ YES ─────┤───── NO │ +│ │ │ │ +│ ▼ ▼ │ +│ Relay ON Relay OFF │ +│ Pump runs Pump stops │ +│ │ +│ Repeat every READ_INTERVAL_MS milliseconds │ +└──────────────────────────────────────────────────────┘ +``` + +1. **Sensor reading** – The soil moisture sensor outputs an analog voltage + proportional to the soil's dielectric constant. The Arduino's 10-bit ADC + converts this to a value between 0 (wet) and 1023 (dry). + +2. **Threshold comparison** – The raw value is compared against + `MOISTURE_THRESHOLD` (default 600). Values above the threshold indicate + dry soil. + +3. **Relay control** – A LOW signal on pin D7 activates the relay coil, + closing the NO-to-COM contacts and completing the pump circuit. + +4. **Timed reading** – The sensor is read every `READ_INTERVAL_MS` + milliseconds (default 2 s for development; increase to 10 min in + production) to avoid rapid pump cycling. + +--- + +## Project Structure + +``` +Smart-Irrigation-System-Using-Arduino/ +├── README.md ← This file +├── code/ +│ ├── smart_irrigation.ino ← Main Arduino sketch (Uno / Nano) +│ └── esp8266_iot_upgrade.ino ← Wi-Fi + MQTT upgrade (NodeMCU) +├── docs/ +│ ├── circuit_diagram.md ← Wiring tables and ASCII schematic +│ ├── components.md ← Full components list with costs +│ └── simulation_guide.md ← Tinkercad & Proteus instructions +└── images/ + └── README.md ← Placeholder / guide for adding images +``` + +--- + +## Setup Instructions + +### Prerequisites + +- [Arduino IDE](https://www.arduino.cc/en/software) 1.8+ or Arduino IDE 2.x +- USB-A to USB-B cable +- Assembled circuit (see [Circuit Diagram](#circuit-diagram)) + +### Steps + +1. **Clone or download** this repository: + ```bash + git clone https://github.com/prashanth-nayak6/Smart-Irrigation-System-Using-Arduino.git + ``` + +2. **Open the sketch** in Arduino IDE: + - File → Open → navigate to `code/smart_irrigation.ino` + +3. **Select your board and port**: + - Tools → Board → Arduino AVR Boards → **Arduino Uno** + - Tools → Port → select the COM port for your Arduino + +4. **Upload the sketch**: + - Click the **Upload** button (right arrow icon) or press `Ctrl + U` + - Wait for "Done uploading" in the status bar + +5. **Open Serial Monitor**: + - Tools → Serial Monitor (or `Ctrl + Shift + M`) + - Set baud rate to **9600** + +6. **Test the system**: + - Insert the soil moisture sensor into dry soil or hold it in air; + the pump/LED should activate + - Place the sensor in moist soil or briefly dip it in water; + the pump/LED should deactivate + +--- + +## Configuration + +All configuration constants are defined at the top of `smart_irrigation.ino`: + +| Constant | Default | Description | +|----------|---------|-------------| +| `MOISTURE_SENSOR_PIN` | `A0` | Analog pin for sensor | +| `RELAY_PIN` | `7` | Digital pin for relay IN | +| `PUMP_LED_PIN` | `13` | LED pin mirroring pump state | +| `MOISTURE_THRESHOLD` | `600` | Raw ADC value; above = dry, trigger pump | +| `RELAY_ACTIVE_LOW` | `true` | Set to `false` for active-HIGH relays | +| `READ_INTERVAL_MS` | `2000` | Milliseconds between sensor reads | + +### Calibrating the Threshold + +1. Open Serial Monitor at 9600 baud. +2. Hold the sensor in open air — note the raw value (typically ~980–1023). +3. Submerge the sensor tip in water — note the raw value (typically ~300–450). +4. Set `MOISTURE_THRESHOLD` to roughly halfway between those two values. + +--- + +## Serial Monitor Output + +``` +=== Smart Irrigation System === +Initialising... +Moisture threshold set to: 600 +System ready. + +Soil Moisture - Raw: 823 | Percent: 19 % | Pump: ON (soil dry - watering started) +Soil Moisture - Raw: 812 | Percent: 20 % | Pump: ON (watering in progress) +Soil Moisture - Raw: 550 | Percent: 46 % | Pump: OFF (soil moist - watering stopped) +Soil Moisture - Raw: 540 | Percent: 47 % | Pump: OFF (soil moisture adequate) +``` + +--- + +## Simulation + +Test the circuit virtually before building on real hardware: + +- **Tinkercad** (free, browser-based) – easiest option +- **Proteus** (desktop, student edition available) – more accurate simulation + +Full step-by-step instructions: [`docs/simulation_guide.md`](docs/simulation_guide.md) + +--- + +## IoT Upgrade – ESP8266 + +The file `code/esp8266_iot_upgrade.ino` upgrades the system to an +Internet-connected smart irrigation controller using the NodeMCU ESP8266. + +### Additional Features + +| Feature | Description | +|---------|-------------| +| Wi-Fi connectivity | Connects to your home/office Wi-Fi network | +| MQTT publishing | Streams moisture % and pump state every 10 seconds | +| Remote control | Send ON / OFF / AUTO commands from any MQTT client | +| Auto-reconnect | Handles Wi-Fi and broker dropouts gracefully | + +### MQTT Topics + +| Topic | Direction | Payload | +|-------|-----------|---------| +| `irrigation/moisture` | Published | Integer 0–100 (%) | +| `irrigation/pump` | Published | `"ON"` or `"OFF"` | +| `irrigation/command` | Subscribed | `"ON"`, `"OFF"`, or `"AUTO"` | + +### Quick Start + +1. Install the **ESP8266 board package** in Arduino IDE: + - File → Preferences → Additional Boards Manager URLs: + `http://arduino.esp8266.com/stable/package_esp8266com_index.json` + - Tools → Board → Boards Manager → search "esp8266" → Install + +2. Install the **PubSubClient** library: + - Sketch → Include Library → Manage Libraries → search "PubSubClient" → Install + +3. Edit `esp8266_iot_upgrade.ino`: + - Set `WIFI_SSID` and `WIFI_PASSWORD` + - Optionally change `MQTT_BROKER` to your own broker + +4. Select board: Tools → Board → **NodeMCU 1.0 (ESP-12E Module)** + +5. Upload and monitor via Serial Monitor at **115200** baud. + +### Recommended MQTT Clients / Dashboards + +- **MQTT Explorer** – desktop client for inspecting topics +- **Node-RED** – drag-and-drop flow-based dashboard +- **Home Assistant** – full smart home integration +- **HiveMQ WebClient** – browser-based test client (https://www.hivemq.com/demos/websocket-client/) + +--- + +## Future Enhancements + +| Enhancement | Description | +|-------------|-------------| +| Multi-zone irrigation | Support multiple sensors and pumps for different plant zones | +| Scheduled watering | Add RTC module (DS3231) to water at set times regardless of moisture | +| Weather integration | Pull weather API data; skip watering if rain is forecast | +| Low-water alert | Float switch in reservoir + buzzer / push notification | +| Data logging | Log readings to SD card or cloud (ThingSpeak / Google Sheets) | +| Solar power | LiPo battery + solar panel for off-grid installation | +| Mobile app | React Native / Flutter app consuming MQTT data | +| Machine learning | Predict optimal watering schedule from historical sensor data | +| LoRaWAN upgrade | Long-range IoT for large farms using LoRa modules | +| Voice control | Integrate with Amazon Alexa or Google Home via IFTTT | + +--- + +## Troubleshooting + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Pump never turns on | Threshold too low or wiring error | Raise `MOISTURE_THRESHOLD`; check relay wiring | +| Pump always on | Threshold too high | Lower `MOISTURE_THRESHOLD`; recalibrate | +| Sensor reads ~1023 always | Sensor not connected / broken | Check AO → A0 wire; replace sensor | +| Relay clicks but pump silent | Pump wiring to relay NO/COM | Rewire pump between COM and NO terminals | +| Upload fails | Wrong board or port selected | Tools → Board/Port; check USB cable | +| Serial output is garbage | Wrong baud rate | Set Serial Monitor to 9600 baud | + +--- + +## License + +This project is licensed under the [MIT License](https://opensource.org/licenses/MIT). +Feel free to use, modify, and distribute it for personal or educational purposes. diff --git a/code/esp8266_iot_upgrade.ino b/code/esp8266_iot_upgrade.ino new file mode 100644 index 0000000..bb9eb26 --- /dev/null +++ b/code/esp8266_iot_upgrade.ino @@ -0,0 +1,196 @@ +/* + * Smart Irrigation System - IoT Upgrade with ESP8266 + * ==================================================== + * Author : Prashanth Nayak + * Date : 2025 + * Version : 1.0 + * + * Description: + * This sketch extends the basic Smart Irrigation System by adding + * remote monitoring and control via Wi-Fi using the ESP8266 + * (NodeMCU / Wemos D1 Mini). Sensor data is published to an MQTT + * broker (e.g. Mosquitto / HiveMQ Cloud) so that any MQTT client + * (Node-RED, Home Assistant, custom dashboard) can display live + * readings and send pump-override commands. + * + * Features: + * - Reads soil moisture sensor on ESP8266 ADC (A0) + * - Controls relay / pump via GPIO D1 (GPIO 5) + * - Connects to Wi-Fi (SSID / password configured below) + * - Publishes moisture % and pump state to MQTT topics + * - Subscribes to a command topic to allow remote pump control + * - Automatic reconnection to Wi-Fi and MQTT broker + * + * Required Libraries (install via Arduino Library Manager): + * - ESP8266WiFi (bundled with ESP8266 Arduino core) + * - PubSubClient by Nick O'Leary (v2.8+) + * + * MQTT Topics: + * Publish: + * irrigation/moisture - soil moisture percentage (integer, 0-100) + * irrigation/pump - pump state ("ON" or "OFF") + * Subscribe: + * irrigation/command - "ON" forces pump on, "OFF" forces pump off, + * "AUTO" returns to automatic mode + * + * Wiring: + * Soil Moisture Sensor OUT -> NodeMCU A0 (via voltage divider if 5V sensor) + * Relay IN -> NodeMCU D1 (GPIO 5) + * VCC, GND -> 3.3V / GND rails as appropriate + * + * License: MIT + */ + +#include +#include + +// --- Wi-Fi Credentials ------------------------------------------------------- +// Replace with your own network details +const char* WIFI_SSID = "YOUR_WIFI_SSID"; +const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD"; + +// --- MQTT Broker Settings ---------------------------------------------------- +const char* MQTT_BROKER = "broker.hivemq.com"; // public test broker +const int MQTT_PORT = 1883; +const char* MQTT_CLIENT_ID = "SmartIrrigationESP"; + +// MQTT topics +const char* TOPIC_MOISTURE = "irrigation/moisture"; +const char* TOPIC_PUMP = "irrigation/pump"; +const char* TOPIC_COMMAND = "irrigation/command"; + +// --- Pin Definitions --------------------------------------------------------- +const int MOISTURE_SENSOR_PIN = A0; // ESP8266 ADC (single channel, 0-1V) +const int RELAY_PIN = 5; // GPIO 5 = D1 on NodeMCU + +// --- Configuration ----------------------------------------------------------- +const int MOISTURE_THRESHOLD = 600; // Raw ADC threshold (0-1023) +const bool RELAY_ACTIVE_LOW = true; // true for most relay modules +const unsigned long PUBLISH_INTERVAL_MS = 10000UL; // Publish every 10 seconds + +// --- Global Objects & State -------------------------------------------------- +WiFiClient wifiClient; +PubSubClient mqttClient(wifiClient); + +unsigned long lastPublishTime = 0; +bool pumpRunning = false; +bool manualMode = false; // true = remote override active +bool manualPumpOn = false; // desired state when in manual mode + +// --- Helper: control relay --------------------------------------------------- +void setPump(bool on) { + digitalWrite(RELAY_PIN, RELAY_ACTIVE_LOW ? (on ? LOW : HIGH) + : (on ? HIGH : LOW)); + pumpRunning = on; + mqttClient.publish(TOPIC_PUMP, on ? "ON" : "OFF", true /* retain */); + Serial.print(F("Pump: ")); + Serial.println(on ? F("ON") : F("OFF")); +} + +// --- MQTT Message Callback --------------------------------------------------- +void onMqttMessage(char* topic, byte* payload, unsigned int length) { + // Build a null-terminated string from the payload + char msg[16]; + unsigned int len = (length < sizeof(msg) - 1) ? length : sizeof(msg) - 1; + memcpy(msg, payload, len); + msg[len] = '\0'; + + Serial.print(F("MQTT command received: ")); + Serial.println(msg); + + if (strcmp(msg, "ON") == 0) { + manualMode = true; + manualPumpOn = true; + setPump(true); + } else if (strcmp(msg, "OFF") == 0) { + manualMode = true; + manualPumpOn = false; + setPump(false); + } else if (strcmp(msg, "AUTO") == 0) { + manualMode = false; + Serial.println(F("Returned to automatic mode.")); + } +} + +// --- Wi-Fi Connection -------------------------------------------------------- +void connectWiFi() { + if (WiFi.status() == WL_CONNECTED) return; + + Serial.print(F("Connecting to Wi-Fi: ")); + Serial.print(WIFI_SSID); + WiFi.begin(WIFI_SSID, WIFI_PASSWORD); + + unsigned long start = millis(); + while (WiFi.status() != WL_CONNECTED) { + if (millis() - start > 15000UL) { + Serial.println(F("\nWi-Fi timeout - retrying later.")); + return; + } + delay(500); + Serial.print('.'); + } + Serial.print(F("\nConnected! IP: ")); + Serial.println(WiFi.localIP()); +} + +// --- MQTT Connection --------------------------------------------------------- +void connectMQTT() { + if (mqttClient.connected()) return; + + Serial.print(F("Connecting to MQTT broker...")); + if (mqttClient.connect(MQTT_CLIENT_ID)) { + Serial.println(F(" connected.")); + mqttClient.subscribe(TOPIC_COMMAND); + } else { + Serial.print(F(" failed, rc=")); + Serial.println(mqttClient.state()); + } +} + +// --- setup() ----------------------------------------------------------------- +void setup() { + Serial.begin(115200); + Serial.println(F("\n=== Smart Irrigation System - IoT Edition ===")); + + pinMode(RELAY_PIN, OUTPUT); + setPump(false); // Pump OFF at boot + + connectWiFi(); + + mqttClient.setServer(MQTT_BROKER, MQTT_PORT); + mqttClient.setCallback(onMqttMessage); + connectMQTT(); + + Serial.println(F("Setup complete.\n")); +} + +// --- loop() ------------------------------------------------------------------ +void loop() { + // Maintain connections + if (WiFi.status() != WL_CONNECTED) connectWiFi(); + if (!mqttClient.connected()) connectMQTT(); + mqttClient.loop(); + + unsigned long now = millis(); + if (now - lastPublishTime >= PUBLISH_INTERVAL_MS) { + lastPublishTime = now; + + // Read moisture sensor + int rawValue = analogRead(MOISTURE_SENSOR_PIN); + int moisturePercent = constrain(map(rawValue, 1023, 0, 0, 100), 0, 100); + + // Publish moisture reading + char buf[8]; + itoa(moisturePercent, buf, 10); + mqttClient.publish(TOPIC_MOISTURE, buf, true /* retain */); + + Serial.print(F("Moisture: ")); + Serial.print(moisturePercent); + Serial.println(F(" %")); + + // Automatic control (ignored when manual override is active) + if (!manualMode) { + setPump(rawValue > MOISTURE_THRESHOLD); + } + } +} diff --git a/code/smart_irrigation.ino b/code/smart_irrigation.ino new file mode 100644 index 0000000..b5e8aba --- /dev/null +++ b/code/smart_irrigation.ino @@ -0,0 +1,146 @@ +/* + * Smart Irrigation System Using Arduino + * ====================================== + * Author : Prashanth Nayak + * Date : 2025 + * Version : 1.0 + * + * Description: + * This sketch reads a soil moisture sensor and automatically + * controls a water pump via a relay module. When the soil + * moisture drops below a configured threshold the relay is + * activated (pump ON); once sufficient moisture is detected + * the relay is de-activated (pump OFF). + * + * Hardware: + * - Arduino Uno / Nano + * - Capacitive or Resistive Soil Moisture Sensor (analog output) + * - 5 V Relay Module (active-LOW or active-HIGH configurable below) + * - 5 V / 12 V Submersible or mini water pump + * - Optional: 16x2 LCD with I2C adapter for display + * - Optional: LED indicators for pump status + * + * Wiring Summary: + * Soil Moisture Sensor --> Arduino A0 + * Relay IN pin --> Arduino D7 + * VCC (sensor + relay) --> Arduino 5 V + * GND (sensor + relay) --> Arduino GND + * + * Notes: + * - Sensor raw value range: 0 (fully wet) - 1023 (fully dry) + * Adjust MOISTURE_THRESHOLD to suit your soil/sensor. + * - Relay type: set RELAY_ACTIVE_LOW to true if your relay + * module triggers on a LOW signal (most common), false otherwise. + * + * License: MIT + */ + +// --- Pin Definitions --------------------------------------------------------- +const int MOISTURE_SENSOR_PIN = A0; // Analog input from soil moisture sensor +const int RELAY_PIN = 7; // Digital output to relay IN pin +const int PUMP_LED_PIN = 13; // Built-in LED mirrors pump state (optional) + +// --- Configuration ----------------------------------------------------------- +/* + * MOISTURE_THRESHOLD: + * Analog value (0-1023) above which the soil is considered DRY. + * Higher raw value means drier soil. + * Typical calibration: + * Place sensor in dry air -> note value (~1023) + * Submerge sensor in water -> note value (~300-400) + * Set threshold somewhere between those two readings, e.g. 600. + */ +const int MOISTURE_THRESHOLD = 600; + +/* + * RELAY_ACTIVE_LOW: + * true - relay activates when IN pin is LOW (most common modules) + * false - relay activates when IN pin is HIGH + */ +const bool RELAY_ACTIVE_LOW = true; + +/* + * READ_INTERVAL_MS: + * How often (milliseconds) the sensor is read. + * Use a shorter interval (e.g. 2000 ms) during development/testing. + * For production use 600000 ms (10 minutes) to reduce sensor wear. + */ +const unsigned long READ_INTERVAL_MS = 2000UL; // 2 seconds (development) + +// --- Global State ------------------------------------------------------------ +unsigned long lastReadTime = 0; // Timestamp of the last sensor read +bool pumpRunning = false; // Tracks current pump state + +// --- Helper: activate / deactivate relay ------------------------------------- +void setPump(bool on) { + if (on) { + digitalWrite(RELAY_PIN, RELAY_ACTIVE_LOW ? LOW : HIGH); + digitalWrite(PUMP_LED_PIN, HIGH); + } else { + digitalWrite(RELAY_PIN, RELAY_ACTIVE_LOW ? HIGH : LOW); + digitalWrite(PUMP_LED_PIN, LOW); + } + pumpRunning = on; +} + +// --- setup() ----------------------------------------------------------------- +void setup() { + Serial.begin(9600); + Serial.println(F("=== Smart Irrigation System ===")); + Serial.println(F("Initialising...")); + + // Configure pins + pinMode(RELAY_PIN, OUTPUT); + pinMode(PUMP_LED_PIN, OUTPUT); + + // Ensure pump is OFF at startup + setPump(false); + + Serial.print(F("Moisture threshold set to: ")); + Serial.println(MOISTURE_THRESHOLD); + Serial.println(F("System ready.\n")); +} + +// --- loop() ------------------------------------------------------------------ +void loop() { + unsigned long now = millis(); + + // Only read sensor at configured interval to avoid rapid cycling + if (now - lastReadTime >= READ_INTERVAL_MS) { + lastReadTime = now; + + // Read raw analog value from soil moisture sensor + int rawValue = analogRead(MOISTURE_SENSOR_PIN); + + // Convert raw value to a percentage (0% = dry, 100% = wet) + // Raw 1023 -> 0% moisture; Raw 0 -> 100% moisture + int moisturePercent = map(rawValue, 1023, 0, 0, 100); + moisturePercent = constrain(moisturePercent, 0, 100); + + // Print readings to Serial Monitor + Serial.print(F("Soil Moisture - Raw: ")); + Serial.print(rawValue); + Serial.print(F(" | Percent: ")); + Serial.print(moisturePercent); + Serial.print(F(" % | Pump: ")); + + // Decision logic + if (rawValue > MOISTURE_THRESHOLD) { + // Soil is DRY -> turn pump ON + if (!pumpRunning) { + setPump(true); + Serial.println(F("ON (soil dry - watering started)")); + } else { + Serial.println(F("ON (watering in progress)")); + } + } else { + // Soil is WET enough -> turn pump OFF + if (pumpRunning) { + setPump(false); + Serial.println(F("OFF (soil moist - watering stopped)")); + } else { + Serial.println(F("OFF (soil moisture adequate)")); + } + } + } +} diff --git a/docs/circuit_diagram.md b/docs/circuit_diagram.md new file mode 100644 index 0000000..f5602ff --- /dev/null +++ b/docs/circuit_diagram.md @@ -0,0 +1,124 @@ +# Circuit Diagram – Smart Irrigation System + +## Overview + +The circuit connects an Arduino Uno to a soil moisture sensor, a 5 V relay +module, a submersible water pump, and (optionally) a 16x2 LCD display for +on-device status readout. + +--- + +## Component Connections + +### Soil Moisture Sensor → Arduino Uno + +| Sensor Pin | Arduino Pin | Notes | +|------------|-------------|-------| +| VCC | 5 V | Power supply | +| GND | GND | Common ground | +| AO (Analog Out) | A0 | Analog moisture reading (0 – 1023) | +| DO (Digital Out)| — | Not used in this project (optional) | + +> **Tip:** For capacitive sensors (recommended over resistive for longevity), +> the AO pin outputs a lower voltage when the soil is wetter. + +--- + +### Relay Module → Arduino Uno + +| Relay Pin | Arduino Pin | Notes | +|-----------|-------------|-------| +| VCC | 5 V | Power supply | +| GND | GND | Common ground | +| IN | D7 | Control signal – LOW activates most modules | + +--- + +### Water Pump → Relay Module + +| Relay Terminal | Connection | Notes | +|---------------------|------------------|-------| +| COM | Pump + / VCC | Common terminal | +| NO (Normally Open) | Power Supply + | Circuit closed (pump ON) when relay is activated | +| NC (Normally Closed)| — | Not connected (pump OFF by default is safe) | +| Pump − | Power Supply − | Complete the circuit through the negative rail | + +> **Important:** If the pump runs on 12 V, use a separate 12 V power supply for +> the pump side; share only the GND with the Arduino. + +--- + +### Optional LCD (16x2 I2C) → Arduino Uno + +| LCD Pin | Arduino Pin | Notes | +|---------|-------------|-------| +| VCC | 5 V | Power supply | +| GND | GND | Common ground | +| SDA | A4 | I2C data line | +| SCL | A5 | I2C clock line | + +--- + +## ASCII Circuit Diagram + +``` + +5V ─────────────────────────┐ + │ + ┌──────────────────┐ ┌─────────┴──────────┐ + │ Soil Moisture │ │ Arduino Uno │ + │ Sensor │ │ │ + │ VCC ────────────┼────────────────────┤ 5V │ + │ GND ────────────┼────────────────────┤ GND │ + │ AO ────────────┼────────────────────┤ A0 │ + └──────────────────┘ │ │ + │ D7 ────────────────┼──── Relay IN + ┌──────────────────┐ │ │ + │ Relay Module │ │ │ + │ VCC ────────────┼────────────────────┤ 5V │ + │ GND ────────────┼────────────────────┤ GND │ + │ IN ────────────┼────────────────────┤ D7 │ + │ │ └─────────┬──────────┘ + │ COM ──── Pump + │ │ + │ NO ──── 5/12V+ │ GND + └──────────────────┘ + │ + ┌──────┴───────┐ + │ Water Pump │ + │ + ──── COM │ + │ − ──── GND │ + └──────────────┘ +``` + +--- + +## Power Supply Considerations + +| Component | Voltage | Typical Current | +|------------------|-------------|-----------------| +| Arduino Uno | 5 V (USB) | ~50 mA | +| Soil Sensor | 3.3 – 5 V | ~5 mA | +| Relay Module | 5 V | ~70 mA (coil) | +| Mini Pump (5 V) | 5 V | 200 – 300 mA | +| Mini Pump (12 V) | 12 V | 300 – 600 mA | + +> Use a separate power adapter for the pump to avoid voltage drops that could +> reset the Arduino. + +--- + +## Safety Notes + +1. **Never connect the mains (AC) side of a relay directly** unless you are + qualified; use only DC pumps for hobby/educational projects. +2. Keep water connections away from all electronics with appropriate enclosures + or cable management. +3. Always add a **flyback diode** across the pump motor terminals (cathode to + +, anode to −) to suppress voltage spikes when the pump turns off. + +--- + +## Proteus / Tinkercad Simulation + +See [`docs/simulation_guide.md`](simulation_guide.md) for step-by-step +instructions on simulating this circuit in Tinkercad or Proteus before +building on real hardware. diff --git a/docs/components.md b/docs/components.md new file mode 100644 index 0000000..32f362b --- /dev/null +++ b/docs/components.md @@ -0,0 +1,88 @@ +# Components List – Smart Irrigation System + +## Required Components + +| # | Component | Specification | Quantity | Estimated Cost (USD) | +|---|-----------|---------------|----------|----------------------| +| 1 | Arduino Uno R3 | ATmega328P, 5 V, 16 MHz | 1 | $10 – $25 | +| 2 | Soil Moisture Sensor | Capacitive (recommended) or Resistive, 3.3 – 5 V | 1 | $1 – $3 | +| 3 | 5 V Relay Module | Single-channel, active-LOW, with optocoupler | 1 | $1 – $3 | +| 4 | Mini Submersible Water Pump | 3 – 5 V DC, ~120 L/h | 1 | $2 – $5 | +| 5 | Silicone Tubing | 6 mm inner diameter, ~1 metre | 1 | $1 – $2 | +| 6 | Jumper Wires | Male-to-Male & Male-to-Female, 20 cm | 1 set | $1 – $3 | +| 7 | Breadboard | 830-point full-size | 1 | $2 – $5 | +| 8 | USB-A to USB-B Cable | For programming Arduino | 1 | $1 – $3 | +| 9 | 5 V Power Supply / Power Bank | >= 1 A output | 1 | $5 – $15 | + +**Estimated Total: $24 – $64** + +--- + +## Optional / Recommended Add-ons + +| # | Component | Purpose | Estimated Cost (USD) | +|---|-----------|---------|----------------------| +| 1 | 16x2 LCD + I2C Adapter | On-device moisture & pump status display | $3 – $6 | +| 2 | DHT11 / DHT22 Temperature & Humidity Sensor | Environmental monitoring | $1 – $4 | +| 3 | LED (Red + Green) + 220 Ohm Resistors | Visual pump status indicators | < $1 | +| 4 | Buzzer (active) | Audible alert when reservoir is low | < $1 | +| 5 | Float Switch | Detects low water level in reservoir | $1 – $2 | +| 6 | Waterproof Enclosure | Protects electronics in outdoor setting | $5 – $15 | +| 7 | 12 V Adapter + DC Barrel Jack | For more powerful pump setups | $3 – $8 | + +--- + +## IoT Upgrade Components (ESP8266 variant) + +| # | Component | Specification | Quantity | Estimated Cost (USD) | +|---|-----------|---------------|----------|----------------------| +| 1 | NodeMCU ESP8266 v3 | Wi-Fi SoC, 3.3 V logic, Arduino-compatible | 1 | $3 – $8 | +| 2 | 3.3 V Voltage Regulator (AMS1117) | If powering 5 V sensor from 3.3 V MCU | 1 | < $1 | +| 3 | Voltage Divider (10 kOhm + 10 kOhm) | Scale 5 V sensor output to 1 V ADC range | 1 | < $1 | + +> **Note:** The ESP8266 ADC accepts a maximum of **1 V** on the A0 pin. If your +> sensor outputs 0 – 3.3 V use a 1:2 voltage divider; if it outputs 0 – 5 V use +> a 1:4 divider (e.g. 10 kOhm + 3.3 kOhm resistors). + +--- + +## Component Descriptions + +### Soil Moisture Sensor + +Two common types are available: + +| Type | Pros | Cons | +|------|------|------| +| **Resistive** (silver/copper probes) | Cheap (< $1) | Corrodes within weeks in soil; inaccurate over time | +| **Capacitive** (brown PCB, no exposed metal) | Long-lasting, accurate, corrosion-free | Slightly more expensive ($1 – $3) | + +**Recommendation:** Use a capacitive sensor for any permanent installation. + +### Relay Module + +The relay acts as an electrically-controlled switch. The Arduino's 5 V GPIO +signal energises the relay coil, which closes (or opens) a separate circuit +powering the pump. + +- Most modules include a built-in optocoupler (PC817) for electrical isolation. +- The module has three output terminals: **COM**, **NO** (Normally Open), and + **NC** (Normally Closed). Wire the pump between COM and NO so that it is + OFF by default and only runs when the Arduino activates the relay. + +### Water Pump + +- **5 V mini submersible pump**: suitable for indoor plant pots and + breadboard prototypes. Powered directly from Arduino's 5 V pin or a USB + power bank. +- **12 V pump**: higher flow rate; requires a separate 12 V supply with a + shared GND connection to the Arduino. + +--- + +## Where to Source Components + +- **Amazon / Flipkart** – individual modules or bundled "Arduino Sensor Kits" +- **AliExpress / Banggood** – lowest prices; allow 2–4 weeks for shipping +- **Adafruit / SparkFun** – higher quality, documentation, US/EU shipping +- **Local electronics stores** – immediate availability; good for urgent builds diff --git a/docs/simulation_guide.md b/docs/simulation_guide.md new file mode 100644 index 0000000..28dd66e --- /dev/null +++ b/docs/simulation_guide.md @@ -0,0 +1,101 @@ +# Simulation Guide – Smart Irrigation System + +Simulating the circuit before assembling real hardware lets you verify your +code logic without risking damage to components. Two free tools are described +below. + +--- + +## Option 1 – Tinkercad Circuits (Browser-based, Free) + +[Tinkercad](https://www.tinkercad.com) is the easiest option; no software +installation is required. + +### Steps + +1. **Create a free Tinkercad account** at https://www.tinkercad.com. +2. Click **Create** → **Circuit**. +3. Add components from the right-side panel: + - **Arduino Uno R3** + - **Soil Moisture Sensor** (search "moisture") + - **Relay** (search "relay") + - Any LEDs / resistors for indicators +4. Connect wires as described in [`docs/circuit_diagram.md`](circuit_diagram.md): + - Sensor AO → Arduino A0 + - Relay IN → Arduino D7 + - Shared 5 V and GND rails +5. Click on the **Arduino block** → **Code** tab → switch to **Text** mode. +6. Paste the contents of [`code/smart_irrigation.ino`](../code/smart_irrigation.ino). +7. Click **Start Simulation**. +8. In the simulation, click the **soil moisture sensor** to adjust the moisture + slider (0% = wet, 100% = dry). +9. Observe the relay LED: it should turn ON when moisture drops below the + threshold and OFF when it rises above it. +10. Open the **Serial Monitor** (bottom of screen) to view debug output. + +> **Tip:** Because Tinkercad does not include an official water pump component, +> use an LED with a 220 Ohm series resistor connected to the relay NO terminal +> as a pump proxy. + +--- + +## Option 2 – Proteus Design Suite (Desktop, Paid / Student Edition) + +[Proteus](https://www.labcenter.com) provides more accurate simulation, +including microcontroller instruction-level emulation. + +### Steps + +1. **Install Proteus** (version 8 or later). A 30-day trial or student licence + is available from Labcenter Electronics. +2. Open Proteus → **New Project** → ISIS Schematic. +3. Add components (press **P** to open the Pick Devices dialog): + - `ARDUINO UNO` (or `ATMEGA328P` with bootloader hex) + - `RES` (resistors) + - `LED-RED`, `LED-GREEN` + - For the relay: use a generic `RELAY-SPDT` plus a transistor driver + (`BC547`) and flyback diode (`1N4007`) +4. Wire the schematic to match the connection table in the circuit diagram doc. +5. Right-click the Arduino component → **Edit Properties** → set the + **Program File** field to your compiled `.hex` file. + - To compile to `.hex`: in the Arduino IDE go to + **Sketch → Export Compiled Binary**. The `.hex` file appears in the + sketch folder. +6. Click the **Play** button (▶) in the bottom-left of Proteus to run the + simulation. +7. Double-click the moisture sensor analogue input source to adjust the voltage + and observe relay behaviour. + +--- + +## Interpreting Simulation Results + +| Serial Monitor Output | Meaning | +|-----------------------|---------| +| `Pump: ON (soil dry - watering started)` | Raw ADC > threshold; relay activated | +| `Pump: OFF (soil moisture adequate)` | Raw ADC <= threshold; relay de-activated | +| Moisture % climbing | Sensor input voltage decreasing (wetter) | +| Moisture % falling | Sensor input voltage increasing (drier) | + +--- + +## Troubleshooting Simulation Issues + +| Problem | Likely Cause | Fix | +|---------|--------------|-----| +| Relay never activates | Threshold set too low | Increase `MOISTURE_THRESHOLD` in the sketch | +| Relay always ON | Threshold set too high | Decrease `MOISTURE_THRESHOLD` | +| Serial output garbled | Baud rate mismatch | Ensure Serial Monitor is set to **9600 baud** | +| Pump (LED) flickers rapidly | No hysteresis in code | Add a small dead-band (+-20 counts) around the threshold | + +--- + +## Next Step: Real Hardware + +Once the simulation behaves as expected: + +1. Assemble the circuit on a breadboard. +2. Upload `smart_irrigation.ino` to a physical Arduino Uno via USB. +3. Open the Serial Monitor (Tools → Serial Monitor) at 9600 baud. +4. Insert the sensor into soil and verify the readings change as expected. +5. Confirm the relay clicks and the pump activates/deactivates correctly. diff --git a/images/README.md b/images/README.md new file mode 100644 index 0000000..0547640 --- /dev/null +++ b/images/README.md @@ -0,0 +1,32 @@ +# Images + +This folder contains circuit diagrams, photos, and screenshots related to the +Smart Irrigation System project. + +## Suggested Images to Add + +| File Name | Description | +|-----------|-------------| +| `circuit_diagram.png` | Full circuit wiring diagram (export from Fritzing / Tinkercad) | +| `breadboard_setup.jpg` | Photo of assembled breadboard prototype | +| `serial_monitor.png` | Screenshot of Arduino Serial Monitor showing live readings | +| `tinkercad_simulation.png` | Screenshot of Tinkercad simulation running | +| `iot_dashboard.png` | Screenshot of MQTT / Node-RED dashboard (IoT upgrade) | +| `assembled_system.jpg` | Photo of complete system with pump and plant pot | + +## Creating a Fritzing Diagram + +1. Download [Fritzing](https://fritzing.org) (open-source EDA tool). +2. Drag components (Arduino Uno, soil moisture sensor, relay module, pump) from + the parts panel onto the breadboard view. +3. Connect the components according to the pin mapping in + [`docs/circuit_diagram.md`](../docs/circuit_diagram.md). +4. Export as PNG via **File → Export → as Image → PNG**. +5. Save the file as `images/circuit_diagram.png` and update this README. + +## Creating a Tinkercad Screenshot + +1. Build and simulate the circuit in [Tinkercad](https://www.tinkercad.com) + as described in [`docs/simulation_guide.md`](../docs/simulation_guide.md). +2. Take a browser screenshot and crop to the circuit canvas. +3. Save as `images/tinkercad_simulation.png`.