import machine
import onewire
import ds18x20
import time
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
from time import sleep
# 0. Set up LCD
i2c = machine.I2C(0, sda=machine.Pin(21), scl=machine.Pin(22), freq=400000)
lcd = I2cLcd(i2c, 0x27, 4, 20)
# 1. Configure EC and pH sensors (simulated via potentiometers)
# 1.1. EC sensor
ec_sensor = machine.ADC(machine.Pin(34))
ec_sensor.atten(machine.ADC.ATTN_11DB)
# 1.2. pH Sensor
ph_sensor = machine.ADC(machine.Pin(35))
ph_sensor.atten(machine.ADC.ATTN_11DB)
# 2. Configure the GPIO pin and sensor limits
ds_pin = machine.Pin(2)
def map_value(x, in_min, in_max, out_min, out_max):
return (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min
# 3. Create the OneWire bus instance
ow = onewire.OneWire(ds_pin)
# 4. Create the DS18B20 sensor instance
ds_sensor = ds18x20.DS18X20(ow)
# 5. Scan for sensors on the bus
roms = ds_sensor.scan()
# 6. Initialize and print loops
print("+------- START --------+")
while True:
roms = ds_sensor.scan()
ds_sensor.convert_temp()
time.sleep(3)
for rom in roms:
# Read EC sensor values
# Raw EC value
raw_ec = ec_sensor.read()
# Map to 0-15 range
ec_value = map_value(raw_ec, 0, 4095, 0, 100)
print(">> EC: {:.2f} mS/cm".format(ec_value))
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr("EC: {:.2f} mS/cm".format(ec_value))
lcd.move_to(0, 1)
lcd.putstr("====================")
lcd.move_to(0, 2)
if ec_value < 1.2:
print("!! LOW (INC. EC)")
lcd.putstr("!! LOW (INC. EC)")
elif ec_value > 2.0:
print("!! HIGH (DEC. EC)")
lcd.putstr("!! HIGH (DEC. EC)")
else:
print("!! IDEAL (MAINTAIN)")
lcd.putstr("!! IDEAL (MAINTAIN)")
print("========================")
time.sleep(3)
# Read pH sensor values
# Raw pH value
raw_ph = ph_sensor.read()
# Map to 0-15 range
ph_value = map_value(raw_ph, 0, 4095, 0, 15)
print(">> pH: {:.2f}".format(ph_value))
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr("pH: {:.2f}".format(ph_value))
lcd.move_to(0, 1)
lcd.putstr("====================")
lcd.move_to(0, 2)
if ph_value < 5.5:
print("!! LOW (INC. pH)")
lcd.putstr("!! LOW (INC. pH)")
elif ph_value > 6.5:
print("!! HIGH (DEC. pH)")
lcd.putstr("!! HIGH (DEC. pH)")
else:
print("!! IDEAL (MAINTAIN)")
lcd.putstr("!! IDEAL (MAINTAIN)")
print("========================")
time.sleep(3)
# Read temperature sensor values
temp = ds_sensor.read_temp(rom)
print(">> Temperature: {:.2f} C".format(temp))
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr("Temperature: {:.2f} C".format(temp))
lcd.move_to(0, 1)
lcd.putstr("====================\n")
lcd.move_to(0, 2)
if temp < 18:
print("!! COLD (INC. TEMP.)")
lcd.putstr("!! COLD (INC. TEMP.)")
elif temp > 24:
print("!! HOT (DEC. TEMP.)")
lcd.putstr("!! HOT (DEC. TEMP.)")
else:
print("!! IDEAL (MAINTAIN)")
lcd.putstr("!! IDEAL (MAINTAIN)")
print("+----------------------+")
time.sleep(3.5)