Skip to content

Project 3.9.3: Smart Agriculture Data Lake

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

Overview

The Pico collects multi-sensor agriculture records, stores them locally in a structured file, and can optionally upload them to a local endpoint.

Agriculture data is less valuable when it is not stored in a consistent structure that can be reused for later analysis.

A Pico 2 W prototype with a soil moisture sensor, BME280, LDR, local JSON-lines storage, and optional Wi-Fi upload.

Structured data capture, local-first logging, and honest data-lake-style wording for a classroom prototype.

Required Components

Raspberry Pi Pico 2 W
Raspberry Pi Pico 2 W
Soil sensor
Soil sensor
Breadboard
Breadboard
Jumper wires
Jumper wires
LDR
LDR
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
LDR divider midpoint GPIO 27 ADC1 GPIO 27 / physical pin 32 Light 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
---

Wiring Diagram

smart agriculture data lake

  Soil sensor AO -> GPIO 26
  LDR divider midpoint -> GPIO 27
  BME280 SDA -> GPIO 20
  BME280 SCL -> GPIO 21
  BME280 VCC -> 3.3V
  BME280 GND -> GND
  Wi-Fi uses the Pico 2 W radio and needs no extra wiring

Step-by-Step Assembly

  1. Connect the soil moisture sensor analog output to GPIO 26.
  2. Build the LDR divider and connect its midpoint to GPIO 27.
  3. Connect the BME280 to Pico 3.3V, GND, GPIO 20 (SDA), and GPIO 21 (SCL).
  4. Enter the Wi-Fi credentials and local endpoint only after the local record file is being created correctly.

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 each sensor separately so the resulting records are based on believable local values.
  3. Test the output device: Write a short test file to the Pico so the local storage path is confirmed before any upload step.
  4. Test the decision logic: Confirm that each loop creates one complete record with the expected fields.
  5. Run the full system: Run the full logger and compare the local file records with any uploaded copies.
  6. Validate the prototype: Review whether the record structure is detailed enough for later analysis.
  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.

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

SOIL_PIN = 26
LIGHT_PIN = 27
BME_SDA_PIN = 20
BME_SCL_PIN = 21
LOG_FILE = 'agri_297.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 = ADC(SOIL_PIN)
light = ADC(LIGHT_PIN)
i2c = I2C(0, sda=Pin(BME_SDA_PIN), scl=Pin(BME_SCL_PIN), freq=400000)
climate = bme280.BME280(i2c=i2c)


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\n'
        'Host: {}\r\n'
        'Content-Type: application/json\r\n'
        'Content-Length: {}\r\n'
        'Connection: 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('Agriculture data lake prototype ready')

while True:
    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

    record = {
        'schema_version': 1,
        'device_id': 'agri_297',
        'uptime_s': time.ticks_ms() // 1000,
        'soil_raw': soil.read_u16(),
        'light_raw': light.read_u16(),
        'temperature_c': temperature,
        'pressure_hpa': pressure,
        'humidity_pct': humidity,
    }

    append_record(record)
    uploaded = upload_record(record)
    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
Structured record schema Creates one record shape with schema_version and device_id fields A data-lake-style workflow depends on consistent records Add or remove fields only when you can keep the schema documented
append_record Stores each record locally in JSON-lines format Local storage is the safest first step before networking is trusted Inspect the log file regularly during testing
upload_record Optionally sends the same record to a local server This keeps the local and uploaded data structures aligned Enable upload only after local logging works correctly
Main loop Collects sensor values, creates the record, stores it, and optionally uploads it Students can validate both data quality and data workflow from one loop Keep the interval long enough that the file and serial output stay readable

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 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
Records are missing fields The BME280 read failed or the record dictionary was changed incorrectly Print the record each loop and verify every field before uploading it
The local file never grows The Pico file system write failed Test a simple text write first and confirm storage is working
Uploads always fail Wi-Fi is disabled or the endpoint is wrong Check UPLOAD_ENABLED, the credentials, and the server path
Light or soil values look constant The analog wiring or divider is incorrect Print the raw ADC values and vary the physical conditions during testing