0
0
Iot-protocolsHow-ToBeginner · 4 min read

How to Use Soil Moisture Sensor with Raspberry Pi Easily

To use a soil moisture sensor with a Raspberry Pi, connect the sensor's analog output to an ADC (like MCP3008) because Pi has no analog input. Then, use Python to read the sensor data via SPI and interpret moisture levels.
📐

Syntax

Here is the basic syntax to read soil moisture sensor data using an MCP3008 ADC with Raspberry Pi in Python:

  • import spidev: Import SPI library to communicate with MCP3008.
  • spi.xfer2([1, (8+channel) << 4, 0]): Send command to read from ADC channel.
  • value = ((adc[1] & 3) << 8) + adc[2]: Combine bytes to get sensor value.
python
import spidev

def read_adc(channel):
    spi = spidev.SpiDev()
    spi.open(0, 0)  # Open SPI bus 0, device 0
    spi.max_speed_hz = 1350000
    adc = spi.xfer2([1, (8 + channel) << 4, 0])
    data = ((adc[1] & 3) << 8) + adc[2]
    spi.close()
    return data
💻

Example

This example reads soil moisture sensor data from channel 0 of MCP3008 and prints moisture percentage.

python
import spidev
import time

def read_adc(channel):
    spi = spidev.SpiDev()
    spi.open(0, 0)
    spi.max_speed_hz = 1350000
    adc = spi.xfer2([1, (8 + channel) << 4, 0])
    data = ((adc[1] & 3) << 8) + adc[2]
    spi.close()
    return data

while True:
    sensor_value = read_adc(0)  # Read channel 0
    moisture_percent = 100 - (sensor_value / 1023.0 * 100)
    print(f"Soil Moisture: {moisture_percent:.1f}%")
    time.sleep(2)
Output
Soil Moisture: 45.3% Soil Moisture: 44.8% Soil Moisture: 45.0% ... (updates every 2 seconds)
⚠️

Common Pitfalls

  • Not using an ADC: Raspberry Pi cannot read analog signals directly; you must use an ADC like MCP3008.
  • Incorrect wiring: Connect sensor VCC to 3.3V, GND to ground, and sensor output to ADC input channel.
  • SPI not enabled: Enable SPI interface on Raspberry Pi via raspi-config.
  • Not closing SPI connection: Always close SPI after reading to avoid errors.
python
import spidev

# Wrong: Not closing SPI
spi = spidev.SpiDev()
spi.open(0, 0)
adc = spi.xfer2([1, (8 + 0) << 4, 0])
data = ((adc[1] & 3) << 8) + adc[2]
print(data)
# spi.close() missing

# Right: Closing SPI
spi.close()
📊

Quick Reference

ComponentConnectionPurpose
Soil Moisture SensorVCC to 3.3V, GND to GND, Output to MCP3008 channelMeasures moisture level
MCP3008 ADCSPI pins (MOSI, MISO, SCLK, CE0) to Raspberry Pi SPIConverts analog to digital
Raspberry PiSPI enabled, runs Python codeReads sensor data and processes it

Key Takeaways

Use an ADC like MCP3008 to read analog soil moisture sensor with Raspberry Pi.
Enable SPI interface on Raspberry Pi before running the code.
Connect sensor output to ADC input, not directly to Raspberry Pi GPIO.
Close SPI connection after each read to avoid communication errors.
Convert raw ADC values to moisture percentage for easy understanding.