Project 3.9.12: Smart Agriculture Optimization System
Advanced Embedded Systems Project Using Raspberry Pi Pico 2 W and MicroPython
Overview
The Pico scores soil dryness, heat, and light so a grower can judge how urgently a crop zone needs optimization.
Optimization decisions are difficult when several farm variables compete and there is no single priority score to compare them.
A Pico 2 W prototype with a soil moisture sensor, BME Sensor, LDR, and OLED optimization dashboard.
Priority scoring, multi-factor interpretation, and practical planning before automation.
Required Components
![]() Raspberry Pi Pico 2 W |
![]() Breadboard |
![]() Jumper wires |
![]() Capacitive soil moisture sensor |
![]() BME280 sensor |
![]() LDR |
![]() 128x64 I2C OLED display |
Project-Specific Setup Notes
- Upload
ssd1306.pyto the root folder of the Pico file system in Thonny before running the full project. - In the Thonny Shell, run
import osandprint(os.listdir())to confirm thatssd1306.pyis present on the Pico. - This project focuses on planning and optimization score design rather than direct actuator control.
import os
print(os.listdir())
Project-Specific Safety Note: Interpret the optimization score as local decision support rather than a complete farm-management model.
Circuit Connections
| Component Pin | Connects To | Pico GPIO / Physical Pin Number | 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 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

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
GPIO 20 -> OLED SDA
GPIO 21 -> OLED SCL
Step-by-Step Assembly
- Connect the soil sensor analog output to GPIO 26.
- Build the LDR divider and connect the midpoint to GPIO 27.
- Connect the BME280 to Pico 3.3V, GND, GPIO 20 (SDA), and GPIO 21 (SCL).
- Connect the OLED to Pico 3.3V, GND, GPIO 20, and GPIO 21.
- Upload
ssd1306.pyand confirm it appears on the Pico before running the optimization dashboard.
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: Read each sensor separately so the score is based on believable input values.
- Test the output device: Run an OLED hello-world test so the display path is verified.
- Test the decision logic: Change one stress factor at a time and confirm the score responds in the expected direction.
- Run the full system: Run the full optimizer and compare the score and suggested action with the real test condition.
- Validate the prototype: Discuss whether the scoring weights match your idea of crop priority.
- Save the project: Save the validated program on the Pico as
main.pyand 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
LIGHT_PIN = 27
BME_SDA_PIN = 20
BME_SCL_PIN = 21
I2C_SDA_PIN = 20
I2C_SCL_PIN = 21
SOIL_DRY_RAW = 48000
SOIL_WET_RAW = 18000
LIGHT_DARK_RAW = 4000
LIGHT_BRIGHT_RAW = 52000
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)
if HAS_OLED:
oled = SSD1306_I2C(128, 64, i2c)
def clamp(value, low, high):
return max(low, min(high, value))
def percent_from_range(raw, low_raw, high_raw):
span = high_raw - low_raw
if span == 0:
return 0
pct = int((raw - low_raw) * 100 / span)
return clamp(pct, 0, 100)
print('Agriculture optimization system ready')
while True:
dry_pct = percent_from_range(soil.read_u16(), SOIL_WET_RAW, SOIL_DRY_RAW)
light_pct = percent_from_range(light.read_u16(), LIGHT_DARK_RAW, LIGHT_BRIGHT_RAW)
try:
values = climate.values
temperature = float(values[0].replace('C', ''))
except Exception:
temperature = 0
score = 0
action = 'MONITOR'
if dry_pct >= 70:
score += 3
action = 'WATER'
if temperature >= 33:
score += 2
action = 'SHADE/VENT'
if light_pct <= 25:
score += 2
if action == 'MONITOR':
action = 'ADD LIGHT'
print('Dry:{}% Light:{}% Temp:{}C Score:{} Action:{}'.format(
dry_pct, light_pct, temperature, score, action
))
if HAS_OLED:
oled.fill(0)
oled.text('Farm Optimize', 0, 0)
oled.text('D:{} L:{}'.format(dry_pct, light_pct), 0, 18)
oled.text('T:{} S:{}'.format(temperature, score), 0, 34)
oled.text(action[:16], 0, 50)
oled.show()
time.sleep(2)
How the Code Works
| Code Section | What It Does | Why It Matters | What to Modify During Testing |
|---|---|---|---|
| Percentage mapping | Converts raw soil and light values into readable percentages. | Optimization scoring is easier to justify with normalized values. | Recalibrate the raw endpoints before tuning the score weights. |
| Score and action logic | Builds a simple priority score and chooses the strongest recommended action. | This turns several farm variables into one planning decision. | Adjust the scoring weights only after collecting repeated test observations. |
| OLED dashboard | Shows the optimization score and action locally. | A local dashboard helps students compare raw conditions with the planning output. | If the OLED is blank, check ssd1306.py and the I2C wiring first. |
| Main loop | Updates the score continuously from live sensor input. | Students can watch the planner respond as conditions change. | If the action feels wrong, inspect the sensor baselines before editing the logic. |
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 |
|---|---|---|
| The score is always high | One sensor threshold is too strict or calibration is wrong | Print the normalized values and retune the largest contributor first. |
| Action never changes | The sensors are not changing enough during testing | Create clearer dry, bright, dark, or warm test conditions. |
| Light percentage is backwards | The LDR calibration order is wrong | Swap the dark and bright reference points if needed. |
| Temperature reads zero | The BME280 read failed | Retest the climate sensor separately and check the I2C wiring. |






