from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
import sys
from time import sleep
from dht import DHT22
# OLED resolution
pix_res_x = 128
pix_res_y = 64
# DHT22 connected to GP15
dht = DHT22(Pin(15))
def init_i2c(scl_pin, sda_pin):
i2c_dev = I2C(1, scl=Pin(scl_pin), sda=Pin(sda_pin), freq=200000)
i2c_addr = [hex(ii) for ii in i2c_dev.scan()]
if not i2c_addr:
print('No I2C Display Found')
sys.exit()
else:
print("I2C Address : {}".format(i2c_addr[0]))
print("I2C Configuration: {}".format(i2c_dev))
return i2c_dev
def main():
# Initialize I2C and OLED only once
i2c_dev = init_i2c(scl_pin=27, sda_pin=26)
oled = SSD1306_I2C(pix_res_x, pix_res_y, i2c_dev)
while True:
try:
dht.measure()
temp = dht.temperature()
hum = dht.humidity()
# Output to console
print(f"Temperature: {temp}°C Humidity: {hum}%")
# Output to OLED
oled.fill(0)
oled.text("Temp: {:.1f}C".format(temp), 5, 5)
oled.text("Hum: {:.1f}%".format(hum), 5, 15)
oled.show()
except OSError as e:
oled.fill(0)
oled.text("Sensor Error", 5, 5)
oled.show()
sleep(2) # Delay between readings
if __name__ == '__main__':
main()