Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
2.4 kB
4
Indexable
Never
import time
import sys
import RPi.GPIO as GPIO
import Adafruit_DHT
from Adafruit_IO import MQTTClient

# Adafruit IO credentials
ADAFRUIT_IO_USERNAME = "C1_G3"
ADAFRUIT_IO_KEY = "aio_zOPC08i4bEtiKkyI080ZmMSRjXvD"

# GPIO Pins setup using GPIO.BOARD
soil_moisture_pin = 11  # Pin 11
rain_sensor_pin = 13   # Pin 13
relay_pin = 16         # Pin 16
# dht_sensor_pin = 15    # Pin 15
# dht_sensor_type = Adafruit_DHT.DHT11

GPIO.setmode(GPIO.BOARD)
GPIO.setup(soil_moisture_pin, GPIO.IN)
GPIO.setup(rain_sensor_pin, GPIO.IN)
GPIO.setup(relay_pin, GPIO.OUT)

# Callback functions for Adafruit IO
def connected(client):
    print('Connected to Adafruit IO. Listening for feed changes...')

def disconnected(client):
    print('Disconnected from Adafruit IO!')
    sys.exit(1)

def message(client, feed_id, payload):
    print(f'Feed {feed_id} received new value: {payload}')

# Create an MQTT client instance
client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
client.on_connect = connected
client.on_disconnect = disconnected
client.on_message = message

client.connect()
client.loop_background()

def read_soil_moisture():
    return GPIO.input(soil_moisture_pin)

def read_rain_sensor():
    return GPIO.input(rain_sensor_pin)

def read_dht_sensor():
    humidity, temperature = Adafruit_DHT.read_retry(11, 27)
    return humidity, temperature

def control_relay(state):
    GPIO.output(relay_pin, state)

try:
    while True:
        soil_moisture = read_soil_moisture()
        rain_detected = read_rain_sensor()
        humidity, temperature = read_dht_sensor()
        
        # Publishing data to Adafruit IO
        client.publish('soil-moisture', soil_moisture)
        client.publish('rain-detected', rain_detected)
        client.publish('Temp', temperature)
        client.publish('Humidity', humidity)
        
        print(f"Moisture Level: {'Dry' if soil_moisture == 0 else 'Wet'}")
        print(f"Rain Detected: {rain_detected}")
        print(f"Temperature: {temperature}°C, Humidity: {humidity}%")
        
        # Logic to control the relay based on sensor data
        if soil_moisture == 0 and not rain_detected and temperature > 25:
            print("Turning ON the relay/bulb.")
            control_relay(True)
        else:
            print("Turning OFF the relay/bulb.")
            control_relay(False)

        time.sleep(10)

finally:
    client.disconnect()
    GPIO.cleanup()
Leave a Comment