import Adafruit_DHT
import RPi.GPIO as GPIO
import time
import spidev # For SPI communication with the ADC
# Constants
DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 22 # GPIO pin for DHT22 data
PIR_PIN = 8 # GPIO pin for PIR sensor
BUZZER_PIN = 20 # GPIO pin for buzzer
LED_PIN = 12 # GPIO pin for LED
PHOTO_CHANNEL = 26 # ADC channel for photoresistor
TEMP_THRESHOLD = 30.0 # Temperature threshold in Celsius
LIGHT_THRESHOLD = 800 # Light level threshold for detecting presence of light
# Setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIR_PIN, GPIO.IN)
GPIO.setup(BUZZER_PIN, GPIO.OUT)
GPIO.setup(LED_PIN, GPIO.OUT)
# SPI setup for MCP3008 ADC
spi = spidev.SpiDev()
spi.open(0, 0) # Open SPI bus 0, device 0
spi.max_speed_hz = 1350000
def read_adc(channel):
"""Read data from MCP3008 ADC"""
adc = spi.xfer2([1, (8 + channel) << 4, 0])
data = ((adc[1] & 3) << 8) + adc[2]
return data
def read_temperature_and_humidity():
"""Read temperature and humidity from DHT22 sensor"""
humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
return humidity, temperature
def read_photoresistor():
"""Read light level from photoresistor"""
value = read_adc(PHOTO_CHANNEL)
return value
def detect_motion():
"""Detect motion using PIR sensor"""
return GPIO.input(PIR_PIN)
def sound_buzzer(duration=0.5):
"""Sound the buzzer for a specified duration"""
GPIO.output(BUZZER_PIN, GPIO.HIGH)
time.sleep(duration)
GPIO.output(BUZZER_PIN, GPIO.LOW)
def turn_on_led():
"""Turn on the LED"""
GPIO.output(LED_PIN, GPIO.HIGH)
def turn_off_led():
"""Turn off the LED"""
GPIO.output(LED_PIN, GPIO.LOW)
try:
while True:
# Read temperature and humidity
humidity, temperature = read_temperature_and_humidity()
if humidity is not None and temperature is not None:
print(f"Temperature: {temperature:.1f}C, Humidity: {humidity:.1f}%")
else:
print("Failed to retrieve data from humidity sensor")
# Read light level
light_level = read_photoresistor()
print(f"Light Level: {light_level}")
# Detect motion
motion_detected = detect_motion()
if motion_detected:
print("Motion detected!")
# Check extreme conditions
extreme_condition = False
if temperature is not None and temperature > TEMP_THRESHOLD:
print("Temperature exceeds threshold!")
extreme_condition = True
if motion_detected and light_level > LIGHT_THRESHOLD:
print("Motion and light detected!")
extreme_condition = True
# Trigger actions on extreme conditions
if extreme_condition:
turn_on_led()
sound_buzzer(1) # Sound the buzzer for 1 second
else:
turn_off_led()
# Wait before next reading
time.sleep(2)
except KeyboardInterrupt:
print("Exiting program")
finally:
GPIO.cleanup()
spi.close()