Skip to content

Project 2.6.20: Smart Irrigation Scheduling Ai

Intermediate Embedded Systems Project Using Raspberry Pi Pico 2 W and MicroPython


Overview

This project uses rule-based decision logic to choose when irrigation should happen based on more than one factor.

Students will build a rule-based AI-style scoring system, not a machine-learning model. The Pico combines several weighted rules and makes one watering decision from the total score.

The final system should calculate a decision score, explain the reasons behind it, and allow watering immediately after startup if the conditions already justify it.

Required Components

Soil moisture sensor
Soil moisture sensor
External power supply
External power supply
Raspberry Pi Pico 2 W
Raspberry Pi Pico 2 W
BME280 sensor module
BME280 sensor module
1-channel relay module
1-channel relay module
Small DC water pump
Small DC water pump
LED and 220 Ω resistor
LED and 220 Ω resistor
Breadboard, jumper wires, tubing, and water container
Breadboard

Circuit Connections

Component terminal Connect to Pico physical pin Notes
Soil sensor AOUT 1 GPIO 26 / physical pin 31 ADC moisture input
BME280 sensor module 1 Requires bme280.py on the Pico
1-channel relay module 1 GPIO 15 / physical pin 20 Verify active-low or active-high logic
Status LED anode GPIO 16 through 220 Ω resistor GPIO 16 / physical pin 21 Pump indicator
Status LED cathode GND Any GND pin LED return
Pump supply path 1 Not a Pico GPIO External power only
BME280 VCC 3.3V Physical pin 36 Sensor power
BME280 GND GND Any GND pin Common ground
BME280 SDA GPIO 2 GPIO 2 / physical pin 4 I2C data
BME280 SCL GPIO 3 GPIO 3 / physical pin 5 I2C clock

Wiring Diagram

Circuit Diagram

  Raspberry Pi Pico 2 W
  ┌─────────────────────┐
  │                     │
  │  GPIO 2  ───────────┤──── BME280 SDA
  │  GPIO 3  ───────────┤──── BME280 SCL
  │                     │
  │  GPIO 26 ───────────┤──── Soil Sensor AOUT
  │                     │
  │  GPIO 15 ───────────┤──── Relay IN
  │                     │
  │  GPIO 16 ────220Ω───┤──── Status LED (+)
  │                     │
  │  3.3V    ───────────┤──── Soil Sensor VCC
  │  3.3V    ───────────┤──── BME280 VCC
  │                     │
  │  GND     ───────────┤──── Soil Sensor GND
  │  GND     ───────────┤──── BME280 GND
  │  GND     ───────────┤──── Status LED (-)
  │  GND     ───────────┤──── Relay GND
  │                     │
  └─────────────────────┘

  Relay Module            External Supply
  ┌──────────┐            ┌────────────┐
  │  COM ────┼────────────┤ (+)        │
  │  NO  ────┼──┐         │            │
  │  VCC ────┼──┼─────────┤ (+) (if    │
  │  GND ────┼──┼──┐      │   needed)  │
  └──────────┘  │  │      │            │
                │  │      └────────────┘
                │  │           │
                │  └───────────┘
                │         Pump (+)
                │
                └────────────── Pump (-) ──── External Supply (-)

Step-by-Step Assembly

Step 1: Place the Raspberry Pi Pico 2W

Place the Raspberry Pi Pico 2W on the breadboard so it sits across the center gap. Keep the USB port facing outward so you can easily connect it to your computer.

Step 2: Position the Soil Moisture Sensor

Place the soil moisture probe so the sensing end can enter the soil sample. Identify VCC, GND, and AOUT / AO / Signal before wiring.

Step 3: Connect the Soil Sensor

Connect soil sensor VCC to 3.3V. Connect soil sensor GND to GND. Connect soil sensor AOUT, AO, or Signal to GPIO 26 (ADC0).

Step 4: Place the BME280 Sensor Module

