Raspberry Pi Smart Irrigation Data Controller (SDG 2 – Zero Hunger)

Last Updated May 28, 2026

Efficient water management is one of the central challenges of global agriculture. A Raspberry Pi smart irrigation controller can combine soil sensors, environmental data, local logging, and automated irrigation control to optimize water use while supporting sustainable food production aligned with SDG 2: Zero Hunger and SDG 6: Clean Water and Sanitation.

Global food systems face a difficult systems problem: food production must become more resilient while operating within tighter environmental limits. Water availability is not only an agricultural issue. It connects food security, freshwater stress, climate adaptation, land management, infrastructure reliability, energy use, rural livelihoods, and the long-term viability of growing systems.

This project demonstrates how to build a Raspberry Pi-based smart irrigation controller capable of reading soil conditions, processing environmental data, activating irrigation systems when needed, and storing operational history for later analysis. While simple, the design reflects a broader sustainability principle: agricultural systems become more resilient when water decisions are driven by measurement rather than fixed schedules.

The project should not be treated as a commercial irrigation controller, a field-hardened farm automation system, a substitute for agronomic expertise, or a fully validated water-management platform. Its purpose is educational and methodological: to show how sensing, edge computing, threshold logic, actuation, logging, calibration, and responsible deployment can work together in a water-aware agricultural control system.

Raspberry Pi smart irrigation controller monitoring soil moisture and crop conditions to support sustainable agriculture and SDG 2 Zero Hunger.
Raspberry Pi smart irrigation system using soil moisture sensors and automated water control to support sustainable agriculture and SDG 2: Zero Hunger.

This project also connects to broader site areas, including Environmental Monitoring Systems, Intelligent Infrastructure Systems, Freshwater Change and Earth System Risk, Land-System Change and Ecological Transformation, Sustainable Development Goals Within Planetary Boundaries, Climate Change as a Planetary Boundary, and Planetary Boundaries. In that wider context, this Raspberry Pi irrigation controller is not only a maker project. It is a small prototype of the sensing, control, and data infrastructure needed for more water-efficient agriculture under climate stress.

Abstract

This project presents a prototype Raspberry Pi smart irrigation controller built around soil moisture sensing, analog-to-digital conversion, environmental telemetry, relay-based irrigation control, local data logging, and optional weather-aware scheduling. The system reads soil conditions through an ADS1115 analog-to-digital converter, applies threshold-based irrigation logic, and activates a relay-controlled valve or pump only when irrigation is justified by measured conditions.

From an engineering perspective, the platform demonstrates a compact agricultural control system with sensing, computation, actuation, logging, and decision layers. From a sustainability perspective, it illustrates how data-driven irrigation can improve water efficiency, agricultural resilience, and food-system sustainability under conditions of climate variability and freshwater constraint.

The system is intentionally limited. It is not a commercial irrigation controller, not a field-hardened farm automation system, not an agronomic decision platform, and not a substitute for local crop, soil, and water expertise. Its value is educational and methodological: it teaches how soil sensing, control logic, irrigation actuation, validation, and data logging can support more responsible water management.

Back to top ↑

SDG Alignment: Food Security, Freshwater Stewardship, Climate Resilience, and Agricultural Infrastructure

This project aligns most directly with SDG 2: Zero Hunger, because it supports more efficient and resilient agricultural water management. Food security depends not only on crop yield, but on the capacity of agricultural systems to remain productive under water stress, climate variability, soil degradation, and infrastructure constraints.

The project also connects strongly to SDG 6: Clean Water and Sanitation, SDG 12: Responsible Consumption and Production, SDG 13: Climate Action, and SDG 9: Industry, Innovation and Infrastructure. Sensor-driven irrigation systems help farmers, educators, researchers, and growers apply water more precisely, reduce waste, and improve crop resilience under increasingly variable climate conditions.

Sustainable Development Goal How the Project Relates Project-Level Mechanism
SDG 2: Zero Hunger Supports agricultural resilience, food-production stability, and more adaptive growing systems. Soil moisture sensing, irrigation thresholds, water-event logging, and crop-zone monitoring.
SDG 6: Clean Water and Sanitation Supports freshwater stewardship by reducing unnecessary irrigation and making water use more visible. Condition-based irrigation, weather-aware scheduling, optional flow sensing, and irrigation-event records.
SDG 12: Responsible Consumption and Production Relates to resource efficiency, reduced waste, and more accountable production systems. Measured water decisions rather than fixed schedules, with logs for later analysis.
SDG 13: Climate Action Supports adaptation to drought, heat, rainfall variability, and shifting growing conditions. Soil-sensor feedback, weather API integration, lockout timing, and climate-aware irrigation logic.
SDG 9: Industry, Innovation and Infrastructure Demonstrates smart agricultural infrastructure, distributed sensing, edge computing, and automated control. Raspberry Pi, ADS1115 ADC, relay control, SQLite logging, and modular irrigation architecture.

The strongest SDG connection is SDG 2. Food security requires resilient agricultural systems that can maintain productivity under drought, heat, rainfall variability, and soil stress. Smart irrigation does not solve food insecurity by itself, but it demonstrates one technical pathway toward more responsive water management in growing systems.

The connection to SDG 6 is equally important. Agriculture is closely tied to freshwater use. Irrigation systems that water on fixed schedules can waste water when soil is already wet or rain is imminent. A sensor-driven controller creates a feedback loop: measure soil conditions, decide whether irrigation is necessary, apply water only when justified, and log the result.

The connection to SDG 13 comes through adaptation. Climate variability can change rainfall timing, increase heat stress, intensify drought, and make fixed irrigation schedules less reliable. Weather-aware irrigation logic helps growing systems respond to changing conditions rather than assuming the past schedule still fits the present climate.

Because the Sustainable Development Goals are broad public frameworks, it is important not to overclaim. This project is not a complete sustainable agriculture strategy, not a field-scale irrigation plan, and not a substitute for soil science, crop management, hydrology, or agronomic expertise. Its value is narrower and still meaningful: it teaches the control-system logic behind water-aware agriculture.

Back to top ↑

Connections to Other Site Areas

