import Adafruit_DHT
import RPi.GPIO as GPIO
import time
# GPIO Setup
GPIO.setmode(GPIO.BCM)
# DHT Sensor Configuration
DHT_SENSOR = Adafruit_DHT.DHT22 # Use DHT11 or DHT22
DHT_PIN = 4 # GPIO pin where the sensor is connected
# LED Configuration
COLD_LED = 17 # GPIO pin for the cold indicator (blue LED)
HOT_LED = 27 # GPIO pin for the hot indicator (red LED)
# Setup GPIO pins for LEDs
GPIO.setup(COLD_LED, GPIO.OUT)
GPIO.setup(HOT_LED, GPIO.OUT)
# Temperature thresholds (in Celsius)
COLD_THRESHOLD = 18 # Below this is "cold"
HOT_THRESHOLD = 30 # Above this is "hot"
try:
while True:
# Read temperature and humidity from the DHT sensor
humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
if temperature is not None:
print(f"Temperature: {temperature:.1f}°C, Humidity: {humidity:.1f}%")
# Control LEDs based on temperature
if temperature < COLD_THRESHOLD:
GPIO.output(COLD_LED, GPIO.HIGH) # Turn on cold LED
GPIO.output(HOT_LED, GPIO.LOW) # Turn off hot LED
print("Cold LED ON")
elif temperature > HOT_THRESHOLD:
GPIO.output(COLD_LED, GPIO.LOW) # Turn off cold LED
GPIO.output(HOT_LED, GPIO.HIGH) # Turn on hot LED
print("Hot LED ON")
else:
GPIO.output(COLD_LED, GPIO.LOW) # Turn off both LEDs
GPIO.output(HOT_LED, GPIO.LOW)
print("Both LEDs OFF")
else:
print("Failed to retrieve data from the sensor.")
# Wait before the next reading
time.sleep(2)
except KeyboardInterrupt:
print("Program stopped by user.")
finally:
GPIO.cleanup() # Reset GPIO settings