Skip to content

Project 2.1.4: Crop Environment Logger

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


Overview

The real-world use case is a small trial where moisture, temperature, and humidity should be logged and compared later in a spreadsheet.

Students will build a file-based logger using soil and BME280 sensor readings and save the data in CSV format on the Pico.

The final system should create a log file, append new records at a fixed interval, and make the saved data easy to inspect or export.

Required Components

Soil moisture sensor
Soil moisture sensor
Raspberry Pi Pico 2 W
Raspberry Pi Pico 2 W
BME280 sensor module
BME280 sensor module
LED and 220 Ω resistor
LED and 220 Ω resistor
Breadboard and jumper wires
Breadboard and jumper wires

Circuit Connections

Component terminal Connect to Pico physical pin Notes
Soil sensor AOUT GPIO 26 GPIO 26 / physical pin 31 ADC input
Status LED anode GPIO 16 through 220 Ω resistor GPIO 16 / physical pin 21 Blinks when a log entry is written
Status LED cathode GND Any GND pin LED return
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
  │                     │
  │  GPIO 16 ────220Ω───┤──── Status LED (+)
  │                     │
  │  3.3V    ───────────┤──── Soil Sensor VCC
  │  3.3V    ───────────┤──── BME280 VCC
  │  GND     ───────────┤──── Soil Sensor GND
  │  GND     ───────────┤──── BME280 GND
  │  GND     ───────────┤──── Status LED (-)
  │                     │
  └─────────────────────┘

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.

Step 5: Place the Status LED

Place the status LED on the breadboard. Identify the long leg as the anode (+) and the short leg as the cathode (-).

Step 6: Connect the Status LED

Connect the status LED long leg through a 220Ω resistor to GPIO 16. Connect the status LED short leg to GND.

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
  • [x] BME280 SCL connects to GPIO 3
  • [x] Status LED long leg connects through a 220Ω resistor to GPIO 16
  • [x] Status LED short leg connects to GND
  • [x] No loose jumper wires

Intermediate Note The BME280 needs a short delay between readings. During logging, avoid removing power while a log entry is being written.

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 two sensor paths and the log-status LED
  • Keep the wiring neat so the logger does not store noisy or inconsistent readings

Test the Input Sensors

  • Check the soil sensor locally and record dry and wet calibration values
  • Run a quick BME280 test and confirm that climate readings appear

Test the Output Data

  • Run the logger long enough to create several CSV rows
  • Confirm that the LED blinks when a new entry is written

Run the Full System

  • Leave the logger running for multiple intervals so the file contains a useful short trend
  • Use os.listdir() and open the file in Thonny to confirm that the records were stored correctly

Save the Project

  • Export the CSV file to your computer for analysis
  • Record the log interval and the calibration values used in your final test

Additional Testing and Calibration Checks

Calibration and tuning notes

  • Use a short log interval during initial testing so you do not have to wait a full minute between entries
  • Open the CSV file in Thonny after a few entries to check formatting before running a longer test
  • Remember that elapsed seconds are relative to power-up, not real clock time
  • Export the file to a computer before resetting or reusing the board

Quick testing checklist

  • [ ] crop_log.csv appears in os.listdir()
  • [ ] New rows are appended at the chosen interval
  • [ ] The status LED blinks when a record is written
  • [ ] CSV rows contain four comma-separated values
  • [ ] The file can be opened in Thonny or exported for spreadsheet analysis

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.

from machine import ADC, I2C, Pin
import bme280
import os
import time

LOG_FILE = "crop_log.csv"
LOG_INTERVAL_S = 60

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)


status_led = Pin(16, Pin.OUT)

dry_reading = 52000
wet_reading = 22000

start_ms = time.ticks_ms()
last_log_ms = time.ticks_add(start_ms, -(LOG_INTERVAL_S * 1000))


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 = dry_reading - wet_reading
    if span == 0:
        return 0
    percent = int(((dry_reading - raw) * 100) / span)
    return clamp(percent, 0, 100)


def environment_values():
    temp_c, humidity, pressure_hpa = read_bme280()
    return temp_c, humidity


def elapsed_seconds():
    return time.ticks_diff(time.ticks_ms(), start_ms) // 1000


def ensure_log_file():
    if LOG_FILE not in os.listdir():
        with open(LOG_FILE, "w") as handle:
            handle.write("elapsed_s,moisture,temp_c,humidity_pct\n")


def append_log(moisture, temp_c, humidity_pct):
    with open(LOG_FILE, "a") as handle:
        handle.write("{},{},{},{}\n".format(elapsed_seconds(), moisture, temp_c, humidity_pct))


def show_recent_logs(limit=5):
    with open(LOG_FILE, "r") as handle:
        lines = handle.readlines()
    for line in lines[-limit:]:
        print(line.strip())


ensure_log_file()
print("Crop environment logger ready")

while True:
    moisture = soil_percent()
    try:
        temp_c, humidity_pct = environment_values()
    except Exception as error:
        print("Sensor error:", error)
        time.sleep(2)
        continue

    print("Soil:{}% Temp:{}C Hum:{}%".format(moisture, temp_c, humidity_pct))

    if time.ticks_diff(time.ticks_ms(), last_log_ms) >= LOG_INTERVAL_S * 1000:
        append_log(moisture, temp_c, humidity_pct)
        status_led.on()
        time.sleep(0.2)
        status_led.off()
        last_log_ms = time.ticks_ms()
        show_recent_logs()

    time.sleep(5)

How the Code Works

Code Section What It Does Why It Matters
ensure_log_file() Creates the CSV file with a header if it does not exist Structured files are easier to analyse later
elapsed_seconds() Returns the time since the program started A real-time clock is not required for basic trend logging
append_log() Appends one sensor record to the CSV file The logger becomes useful only when records are saved consistently
show_recent_logs() and status LED Confirm that logging is working Immediate feedback helps catch file problems early

Expected Result

The Pico should create a file named crop_log.csv and add new rows containing elapsed time, moisture, temperature, and humidity. The LED should blink briefly when each new row is written, and the recent rows should appear in the Shell for verification.


Troubleshooting

Problem Possible cause Solution
No file is created The program did not start or the os module failed Run the setup code again and check os.listdir() in Thonny
Rows are missing or duplicated The log interval logic is not working correctly Print the interval timing values and keep the board powered during the test
The LED never blinks The LED wiring is wrong or no logs are being written Check the LED polarity and confirm the logger is appending rows
The CSV contains unrealistic values Sensor calibration or wiring is incorrect Recheck the sensor wiring and update the calibration values