This Raspberry Pi smart irrigation controller belongs to a wider body of work on environmental monitoring, intelligent infrastructure, and resource stewardship. It connects directly to Environmental Monitoring Systems, because soil moisture, humidity, temperature, rainfall, and irrigation events are measurable environmental signals that can guide better decisions.

It also connects to Intelligent Infrastructure Systems. Irrigation becomes intelligent when sensing nodes can observe conditions, store data, evaluate thresholds, control valves or pumps, and support dashboard-based decision-making.

At the planetary-boundary level, this project relates directly to Freshwater Change and Earth System Risk. A small irrigation prototype does not represent the entire freshwater boundary, but it demonstrates the same principle: freshwater systems become more manageable when use decisions are tied to physical conditions rather than assumptions.

The project also connects to Land-System Change and Ecological Transformation, because irrigation practices shape soil conditions, crop productivity, water demand, salinity risk, nutrient movement, and the ecological footprint of agricultural systems.

Back to top ↑

Food Security and the Water Challenge of SDG 2

Food security is deeply connected to water availability. Crops require consistent soil moisture levels to grow effectively, but irrigation must also avoid overwatering that can increase nutrient loss, soil erosion, salinization risk, waterlogging, energy use, and unnecessary freshwater withdrawals.

SDG 2 focuses on several agricultural priorities, including:

  • increasing agricultural productivity
  • strengthening small-scale food production
  • improving resilience to climate variability
  • promoting sustainable land and water management
  • supporting more stable and adaptive food systems

Smart irrigation systems contribute to these goals by enabling growers to monitor soil conditions in real time and adjust irrigation accordingly. Rather than irrigating based on fixed schedules, sensor-driven systems deliver water only when soil moisture levels fall below meaningful thresholds.

That shift matters because water decisions are often made under uncertainty. A grower may know the forecast, remember the last irrigation event, or observe plant stress, but the root-zone water condition may still be unclear. Soil moisture sensing gives the irrigation decision a physical feedback signal.

Back to top ↑

Precision Agriculture and Data-Driven Irrigation

Modern agricultural systems increasingly rely on precision agriculture techniques that use environmental sensors, remote sensing, weather data, automation, and data analytics to optimize crop production.

Precision irrigation systems typically monitor:

  • soil moisture levels
  • ambient temperature
  • relative humidity
  • rainfall
  • solar radiation
  • weather forecasts
  • irrigation event history
  • crop or substrate response after watering

These measurements allow irrigation systems to respond dynamically to environmental conditions rather than relying on fixed watering schedules. A Raspberry Pi controller can serve as the computational center of such a system, collecting sensor data, analyzing environmental conditions, controlling irrigation valves, and storing operational records for later analysis.

More advanced systems may incorporate evapotranspiration estimates, crop-stage models, weather forecasts, anomaly detection, soil-zone mapping, and predictive scheduling. This prototype provides a small but practical foundation for that broader precision-agriculture architecture.

Precision agriculture should still be interpreted carefully. Better instrumentation can improve water decisions, but it can also introduce cost, complexity, unequal access, data-dependence, or maintenance burdens. The strongest designs keep the technology accountable to agronomic purpose and local context.

Back to top ↑

System Overview

The Raspberry Pi smart irrigation controller reads soil moisture through an analog sensor connected to an ADS1115 analog-to-digital converter. The Raspberry Pi converts the raw signal into an estimated moisture value, compares that value with a threshold, checks lockout and weather conditions, and then activates a relay-controlled irrigation valve or pump when watering is appropriate.

The system can include:

  • soil moisture sensing through ADS1115 ADC
  • optional temperature and humidity sensing
  • relay-based valve or pump control
  • local SQLite logging
  • optional weather API integration
  • optional dashboarding or CSV export
  • optional flow sensing for water-use measurement

The key design pattern is feedback control. The system does not water because a clock says it is time. It waters because measured soil conditions, threshold logic, lockout rules, and optional weather forecasts indicate that irrigation may be justified.

Back to top ↑

System Requirements

A smart irrigation controller becomes useful only when its requirements are explicit. The system must measure soil conditions, control actuation safely, store operating history, and avoid watering based on noisy or uncalibrated readings.

Requirement Design Target Reason
Soil moisture sensing Read calibrated soil moisture through ADS1115 analog input Raspberry Pi does not have native analog input, and irrigation decisions need physical feedback
Threshold logic Trigger irrigation only when soil moisture falls below a calibrated threshold Prevents fixed-schedule watering and supports more responsive water use
Actuation safety Control valve or pump through relay or driver hardware, not direct GPIO power Protects the Raspberry Pi and reduces electrical risk
Lockout timing Prevent rapid repeated watering cycles Allows soil moisture to respond and reduces overwatering
Local logging Store sensor readings and irrigation events with timestamps Enables analysis of water use, sensor response, and system behavior
Weather awareness Delay irrigation when meaningful rainfall is expected Improves water efficiency and climate responsiveness
Responsible deployment Use within prototype, greenhouse, garden, educational, or supervised field contexts Clarifies that this is not a commercial unattended irrigation system without further validation

These requirements frame the project as a water-control system, not only as a soil sensor demo. The system must sense, decide, act, log, and fail safely.

Back to top ↑

System Architecture

A Raspberry Pi smart irrigation system integrates several functional layers.

Sensor Layer

  • capacitive soil moisture sensors
  • temperature and humidity sensors
  • optional rainfall sensor
  • optional flow meter or water-use sensor

Acquisition Layer

  • ADS1115 analog-to-digital converter for soil sensor readings
  • I2C interface for sensor communication
  • GPIO interface for relay control

Control Layer

  • Raspberry Pi computing platform
  • threshold-based irrigation logic
  • lockout timing to prevent rapid repeated watering
  • optional forecast-aware scheduling

Data Layer

  • local SQLite database for environmental observations
  • irrigation event log
  • optional dashboard or CSV export

Typical architecture:

Soil Sensors → ADS1115 ADC → Raspberry Pi → Irrigation Logic → Relay Module → Valve or Pump → Soil Moisture Response → Data Logging

This structure makes the project more than a single-purpose watering device. It becomes a compact agricultural data system capable of collecting environmental observations, making irrigation decisions, controlling actuation, and storing operational history for later analysis.

