Project 2.1.2: Cloud-based Crop Healthchart
Intermediate Embedded Systems Project Using Raspberry Pi Pico 2 W and MicroPython
Overview
This project sends crop-condition data to the cloud so students can view moisture, climate, and health-score trends as charts over time.
Students will collect soil moisture, temperature, and humidity, calculate a rule-based crop health score, and upload the values to a charting service such as ThingSpeak.
The final system should connect to Wi-Fi, calculate a health score, and publish the measurements so the crop condition can be visualised remotely.
Required Components
![]() Soil moisture sensor |
![]() Raspberry Pi Pico 2 W |
![]() BME280 sensor module |
![]() Phone or computer |
![]() Breadboard and jumper wires |
Circuit Connections
| Component terminal | Connect to | Pico physical pin | Notes |
|---|---|---|---|
| Soil sensor AOUT | GPIO 26 / physical pin 31 | ADC moisture input | |
| BME280 sensor module | Requires bme280.py on the Pico |
||
| 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

Raspberry Pi Pico 2 W
┌─────────────────────┐
│ │
│ GPIO 2 ───────────┤──── BME280 SDA
│ GPIO 3 ───────────┤──── BME280 SCL
│ │
│ GPIO 26 ───────────┤──── Soil Sensor AOUT
│ │
│ 3.3V ───────────┤──── Soil Sensor VCC
│ 3.3V ───────────┤──── BME280 VCC
│ │
│ GND ───────────┤──── Soil Sensor GND
│ GND ───────────┤──── BME280 GND
│ │
└─────────────────────┘
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 the Soil Moisture Sensor
Place the soil moisture probe so the sensing end can enter the soil sample. Identify VCC, GND, and AOUT / AO / Signal before wiring.
Step 3: Connect the Soil Sensor
Connect soil sensor VCC to 3.3V. Connect soil sensor GND to GND. Connect soil sensor AOUT, AO, or Signal to GPIO 26 (ADC0).
Step 4: Place the BME280 Sensor Module
Identify BME280 VCC, GND, SDA, and SCL before wiring. Connect BME280 VCC to 3.3V. Connect BME280 GND to GND. Connect BME280 SDA to GPIO 2 and BME280 SCL to GPIO 3. If you are using a bare BME280 sensor, use the module pins labeled VCC, GND, SDA, and SCL.
Step 5: Prepare for Cloud Testing
Keep the local sensor wiring complete before testing cloud uploads. Update the Wi-Fi credentials and ThingSpeak API key in the code before running the networking part.
Wiring Check
- [x] Pico 2W is placed correctly across the breadboard center gap
- [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 2W is connected to Wi-Fi for the cloud upload part
- [x] No loose jumper wires
Intermediate Note When running the networking part, the Pico 2W must be connected to Wi-Fi. Replace the SSID and PASSWORD placeholders in the MicroPython code before testing. Do not start cloud testing until the local soil and BME280 readings are believable. Configure the cloud API key before expecting chart updates.
Safety Note Do not pour water onto the Pico, breadboard, USB cable, or jumper wires. Add water to the soil sample away from the electronics.
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 sensor circuits first
- Do not start cloud testing until the local sensor values are believable
Test the Input Sensors
- Calibrate the soil sensor and confirm the BME280 returns stable values
- Check the local health score before publishing anything to the cloud
Test Communication
- Connect to Wi-Fi and confirm that the board reports a successful connection
- Send one chart update and confirm that the correct fields change on the dashboard
Run the Full System
- Let the project send several updates over time so the chart shows a trend, not only one point
- Change one environmental factor and confirm that both the raw fields and the health score respond
Save the Project
- Save the final code and record the field mapping and send interval used in your test
- Write down whether the chart made the health trend easier to understand than raw serial output
Additional Testing and Calibration Checks
Calibration and tuning notes
- Verify the local sensor readings and the local health score before testing cloud uploads
- Use a short send interval during classroom testing and a longer interval for real logging
- If a cloud update fails, check the API key and whether the network allows the request
- Remember that the health score is rule-based, not a laboratory crop-health measurement
Quick testing checklist
- [ ] Wi-Fi connection succeeds
- [ ] Local soil, temperature, and humidity values look correct
- [ ] The health score changes when the environment changes
- [ ] ThingSpeak fields update correctly
- [ ] The chart shows several points over time
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 network
import socket
import time
from machine import ADC, I2C, Pin
import bme280
SSID = "YOUR_WIFI_NAME"
PASSWORD = "YOUR_WIFI_PASSWORD"
THINGSPEAK_HOST = "api.thingspeak.com"
API_KEY = "YOUR_WRITE_API_KEY"
soil = 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)
soil_dry = 52000
soil_wet = 22000
SEND_INTERVAL_S = 60
last_send = time.time() - SEND_INTERVAL_S
def clamp(value, low, high):
if value < low:
return low
if value > high:
return high
return value
def soil_percent():
raw = soil.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 climate_values():
temp_c, humidity, pressure_hpa = read_bme280()
return temp_c, humidity
def health_score(moisture, temp_c, humidity_pct):
score = 0
if 40 <= moisture <= 70:
score += 40
elif 30 <= moisture < 40 or 70 < moisture <= 80:
score += 20
if 18 <= temp_c <= 30:
score += 30
elif 15 <= temp_c < 18 or 30 < temp_c <= 34:
score += 15
if 35 <= humidity_pct <= 80:
score += 30
elif 25 <= humidity_pct < 35 or 80 < humidity_pct <= 90:
score += 15
return clamp(score, 0, 100)
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to Wi-Fi...")
wlan.connect(SSID, PASSWORD)
start = time.time()
while not wlan.isconnected():
if time.time() - start > 20:
raise RuntimeError("Wi-Fi connection timeout")
time.sleep(0.5)
print("Wi-Fi connected:", wlan.ifconfig()[0])
def send_to_thingspeak(moisture, temp_c, humidity_pct, health):
path = "/update?api_key={}&field1={}&field2={}&field3={}&field4={}".format(
API_KEY,
moisture,
temp_c,
humidity_pct,
health,
)
address = socket.getaddrinfo(THINGSPEAK_HOST, 80)[0][-1]
client = socket.socket()
client.settimeout(10)
client.connect(address)
request = "GET {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n\r\n".format(path, THINGSPEAK_HOST)
client.send(request.encode())
response = client.recv(128)
client.close()
return response.startswith(b"HTTP/1.1 200") or response.startswith(b"HTTP/1.0 200")
connect_wifi()
print("Cloud-based crop health chart ready")
while True:
moisture = soil_percent()
temp_c, humidity_pct = climate_values()
health = health_score(moisture, temp_c, humidity_pct)
print("Soil:{}% Temp:{}C Hum:{}% Health:{}".format(moisture, temp_c, humidity_pct, health))
if time.time() - last_send >= SEND_INTERVAL_S:
if send_to_thingspeak(moisture, temp_c, humidity_pct, health):
print("Cloud chart updated")
last_send = time.time()
else:
print("Cloud update failed")
time.sleep(5)
How the Code Works
| Code Section | 1 | Why It Matters |
|---|---|---|
health_score() |
1 | Charts are more meaningful when a summary score is available alongside raw readings |
send_to_thingspeak() |
1 | The cloud dashboard needs consistent field mapping |
SEND_INTERVAL_S |
1 | Interval-based uploads reduce noise and unnecessary traffic |
| Local printout | 1 | Students can compare local and remote monitoring directly |
Expected Result
The Pico should join Wi-Fi, calculate soil moisture, temperature, humidity, and a crop health score, then upload those values to the configured ThingSpeak channel. Over time, the dashboard should display charts for the raw fields and the health score.
Troubleshooting
| Problem | 1 | Solution |
|---|---|---|
| The dashboard shows no data | 1 | Recheck the ThingSpeak channel configuration and the API_KEY value |
| The health score looks unrealistic | 1 | Tune the score bands after observing real readings |
| Wi-Fi never connects | 1 | Confirm the network credentials and test closer to the router |
| Only some chart fields change | 1 | Check that field1 to field4 match the intended order in the channel |




