Skip to content

Project 2.6.1: Smart Agricultural Iot Hub

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


Overview

This project builds a local Wi-Fi hub that combines farm sensor readings and serves them to a browser and a simple JSON endpoint.

Students will combine a soil sensor, a BME280 sensor, Wi-Fi setup, a browser dashboard, and a machine-readable /api endpoint into one connected project.

The final system should connect to Wi-Fi, show an IP address, serve a live HTML dashboard, and return JSON data from an API endpoint that could be used by another dashboard later.

Required Components

Soil moisture sensor (analog output)
Soil moisture sensor (analog output)
Raspberry Pi Pico 2 W
Raspberry Pi Pico 2 W
BME280 sensor module
BME280 sensor module
Built-in Pico LED
Built-in Pico LED
Breadboard and jumper wires
Breadboard and jumper wires

Circuit Connections

Component terminal Connect to Pico physical pin Notes
Soil sensor VCC Physical pin 36 Physical pin 36 Sensor power
Soil sensor GND Any GND pin Any GND pin Common ground
Soil sensor AOUT GPIO 26 / physical pin 31 GPIO 26 / physical pin 31 Analog soil input
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 26 ───────────┤──── Soil Sensor AOUT
  │                     │
  │  GPIO 2  ───────────┤──── BME280 SDA
  │  GPIO 3  ───────────┤──── BME280 SCL
  │                     │
  │  3.3V    ───────────┤──── Soil Sensor VCC
  │  3.3V    ───────────┤──── BME280 VCC
  │                     │
  │  GND     ───────────┤──── Soil Sensor GND
  │  GND     ───────────┤──── BME280 GND
  │                     │
  │  Built-in LED (Wi-Fi status, no wiring needed)
  └─────────────────────┘

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 and Connect the Soil Sensor

Place the soil moisture probe so the sensing end can enter the soil sample. Connect soil sensor VCC to 3.3V. Connect soil sensor GND to GND. Connect soil sensor AOUT, AO, or Signal to GPIO 26.

Step 3: Place the BME280 Sensor Module

Place the BME280 module where it can sense the agricultural hub environment. Connect BME280 VCC to 3.3V. Connect BME280 GND to GND. Connect BME280 SDA to GPIO 2 and BME280 SCL to GPIO 3. If your BME280 is bare, use the module pins labeled VCC, GND, SDA, and SCL.

Step 4: Prepare for Wi-Fi Hub Testing

The built-in Pico LED is used for Wi-Fi connection state, so no extra status LED is needed. Prepare your Wi-Fi name and password in your local code copy before testing the hub page.

Wiring Check

  • [x] Pico 2W is placed correctly across the breadboard center gap
  • [x] Soil sensor VCC connects to 3.3V
  • [x] Soil sensor GND connects to GND
  • [x] Soil sensor AOUT / AO / Signal connects to GPIO 26
  • [x] BME280 SDA connects to GPIO 2 and SCL connects to GPIO 3
  • [x] Pico built-in LED is used for Wi-Fi status
  • [x] Pico 2W is connected to Wi-Fi for the IoT hub page
  • [x] No loose jumper wires

Intermediate Note When running the networking part, the Pico 2W must be connected to Wi-Fi. Keep real Wi-Fi credentials private and enter them only in your local copy of the code. Confirm local soil and BME280 readings before debugging the web page or JSON-style hub data.

Safety Note Do not pour water onto the Pico, breadboard, USB cable, or jumper wires. Keep the soil sample away from the USB connection.


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 and BME280 wiring before trying the Wi-Fi features
  • Check the power and ground connections carefully because both sensors depend on stable wiring

Test the Input Sensor

  • Record dry and wet soil values so the soil percentage is realistic
  • Read the BME280 locally in the Shell and confirm the temperature and humidity values look believable

Test the Output Device

  • Confirm the built-in LED blinks during connection and stays on after Wi-Fi connects
  • Check that the HTML page and JSON API both respond after the server starts

Test Communication

  • Open the printed IP address in a browser and confirm the dashboard loads
  • Then open /api and confirm that a JSON response appears instead of HTML

Run the Full System

  • Change soil and climate conditions and confirm both the HTML page and the JSON output update
  • Use the condition summary to explain the overall plant state in simple terms

Save the Project

  • Save the final code without exposing real credentials in any shared copy
  • Record the IP address behaviour and the condition rules that worked best on your network

Additional Testing and Calibration Checks

  • Dry/wet reading test: calibrate the soil sensor so the moisture percentage is realistic
  • Normal condition test: confirm the page and API both show stable readings when the environment is unchanged
  • Threshold condition test: change the soil or climate and confirm the condition summary updates
  • Wi-Fi setup test: ensure the Pico and the browser device are on the same 2.4 GHz network
  • Response test: open both / and /api and confirm they return the correct content type and live values
  • Calibration note: if the soil percentage direction is wrong, update SOIL_DRY and SOIL_WET using measured values

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.

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

WIFI_SSID = 'YOUR_WIFI_NAME'
WIFI_PASSWORD = 'YOUR_WIFI_PASSWORD'