Back to top ↑

Bill of Materials

  • Raspberry Pi 4, Raspberry Pi 5, or Raspberry Pi Zero 2 W
  • capacitive soil moisture sensor
  • DHT22 temperature and humidity sensor, optional but useful for context
  • ADS1115 analog-to-digital converter
  • relay module
  • solenoid irrigation valve or water pump
  • external power supply for valve or pump
  • microSD card with adequate endurance for logging
  • weather-resistant electronics enclosure
  • terminal blocks or secure wiring connectors
  • optional flow sensor
  • optional rain sensor
  • optional dashboard display or local web server

Capacitive soil moisture sensors are often preferred because they are more resistant to corrosion than resistive sensors. The ADS1115 is useful because Raspberry Pi GPIO pins do not support direct analog input.

For long-term deployment, secure wiring, waterproofing, strain relief, power isolation, valve rating, and enclosure design are just as important as the Raspberry Pi code.

Back to top ↑

Engineering Specifications

Parameter Reference Design
Compute platform Raspberry Pi 4, Raspberry Pi 5, or Raspberry Pi Zero 2 W
Primary sensor Capacitive soil moisture sensor
Environmental sensor DHT22 temperature and humidity sensor, optional but useful for context
ADC interface ADS1115 over I2C
Actuation Relay-controlled solenoid valve or pump
Storage options CSV, SQLite, InfluxDB, or lightweight dashboard logging
Control mode Threshold-based irrigation with optional forecast integration
Deployment mode Greenhouse, garden, classroom, field-lab, or prototype agricultural system
Target scope Educational, prototype, and experimental precision irrigation

The reference design is modular. It can begin with one soil moisture sensor and one relay, then expand to multiple irrigation zones, additional sensors, weather data, flow measurement, and dashboard visualization.

Back to top ↑

Measurement Principle: Soil Moisture, Control Logic, and Irrigation Response

Soil moisture sensors do not directly solve irrigation. They provide a signal that must be calibrated, interpreted, and connected to an irrigation decision. A capacitive sensor produces an analog value related to the dielectric properties of the surrounding soil or growing medium. That signal changes as water content changes, but the relationship depends on soil texture, salinity, sensor depth, sensor construction, temperature, root distribution, and local placement.

The Raspberry Pi cannot read analog voltage directly, so the ADS1115 converts the soil sensor’s analog output into a digital value. Firmware then maps that value into an estimated moisture percentage using locally measured wet and dry calibration values.

Once the system has an estimated moisture value, the control logic compares it with a threshold. If soil is dry enough, irrigation may be allowed. But a responsible controller should also check lockout timing, weather forecasts, recent rainfall, valve state, and safety conditions before activating a pump or solenoid valve.

The measurement principle is therefore not simply “read a moisture sensor.” It is: measure a soil signal, calibrate it locally, decide whether irrigation is justified, actuate safely, log the result, and observe whether the soil responds as expected.

Back to top ↑

Mathematical Lens: From Soil Readings to Water Decisions

The Raspberry Pi smart irrigation controller can be understood as a feedback-control system. It transforms raw soil sensor readings into estimated moisture values, compares those values with thresholds, and applies water only when conditions justify it.

\[
M = 100 \cdot \frac{x_{\mathrm{dry}}-x}{x_{\mathrm{dry}}-x_{\mathrm{wet}}}
\]

Interpretation: Estimated moisture percentage \(M\) can be calculated from a raw sensor reading \(x\) using locally calibrated dry and wet reference values.

This formula assumes a sensor where dry soil produces a higher raw reading and wet soil produces a lower raw reading. Some sensors behave differently, so calibration must be checked locally.

\[
I_t =
\begin{cases}
1, & M_t < T_M \ \text{and lockout is inactive} \\ 0, & M_t \geq T_M \ \text{or lockout is active} \end{cases} \]

Interpretation: Irrigation state \(I_t\) turns on only when moisture \(M_t\) falls below a threshold \(T_M\) and the lockout period allows irrigation.

Threshold logic prevents unnecessary watering, while lockout timing prevents rapid repeated cycles before water has moved through the soil.

\[
\Delta M = M_{t+\Delta t}-M_t
\]

Interpretation: Soil moisture response after irrigation can be measured by comparing moisture before and after watering.

If moisture does not increase after irrigation, the system may have a valve problem, pump problem, clogged line, sensor placement issue, or uneven water distribution.

\[
W = q \cdot d
\]

Interpretation: Water applied \(W\) can be estimated from flow rate \(q\) and irrigation duration \(d\), if flow is known or measured.

A future version with a flow meter can estimate water use more directly and compare water applied with soil moisture response.

\[
D_t =
\begin{cases}
1, & P_{\mathrm{forecast}} \geq P_{\mathrm{threshold}} \\
0, & P_{\mathrm{forecast}} < P_{\mathrm{threshold}} \end{cases} \]

Interpretation: A weather-aware delay flag can postpone irrigation when forecast precipitation exceeds a chosen threshold.

The mathematical lens shows why the controller is more than an automation script. It is a feedback loop that links sensor calibration, decision thresholds, actuation, water application, and post-irrigation response.

Back to top ↑

Connecting the Soil Moisture Sensor

The soil moisture sensor typically connects through an analog-to-digital converter such as the ADS1115 because Raspberry Pi GPIO pins do not support analog input directly.

Typical wiring:

  • soil moisture sensor analog output → ADS1115 A0
  • ADS1115 VCC → Raspberry Pi 3.3V or compatible sensor supply configuration
  • ADS1115 GND → Raspberry Pi Ground
  • ADS1115 SDA → Raspberry Pi GPIO 2
  • ADS1115 SCL → Raspberry Pi GPIO 3
  • relay module signal → Raspberry Pi GPIO 17 or selected GPIO pin
  • valve or pump → external power circuit switched through relay

This configuration allows the Raspberry Pi to read soil moisture values and control irrigation valves. It also makes the system easier to extend later with multiple soil zones, additional environmental sensors, or dashboard logging.

Enable I2C before running the scripts:

sudo raspi-config
# Interface Options → I2C → Enable

sudo apt update
sudo apt install -y i2c-tools
i2cdetect -y 1

