import dht
from machine import Pin, I2C, ADC
import time
# DHT22 setup
dht_sensor = dht.DHT22(Pin(15))
def read_dht22():
dht_sensor.measure()
temp = dht_sensor.temperature()
humidity = dht_sensor.humidity()
print(f"Temperature: {temp:.2f}°C, Humidity: {humidity:.2f}%")
return temp, humidity
# I2C setup for BH1750
i2c = I2C(0, scl=Pin(5), sda=Pin(4))
class BH1750:
PWR_DOWN = 0x00
PWR_ON = 0x01
RESET = 0x07
CONT_H_RES_MODE = 0x10
def __init__(self, i2c, addr=0x23):
self.i2c = i2c
self.addr = addr
self.i2c.writeto(self.addr, bytearray([self.PWR_ON]))
def luminance(self):
self.i2c.writeto(self.addr, bytearray([self.CONT_H_RES_MODE]))
time.sleep(0.2)
data = self.i2c.readfrom(self.addr, 2)
return (data[0] << 8 | data[1]) / 1.2
# BH1750 sensor instance
bh1750 = BH1750(i2c)
def read_bh1750():
lux = bh1750.luminance()
print(f"Light Intensity: {lux:.2f} lux")
return lux
# MQ-135 setup
mq135_sensor = ADC(Pin(26))
def read_mq135():
air_quality = mq135_sensor.read_u16() # Read a 16-bit analog value
print(f"Air Quality (Analog): {air_quality}")
return air_quality
# Main loop
def main():
while True:
# Read data from DHT22
temperature, humidity = read_dht22()
# Read data from BH1750
light_intensity = read_bh1750()
# Read data from MQ-135
air_quality = read_mq135()
# Wait before next reading
time.sleep(2)
if __name__ == "__main__":
main()