Introduction
A rain or soil moisture sensor is a simple but powerful tool for any gardener, farmer, or IoT enthusiast. It measures the water content in soil or detects rainfall, enabling automated irrigation systems that save water and keep plants healthy. But why stop at a basic timer-based controller? By connecting this sensor to an AI agent like ASI Biont, you can create a truly intelligent garden that adapts to weather forecasts, learns plant needs, and sends you alerts — all without writing a single line of integration code yourself. This article is a step-by-step integration guide for connecting a capacitive soil moisture sensor (e.g., SEN0193 or a rain sensor module) to ASI Biont using an ESP32 and MQTT. You'll learn how to automate watering, monitor soil conditions in real time, and receive AI-driven recommendations.
Why Connect a Soil Moisture Sensor to an AI Agent?
Traditional soil moisture sensors give you raw data — a number from 0 to 4095. An AI agent like ASI Biont can interpret that data in context: it can compare readings against historical trends, combine them with weather data from the internet, and decide when to water. For example, if the soil is dry but rain is forecast in two hours, the AI might delay watering. If a sensor shows consistently low moisture every afternoon, the AI can adjust the schedule proactively. This turns a dumb sensor into a smart decision-maker.
Choosing the Right Connection Method
ASI Biont supports multiple communication protocols (see the full list in the introduction), but for a low-power, wireless IoT sensor like an ESP32 + moisture probe, MQTT is the best choice. MQTT is lightweight, supports publish/subscribe messaging, and works well over Wi-Fi. The ESP32 reads the sensor's analog value, publishes it to a topic like garden/soil/moisture, and ASI Biont subscribes to that topic via a Python script running in its sandbox environment. Alternatively, if your sensor is wired to an Arduino connected to a PC, you could use the Hardware Bridge with COM port — but MQTT gives you remote access without a local computer.
Step-by-Step Integration: ESP32 + Capacitive Soil Moisture Sensor
1. Hardware Setup
Connect your capacitive soil moisture sensor (VCC, GND, Analog Output) to an ESP32:
- Sensor VCC → ESP32 3.3V pin
- Sensor GND → ESP32 GND
- Sensor Analog Out → ESP32 GPIO 34 (ADC1_CH6)
A capacitive sensor is preferred over resistive ones because it doesn't corrode and lasts longer. The SEN0193 works well and outputs 0–3.3V, which maps to 0–4095 on the ESP32's 12-bit ADC.
2. ESP32 MicroPython Code
Flash your ESP32 with MicroPython, then upload this script using a tool like Thonny or ampy. The script reads the sensor every 10 seconds and publishes the value via MQTT.
import network
import time
from machine import Pin, ADC
from umqtt.simple import MQTTClient
# Wi-Fi credentials
WIFI_SSID = "YourWiFiName"
WIFI_PASS = "YourWiFiPassword"
# MQTT broker (use your broker IP or cloud broker like HiveMQ)
MQTT_BROKER = "broker.hivemq.com"
MQTT_TOPIC = "garden/soil/moisture"
CLIENT_ID = "esp32_soil_sensor"
# Set up ADC on pin 34
adc = ADC(Pin(34))
adc.atten(ADC.ATTN_11DB) # Full range 0-3.3V
# Connect to Wi-Fi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
time.sleep(1)
print("Wi-Fi connected")
# Connect to MQTT
client = MQTTClient(CLIENT_ID, MQTT_BROKER)
client.connect()
print("MQTT connected")
while True:
raw_value = adc.read() # 0-4095
# Convert to percentage: dry soil ~3000, wet soil ~1000
moisture_percent = (4095 - raw_value) / 4095 * 100
payload = f"{{\"moisture\": {moisture_percent:.1f}}}"
client.publish(MQTT_TOPIC, payload)
print("Published:", payload)
time.sleep(10)
3. Connecting ASI Biont via MQTT
In the ASI Biont chat, simply describe your setup:
"Connect to MQTT broker at broker.hivemq.com. Subscribe to topic garden/soil/moisture. Read the JSON payload with moisture percentage. If moisture drops below 30%, publish a command to topic garden/valve/control with payload 'ON'. Also send me a Telegram alert. If moisture is above 70%, publish 'OFF'."
ASI Biont will generate and execute a Python script using its sandbox (execute_python). Here's an example of what AI writes:
import paho.mqtt.client as mqtt
import json
import time
BROKER = "broker.hivemq.com"
TOPIC_MOISTURE = "garden/soil/moisture"
TOPIC_VALVE = "garden/valve/control"
THRESHOLD_DRY = 30.0
THRESHOLD_WET = 70.0
valve_state = None # None = unknown
def on_message(client, userdata, msg):
global valve_state
try:
data = json.loads(msg.payload)
moisture = data["moisture"]
print(f"Received moisture: {moisture}%")
if moisture < THRESHOLD_DRY and valve_state != "ON":
client.publish(TOPIC_VALVE, "ON")
valve_state = "ON"
print("Valve turned ON")
# You could also send a Telegram alert here
elif moisture > THRESHOLD_WET and valve_state != "OFF":
client.publish(TOPIC_VALVE, "OFF")
valve_state = "OFF"
print("Valve turned OFF")
except Exception as e:
print(f"Error: {e}")
mqtt_client = mqtt.Client()
mqtt_client.on_message = on_message
mqtt_client.connect(BROKER, 1883, 60)
mqtt_client.subscribe(TOPIC_MOISTURE)
mqtt_client.loop_forever()
The AI runs this script in its sandbox (with a 30-second timeout per execution), but for continuous operation, it would use the industrial_command tool with the publish command to keep the loop running. In practice, you'd run the script on a Raspberry Pi or a cloud VM that stays online 24/7.
4. Real-World Scenario: Automated Garden Watering
Imagine you have a vegetable garden with three zones. Each zone has an ESP32 + soil moisture sensor and a solenoid valve controlled by a relay. By integrating with ASI Biont, you can:
- Monitor each zone's moisture in real time via a dashboard (e.g., Grafana connected to MQTT).
- Have the AI automatically open or close valves based on thresholds.
- Get daily summaries: "Zone 1 watered 2 times, Zone 2 stayed wet due to rain."
- Integrate with a weather API: the AI can skip watering if rain is expected within 6 hours.
- Receive alerts: "Soil moisture in Zone 3 is critically low — check for leaks."
All of this is configured through natural language in the chat. No need to manually code each integration.
Why Use ASI Biont Instead of a Traditional Controller?
Traditional IoT platforms require you to set up dashboards, write MQTT clients, configure rules engines, and maintain servers. ASI Biont eliminates that overhead. You describe what you want in plain English, and the AI writes the exact Python code needed — using paho-mqtt, pymodbus, pyserial, or any other library. It's like having a senior DevOps engineer who instantly implements your requirements.
Conclusion
Connecting a rain or soil moisture sensor to ASI Biont turns a simple analog probe into an intelligent gardening assistant. Using an ESP32 and MQTT, you can monitor soil conditions, automate irrigation, and receive AI-driven insights — all set up through a chat conversation. No dashboard panels, no "add device" buttons, no waiting for firmware updates. Just describe your hardware and goals, and the AI does the rest. Try it yourself at asibiont.com and build a smarter garden today.
Comments