The ADS1115 often appears at address 0x48, though this may vary depending on address pin configuration.

Back to top ↑

Water, Electrical, and Deployment Safety

Smart irrigation systems place electronics near water, soil, pumps, valves, outdoor wiring, and humid environments. That creates practical safety and reliability issues that should be addressed before deployment.

  • Do not power pumps, solenoids, or irrigation loads directly from Raspberry Pi GPIO pins.
  • Use an external power supply rated for the pump or valve.
  • Use relay modules, MOSFET drivers, or proper control hardware rated for the load.
  • Protect Raspberry Pi hardware, breadboards, and wiring from splashes, condensation, and soil contact.
  • Use sealed enclosures, strain relief, and secure connectors for longer deployments.
  • Verify relay default state so the system does not unintentionally irrigate during startup or failure.
  • Do not connect prototype circuits to mains irrigation controllers unless qualified and properly protected.
  • Test the valve or pump under supervision before unattended operation.

This project is intended for educational and prototype low-voltage irrigation control. Field-scale irrigation systems, commercial deployments, mains-powered pumps, and unattended installations require properly rated electrical components, enclosures, fusing, isolation, and qualified installation practices.

Back to top ↑

Software Environment and Dependencies

The project uses Python because Raspberry Pi systems support sensor libraries, GPIO control, SQLite logging, weather APIs, and analytics libraries in one environment.

sudo apt update
sudo apt install -y python3-pip python3-venv i2c-tools sqlite3

python3 -m venv .venv
source .venv/bin/activate

pip install adafruit-circuitpython-ads1x15 adafruit-blinka requests RPi.GPIO

For long-running deployments, the irrigation controller should eventually run as a managed service rather than as a manually launched terminal process. A later version can use systemd, cron, or a process supervisor, but the scripts should first be tested manually so that wiring, calibration, and valve-control issues are visible.

Because this project includes actuation, software errors can have physical consequences. Debugging should begin with the valve disconnected or with a harmless test load before water is introduced.

Back to top ↑

Python Code for Soil Moisture Monitoring

The following Python example reads soil moisture values through an ADS1115. It uses a structured data class, repeated sampling, and simple calibration placeholders so that raw sensor values can later be interpreted more carefully.

"""
Raspberry Pi Smart Irrigation Controller
ADS1115 Soil Moisture Reader

Reads:
- raw soil moisture value from ADS1115 channel A0
- sensor voltage
- estimated moisture percentage using calibration values

Notes:
- Soil moisture sensors require calibration for the actual soil, sensor depth,
  crop type, container geometry, and deployment conditions.
- Raw values are relative signals, not universal moisture measurements.
"""

import time
from dataclasses import dataclass

import board
import busio
from adafruit_ads1x15.ads1115 import ADS1115
from adafruit_ads1x15.analog_in import AnalogIn


@dataclass
class SoilMoistureReading:
    """Structured container for one soil moisture observation."""
    raw_value: int
    voltage: float
    estimated_moisture_percent: float


def initialize_ads1115() -> ADS1115:
    """Initialize ADS1115 over the Raspberry Pi I2C bus."""
    i2c = busio.I2C(board.SCL, board.SDA)
    ads = ADS1115(i2c)

    # Gain controls the measurable voltage range.
    # Adjust based on your sensor output and wiring.
    ads.gain = 1

    return ads


def estimate_moisture_percent(
    raw_value: int,
    dry_raw: int = 26000,
    wet_raw: int = 12000,
) -> float:
    """
    Convert raw sensor reading into an approximate moisture percentage.

    Many capacitive sensors produce higher readings in dry soil and lower
    readings in wet soil, but behavior varies by module.

    Calibrate dry_raw and wet_raw using real local measurements.
    """
    if dry_raw == wet_raw:
        raise ValueError("dry_raw and wet_raw calibration values cannot match.")

    moisture = (dry_raw - raw_value) / (dry_raw - wet_raw) * 100.0

    # Clamp to 0–100 for readability.
    return max(0.0, min(100.0, moisture))


def read_soil_moisture(channel: AnalogIn) -> SoilMoistureReading:
    """Read one soil moisture observation from the ADS1115 channel."""
    raw_value = channel.value
    voltage = channel.voltage

    return SoilMoistureReading(
        raw_value=raw_value,
        voltage=voltage,
        estimated_moisture_percent=estimate_moisture_percent(raw_value),
    )


if __name__ == "__main__":
    ads = initialize_ads1115()
    soil_channel = AnalogIn(ads, ADS1115.P0)

    print("Raspberry Pi Smart Irrigation Controller")
    print("Reading soil moisture from ADS1115...")
    print("----------------------------------------")

    while True:
        try:
            reading = read_soil_moisture(soil_channel)

            print(
                f"Raw: {reading.raw_value} | "
                f"Voltage: {reading.voltage:.3f} V | "
                f"Estimated moisture: {reading.estimated_moisture_percent:.1f}%"
            )

        except Exception as exc:
            print(f"Soil moisture read error: {exc}")

        time.sleep(10)

This basic monitoring loop can be extended with threshold logic, logging, dashboards, multiple zones, weather integration, or automated valve control. The most important improvement is calibration: dry and wet reference values should be measured locally rather than copied from an example.

Back to top ↑

Automated Irrigation Control

The Raspberry Pi can activate irrigation valves using a relay module connected to a GPIO pin. The following example includes safety-oriented structure: explicit relay initialization, irrigation lockout timing, threshold checks, and controlled watering duration.

"""
Relay-Based Irrigation Control Example

Controls a low-voltage irrigation valve or pump through a relay module.

Safety notes:
- Do not power irrigation loads directly from Raspberry Pi GPIO pins.
- Use a properly rated relay, MOSFET driver, valve, pump, and power supply.
- Confirm whether your relay is active-high or active-low before deployment.
"""

import time

import RPi.GPIO as GPIO


VALVE_PIN = 17

# Many relay modules are active-low. Set this according to your hardware.
RELAY_ACTIVE_LOW = True

# Irrigation settings.
IRRIGATION_DURATION_SECONDS = 30
LOCKOUT_SECONDS = 15 * 60

# Example threshold using estimated moisture percentage.
DRY_THRESHOLD_PERCENT = 35.0

