Skip to content

Project 3.9.4: Smart Agriculture Digital Platform

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

Overview

The Pico creates structured agriculture records locally and can optionally upload them to a local network endpoint for dashboard testing.

Digital platforms are not useful if the field node cannot preserve trustworthy local records and explain what each data field means.

A Pico 2 W prototype with a soil moisture sensor, BME280, status LED, local data log, and optional Wi-Fi upload.

Local-first farm records, optional network communication, and honest platform-prototype design.

Required Components

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

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
BME280 SCL GPIO 21 GPIO 21 / physical pin 27 I2C0 SCL
LED anode 220 ohm resistor to GPIO 16 GPIO 16 / physical pin 21 Activity LED
---

Wiring Diagram

Circuit Diagram

Soil sensor AO -> GPIO 26
BME280 SDA -> GPIO 20
BME280 SCL -> GPIO 21
GPIO 16 -> 220 ohm resistor -> LED anode
Common GND -> soil sensor, BME280, and LED
BME280 VCC -> 3.3V
BME280 GND -> GND

Diagram Placeholder [Insert wiring diagram or breadboard image here]


Step-by-Step Assembly

  1. Connect the soil sensor analog output to GPIO 26 and note that you will calibrate wet and dry references later.
  2. Connect the BME280 to Pico 3.3V, GND, GPIO 20 (SDA), and GPIO 21 (SCL).
  3. Wire the LED to GPIO 16 through a 220 ohm resistor and connect the LED cathode to ground.
  4. Enter Wi-Fi credentials and local server settings only after the local log file is working correctly.
  5. Measure dry and wet soil references before trusting the dryness percentage field.

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 each record field has a believable baseline.
  3. Test the output device: Blink the LED and test local file writing before enabling optional upload.
  4. Test the decision logic: Confirm that one loop creates one record and that the irrigation recommendation changes logically with the sensor values.
  5. Run the full system: Run the full node and compare local records with any uploaded copies to a local server.
  6. Validate the prototype: Disable Wi-Fi and confirm the node still logs records locally so the prototype remains useful offline.
  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.

Upload and run this code after the individual tests work correctly.

import bme280
import network
import socket
import time
import ujson as json
from machine import ADC, I2C, Pin

SOIL_PIN = 26
BME_SDA_PIN = 20
BME_SCL_PIN = 21
LED_PIN = 16
LOG_FILE = 'agri_329.jsonl'
UPLOAD_ENABLED = False
WIFI_SSID = 'YOUR_WIFI'
WIFI_PASSWORD = 'YOUR_PASSWORD'
SERVER_HOST = '192.168.1.50'
SERVER_PORT = 8000
SERVER_PATH = '/agriculture'
INTERVAL_S = 60
SOIL_DRY_RAW = 48000
SOIL_WET_RAW = 18000

soil = ADC(SOIL_PIN)
i2c = I2C(0, sda=Pin(BME_SDA_PIN), scl=Pin(BME_SCL_PIN), freq=400000)
climate = bme280.BME280(i2c=i2c)
led = Pin(LED_PIN, Pin.OUT)


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


def dryness_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)


def connect_wifi(timeout_s=15):
    wlan = network.WLAN(network.STA_IF)
    if wlan.isconnected():
        return wlan
    wlan.active(True)
    wlan.connect(WIFI_SSID, WIFI_PASSWORD)
    for _ in range(timeout_s):
        if wlan.isconnected():
            return wlan
        time.sleep(1)
    return None


def append_record(record):
    try:
        with open(LOG_FILE, 'a') as handle:
            handle.write(json.dumps(record) + '\n')
    except OSError:
        print('Could not write local record')


def upload_record(record):
    if not UPLOAD_ENABLED:
        return False
    wlan = connect_wifi()
    if wlan is None:
        return False
    address = socket.getaddrinfo(SERVER_HOST, SERVER_PORT)[0][-1]
    body = json.dumps(record)
    request = 'POST {} HTTP/1.1\r\nHost: {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}'.format(
        SERVER_PATH,
        SERVER_HOST,
        len(body),
        body,
    )
    sock = socket.socket()
    try:
        sock.connect(address)
        sock.send(request.encode())
        sock.recv(128)
        return True
    finally:
        sock.close()


print('Smart agriculture digital platform prototype ready')

while True:
    dry_pct = dryness_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 Exception:
        temperature = 0
        pressure = 0
        humidity = 0

    if dry_pct >= 65:
        recommendation = 'IRRIGATE'
    elif dry_pct >= 40:
        recommendation = 'MONITOR'
    else:
        recommendation = 'HOLD'

    record = {
        'schema_version': 1,
        'device_id': 'agri_329',
        'uptime_s': time.ticks_ms() // 1000,
        'dryness_pct': dry_pct,
        'temperature_c': temperature,
        'humidity_pct': humidity,
        'irrigation_recommendation': recommendation,
    }

    append_record(record)
    uploaded = upload_record(record)
    led.value(1)
    time.sleep_ms(120)
    led.value(0)
    print(record, 'uploaded' if uploaded else 'local_only')
    time.sleep(INTERVAL_S)

How the Code Works

Code Section What It Does Why It Matters What to Modify During Testing
Record schema Creates one documented agriculture record with sensor values and an action recommendation. A platform-ready node starts with a trustworthy local record format. Add fields only when you can test and document them clearly.
append_record Stores every record locally in JSON-lines format. Local storage protects the project from network failure during testing. Inspect the log file before assuming upload problems are the main issue.
upload_record Optionally sends the same record to a local HTTP endpoint. This demonstrates digital-platform readiness without overclaiming a finished service. Enable upload only after the local records look correct.
Recommendation field Adds a simple irrigation action to each record. The record becomes more useful when it includes both measurements and an interpretable action. Recalibrate the dryness thresholds after measuring your own soil sensor.

Expected Result

The serial monitor prints one agriculture record per interval with dryness, temperature, humidity, and irrigation recommendation fields.

The Pico stores the record locally even if Wi-Fi or the local endpoint is unavailable.

When upload is enabled and working, the same record can be compared with the server copy for validation.

Validation Checks

  • Normal condition test: confirm that one record is written locally each interval under stable conditions.
  • Sensor validation test: change soil moisture and confirm the dryness_pct field responds in the record.
  • Decision logic test: dry the soil and confirm the irrigation_recommendation changes from HOLD to MONITOR or IRRIGATE.
  • Communication validation test: enable upload and compare the uploaded payload with the local file entry.
  • Fallback test: disable Wi-Fi and confirm the node still logs locally without crashing.

Deployment and Limitations

  • This prototype is suitable for local pilots where sensor data must be logged or transmitted over short periods.
  • Before deployment, network reliability, power backup, and endpoint security need attention.
  • The system should keep useful local behavior even when communication fails.

Troubleshooting

Problem Possible Cause Solution
The log file stays empty Local file writing failed Test a simple text write and confirm the Pico file system is writable.
Uploads always fail The Wi-Fi credentials or server settings are wrong Check UPLOAD_ENABLED, Wi-Fi details, and the local endpoint path.
Dryness never changes The soil sensor wiring or calibration is wrong Print the raw soil value and re-measure the wet and dry references.
Climate fields stay at zero The BME280 read failed Test the BME280 separately and shorten the I2C wires if needed.