Identify BME280 VCC, GND, SDA, and SCL before wiring. Connect BME280 VCC to 3.3V. Connect BME280 GND to GND. Connect BME280 SDA to GPIO 2 and BME280 SCL to GPIO 3. If you are using a bare BME280 sensor, use the module pins labeled VCC, GND, SDA, and SCL.

Step 5: Place and Wire the Relay Module

Identify relay VCC, GND, IN, COM, NO, and NC. Connect relay IN to GPIO 15. Power the relay module from the supply required by its label. Connect relay GND to Pico GND and to the external pump supply GND where shared grounding is required.

Step 6: Place the Status LED

Place the status LED on the breadboard. Connect its long leg through a 220Ω resistor to GPIO 16. Connect its short leg to GND.

Step 7: Wire the Pump Through the Relay

Connect the external pump supply positive wire to relay COM. Connect relay NO to the pump positive lead. Connect the pump negative lead to the external pump supply negative wire.

Step 8: Confirm the Pump Position

Place the pump intake safely before powering the system, because the code can decide to water after startup.

Wiring Check

  • [x] Pico 2W is placed correctly across the breadboard center gap
  • [x] Soil sensor AOUT / AO / Signal connects to GPIO 26
  • [x] DHT22 DATA connects to GPIO 4
  • [x] Relay IN connects to GPIO 15
  • [x] Status LED long leg connects through a 220Ω resistor to GPIO 16
  • [x] Status LED short leg connects to GND
  • [x] Pump positive path uses relay COM and NO
  • [x] Pump negative connects to external pump supply negative
  • [x] No loose jumper wires

Intermediate Note This project uses rule-based AI logic, not machine learning. Test dry and wet soil readings before trusting the score, and allow BME280 readings time to settle.

Safety Note Do not power the pump from the Pico. Use an external pump supply, keep electronics away from water, and test the relay with a safe load before the real pump.


Testing Individual Components

Before running the full project, test each part separately. This makes it easier to find wiring, library, or code problems.

Hardware Setup

  • Build the soil, BME280, LED, and relay wiring before any live pump test
  • Keep the water path ready before power-up because the startup logic allows immediate watering if justified

Test the Input Sensor

  • Calibrate the soil sensor and test the BME280 temperature reading separately
  • Confirm that both values change in believable ways before trusting the decision score

Test the Output Device

  • Test the relay and status LED before connecting the real pump
  • Use a short pump run time during the first live test

Run the Full System

  • Upload the final code and observe the printed score and reasons
  • Check that the controller can water immediately on startup if the soil is already dry enough and the time rule allows it
  • Compare how the score changes when temperature changes or when the soil moisture recovers

Save the Project

  • Save the final code and record the rule weights and thresholds used in your test
  • Write down which rules had the biggest influence on the watering decision

Additional Testing and Calibration Checks

Calibration and tuning notes

  • Verify the startup behaviour carefully; this project is intentionally allowed to water immediately if the rules say it should
  • Test the moisture and temperature effects separately so you can see how each rule changes the score
  • If the score always stays too high or too low, adjust the rule weights rather than only one threshold
  • Remember that this is a rule-based AI demonstration, so the quality depends on the rules you chose

Quick testing checklist

  • [ ] Soil and temperature readings appear correctly
  • [ ] The score changes when the environment changes
  • [ ] Reasons explain why the score increased or decreased
  • [ ] The system can water immediately after startup when justified
  • [ ] Watering updates the schedule so recent cycles reduce the next score

Full Project Code

After completing and checking the circuit connections, open Thonny IDE. Copy and paste the code below into a new file, or upload the project file to the Raspberry Pi Pico 2 W, then run it from Thonny.

from machine import ADC, I2C, Pin
import bme280
import time

RELAY_ON = 0
RELAY_OFF = 1
PUMP_RUN_S = 5
HOURS_BETWEEN = 12