last_irrigation_time = 0.0


def setup_relay() -> None:
    """Configure relay GPIO and initialize irrigation valve to OFF."""
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(VALVE_PIN, GPIO.OUT)
    set_valve(False)


def set_valve(open_valve: bool) -> None:
    """Open or close the irrigation valve."""
    if RELAY_ACTIVE_LOW:
        GPIO.output(VALVE_PIN, GPIO.LOW if open_valve else GPIO.HIGH)
    else:
        GPIO.output(VALVE_PIN, GPIO.HIGH if open_valve else GPIO.LOW)


def can_irrigate_now() -> bool:
    """Prevent rapid repeated watering cycles."""
    elapsed = time.time() - last_irrigation_time
    return elapsed >= LOCKOUT_SECONDS


def run_irrigation_cycle() -> None:
    """Run one controlled irrigation cycle."""
    global last_irrigation_time

    print("Opening irrigation valve.")
    set_valve(True)

    time.sleep(IRRIGATION_DURATION_SECONDS)

    set_valve(False)
    last_irrigation_time = time.time()

    print("Irrigation cycle complete.")


def irrigation_decision(moisture_percent: float) -> bool:
    """Return True when moisture is below the dry threshold."""
    return moisture_percent < DRY_THRESHOLD_PERCENT and can_irrigate_now()


if __name__ == "__main__":
    try:
        setup_relay()

        # Example value. Replace with live calibrated soil moisture reading.
        current_moisture_percent = 28.5

        if irrigation_decision(current_moisture_percent):
            run_irrigation_cycle()
        else:
            print("No irrigation needed.")

    finally:
        set_valve(False)
        GPIO.cleanup()

In a full system, current_moisture_percent would come from the ADS1115 soil-moisture reading workflow, and each irrigation event would be logged for later analysis.

For field testing, begin with a relay indicator light or disconnected valve before controlling real water flow. This prevents accidental overwatering while the logic is still being validated.

Back to top ↑

Logging Soil and Irrigation Data

Smart irrigation systems become more useful when observations and irrigation events are logged over time. A lightweight SQLite database can store soil moisture, voltage, estimated moisture percentage, valve state, and environmental context.

"""
SQLite Logger for Raspberry Pi Smart Irrigation Controller

Stores timestamped soil moisture readings and irrigation events.
The resulting dataset can be analyzed with Python, R, SQL, or dashboards.
"""

import sqlite3
from datetime import datetime, timezone
from pathlib import Path


DATABASE_PATH = Path("irrigation_monitor.db")


def create_connection(db_path: Path = DATABASE_PATH) -> sqlite3.Connection:
    """Create and return a SQLite database connection."""
    return sqlite3.connect(db_path)


def initialize_database(conn: sqlite3.Connection) -> None:
    """Create irrigation_readings table if it does not already exist."""
    cursor = conn.cursor()

    cursor.execute("""
        CREATE TABLE IF NOT EXISTS irrigation_readings (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp_utc TEXT NOT NULL,
            raw_soil_value INTEGER,
            soil_voltage REAL,
            moisture_percent REAL,
            temperature_c REAL,
            humidity_percent REAL,
            valve_open INTEGER DEFAULT 0,
            irrigation_duration_seconds REAL,
            sensor_id TEXT DEFAULT 'soil_node_01',
            location_id TEXT DEFAULT 'prototype_irrigation_zone',
            quality_flag TEXT DEFAULT 'unchecked',
            notes TEXT DEFAULT ''
        )
    """)

    conn.commit()


def log_irrigation_reading(
    conn: sqlite3.Connection,
    raw_soil_value: int | None,
    soil_voltage: float | None,
    moisture_percent: float | None,
    temperature_c: float | None,
    humidity_percent: float | None,
    valve_open: bool,
    irrigation_duration_seconds: float | None,
    sensor_id: str = "soil_node_01",
    location_id: str = "prototype_irrigation_zone",
    quality_flag: str = "unchecked",
    notes: str = "",
) -> None:
    """Insert one irrigation monitoring record into SQLite."""
    cursor = conn.cursor()

    cursor.execute("""
        INSERT INTO irrigation_readings (
            timestamp_utc,
            raw_soil_value,
            soil_voltage,
            moisture_percent,
            temperature_c,
            humidity_percent,
            valve_open,
            irrigation_duration_seconds,
            sensor_id,
            location_id,
            quality_flag,
            notes
        )
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    """, (
        datetime.now(timezone.utc).isoformat(),
        raw_soil_value,
        soil_voltage,
        moisture_percent,
        temperature_c,
        humidity_percent,
        1 if valve_open else 0,
        irrigation_duration_seconds,
        sensor_id,
        location_id,
        quality_flag,
        notes,
    ))

    conn.commit()


def read_recent_records(conn: sqlite3.Connection, limit: int = 10) -> list[tuple]:
    """Return recent irrigation records for inspection."""
    cursor = conn.cursor()

    cursor.execute("""
        SELECT timestamp_utc, moisture_percent, valve_open, irrigation_duration_seconds
        FROM irrigation_readings
        ORDER BY timestamp_utc DESC
        LIMIT ?
    """, (limit,))

    return cursor.fetchall()


if __name__ == "__main__":
    conn = create_connection()
    initialize_database(conn)

    # Example row. Replace values with live sensor readings and control state.
    log_irrigation_reading(
        conn=conn,
        raw_soil_value=24500,
        soil_voltage=1.84,
        moisture_percent=31.5,
        temperature_c=28.2,
        humidity_percent=48.0,
        valve_open=True,
        irrigation_duration_seconds=30,
        quality_flag="demo",
        notes="example irrigation event",
    )

    for row in read_recent_records(conn):
        print(row)

    conn.close()

Over time, this dataset can reveal whether irrigation events are reducing water stress, whether thresholds are too aggressive, and whether soil moisture responds predictably after watering.

Back to top ↑

Irrigation Data Model

A smart irrigation system should store more than the latest moisture value. Good irrigation data includes sensor identity, location, calibration information, control state, water-event history, and environmental context.

