from machine import Pin, I2C, ADC
from time import sleep, ticks_us, ticks_diff
from i2c_lcd import I2cLcd
from keypad import Keypad
import math
# Cấu hình relay bơm nước
relay1 = Pin(27, Pin.OUT)
relay1.off()
# Cấu hình relay nhiệt độ
relay2 = Pin(14, Pin.OUT)
relay2.off() # đảm bảo tắt relay ban đầu
# Hệ số Beta của NTC
BETA = 3950
TEMP_THRESHOLD = 40 # Ngưỡng nhiệt độ (°C)
# Cấu hình ADC chân 14
adc = ADC(Pin(15))
adc.atten(ADC.ATTN_11DB)
# LCD I2C setup
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
lcd.backlight_on()
# Keypad setup
ROWS = [19, 18, 5, 17]
COLS = [16, 4, 0, 2]
KEYS = [
['1','2','3','A'],
['4','5','6','B'],
['7','8','9','C'],
['*','0','#','D']
]
row_pins = [Pin(pin, Pin.IN, Pin.PULL_UP) for pin in ROWS]
col_pins = [Pin(pin, Pin.OUT) for pin in COLS]
keypad = Keypad(row_pins, col_pins, KEYS)
# HC-SR04 setup
TRIG = Pin(26, Pin.OUT)
ECHO = Pin(25, Pin.IN)
# đọc giá trị từ cảm biến siêu âm
def read_distance():
TRIG.value(0)
sleep(0.002)
TRIG.value(1)
sleep(0.00001)
TRIG.value(0)
while ECHO.value() == 0:
start = ticks_us()
while ECHO.value() == 1:
end = ticks_us()
duration = ticks_diff(end, start)
distance = duration * 0.0343 / 2
return distance
# nhập chiều cao bình
def input_tank_height():
lcd.clear()
lcd.putstr("Nhap cao be (cm):")
lcd.move_to(0, 1)
value = ""
while True:
key = keypad.get_key()
if key:
if key == "#": # Xác nhận
if value:
break
elif key == "*": # Xóa
value = ""
lcd.move_to(0, 1)
lcd.putstr(" " * 16)
lcd.move_to(0, 1)
elif key.isdigit() and len(value) < 4:
value += key
lcd.putstr(key)
sleep(0.2)
return int(value)
# đọc giá trị từ cảm biến nhiệt độ
def read_ntc_temperature():
analog_value = adc.read()
print("ADC Value:", analog_value)
if analog_value <= 0 or analog_value >= 4095:
return None # tránh chia 0 hoặc log âm
# Tính nhiệt độ từ giá trị ADC (dựa trên phân áp chuẩn)
temperature_celsius = 1 / (
math.log(1 / (4096 / analog_value - 1)) / BETA + 1.0 / 298.15
) - 273.15
return temperature_celsius
# hàm chính
lcd.clear()
tank_height = input_tank_height()
tank_full = (tank_height * 0.9)
while True:
distance = read_distance()
water_level = tank_height - distance
percent = max(0, min(100, (water_level / tank_height) * 100))
if water_level <= tank_full:
relay1.on()
else:
relay1.off()
temperature = read_ntc_temperature()
if temperature is None:
print("Lỗi đo nhiệt độ! Kiểm tra mạch.")
else:
print("Nhiệt độ: {:.2f} ℃".format(temperature))
# Điều khiển relay theo nhiệt độ
if (water_level >= tank_height*0.1):
if (temperature >= TEMP_THRESHOLD):
relay2.on()
else:
relay2.off()
else:
relay2.off()
lcd.clear()
lcd.putstr("Muc nuoc: {:.1f}cm".format(water_level))
lcd.move_to(0, 1)
lcd.putstr("=> {:>3.0f}%".format(percent))
sleep(3)