print("Project: Smart Solar Energy Monitoring System")
print("Developed by: Han")
print("Date: 22/4/2025")
from machine import Pin, ADC, I2C, PWM
import time
import dht
import ssd1306
# === Initialization ===
print("Initializing devices...")
# Initialize I2C for OLED display
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=20000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Light Sensor (LDR)
ldr = ADC(Pin(34))
ldr.atten(ADC.ATTN_0DB)
# DHT22 sensor (Temperature & Humidity)
dht_sensor = dht.DHT22(Pin(2))
# Relay for controlling appliances
relay = Pin(5, Pin.OUT)
# LEDs (Green and Red)
green_led = Pin(12, Pin.OUT)
red_led = Pin(13, Pin.OUT)
# Buzzer (PWM for audible tone)
buzzer = PWM(Pin(4)) # Buzzer pin using PWM
buzzer.duty(0) # Initial duty cycle (off)
# Servo Motor (for solar panel adjustment)
servo = PWM(Pin(14), freq=50)
# === Functions ===
def read_ldr():
value = ldr.read()
print("LDR value:", value)
return value
def read_dht():
try:
dht_sensor.measure()
temp = dht_sensor.temperature()
humidity = dht_sensor.humidity()
print("Temp:", temp, "Humidity:", humidity)
return temp, humidity
except OSError as e:
print("DHT read error:", e)
return None, None
def display_data(ldr_value, temp, humidity):
oled.fill(0)
oled.text('LDR: {}'.format(ldr_value), 0, 0)
if temp is not None:
oled.text('Temp: {}C'.format(temp), 0, 10)
if humidity is not None:
oled.text('Humidity: {}%'.format(humidity), 0, 20)
oled.show()
def control_relay_and_leds(ldr_value):
if ldr_value > 2000:
relay.value(1)
green_led.value(1)
red_led.value(0)
print("Relay: ON (good sunlight)")
else:
relay.value(0)
green_led.value(0)
red_led.value(1)
print("Relay: OFF (low sunlight)")
def control_buzzer(ldr_value):
if ldr_value < 1000:
buzzer.freq(1000) # Set frequency to 1 kHz
buzzer.duty(512) # Half duty cycle (for audible tone)
print("Buzzer: ON (low light)")
else:
buzzer.duty(0) # Turn off buzzer
print("Buzzer: OFF")
def control_servo(ldr_value):
if ldr_value > 2000:
servo.duty(40) # Adjust servo to a specific position (based on light intensity)
print("Servo: Adjusted")
else:
servo.duty(0) # Reset servo position
print("Servo: Reset")
# === Main Loop ===
while True:
print("Reading sensors...")
ldr_value = read_ldr()
temp, humidity = read_dht()
print("Updating OLED...")
display_data(ldr_value, temp, humidity)
print("Controlling outputs...")
control_relay_and_leds(ldr_value)
control_buzzer(ldr_value)
control_servo(ldr_value)
print("Waiting...\n")
time.sleep(2)