Skip to lesson content

Hardware & Sensors · Lesson 12 of 17

Read a capacitive soil moisture sensor

Capacitive soil moisture probe

Connect the probe to analogue input 1

Use a probe rated for a 3.3 V supply. Shut down the Pi and disconnect its power before wiring.

  1. Connect the probe's power lead (VCC) to a 3.3 V supply pin and its ground lead (GND) to GND on the HAT.
  2. Connect the probe's analogue output (AOUT) to analogue input 1 on the HAT. The examples below read that channel.
  3. Reconnect power and activate the Python environment in which you installed the HAT libraries.

Read the sensor voltage

Start Python in that environment. The read() method returns the voltage on channel 1. Keep the reading in the same session for the conversion below.

import automationhat

humidity_adc_value = automationhat.analog.one.read()
print(humidity_adc_value)

View source on GitHub

Calibrate a relative moisture scale

Take a reading in dry growing medium, then another in the same medium after watering. Keep the insertion depth the same and the probe electronics dry. The example assumes the voltage drops as the medium gets wetter. Replace min_value with the wet voltage and max_value with the dry voltage. The two readings must differ.

def convert_to_humidity(analog_value):
    min_value = 1.05 
    max_value = 2.09 
    return 100 - ((analog_value - min_value) / (max_value - min_value)) * 100.0

humidity_percentage = int(convert_to_humidity(humidity_adc_value))

View source on GitHub

This calculation assigns 0% to your dry reference and 100% to your wet reference. Readings outside those references can fall below 0% or above 100%.

Show relative moisture on the screen

The original project code labels the value “Humidity”. It represents relative moisture in the growing medium. Use “Moisture” as the display label in your copy. This snippet assumes you have initialised the HAT Mini display and drawing surface and imported time.

draw.rectangle((0, 0, WIDTH, HEIGHT), (0, 0, 0))  # Clear the screen
draw.text((10, 10), f'Humidity: {humidity_percentage}%', fill=(255, 255, 255))
disp.display(img)
time.sleep(1)

View source on GitHub

Refresh the reading once a second

Add this loop after the display setup and conversion function. Press Ctrl+C to stop it.

import automationhat

while True:
    humidity_adc_value = automationhat.analog.one.read()
    humidity_percentage = int(convert_to_humidity(humidity_adc_value))
    draw.rectangle((0, 0, WIDTH, HEIGHT), (0, 0, 0))  # Clear the screen
    draw.text((10, 10), f'Humidity: {humidity_percentage}%', fill=(255, 255, 255))
    disp.display(img)
    time.sleep(1)

View source on GitHub