print("Starting Smart Plant System...")
# ===================== IMPORT LIBRARIES =====================
from machine import Pin, ADC, I2C, SPI
from time import sleep, localtime
from i2c_lcd import I2cLcd
import ds1307
import sdcard
import os
# ===================== INIT I2C for LCD + RTC =====================
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
lcd = I2cLcd(i2c, 0x27, 2, 16)
rtc = ds1307.DS1307(i2c)
# Optional: Set time once (only if needed)
# rtc.datetime((2025, 7, 14, 0, 12, 0, 0, 0)) # (year, month, day, weekday, hour, min, sec, 0)
# ===================== INIT SPI for SD CARD =====================
spi = SPI(1, sck=Pin(18), mosi=Pin(23), miso=Pin(19))
cs = Pin(5, Pin.OUT)
sd = sdcard.SDCard(spi, cs)
os.mount(sd, "/sd")
# ===================== INIT PINS =====================
ldr = Pin(35, Pin.IN)
ntc = ADC(Pin(34))
ntc.atten(ADC.ATTN_11DB)
button = Pin(25, Pin.IN, Pin.PULL_UP)
relay = Pin(26, Pin.OUT)
led_r = Pin(27, Pin.OUT)
led_g = Pin(14, Pin.OUT)
led_b = Pin(12, Pin.OUT)
# ===================== HELPER FUNCTIONS =====================
def set_rgb(r, g, b):
led_r.value(not r)
led_g.value(not g)
led_b.value(not b)
def water(reason="Auto"):
lcd.clear()
lcd.putstr("Watering [{}]".format(reason))
relay.on()
set_rgb(0, 1, 0)
sleep(3)
relay.off()
set_rgb(1, 1, 1)
def log_data(temp, light, reason="-"):
now = rtc.datetime()
time_str = "{:02d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(now[0], now[1], now[2], now[4], now[5], now[6])
data = "{}, Temp:{}, Light:{}, Reason:{}\n".format(time_str, temp, light, reason)
with open("/sd/log.txt", "a") as f:
f.write(data)
print(data.strip())
def show_lcd(temp, light):
now = rtc.datetime()
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr("T:{} L:{}".format(temp, "Dark" if light == 0 else "Bright"))
lcd.move_to(0, 1)
lcd.putstr("{:02d}:{:02d}:{:02d}".format(now[4], now[5], now[6]))
# ===================== MAIN LOOP =====================
def main():
while True:
temp = ntc.read()
light = ldr.value()
is_manual = not button.value()
reason = ""
# Display on LCD
show_lcd(temp, light)
# RGB based on temp
if temp < 1000:
set_rgb(1, 0, 1) # Green
elif temp > 2500:
set_rgb(0, 1, 1) # Red
else:
set_rgb(1, 1, 0) # Blue
# Decide watering
if is_manual:
water("Manual")
reason = "Manual"
elif 1000 < temp < 2500:
water("Auto")
reason = "Auto"
# Log data
log_data(temp, "Dark" if light == 0 else "Bright", reason if reason else "-")
sleep(5)
# ===================== RUN =====================
if __name__ == "__main__":
main()