from machine import Pin, ADC, PWM
import dht
import time
import math
# ==========================
# Pin Definitions
# ==========================
DHT_PIN = 4
THERM_PIN = 1
SERVO_PIN = 18
BUTTON_PIN = 15
# ==========================
# Devices
# ==========================
dht_sensor = dht.DHT22(Pin(DHT_PIN))
thermistor = ADC(Pin(THERM_PIN))
thermistor.atten(ADC.ATTN_11DB)
button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_UP)
servo = PWM(Pin(SERVO_PIN), freq=50)
# ==========================
# Servo Function
# ==========================
def set_servo_angle(angle):
angle = max(0, min(180, angle))
pulse_us = 500 + (angle / 180) * 2000
duty = int((pulse_us / 20000) * 1023)
servo.duty(duty)
# ==========================
# Thermistor Function
# 10k NTC, Beta = 3950
# ==========================
def thermistor_temp():
adc = thermistor.read()
if adc <= 0 or adc >= 4095:
return 0
# ADC to Voltage
voltage = (adc / 4095) * 3.3
# Voltage divider calculation
R_FIXED = 10000
resistance = R_FIXED * voltage / (3.3 - voltage)
# Beta equation
BETA = 3950
R0 = 10000
T0 = 298.15 # 25°C in Kelvin
temp_k = 1 / (
(1 / T0) +
(math.log(resistance / R0) / BETA)
)
temp_c = temp_k - 273.15
return temp_c
# ==========================
# Main Program
# ==========================
print("System Started")
while True:
if button.value() == 0:
print("Interrupt Triggered")
print("Program Ended")
set_servo_angle(0)
break
try:
# Read DHT22
dht_sensor.measure()
dht_temp = dht_sensor.temperature()
humidity = dht_sensor.humidity()
# Read Thermistor
therm_temp = thermistor_temp()
# Calculate Average Temperature
avg_temp = (dht_temp + therm_temp) / 2
# Servo follows humidity
servo_angle = int((humidity / 100) * 180)
set_servo_angle(servo_angle)
# Print values
print("------------------------")
print("DHT22 Temp : {:.1f} C".format(dht_temp))
print("Humidity : {:.1f} %".format(humidity))
print("Thermistor Temp : {:.1f} C".format(therm_temp))
print("Average Temp : {:.1f} C".format(avg_temp))
print("Servo Angle : {} deg".format(servo_angle))
except Exception as e:
print("Error:", e)
time.sleep(2)
servo.deinit()