import machine
import dht
import ssd1306
import time
# Initialize the DHT22 sensor
dht22 = dht.DHT22(machine.Pin(2)) # Use the appropriate pin (e.g., GPIO 2)
# Initialize the fan control (PWM)
fan_pin = machine.Pin(14, machine.Pin.OUT)
fan_pwm = machine.PWM(fan_pin, freq=1000, duty=0) # Adjust the pin number as needed
# Initialize the OLED display
i2c = machine.SoftI2C(scl=machine.Pin(22), sda=machine.Pin(21)) # Adjust the pins for your setup
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
while True:
try:
dht22.measure()
temperature = dht22.temperature()
# Control fan speed based on temperature
if temperature < 25:
fan_pwm.duty(0) # Fan off
elif temperature >= 25 and temperature < 30:
fan_pwm.duty(512) # Fan at half speed
else:
fan_pwm.duty(1023) # Fan at full speed
# Display temperature on OLED
oled.fill(0) # Clear the display
oled.text("Temperature:", 0, 0)
oled.text("{:.1f} C".format(temperature), 0, 20)
oled.show()
except Exception as e:
print("Error:", e)
time.sleep(5) # Adjust the interval as needed