import machine
import dht
import time
# Initialize the DHT22 sensor on GPIO pin 4
dht_sensor = dht.DHT22(machine.Pin(4))
# Define the GP26 (pin 26) as an ADC (Analog to Digital Converter) pin
adc = machine.ADC(26)
# Define the LED pin (for example, GP18, change it to your preferred GPIO pin)
led_pin = machine.Pin(9, machine.Pin.OUT)
# Function to read temperature from LM35 sensor
def read_lm35_temperature():
lm35_pin = machine.Pin(0) # GP0 (pin 0) for analog input
adc_value = adc.read_u16() # Read ADC value (0-65535)
voltage = (adc_value / 65535) * 3.3 # Convert ADC value to voltage
temperature_celsius = (voltage - 0.5) * 100 # LM35 linear temperature conversion
return temperature_celsius
# Function to read light intensity from LDR sensor
def read_ldr_light_intensity():
ldr_value = adc.read_u16() # Read ADC value from LDR
return ldr_value
while True:
try:
# Read temperature and humidity from DHT22 sensor
dht_sensor.measure()
temperature_celsius = dht_sensor.temperature()
humidity_percentage = dht_sensor.humidity()
# Read temperature from LM35 sensor
lm35_temperature = read_lm35_temperature()
# Read light intensity from LDR sensor
ldr_intensity = read_ldr_light_intensity()
# Print the sensor readings
print(f"DHT22 Temperature: {temperature_celsius}°C, Humidity: {humidity_percentage}%")
print(f"LM35 Temperature: {lm35_temperature}°C")
print(f"LDR Light Intensity: {ldr_intensity}")
# Control LED based on LDR intensity
if ldr_intensity < 5000: # Adjust this threshold as needed
led_pin.value(1) # Turn on the LED
else:
led_pin.value(0) # Turn off the LED
# Delay for a moment before taking the next reading
time.sleep(2)
except Exception as e:
print(f"Error: {e}")