import dht
import machine
import utime
# Pin configurations
DHT_PIN = 4 # Choose the appropriate GPIO pin for DHT22
LDR_PIN = 34 # Choose the appropriate ADC pin for LDR
LED_PIN = 27 # Choose a GPIO pin for the LED
# Initialize DHT22 sensor
dht_sensor = dht.DHT22(machine.Pin(DHT_PIN))
# Initialize ADC for LDR
adc = machine.ADC(machine.Pin(LDR_PIN))
adc.atten(machine.ADC.ATTN_11DB) # Set attenuation for proper voltage range (adjust if needed)
LDR_THRESHOLD = 2000
# Initialize LED pin
led = machine.Pin(LED_PIN, machine.Pin.OUT)
# Initialize RTC
rtc = machine.RTC()
i2c = machine.I2C(sda=machine.Pin(21), scl=machine.Pin(22))
# RTC address (7-bit address)
rtc_address = 0x68
def read_rtc():
i2c.writeto(rtc_address, bytes([0x00])) # Set the register pointer to 0x00 (seconds)
raw_data = i2c.readfrom(rtc_address, 7) # Read 7 bytes (seconds, minutes, hours, day, date, month, year)
seconds = raw_data[0]
minutes = raw_data[1]
hours = raw_data[2]
day = raw_data[3]
date = raw_data[4]
month = raw_data[5]
year = raw_data[6]
return seconds, minutes, hours, day, date, month, year
def read_dht22():
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
return temperature, humidity
def read_ldr():
ldr_value = adc.read()
return ldr_value
while True:
temperature, humidity = read_dht22()
ldr_value = read_ldr()
current_time = rtc.datetime() # Get current date and time from RTC
print("Date and Time: {}/{}/{} {}:{}:{}".format(
current_time[0], current_time[1], current_time[2],
current_time[3], current_time[4], current_time[5]
))
print("Temperature:", temperature)
print("Humidity:", humidity)
print("LDR Value:", ldr_value)
if ldr_value > LDR_THRESHOLD:
led.on()
print("LED ON")
else:
led.off()
print("LED OFF")
seconds, minutes, hours, day, date, month, year = read_rtc()
print("Time: {:02d}:{:02d}:{:02d}".format(hours, minutes, seconds))
print("Date: {}/{}/{}".format(date, month, year))
utime.sleep(1)
print("========================")
utime.sleep(1) # Sleep for 1 second before taking the next reading
# You can add more logic here to do something with the sensor readings