# main.py - MicroPython for Raspberry Pi Pico (reads soil sensor on GP26 / ADC0)
from machine import ADC, Pin
import utime
# === Configuration ===
ADC_PIN = 26 # GP26 -> ADC0, connect to sensor OUT
DIGITAL_PIN = 15 # GP15 -> digital wet/dry output from sensor (HIGH = wet)
PUMP_PIN = 16 # GP16 -> LED or relay driver (active HIGH)
VREF = 3.3 # Pico reference voltage (volts)
SAMPLE_INTERVAL = 1.0 # seconds
# Optional: software threshold for moisture_pct (0-100)
# If sensor provides digital wet/dry, you can ignore this and use DIGITAL_PIN state instead.
MOISTURE_THRESHOLD = 30.0 # percent (used to decide pump if digital pin not available)
# === Setup hardware ===
adc = ADC(ADC_PIN) # ADC(26) for GP26
digital_in = Pin(DIGITAL_PIN, Pin.IN, Pin.PULL_DOWN) # sensor's wet/dry output
pump = Pin(PUMP_PIN, Pin.OUT)
pump.value(0) # ensure off initially
def raw_to_voltage(raw):
# raw is 0..65535 for read_u16()
# voltage = raw * VREF / 65535
return (raw * VREF) / 65535.0
def voltage_to_moisture_pct(voltage):
# Simple linear mapping: 0V -> 0%, VREF -> 100%
# Replace with calibration formula if you have sensor-specific mapping
return (voltage / VREF) * 100.0
print("Soil sensor monitor starting - ADC pin: GP{}".format(ADC_PIN))
print("Digital wet/dry pin: GP{}, Pump pin: GP{}".format(DIGITAL_PIN, PUMP_PIN))
print("Sampling every {:.2f} s".format(SAMPLE_INTERVAL))
print()
while True:
raw = adc.read_u16() # 0..65535
voltage = raw_to_voltage(raw)
moisture_pct = voltage_to_moisture_pct(voltage)
# digital state from sensor: HIGH = wet (moisture >= threshold set in the chip)
digital_state = digital_in.value()
# Decision: use digital pin if present; else use analog threshold
if digital_state == 0:
# sensor says DRY -> turn pump ON
pump.value(1)
pump_status = "ON"
else:
# sensor says WET -> turn pump OFF
pump.value(0)
pump_status = "OFF"
# Uncomment to use analog-only decision (if you prefer)
# if moisture_pct < MOISTURE_THRESHOLD:
# pump.value(1); pump_status = "ON (analog)"
# else:
# pump.value(0); pump_status = "OFF (analog)"
# Print human-readable monitoring output
print("Raw: {:5d} | Voltage: {:.3f} V | Moisture: {:.1f}% | Digital wet: {} | Pump: {}"
.format(raw, voltage, moisture_pct, "YES" if digital_state else "NO", pump_status))
utime.sleep(SAMPLE_INTERVAL)