from machine import Pin, PWM, I2C
import dht
import time
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
# Setup sensor DHT22 di GPIO4
dht_sensor = dht.DHT22(Pin(4))
# Setup LED indikator suhu > 35°C di GPIO2
led_warning = Pin(2, Pin.OUT)
# Setup PWM untuk simulasi motor di GPIO15
pwm_motor = PWM(Pin(15))
pwm_motor.freq(1000) # PWM frequency 1kHz
# Setup I2C untuk LCD (SDA=GPIO21, SCL=GPIO22)
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16) # alamat 0x27 untuk LCD I2C 16x2
def motor_control(temperature):
"""Atur kecepatan motor berdasarkan suhu."""
if temperature < 25:
pwm_motor.duty_u16(0) # motor OFF
elif 25 <= temperature <= 30:
pwm_motor.duty_u16(int(65535 * 0.5)) # 50% duty cycle
else:
pwm_motor.duty_u16(65535) # 100% duty cycle
def main():
while True:
try:
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
motor_control(temp)
# LED peringatan suhu > 35°C
if temp > 35:
led_warning.on()
else:
led_warning.off()
# Update LCD dengan data terbaru
lcd.clear()
lcd.putstr("Temp: {:.1f} C\n".format(temp))
lcd.putstr("Hum: {:.1f} %".format(hum))
# Debug output ke serial
print("Temperature: {:.1f} C, Humidity: {:.1f} %".format(temp, hum))
except OSError as e:
print("Failed to read sensor:", e)
time.sleep(2)
if __name__ == "__main__":
main()