Field Example Purpose
timestamp_utc 2026-05-28T09:15:00Z Creates a consistent time reference for analysis
location_id greenhouse_bed_02 Identifies the irrigation zone or growing bed
sensor_id soil_node_01 Links readings to specific hardware
raw_soil_value 24500 Preserves the raw ADC-derived signal for debugging
moisture_percent 31.5 Estimated calibrated moisture value
valve_open 1 Records whether irrigation was active
irrigation_duration_seconds 30 Documents how long water was applied
weather_delay false Records whether forecast conditions prevented irrigation
quality_flag valid Marks readings as valid, suspect, demo, calibration-needed, or missing
notes sensor moved deeper after test Preserves field and maintenance context

A consistent data model helps turn irrigation from an automatic action into a learning system. Growers can see when water was applied, how soil responded, and whether thresholds should be adjusted.

Back to top ↑

Weather-Aware Irrigation Scheduling

More advanced irrigation controllers incorporate weather data to avoid unnecessary watering during expected rainfall events. Forecast-aware irrigation becomes much more resilient than schedule-based watering because it responds to both current soil conditions and expected environmental change.

The following example uses a public weather API-style workflow to check whether rainfall is expected before allowing irrigation. It is written as scaffolding and should be adapted to the chosen weather source and local deployment context.

"""
Weather-Aware Irrigation Scheduling Example

Checks whether rainfall is expected before irrigation.

Notes:
- This example uses Open-Meteo-style public forecast data.
- Real deployments should handle API failures and local forecast uncertainty.
- Weather data should support, not replace, direct soil measurement.
"""

import requests


def forecast_rain_expected(
    latitude: float,
    longitude: float,
    hourly_threshold_mm: float = 1.0,
) -> bool:
    """
    Return True if near-term rain is expected above the threshold.

    This checks forecast precipitation values and determines whether irrigation
    should be delayed.
    """
    url = "https://api.open-meteo.com/v1/forecast"

    params = {
        "latitude": latitude,
        "longitude": longitude,
        "hourly": "precipitation",
        "forecast_days": 1,
    }

    response = requests.get(url, params=params, timeout=20)
    response.raise_for_status()

    data = response.json()
    precipitation_values = data.get("hourly", {}).get("precipitation", [])

    if not precipitation_values:
        return False

    # Look at the first several hourly forecast values.
    next_six_hours = precipitation_values[:6]

    return any(value >= hourly_threshold_mm for value in next_six_hours)


def should_delay_irrigation_for_weather(latitude: float, longitude: float) -> bool:
    """Wrapper for weather-aware irrigation decisions."""
    try:
        return forecast_rain_expected(latitude, longitude)
    except requests.RequestException as exc:
        print(f"Weather API error: {exc}")
        return False


if __name__ == "__main__":
    # Example coordinates near St. Louis, Missouri.
    rain_expected = should_delay_irrigation_for_weather(
        latitude=38.6,
        longitude=-90.2,
    )

    if rain_expected:
        print("Rain expected. Delay irrigation.")
    else:
        print("No meaningful rain expected. Soil-based irrigation may proceed.")

Weather-aware scheduling should be combined with local soil moisture sensing. Forecasts can be wrong, and rainfall can vary significantly across short distances. A responsible controller should use forecast data as one input rather than as final authority.

Back to top ↑

Extending the System with AI and Predictive Agriculture

Machine learning models can extend irrigation systems by analyzing historical environmental data and predicting crop water requirements or soil moisture trends.

Possible applications include:

  • predicting irrigation demand
  • detecting soil moisture anomalies
  • optimizing irrigation timing
  • estimating post-irrigation recovery patterns
  • identifying sensor drift or sensor failure
  • analyzing crop growth conditions across zones

The following lightweight example uses a rolling baseline to detect unusual soil moisture drops. It is a prototype heuristic rather than a complete agronomic model.

"""
Soil Moisture Anomaly Detector

Tracks recent moisture readings and flags unusually dry conditions relative
to a rolling local baseline.

This is a lightweight prototype heuristic for irrigation monitoring.
"""

from collections import deque
from statistics import mean


class SoilMoistureAnomalyDetector:
    """Detects unusual soil moisture drops relative to recent readings."""

    def __init__(self, window_size: int = 24, drop_threshold_percent: float = 15.0):
        self.window_size = window_size
        self.drop_threshold_percent = drop_threshold_percent
        self.recent_moisture = deque(maxlen=window_size)

    def add_reading(self, moisture_percent: float) -> dict:
        """
        Add a moisture reading and return anomaly diagnostics.

        A sharp drop may indicate rapid drying, sensor movement, leakage,
        irrigation failure, or unusual environmental stress.
        """
        if len(self.recent_moisture) == 0:
            baseline = moisture_percent
        else:
            baseline = mean(self.recent_moisture)

        drop = baseline - moisture_percent
        unusually_dry = drop >= self.drop_threshold_percent

        self.recent_moisture.append(moisture_percent)

        return {
            "moisture_percent": moisture_percent,
            "baseline_percent": baseline,
            "drop_percent": drop,
            "unusually_dry": unusually_dry,
        }


if __name__ == "__main__":
    detector = SoilMoistureAnomalyDetector(window_size=6, drop_threshold_percent=12.0)

    sample_values = [48, 47, 46, 46, 45, 44, 28]

    for value in sample_values:
        result = detector.add_reading(value)
        print(result)

Lightweight machine learning frameworks such as TensorFlow Lite can run on Raspberry Pi devices and provide predictive capabilities directly at the edge. This moves the system from reactive irrigation toward anticipatory agricultural management, but models must be validated against local soil, crop, weather, and irrigation conditions before they influence real decisions.

Back to top ↑

GitHub Repository

The article body includes the core monitoring, control, logging, weather, and analytics examples so the build remains readable. The full repository expands the project into a reproducible prototype package, including Python soil-moisture monitoring scripts, ADS1115 examples, relay-control workflows, SQLite irrigation logging, weather-aware scheduling scaffolding, deployment notes, and example irrigation datasets.

The repository contains the complete prototype build materials:

  • Python monitoring and control scripts
  • sensor setup documentation
  • relay-control examples
  • soil-moisture calibration notes
  • SQLite logging examples
  • weather API integration scaffolding
  • deployment notes
  • example irrigation datasets

