Project 3.9.6: Smart Agriculture Future Lab
Advanced Embedded Systems Project Using Raspberry Pi Pico 2 W and MicroPython
Overview
The Pico collects experimental agriculture records locally, tags each sampling session, and can optionally upload the records to a local server.
Research-style prototypes are weak when sample data is not labeled clearly enough for later comparison.
A Pico 2 W prototype with a soil moisture sensor, BME280, sample-tag button, status LED, local log, and optional Wi-Fi upload.
Structured experiment logging, sample tagging, and honest future-lab prototype framing.
Required Components
![]() Raspberry Pi Pico 2 W |
![]() Soil sensor |
![]() Breadboard |
![]() Jumper wires |
![]() LED |
![]() Resistor |
![]() BME280 |
![]() Push button |
| --- |
Circuit Connections
| Component terminal | Connect to | Pico physical pin | Notes |
|---|---|---|---|
| Soil sensor AO | GPIO 26 ADC0 | GPIO 26 / physical pin 31 | Soil input |
| BME280 SDA | GPIO 20 | GPIO 20 / physical pin 26 | I2C0 SDA |
| BME280 SCL | GPIO 21 | GPIO 21 / physical pin 27 | I2C0 SCL |
| Button leg 1 | GPIO 16 | GPIO 16 / physical pin 21 | Sample-tag button input |
| Button leg 2 | 3.3V output | Physical pin 36 | High when pressed |
| LED anode | 220 ohm resistor to GPIO 17 | GPIO 17 / physical pin 22 | Activity LED |
| --- |
Wiring Diagram

Soil sensor AO -> GPIO 26
BME280 SDA -> GPIO 20
BME280 SCL -> GPIO 21
Button -> GPIO 16 and 3.3V
GPIO 17 -> 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
- Connect the soil sensor analog output to GPIO 26.
- Connect the BME280 to Pico 3.3V, GND, GPIO 20 (SDA), and GPIO 21 (SCL).
- Wire the button between GPIO 16 and 3.3V so the input goes high when pressed.
- Wire the LED to GPIO 17 through a 220 ohm resistor and connect the LED cathode to ground.
- Enter Wi-Fi and local endpoint details only after the local record loop works 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.
- Hardware setup: Assemble the Pico, sensor, indicator, and load wiring exactly as shown in the connection table before applying power.
- Test the input sensor: Test the soil sensor, BME280, and sample-tag button separately before recording experiments.
- Test the output device: Blink the LED and test local file writing before enabling upload.
- Test the decision logic: Press the button to start new sample sets and confirm one press changes one tag only.
- Run the full system: Run the full future-lab node and compare records from different sample sets.
- Validate the prototype: Discuss what other metadata a real agriculture research lab would still need.
- 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
BUTTON_PIN = 16
LED_PIN = 17
LOG_FILE = 'future_lab_341.jsonl'
UPLOAD_ENABLED = False
WIFI_SSID = 'YOUR_WIFI'
WIFI_PASSWORD = 'YOUR_PASSWORD'
SERVER_HOST = '192.168.1.50'
SERVER_PORT = 8000
SERVER_PATH = '/future_lab'
INTERVAL_S = 30
soil = ADC(SOIL_PIN)
i2c = I2C(0, sda=Pin(BME_SDA_PIN), scl=Pin(BME_SCL_PIN), freq=400000)
climate = bme280.BME280(i2c=i2c)
button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_DOWN)
led = Pin(LED_PIN, Pin.OUT)
sample_set = 1
last_button = 0
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 future lab ready')
while True:
button_now = button.value()
if button_now == 1 and last_button == 0:
sample_set += 1
print('New sample set:', sample_set)
last_button = button_now
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,
'lab_node': 'future_lab_341',
'sample_set': sample_set,
'uptime_s': time.ticks_ms() // 1000,
'soil_raw': soil.read_u16(),
'temperature_c': temperature,
'humidity_pct': humidity,
}
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 |
|---|---|---|---|
| Sample-set tagging | Uses a button to advance the active sample-set identifier. | Tagged records are easier to compare during later analysis. | Press once per new test condition and verify the sample_set field changes once. |
| Structured experiment record | Stores the sample set and measured values in one clear record. | Research-style prototypes depend on understandable records as much as on sensors. | Add metadata fields only if you can fill them consistently. |
| Local-first logging | Keeps the records locally even if upload is disabled or unavailable. | Local storage protects the experiment history from network failure. | Inspect the local file before debugging upload issues. |
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 |
|---|---|---|
| The sample set jumps too far | The button is bouncing or being held too long | Use deliberate presses and verify the edge-based button logic. |
| Records are missing climate data | The BME280 read failed | Test the BME280 separately and shorten the I2C wires if needed. |
| Uploads always fail | The Wi-Fi details or endpoint settings are wrong | Check UPLOAD_ENABLED, the credentials, and the server host, port, and path. |
| The local file stays empty | Local file writing failed | Test a short text write and confirm the Pico file system is writable. |







