Skip to content

Project 3.9.14: Smart Agriculture Predictive Analytics

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

Overview

The Pico tracks soil and climate trends, then predicts whether irrigation demand is likely to rise soon.

Agriculture planning becomes reactive when learners watch only the current reading instead of the trend leading up to it.

A Pico 2 W prototype with a soil moisture sensor, BME280, and OLED predictive-analytics dashboard.

Trend-based interpretation, irrigation-demand prediction, and honest forecasting language.

Required Components

Raspberry Pi Pico 2 W
Raspberry Pi Pico 2 W
Soil sensor
Soil sensor
Breadboard
Breadboard
Jumper wires
Jumper wires
BME280
BME280
OLED
OLED
---

Circuit Connections

Component terminal Connect to Pico physical pin Notes
Soil sensor AO GPIO 26 ADC0 GPIO 26 / physical pin 31 Soil input
BME280 VCC 3.3V output Physical pin 36 Sensor power
BME280 GND GND Physical pin 38 Common ground
BME280 SDA GPIO 20 GPIO 20 / physical pin 26 I2C0 SDA shared with OLED
BME280 SCL GPIO 21 GPIO 21 / physical pin 27 I2C0 SCL shared with OLED
OLED SDA GPIO 20 GPIO 20 / physical pin 26 I2C0 SDA
OLED SCL GPIO 21 GPIO 21 / physical pin 27 I2C0 SCL
---

Wiring Diagram

Circuit Diagram

  Soil sensor AO -> GPIO 26
  BME280 SDA -> GPIO 20
  BME280 SCL -> GPIO 21
  GPIO 20 -> OLED SDA
  GPIO 21 -> OLED SCL
  BME280 VCC -> 3.3V
  BME280 GND -> GND

Step-by-Step Assembly

  1. Connect the soil sensor analog output to GPIO 26.
  2. Connect the BME280 to Pico 3.3V, GND, GPIO 20 (SDA), and GPIO 21 (SCL).
  3. Connect the OLED to Pico 3.3V, GND, GPIO 20, and GPIO 21.
  4. Upload ssd1306.py and confirm it appears on the Pico before running the dashboard.
  5. Record dry and wet soil baselines before trusting the dryness percentage.

Testing Individual Components

Before running the full project, test each subsystem separately. This makes it easier to find wiring, library, or logic problems before full integration.

  1. Hardware setup: Assemble the Pico, sensor, indicator, and load wiring exactly as shown in the connection table before applying power.
  2. Test the input sensor: Test the soil sensor and BME280 separately so the trend window starts from believable data.
  3. Test the output device: Run an OLED hello-world test before adding the predictive logic.
  4. Test the decision logic: Dry the soil gradually or increase temperature and confirm the demand prediction changes after the history window fills.
  5. Run the full system: Run the full dashboard and compare the prediction with the live sensor trend.
  6. Validate the prototype: Discuss how sample interval and calibration affect the usefulness of the prediction.
  7. Save the project: Save the validated program on the Pico as main.py and keep a copy on the computer for future edits.

Full Project Code

After completing and checking the circuit connections, open Thonny IDE, copy and paste this code 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

try:
    from ssd1306 import SSD1306_I2C
    HAS_OLED = True
except ImportError:
    HAS_OLED = False

SOIL_PIN = 26
BME_SDA_PIN = 20
BME_SCL_PIN = 21
I2C_SDA_PIN = 20
I2C_SCL_PIN = 21
SOIL_DRY_RAW = 48000
SOIL_WET_RAW = 18000
HISTORY_LENGTH = 6

soil = ADC(SOIL_PIN)
i2c = I2C(0, sda=Pin(BME_SDA_PIN), scl=Pin(BME_SCL_PIN), freq=400000)
climate = bme280.BME280(i2c=i2c)
if HAS_OLED:
    oled = SSD1306_I2C(128, 64, i2c)

history = []


def clamp(value, low, high):
    return max(low, min(high, value))


def dry_percent(raw):
    span = SOIL_DRY_RAW - SOIL_WET_RAW
    if span <= 0:
        return 0
    pct = int((raw - SOIL_WET_RAW) * 100 / span)
    return clamp(pct, 0, 100)


print('Agriculture predictive analytics ready')

while True:
    dry_pct = dry_percent(soil.read_u16())
    try:
        values = climate.values
        temperature = float(values[0].replace('C', ''))
        pressure = float(values[1].replace('hPa', ''))
        humidity = float(values[2].replace('%', ''))
    except OSError:
        temperature = 0

    history.append((dry_pct, temperature))
    history = history[-HISTORY_LENGTH:]

    if len(history) >= 2 and (history[-1][0] - history[0][0] >= 15 or history[-1][1] - history[0][1] >= 3):
        prediction = 'DEMAND RISING'
    else:
        prediction = 'STABLE'

    print('Dry:{}% Temp:{}C Prediction:{}'.format(dry_pct, temperature, prediction))

    if HAS_OLED:
        oled.fill(0)
        oled.text('Agri Trend', 0, 0)
        oled.text('Dry:{}%'.format(dry_pct), 0, 18)
        oled.text('Temp:{}C'.format(temperature), 0, 34)
        oled.text(prediction[:16], 0, 50)
        oled.show()

    time.sleep(5)

How the Code Works

Code Section What It Does Why It Matters What to Modify During Testing
History tracking Stores recent dryness and temperature values for trend comparison Prediction depends on recent change, not one isolated reading Adjust HISTORY_LENGTH after testing the stability you want
Trend rule Reports DEMAND RISING when dryness or heat increases clearly across the history window This gives the user an honest predictive-analytics label without overclaiming full forecasting Tune the trend deltas after repeated dry and warm test cases
OLED dashboard Shows current conditions and the current prediction on one screen The dashboard helps students compare the raw values with the prediction If the display fails, verify ssd1306.py and the I2C wiring first

Expected Result

The serial monitor reports the current reading or state clearly.

The hardware output responds when the decision logic changes state.

Subsystem behavior matches the thresholds, timing, or rules described in the document.

Validation Checks

  • Normal condition test: confirm the system stays in its safe or idle state under baseline conditions
  • Warning condition test: move the input close to the chosen threshold and confirm the transition is sensible
  • Critical condition test: trigger the strongest alert or control state and confirm the output response is correct
  • Calibration test: compare the sensor or timing against a known reference or repeated trial
  • Limitation test: deliberately create an awkward or noisy condition and note how the prototype behaves

Deployment and Limitations

  • This prototype works well for classroom demonstrations and local monitoring pilots
  • Before deployment, it needs calibration records, protective mounting, and regular validation checks
  • Display-only systems still depend on correct sensor placement and trained users

Troubleshooting

Problem Possible Cause Solution
Prediction never changes The history window is too strict or the conditions are not changing enough Create clearer dry or warm conditions or lower the trend threshold slightly
Dryness is always 0 or 100 The soil calibration values are wrong Re-measure dry and wet reference values and update the constants
Temperature is always zero The BME280 read failed Test the BME280 separately and shorten the I2C wires if needed
OLED is blank The display library or I2C wiring is wrong Confirm ssd1306.py is present and recheck GPIO 20 and GPIO 21