Repository Structure

raspberry-pi-smart-irrigation-controller/

README.md
LICENSE
requirements.txt

src/
  read_soil_moisture.py
  control_irrigation.py
  log_irrigation.py
  weather_schedule.py
  moisture_anomaly.py

docs/
  setup_guide.md
  deployment_notes.md
  sensor_notes.md
  calibration.md
  safety_notes.md
  data_model.md

data/
  example_irrigation_readings.csv

hardware/

Engineers can clone the repository, fork the design, or download the complete project using GitHub’s Download ZIP feature. All materials are released under the MIT License to support reuse in research, education, agricultural prototyping, and environmental engineering work.

Back to top ↑

Smart Irrigation and Climate Resilience

As climate variability increases, agricultural systems must become more resilient to drought, heat stress, shifting rainfall patterns, and changing growing conditions.

Sensor-driven irrigation systems provide growers with the ability to monitor environmental conditions continuously and respond to water stress more effectively. This approach supports:

  • SDG 2: Zero Hunger by improving agricultural resilience and productivity
  • SDG 6: Clean Water and Sanitation by reducing unnecessary freshwater use
  • SDG 13: Climate Action by improving adaptation to drought and climate variability
  • SDG 9: Industry, Innovation and Infrastructure by demonstrating smart agricultural infrastructure

In practice, irrigation systems like this support broader adaptation strategies by helping agricultural systems respond more intelligently to local climate stress. They also create datasets that can be reviewed after the season: when water was applied, how soil responded, whether rainfall reduced irrigation demand, and whether thresholds need adjustment.

The strongest climate-resilience designs combine soil sensing with crop knowledge, weather information, water-use measurement, and local management judgment. Automation should support growers, not hide the complexity of water, soil, plant, and climate relationships.

Back to top ↑

Engineering Notes

A few technical considerations are especially important in this build:

  • ADC dependency: the Raspberry Pi requires an external ADC such as the ADS1115 for analog soil sensing.
  • Relay safety: irrigation control systems must avoid unintended switching on boot or fault conditions.
  • Threshold calibration: soil moisture values are only meaningful when interpreted against real soil conditions.
  • Sensor placement: one probe may not represent an entire bed, field, container, or irrigation zone.
  • Field deployment: enclosures, connectors, waterproofing, and power systems matter as much as code in agricultural environments.
  • Decision quality: better irrigation decisions come from combining current sensing with context such as weather, crop stage, soil type, and historical data.
  • Actuator reliability: pumps and valves must be tested under real hydraulic conditions before unattended use.
  • Data integrity: irrigation decisions should be logged so system behavior can be reviewed after the fact.

These constraints make the project more than a sensor demo. It becomes a prototype agricultural control system requiring calibration, validation, and responsible deployment.

Back to top ↑

Deployment Scope and Data-Quality Considerations

This prototype is designed for educational, experimental, greenhouse, garden, field-lab, and early-stage precision-agriculture work. It should not be treated as a field-hardened commercial irrigation controller or a substitute for agronomic expertise.

Data quality depends on sensor calibration, soil texture, soil salinity, sensor depth, root distribution, irrigation method, water distribution, drainage, rainfall, evapotranspiration, and plant type. A sensor inserted near a drip emitter may overestimate water availability; a sensor placed too far from the root zone may underestimate it.

These limitations do not make the system unhelpful. They define the appropriate scope of use: local observation, irrigation experimentation, educational prototyping, greenhouse automation, water-efficiency analysis, and early-stage agricultural data infrastructure.

Responsible data use also requires uncertainty. Moisture estimates should be labeled as calibrated estimates, not universal soil-water measurements. Thresholds should be tested and adjusted rather than assumed.

Back to top ↑

Failure Modes and Practical Risks

A useful irrigation-control article should explain not only how the system works, but how it can fail. Irrigation systems have physical consequences: too much water can damage plants, waste freshwater, promote disease, or cause runoff; too little water can stress crops and reduce yield.

  • Sensor misplacement: one sensor may not represent the root zone or the whole irrigation area.
  • Poor calibration: copied dry/wet values may produce misleading moisture percentages.
  • Soil variability: clay, sand, compost, potting mix, salinity, and compaction affect sensor response.
  • Relay default error: a relay may turn on unexpectedly during boot if active-low behavior is not handled correctly.
  • Valve failure: valves may stick open or closed under real pressure conditions.
  • Pump dry-run risk: pumps can be damaged if reservoirs run empty.
  • Water distribution error: soil near the sensor may be wet while other areas remain dry.
  • API failure: weather-aware logic may fail if the network or weather service is unavailable.
  • Power instability: voltage drops can cause reboots, missed logs, or incomplete irrigation cycles.
  • False confidence: automated watering may appear intelligent even when thresholds are poorly chosen.

These risks do not make the project unusable. They make calibration, supervised testing, physical inspection, and fail-safe behavior essential. A responsible irrigation controller should default to safe behavior, log decisions, and remain easy for a human to override.

Back to top ↑

Validation and Testing

To bring this project closer to engineering-grade documentation, validation should include:

  1. verify I2C communication with the ADS1115
  2. confirm that soil moisture readings change plausibly between wet and dry conditions
  3. calibrate wet and dry sensor values for the actual soil and deployment depth
  4. test relay control safely without the irrigation load first
  5. validate valve or pump behavior under real hydraulic conditions
  6. confirm that irrigation stops reliably after the intended duration
  7. verify that threshold-based irrigation triggers only under intended conditions
  8. test weather-aware scheduling logic if forecast integration is used
  9. check SQLite logging across repeated observations and irrigation events
  10. evaluate post-irrigation soil moisture response at multiple points, not only near the sensor

If the system irrigates inconsistently, the issue may be related to sensor placement, threshold calibration, relay behavior, valve pressure, power stability, drainage, uneven water distribution, or environmental assumptions rather than to the control concept itself.

Example Validation Record

