from machine import Pin, ADC, I2C
import dht
import ssd1306
import time
# Inisialisasi I2C untuk OLED
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Inisialisasi Sensor
dht22 = dht.DHT22(Pin(15)) # DHT22 di GPIO15
mq_analog = ADC(Pin(33)) # MQ AO dipindah ke GPIO33 ✅
mq_digital = Pin(23, Pin.IN) # MQ DO tetap di GPIO23
# Loop utama
while True:
try:
dht22.measure()
suhu = dht22.temperature()
lembab = dht22.humidity()
gas_ao = mq_analog.read()
gas_do = mq_digital.value()
# OLED Display
oled.fill(0)
oled.text("Suhu: {:.1f}C".format(suhu), 0, 0)
oled.text("Lembab: {:.1f}%".format(lembab), 0, 10)
oled.text("Gas AO: {}".format(gas_ao), 0, 20)
oled.text("Gas: {}".format("Bahaya" if gas_do == 0 else "Aman"), 0, 30)
oled.show()
# Print juga ke serial (opsional)
print("Suhu: {:.1f} C".format(suhu))
print("Lembab: {:.1f} %".format(lembab))
print("Gas AO:", gas_ao)
print("Gas DO:", "Terdeteksi!" if gas_do == 0 else "Aman")
print("---------------")
time.sleep(2)
except Exception as e:
print("Error:", e)
time.sleep(2)