soil = ADC(26)
i2c_bme = I2C(1, sda=Pin(2), scl=Pin(3), freq=400000)
bme = bme280.BME280(i2c=i2c_bme)


def number_from_bme(text_value):
    cleaned = "".join(ch for ch in str(text_value) if ch.isdigit() or ch in ".-")
    return float(cleaned)


def read_bme280():
    temp_text, pressure_text, humidity_text = bme.values
    return number_from_bme(temp_text), number_from_bme(humidity_text), number_from_bme(pressure_text)


relay = Pin(15, Pin.OUT)
status_led = Pin(16, Pin.OUT)

soil_dry = 52000
soil_wet = 22000
moisture_critical = 20
moisture_low = 35
moisture_recovery = 45
temp_hot = 32
temp_cold = 15

last_watered = time.time() - (HOURS_BETWEEN * 3600)

relay.value(RELAY_OFF)
status_led.value(0)


def clamp(value, low, high):
    if value < low:
        return low
    if value > high:
        return high
    return value


def moisture_percent():
    raw = soil.read_u16()
    span = soil_dry - soil_wet
    if span == 0:
        return 0
    percent = int(((soil_dry - raw) * 100) / span)
    return clamp(percent, 0, 100)


def temperature_value():
    temp_c, humidity, pressure_hpa = read_bme280()
    return temp_c


def decision_score(moisture, temp_c, hours_since):
    score = 0
    reasons = []

    if moisture <= moisture_critical:
        score += 55
        reasons.append("critical dry soil")
    elif moisture <= moisture_low:
        score += 30
        reasons.append("low soil moisture")
    elif moisture >= moisture_recovery:
        score -= 20
        reasons.append("soil recovered")

    if hours_since < HOURS_BETWEEN:
        score -= 25
        reasons.append("recent watering")

    if temp_c >= temp_hot:
        score += 20
        reasons.append("hot weather")
    elif temp_c <= temp_cold:
        score -= 10
        reasons.append("cold weather")

    return clamp(score, 0, 100), reasons


def water_once():
    global last_watered
    relay.value(RELAY_ON)
    status_led.value(1)
    print("Pump ON: decision score requested watering")
    time.sleep(PUMP_RUN_S)
    relay.value(RELAY_OFF)
    status_led.value(0)
    last_watered = time.time()
    print("Pump OFF: timed cycle complete")


print("Smart irrigation scheduling AI ready")

while True:
    moisture = moisture_percent()
    try:
        temp_c = temperature_value()
    except Exception:
        temp_c = 25

    hours_since = (time.time() - last_watered) / 3600
    score, reasons = decision_score(moisture, temp_c, hours_since)

    print("Moisture:{}% Temp:{}C HoursSince:{:.1f}".format(moisture, temp_c, hours_since))
    print("Decision score:{} Reasons:{}".format(score, ", ".join(reasons) if reasons else "none"))

    if score >= 60:
        water_once()
    else:
        print("Decision: wait")

    time.sleep(60)

How the Code Works

Code Section 1 Why It Matters
last_watered initialisation 1 This allows immediate watering at startup when conditions justify it
decision_score() 1 The project uses rule-based AI logic rather than machine learning
Reasons list 1 Students can inspect why a decision happened
water_once() 1 Time-aware scheduling only works if each cycle updates the schedule state

Expected Result

The system should print a moisture reading, a temperature reading, a decision score, and the reasons behind that score. If the score is high enough, the pump should run for one timed cycle. Because last_watered is initialised with a startup offset, the project can water immediately after boot if the rules support that decision.


Troubleshooting

Problem Possible cause Solution
The system never waters on startup 1 Use last_watered = time.time() - (HOURS_BETWEEN * 3600)
The score is always high 1 Review the scoring weights and compare the live sensor values with the thresholds
The score is always low 1 Adjust HOURS_BETWEEN or reduce the negative weight for recent watering
The reasons list is confusing 1 Test one condition at a time and print the sensor values beside the reasons