Soil Moisture MQTT client

Hello,

Could somebody help me out? I’d like to implement a soil moisture sensor on my raspberry PI, I figured out the below code would be useful but I’ve no idea how to implement MQTT along with that so I can see the data on my dashboard.


#!/usr/bin/python
import RPi.GPIO as GPIO
import time

#GPIO SETUP
channel = 21
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN)

def callback(channel):
if GPIO.input(channel):
print “Water Detected!”
else:
print “Water Detected!”

GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300) # let us know when the pin goes HIGH or LOW
GPIO.add_event_callback(channel, callback) # assign function to GPIO PIN, Run function on change

infinite loop

while True:
time.sleep(1)


Many thanks for your help!

you can use a two-state widget to show if the moisture is detected or not. To send data use this code https://github.com/myDevicesIoT/Cayenne-MQTT-Python/blob/master/examples/Example-03-CayenneClient.py and add the code for the sensor. The only change in your code will be:

def callback(channel):
if GPIO.input(channel):
print “Water Detected!”
client.virtualWrite(1,1,"digital_sensor","d")
else:
print “Water Detected!”
client.virtualWrite(1,0,"digital_sensor","d")

Thanks a lot for your quick reply, does that look ok to you?

#!/usr/bin/env python
import cayenne.client as cayenne
import RPi.GPIO as GPIO
import time

#Cayenne MQTT setup
MQTT_USERNAME = “MQTT_USERNAME”
MQTT_PASSWORD = “MQTT_PASSWORD”
MQTT_CLIENT_ID = “MQTT_CLIENT_ID”

client = cayenne.CayenneMQTTClient()
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID)

#GPIO SETUP
channel = 21
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN)

timestamp = 0

def callback(channel):
GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300) # let us know when the pin goes HIGH or LOW
GPIO.add_event_callback(channel, callback) # assign function to GPIO PIN, Run function on change

while True:
client.loop(time.time() > timestamp + 5)
if GPIO.input(channel):
print “ Water detected”
client.virtualWrite(1,1,“digital_sensor”,“d”)
else:
print “ No Water detected”
client.virtualWrite(1,0,“digital_sensor”,“d”)
timestamp = time.time()

#!/usr/bin/python
import RPi.GPIO as GPIO
import time
import cayenne.client as cayenne

client = cayenne.CayenneMQTTClient()
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID)

#GPIO SETUP
channel = 21
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN)

def callback(channel):
if GPIO.input(channel):
print “Water Detected!”
client.virtualWrite(1,1,“digital_sensor”,“d”)
else:
print “Water Detected!”
client.virtualWrite(1,0,“digital_sensor”,“d”)

GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300) # let us know when the pin goes HIGH or LOW
GPIO.add_event_callback(channel, callback) # assign function to GPIO PIN, Run function on change

# infinite loop

while True:
client.loop()

OK, I was complicating things… thanks a lot!

2 Likes