Test Expected Result Observed Result Likely Issue Action
ADS1115 I2C scan ADC appears on I2C bus Device appears at 0x48 None Proceed to sensor test
Dry calibration Stable dry reading Raw value fluctuates Loose wiring or unstable sensor placement Secure wiring and repeat test
Wet calibration Reading changes after watering Small change only Sensor not in wetted zone Move sensor into root-zone area
Relay test Valve remains off at startup Valve briefly opens Active-low relay initialization Correct startup logic and hardware fail-safe
Post-irrigation response Moisture rises after watering No response Emitter not reaching sensor or valve failure Inspect water distribution

A validation record like this helps separate software logic from physical irrigation behavior. That distinction is essential in any system that controls water.

Back to top ↑

Suggested Performance Metrics

For a more rigorous evaluation, the controller can be assessed using several simple metrics:

  • sensor stability: consistency of soil moisture readings under unchanged conditions
  • calibration quality: whether estimated moisture values correspond to real wet and dry conditions
  • trigger reliability: whether irrigation occurs only when intended
  • water-use efficiency: whether the system reduces unnecessary irrigation compared with fixed scheduling
  • post-irrigation response: whether soil moisture rises predictably after watering
  • logging reliability: whether observations and irrigation events are stored without loss
  • system uptime: how consistently the controller operates without intervention
  • weather-delay usefulness: whether forecast-aware delays actually reduce unnecessary watering
  • maintenance burden: how often sensors, tubing, valves, wiring, or enclosures require attention

Even simple tracking of these metrics improves the project’s value as a precision agriculture prototype. A smart irrigation system should be evaluated by whether it improves water decisions, not merely by whether it turns a relay on and off.

Back to top ↑

Field Deployment, Water Distribution, Power, and Maintenance

Field deployment is where irrigation prototypes often become difficult. Soil, water, power, roots, insects, pumps, valves, tubing, sunlight, rain, and seasonal change all introduce reliability problems that do not appear on a workbench.

Responsible deployment should address:

  • weather-resistant enclosures for electronics
  • strain relief and sealed connectors
  • safe routing of low-voltage and pump/valve wiring
  • sensor placement within the active root zone
  • multiple sensors for larger beds or uneven irrigation zones
  • valve and pump testing under real pressure conditions
  • reservoir-level monitoring where pumps are used
  • flow measurement where water-use accounting matters
  • manual override and shutdown capability
  • regular inspection of tubing, emitters, leaks, and clogging

Maintenance is not separate from smart irrigation. A clogged emitter, shifted sensor, failing relay, dead pump, or dried reservoir can make the software appear wrong when the physical system is failing. Logs should therefore be paired with physical inspection notes.

Back to top ↑

The Future of Precision Agriculture

Precision agriculture technologies are increasingly combining:

  • sensor networks
  • satellite imagery
  • weather forecasts
  • machine learning models
  • automated farm equipment
  • soil and crop analytics
  • decision-support dashboards
  • water-use optimization tools

Platforms such as Raspberry Pi make it possible for researchers, students, educators, and agricultural innovators to prototype these systems at relatively low cost. Projects like this demonstrate how accessible computing technologies can support more sustainable agricultural systems.

The long-term challenge is not merely automating irrigation. It is building agricultural systems that are observable, adaptive, efficient, and resilient under real conditions of climate stress, freshwater constraint, and food-system demand.

That future should remain socially and ecologically grounded. Precision agriculture can improve efficiency, but it should also support small growers, reduce unnecessary resource use, protect soils and watersheds, and avoid becoming a technology layer that deepens inequality or hides environmental costs.

Back to top ↑

Responsible Deployment

This prototype is appropriate for classrooms, makerspaces, greenhouses, gardens, field labs, community agriculture projects, and early-stage precision-agriculture experiments. It should not be used as an unattended field-scale irrigation controller without substantial validation, physical safety review, and fail-safe design.

Responsible deployment means matching the system to the consequence of error. A classroom test can tolerate rough readings and a simulated relay. A greenhouse, garden, or field plot requires safe wiring, tested valves, calibrated sensors, visible overrides, leak awareness, and inspection. A commercial or unattended system requires much more robust engineering.

A responsible version should include clear sensor calibration, documented thresholds, flow or water-use measurement where possible, manual override, lockout timing, valve fail-safe behavior, maintenance logs, and conservative defaults. If the system fails, it should fail safely rather than flooding plants, wasting water, or damaging equipment.

The central rule is simple: automation should make water stewardship more careful, not less accountable.

Back to top ↑

Reproducibility

All code, documentation, and supporting build materials necessary to reproduce the prototype are included in the project repository. The design intentionally relies on widely available Raspberry Pi hardware, open-source Python libraries, and common agricultural sensing components so that it can be rebuilt in classrooms, labs, greenhouses, gardens, makerspaces, and independent field projects.

The system is intended as a reference implementation rather than a field-hardened commercial irrigation controller. Engineers adapting it for long-term deployment should validate enclosures, power systems, valve safety, sensor calibration, water distribution, weather integration, data retention, and local operating conditions.

For the rest of this project series, reproducibility should mean more than making code available. Each article should include a clear bill of materials, setup instructions, validation notes, data model, known failure modes, test procedure, responsible-use framing, and realistic statement of appropriate scope.

Back to top ↑

Conclusion

Building a Raspberry Pi smart irrigation controller demonstrates how embedded sensing and edge computing can support sustainable agriculture. By combining soil moisture monitoring, environmental telemetry, automated valve control, local logging, and optional weather-aware scheduling, the system creates a flexible platform for water-aware agricultural management.

Although compact, the design reflects a broader sustainability principle: agricultural resilience depends on environmental visibility. When water conditions can be measured clearly and irrigation decisions can respond dynamically, food systems become more efficient and better adapted to climate stress.

For classrooms, makerspaces, greenhouses, gardens, field labs, community agriculture projects, and early-stage precision-agriculture experiments, this Raspberry Pi smart irrigation controller provides a practical foundation for understanding how sensing, data infrastructure, and water stewardship can work together.

The deeper lesson is not simply that a Raspberry Pi can turn on a pump. The deeper lesson is that agricultural water management requires feedback: calibrated sensors, safe actuation, weather context, irrigation records, post-watering response, physical inspection, and responsible interpretation. When those layers are treated seriously, even a small prototype can demonstrate the logic of more resilient agricultural infrastructure.

Back to top ↑

Further Reading

Back to top ↑

References

Back to top ↑

Scroll to Top