import time
import dht
from machine import Pin, ADC
# Pin configuration
DHT_PIN = 4
LDR_PIN = 34
PIR_PIN = 27
FAN_LED_PIN = 25
LIGHT_LED_PIN = 26
BUZZER_PIN = 33
# Hardware setup
sensor = dht.DHT22(Pin(DHT_PIN))
ldr = ADC(Pin(LDR_PIN))
ldr.atten(ADC.ATTN_11DB)
pir = Pin(PIR_PIN, Pin.IN)
fan_led = Pin(FAN_LED_PIN, Pin.OUT)
light_led = Pin(LIGHT_LED_PIN, Pin.OUT)
buzzer = Pin(BUZZER_PIN, Pin.OUT)
# Turn outputs OFF initially
fan_led.value(0)
light_led.value(0)
buzzer.value(0)
# -------- Rule Base --------
def evaluate_rules(t, h, light, motion):
fan = False
light_on = False
alarm = False
# Rule R1: High temperature
if t > 30:
fan = True
print("[R1] Temperature > 30 C -> FAN ON")
# Rule R2: High humidity + heat
if h > 80 and t > 28:
fan = True
print("[R2] Humidity > 80% AND Temperature > 28 C -> FAN ON")
# Rule R3: Critical temperature
if t > 35:
alarm = True
print("[R3] Temperature > 35 C -> ALARM ON")
# Rule R4: Dark + motion
if light < 1200 and motion:
light_on = True
print("[R4] Dark AND Motion -> LIGHT ON")
return fan, light_on, alarm
print("===================================")
print(" RULE-BASED INTELLIGENT SYSTEM")
print("===================================")
print("System online")
while True:
try:
# Read DHT22
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
# Read light sensor
light = ldr.read()
# Read PIR
motion = pir.value()
# Convert PIR value to True/False
motion_detected = (motion == 1)
print()
print("----------- SENSING -----------")
print("Temperature :", temperature, "C")
print("Humidity :", humidity, "%")
print("Light :", light)
print("Motion :", motion_detected)
# Evaluate rules
fan, light_on, alarm = evaluate_rules(
temperature,
humidity,
light,
motion_detected
)
# Control blue LED (fan)
if fan:
fan_led.value(1)
else:
fan_led.value(0)
# Control yellow LED (room light)
if light_on:
light_led.value(1)
else:
light_led.value(0)
# Control buzzer
if alarm:
buzzer.value(1)
else:
buzzer.value(0)
print("Fan LED :", "ON" if fan else "OFF")
print("Light LED :", "ON" if light_on else "OFF")
print("Buzzer :", "ON" if alarm else "OFF")
print("-------------------------------")
except Exception as e:
print("ERROR:", e)
time.sleep(2)