soil_sensor = 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)


status_led = Pin('LED', Pin.OUT)

SOIL_DRY = 52000
SOIL_WET = 22000
REFRESH_SECONDS = 5


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


def soil_percent():
    raw = soil_sensor.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 read_environment():
    try:
        temp_c, humidity, pressure_hpa = read_bme280()
        return temp_c, humidity
    except Exception as error:
        print('BME28022 read error:', error)
        return None, None


def condition_summary(moisture, temp_c, humidity):
    if temp_c is None or humidity is None:
        return 'SENSOR ERROR'
    if moisture < 35 and temp_c > 30:
        return 'HOT AND DRY'
    if moisture < 35:
        return 'DRY'
    if humidity > 85:
        return 'TOO HUMID'
    return 'NORMAL'


def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('Connecting to Wi-Fi...')
        wlan.connect(WIFI_SSID, WIFI_PASSWORD)
        start = time.time()
        while not wlan.isconnected():
            status_led.value(1 - status_led.value())
            if time.time() - start > 20:
                raise RuntimeError('Wi-Fi connection timeout')
            time.sleep(0.5)
    status_led.value(1)
    print('Wi-Fi connected:', wlan.ifconfig()[0])
    return wlan


def latest_data(ip_address):
    moisture = soil_percent()
    temp_c, humidity = read_environment()
    return {
        'ip': ip_address,
        'soil_moisture_percent': moisture,
        'temperature_c': temp_c,
        'humidity_percent': humidity,
        'condition': condition_summary(moisture, temp_c, humidity),
        'timestamp': time.time()
    }


def html_page(data):
    temp_text = '--' if data['temperature_c'] is None else '{} C'.format(data['temperature_c'])
    humidity_text = '--' if data['humidity_percent'] is None else '{} %'.format(data['humidity_percent'])
    return """<!DOCTYPE html>
<html>
<head>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <meta http-equiv='refresh' content='{}'>
    <title>Smart Agricultural IoT Hub</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 20px; background: #f4fbf2; }}
        h1 {{ color: #21563a; }}
        .card {{ background: white; border-radius: 10px; padding: 14px; margin-bottom: 12px; box-shadow: 0 0 4px rgba(0,0,0,0.12); }}
        .state {{ font-weight: bold; color: #0d5c3f; }}
    </style>
</head>
<body>
    <h1>Smart Agricultural IoT Hub</h1>
    <div class='card'>IP Address: {}</div>
    <div class='card'>Soil Moisture: {}%</div>
    <div class='card'>Temperature: {}</div>
    <div class='card'>Humidity: {}</div>
    <div class='card state'>Condition: {}</div>
    <div class='card'>JSON API: <a href='/api'>/api</a></div>
</body>
</html>""".format(
        REFRESH_SECONDS,
        data['ip'],
        data['soil_moisture_percent'],
        temp_text,
        humidity_text,
        data['condition']
    )


wlan = connect_wifi()
ip_address = wlan.ifconfig()[0]
address = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
server = socket.socket()
server.bind(address)
server.listen(1)

print('Open http://{}/ in a browser on the same Wi-Fi network.'.format(ip_address))

while True:
    client, remote_address = server.accept()
    request = client.recv(1024).decode('utf-8')
    first_line = request.split('\r\n')[0] if request else ''
    data = latest_data(ip_address)

    if 'GET /api ' in first_line:
        response_body = json.dumps(data)
        client.send(b'HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n')
        client.sendall(response_body.encode())
    else:
        response_body = html_page(data)
        client.send(b'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n')
        client.sendall(response_body.encode())

    client.close()
    print('Served request from {} | Condition: {}'.format(remote_address, data['condition']))

How the Code Works

Code Section What It Does Why It Matters
Wi-Fi setup Connects the Pico 2 W to the local network and sets up the server Students need a stable connection before the hub can be tested
latest_data() Gathers the current sensor values into a single dictionary This is the hub behaviour that supports both HTML and JSON outputs
html_page() Builds a human-friendly dashboard page Human users can check the live farm status quickly from any device on the network
/api endpoint Returns the latest data as JSON when the /api path is requested This makes the project more like a real IoT hub that other tools could read later

Expected Result

After a successful Wi-Fi connection, the built-in LED should stay on and the Thonny Shell should show the IP address.

Opening the IP address in a browser should show a live dashboard with soil, temperature, humidity, and condition summary values.

Opening the /api path should show a JSON response containing the same data in machine-readable form.


Troubleshooting

Problem Possible cause Solution
The web page never loads Network connectivity issue Check the Shell for the IP address and ensure both devices are on the same 2.4 GHz network
The /api page is not JSON The request was not matching the /api route correctly Open the exact /api path and check the first request line printed in the serial log if needed
The dashboard shows missing climate values BME280 wiring or read timing issue Check the GPIO 2/3 wiring and the pull-up resistor if using a bare sensor
The moisture percentage is unrealistic Calibration values do not match the sensor Measure new dry and wet readings and update SOIL_DRY and SOIL_WET