# Mahdi Zandian
from machine import Pin, PWM
from lcd_sa import *
import time
import dht
# DHT sensor init
sensor = dht.DHT22(Pin(4))
# Servo init
servo_pwm = PWM(Pin(0))
servo_pwm.freq(50)
# LCD init
setlcd()
# Constants for fan speed
MAX_SPEED = 3000
MEDIUM_SPEED = 1000
# get temperature and humidity info
def get_temp():
try:
sensor.measure()
temp = sensor.temperature() # in Celsius
humidity = sensor.humidity() # in percentage
return (temp, humidity)
except Exception as e:
print('Error in getting temp info:', e)
# helper functions for controlling fan (enable or disable based on temp)
def run_servo_loop(speed, start, end):
for a in range(start, end, speed):
servo_pwm.duty_u16(a)
print(a)
time.sleep(0.5)
def active_fan(speed):
print(speed)
if speed == MAX_SPEED: # Max speed
run_servo_loop(speed, 1000, 9000)
run_servo_loop(-speed, 9000, 1000)
elif speed == MEDIUM_SPEED: # Medium speed
run_servo_loop(speed, 1000, 9000)
run_servo_loop(-speed, 9000, 1000)
else: # Turn off fan
servo_pwm.duty_u16(0)
def control_fan(temp):
try:
if temp > 30:
active_fan(MAX_SPEED) # Max speed
elif temp > 20:
active_fan(MEDIUM_SPEED) # Medium speed
else:
servo_pwm.duty_u16(0)
except Exception as e:
print('Error in controlling fan:', e)
# show info on LCD and control the fan (based on temp updates)
def read_sensor(cachTemp):
try:
temp, humidity = get_temp()
print(cachTemp, temp, humidity)
if temp == cachTemp[0] and humidity == cachTemp[1]:
control_fan(temp)
else:
cachTemp = (temp, humidity)
print('Temperature: {}°C, Humidity: {}%'.format(temp, humidity))
lcdwrite(1,0,'Temp: {}°C'.format(temp))
lcdwrite(2,0, 'Humidity: {}%'.format(humidity))
control_fan(temp)
return cachTemp
except Exception as e:
print('Error reading the sensor:', e)
return cachTemp
# Main loop + Cache
cachTemp = (None, None)
while True:
cachTemp = read_sensor(cachTemp)