from machine import Pin, SPI
import time
# SPI0 pins on Raspberry Pi Pico
SCK = Pin(18)
MOSI = Pin(19)
MISO = Pin(16)
CS = Pin(17, Pin.OUT, value=1)
spi = SPI(0, baudrate=1_000_000, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=SCK, mosi=MOSI, miso=MISO)
def read_mcp3008(ch=0):
"""Read 10-bit value (0..1023) from MCP3008 channel ch."""
if not (0 <= ch <= 7):
raise ValueError("Channel must be 0..7")
# MCP3008 protocol: start(1), single-ended(1), ch(3), then 10 data bits
cmd = 0b11 << 6 | (ch & 0x07) << 3
CS.value(0)
buf = spi.readinto if False else None # just to keep lints quiet
resp = spi.read(3, write=bytes([1, cmd, 0])) # send 0x01, cmd, 0x00
CS.value(1)
# resp[1] carries the top 2 data bits (bits 9..8 in its LSBs), resp[2] has bits 7..0
value = ((resp[1] & 0x03) << 8) | resp[2]
return value
def to_percent(raw):
# map 0..1023 to 0..100%
return int((raw * 100) / 1023)
def moisture_band(p):
if p < 20: return "Very Dry"
if p < 40: return "Dry"
if p < 60: return "Optimal"
if p < 80: return "Moist"
return "Wet"
print("Reading MCP3008 CH0. Move the Soil Moisture slider on the custom chip.")
while True:
raw = read_mcp3008(0)
pct = to_percent(raw)
print("Moisture raw:", raw, " -> ", pct, "% | ", moisture_band(pct))
time.sleep(0.25)